Lesson 2 of 10 Foundations

Redis Strings, Keys and Expiry (TTL)

Redis strings and keys in practice: atomic counters, TTL expiry, SET NX for first-writer-wins, MGET batching, key naming, and SCAN instead of KEYS.

30-40 min beginner 0/10 lessons done
Course contents Lesson 2 of 10 · 0 done
On this page (8 sections)
  1. What you will learn
  2. The code
  3. What’s happening
  4. Naming keys
  5. Never use KEYS in production
  6. Key takeaways
  7. Exercises
  8. Quiz

What you will learn

  • Strings as values, counters and flags.
  • Expiry with EX/PX, TTL and how Redis deletes expired keys.
  • SET NX for “only if absent”, and batching with MGET/MSET.
  • Naming keys and iterating safely with SCAN.

The code

"""Strings and keys: counters, expiry, SET NX, and batching with MGET."""
import os
import time

import redis

r = redis.Redis(port=int(os.getenv("REDIS_PORT", 6379)), decode_responses=True)
r.flushdb()  # demo database only!

# Counters are atomic: no read-modify-write race in your app
for _ in range(3):
    r.incr("page:home:views")
r.incrby("page:home:views", 10)
print("views:", r.get("page:home:views"))

# Expiry: the key deletes itself
r.set("otp:user:42", "913204", ex=2)
print("otp ttl:", r.ttl("otp:user:42"))
time.sleep(2.1)
print("otp after expiry:", r.get("otp:user:42"))

# SET NX: only set if absent (first writer wins)
print("first claim:", r.set("signup:email:asha@example.com", "user:42", nx=True))
print("second claim:", r.set("signup:email:asha@example.com", "user:99", nx=True))

# Batch reads in one round trip
r.mset({"price:sku:1": 499, "price:sku:2": 1299})
print("mget:", r.mget("price:sku:1", "price:sku:2", "price:sku:missing"))

# Inspect types and memory of keys
print("type:", r.type("page:home:views"), "| encoding:", r.object("encoding", "page:home:views"))

Output:

views: 13
otp ttl: 2
otp after expiry: None
first claim: True
second claim: None
mget: ['499', '1299', None]
type: string | encoding: int

What’s happening

  • Counters: INCR and INCRBY run inside Redis, so concurrent clients never lose updates. Compare with reading a value in your app, adding one and writing it back, which races. Strings that hold integers are stored in a compact int encoding.
  • Expiry: SET key value EX 2 sets a time-to-live. TTL returns the remaining seconds (-1 means no expiry, -2 means the key doesn’t exist). Redis removes expired keys lazily when they’re accessed, plus an active background sweep, so expired keys never come back.
  • SET NX (“not exists”) returns success only for the first writer. That’s the basis of idempotency keys, unique claims, and the locks in lesson 8. The response None means “not set”.
  • MGET/MSET move many keys in one round trip; missing keys come back as None.

Useful extras: SET key value KEEPTTL (update without resetting expiry), GETEX (read and change TTL), GETDEL, APPEND, SETRANGE/GETRANGE, and INCRBYFLOAT.

Naming keys

Use colon-separated namespaces: object-type:id:field, such as user:42:sessions or rl:api:ip:10.0.0.1. Benefits:

  • Easy to read in redis-cli and monitoring tools.
  • Easy to find with SCAN 0 MATCH user:42:* COUNT 100.
  • Hash tags like {user:42} later control placement in Redis Cluster (lesson 10).

Keep keys short but readable; at millions of keys, a few saved bytes per key add up.

Never use KEYS in production

KEYS pattern walks the whole keyspace in one blocking command. SCAN returns a cursor and a small batch each call, letting other clients run in between:

for key in r.scan_iter(match="user:*", count=500):
    print(key)

SCAN may return a key more than once, so make the work idempotent.

Key takeaways

  • INCR-family commands are atomic counters; don’t read-modify-write in the app.
  • Use EX/PX for anything temporary; TTL -1 means no expiry, -2 means missing.
  • SET NX gives first-writer-wins semantics.
  • Batch with MGET/MSET; iterate with SCAN, never KEYS, in production.

Exercises

  1. Build a “views in the last hour” counter with one key per hour (views:2026-11-22T10) and a 2-hour TTL.
  2. Use SET NX EX to implement idempotency: process a payment request only once per Idempotency-Key.
  3. Write a script that uses SCAN to count keys per prefix (user, product, …).

Quiz

  1. What does TTL return for a key without expiry, and for a missing key?
  2. Why is INCR safer than GET-then-SET for counters?
  3. What does SET key value NX return when the key already exists?
Show answers
  1. -1 for a key without expiry, -2 for a key that doesn’t exist.
  2. It runs atomically inside Redis; GET-then-SET from two clients can interleave and lose an increment.
  3. Nil (None in redis-py): nothing was set.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).