What you will learn
- Strings as values, counters and flags.
- Expiry with
EX/PX,TTLand how Redis deletes expired keys. SET NXfor “only if absent”, and batching withMGET/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:
INCRandINCRBYrun 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 compactintencoding. - Expiry:
SET key value EX 2sets a time-to-live.TTLreturns 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
Nonemeans “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-cliand 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/PXfor anything temporary;TTL-1 means no expiry, -2 means missing. SET NXgives first-writer-wins semantics.- Batch with
MGET/MSET; iterate withSCAN, neverKEYS, in production.
Exercises
- Build a “views in the last hour” counter with one key per hour (
views:2026-11-22T10) and a 2-hour TTL. - Use
SET NX EXto implement idempotency: process a payment request only once perIdempotency-Key. - Write a script that uses
SCANto count keys per prefix (user,product, …).
Quiz
- What does
TTLreturn for a key without expiry, and for a missing key? - Why is
INCRsafer than GET-then-SET for counters? - What does
SET key value NXreturn when the key already exists?
Show answers
- -1 for a key without expiry, -2 for a key that doesn’t exist.
- It runs atomically inside Redis; GET-then-SET from two clients can interleave and lose an increment.
- Nil (
Nonein redis-py): nothing was set.