Redis Basics & Patterns
This chapter chooses Redis data types by operation—not by appearance—then builds caches, locks, rate limits, pub/sub flows, and geospatial queries with explicit consistency and expiry semantics.
- Explain Data structures by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Caching strategies by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Distributed locking by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Pub/Sub & Redis GEO by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Expiry, eviction & transactions by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Redis Basics & Patterns, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the data learning arc appropriate to this subject.
The problem this chapter solves
This chapter chooses Redis data types by operation—not by appearance—then builds caches, locks, rate limits, pub/sub flows, and geospatial queries with explicit consistency and expiry semantics.
It offers predictable low-latency primitives for caching, coordination, counters, rate limits, ephemeral state, and real-time delivery when their failure semantics are explicitly designed.
Learning outcomes
- Explain Data structures by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Caching strategies by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Distributed locking by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Pub/Sub & Redis GEO by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Expiry, eviction & transactions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
Commands are executed serially by Redis's core event-loop model, while networking and persistence can use additional threads or processes. Atomicity applies to one command or a server-side transaction/script, not to an arbitrary client-side read-modify-write sequence. Expiry is enforced lazily on access and actively by periodic sampling. In Redis Basics & Patterns, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The client borrows a bounded connection, encodes the command, and sends it to the node responsible for the key or hash slot.
- Redis executes the command atomically in its core event-loop order; transactions queue commands and Lua scripts perform one bounded server-side decision.
- Expiry, persistence, replication, eviction, and failover policy determine how long the result remains available and what loss window is possible.
- The client decodes the reply, handles redirection or timeout according to bounded retry policy, and releases the connection.
- Tests cover TTL boundaries, races, stale lease owners, failover, resharding, pending work, and memory pressure with latency and error metrics.
Memory and performance lens
Redis stores keys, metadata, and encodings in RAM; logical payload size understates actual memory use. Eviction policy, fragmentation, replication buffers, client output buffers, streams' pending entries, and copy-on-write during persistence all affect capacity. For Redis Basics & Patterns, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Redis Basics & Patterns, measure rows and bytes scanned, plan estimates versus actuals, buffer hits/reads, spill, lock time, cache memory, and tail latency rather than optimizing from source-code appearance.
1. Data structures
The Data structures unit begins with String: SET/GET/INCR/SETEX: Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. Choose the type that performs the needed update in one bounded command. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Data structures
| Concept | Meaning | Engineering decision |
|---|---|---|
| String: SET/GET/INCR/SETEX | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
| Hash: HSET/HGET/HGETALL for objects | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
| List: LPUSH/RPUSH/BLPOP for queues | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
| Set: SADD/SINTER/SUNION/SDIFF | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
| Sorted Set: ZADD/ZRANGEBYSCORE for leaderboards | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
| HyperLogLog and Bitmaps | Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. | Choose the type that performs the needed update in one bounded command. |
Storage, planning, and execution: Data structures
String: SET/GET/INCR/SETEX. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
Hash: HSET/HGET/HGETALL for objects. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
List: LPUSH/RPUSH/BLPOP for queues. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
Set: SADD/SINTER/SUNION/SDIFF. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
Sorted Set: ZADD/ZRANGEBYSCORE for leaderboards. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
HyperLogLog and Bitmaps. The server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands.
Read these as one system: String: SET/GET/INCR/SETEX establishes the starting contract, Hash: HSET/HGET/HGETALL for objects changes how that contract is executed or represented, and HyperLogLog and Bitmaps exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Data structures
1async with redis.pipeline(transaction=True) as pipe:2 pipe.hset(f"string_set_get_incr_setex:{entity_id}", mapping=payload)3 pipe.expire(f"string_set_get_incr_setex:{entity_id}", ttl_seconds)4 await pipe.execute()This Data structures slice makes String: SET/GET/INCR/SETEX observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward HyperLogLog and Bitmaps, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Data structures
| Risk | Why it matters |
|---|---|
| String: SET/GET/INCR/SETEX | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
| Hash: HSET/HGET/HGETALL for objects | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
| List: LPUSH/RPUSH/BLPOP for queues | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
| Set: SADD/SINTER/SUNION/SDIFF | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
| Sorted Set: ZADD/ZRANGEBYSCORE for leaderboards | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
| HyperLogLog and Bitmaps | Large aggregate keys create latency spikes, replication cost, and difficult resharding. |
Data investigation: Data structures
- Foundation: implement or demonstrate String: SET/GET/INCR/SETEX with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine String: SET/GET/INCR/SETEX with Hash: HSET/HGET/HGETALL for objects. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for HyperLogLog and Bitmaps. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Caching strategies
The Caching strategies unit begins with cache-aside (lazy) with TTL: A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. Document key version, TTL jitter, negative caching, and source-of-truth behavior. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Caching strategies
| Concept | Meaning | Engineering decision |
|---|---|---|
| cache-aside (lazy) with TTL | A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| write-through: cache + DB simultaneously | A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| write-behind (async DB writes) | A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| cache stampede prevention: mutex lock + probabilistic expiry | A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
Storage, planning, and execution: Caching strategies
cache-aside (lazy) with TTL. Cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses.
write-through: cache + DB simultaneously. Cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses.
write-behind (async DB writes). Cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses.
cache stampede prevention: mutex lock + probabilistic expiry. Cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses.
Read these as one system: cache-aside (lazy) with TTL establishes the starting contract, write-through: cache + DB simultaneously changes how that contract is executed or represented, and cache stampede prevention: mutex lock + probabilistic expiry exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Caching strategies
1async with redis.pipeline(transaction=True) as pipe:2 pipe.hset(f"cache_aside_lazy_with_ttl:{entity_id}", mapping=payload)3 pipe.expire(f"cache_aside_lazy_with_ttl:{entity_id}", ttl_seconds)4 await pipe.execute()This Caching strategies slice makes cache-aside (lazy) with TTL observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward cache stampede prevention: mutex lock + probabilistic expiry, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Caching strategies
| Risk | Why it matters |
|---|---|
| cache-aside (lazy) with TTL | Delete/update races can repopulate stale values; cache correctness is a protocol. |
| write-through: cache + DB simultaneously | Delete/update races can repopulate stale values; cache correctness is a protocol. |
| write-behind (async DB writes) | Delete/update races can repopulate stale values; cache correctness is a protocol. |
| cache stampede prevention: mutex lock + probabilistic expiry | Delete/update races can repopulate stale values; cache correctness is a protocol. |
Data investigation: Caching strategies
- Foundation: implement or demonstrate cache-aside (lazy) with TTL with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine cache-aside (lazy) with TTL with write-through: cache + DB simultaneously. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for cache stampede prevention: mutex lock + probabilistic expiry. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Distributed locking
The Distributed locking unit begins with Redlock algorithm: A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Distributed locking
| Concept | Meaning | Engineering decision |
|---|---|---|
| Redlock algorithm | A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| Python redlock-py implementation | A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| SET NX PX pattern | A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| fencing tokens for safety | A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
Storage, planning, and execution: Distributed locking
Redlock algorithm. Redis SET key token NX PX ttl acquires one lease and a compare-delete script releases only the owner's token. Redlock combines independent nodes under timing assumptions.
Python redlock-py implementation. Redis SET key token NX PX ttl acquires one lease and a compare-delete script releases only the owner's token. Redlock combines independent nodes under timing assumptions.
SET NX PX pattern. Redis SET key token NX PX ttl acquires one lease and a compare-delete script releases only the owner's token. Redlock combines independent nodes under timing assumptions.
fencing tokens for safety. Redis SET key token NX PX ttl acquires one lease and a compare-delete script releases only the owner's token. Redlock combines independent nodes under timing assumptions.
Read these as one system: Redlock algorithm establishes the starting contract, Python redlock-py implementation changes how that contract is executed or represented, and fencing tokens for safety exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Distributed locking
1async with redis.pipeline(transaction=True) as pipe:2 pipe.hset(f"redlock_algorithm:{entity_id}", mapping=payload)3 pipe.expire(f"redlock_algorithm:{entity_id}", ttl_seconds)4 await pipe.execute()This Distributed locking slice makes Redlock algorithm observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward fencing tokens for safety, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Distributed locking
| Risk | Why it matters |
|---|---|
| Redlock algorithm | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. |
| Python redlock-py implementation | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. |
| SET NX PX pattern | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. |
| fencing tokens for safety | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. |
Data investigation: Distributed locking
- Foundation: implement or demonstrate Redlock algorithm with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Redlock algorithm with Python redlock-py implementation. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for fencing tokens for safety. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Pub/Sub & Redis GEO
The Pub/Sub & Redis GEO unit begins with PUBLISH/SUBSCRIBE/PSUBSCRIBE: Pub/Sub delivers live messages to currently connected subscribers; GEO indexes locations in a sorted set representation for radius or box search. Use Streams or Kafka when replay is required and model location freshness separately. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Pub/Sub & Redis GEO
| Concept | Meaning | Engineering decision |
|---|---|---|
| PUBLISH/SUBSCRIBE/PSUBSCRIBE | Pub/Sub delivers live messages to currently connected subscribers; GEO indexes locations in a sorted set representation for radius or box search. | Use Streams or Kafka when replay is required and model location freshness separately. |
| aioredis async pub/sub | Pub/Sub delivers live messages to currently connected subscribers; GEO indexes locations in a sorted set representation for radius or box search. | Use Streams or Kafka when replay is required and model location freshness separately. |
| GEOADD/GEOSEARCH for nearby locations | Pub/Sub delivers live messages to currently connected subscribers; GEO indexes locations in a sorted set representation for radius or box search. | Use Streams or Kafka when replay is required and model location freshness separately. |
Storage, planning, and execution: Pub/Sub & Redis GEO
PUBLISH/SUBSCRIBE/PSUBSCRIBE. Pub/Sub does not retain history. GEO commands encode coordinates to sortable scores and filter candidates by geometry.
aioredis async pub/sub. Pub/Sub does not retain history. GEO commands encode coordinates to sortable scores and filter candidates by geometry.
GEOADD/GEOSEARCH for nearby locations. Pub/Sub does not retain history. GEO commands encode coordinates to sortable scores and filter candidates by geometry.
Read these as one system: PUBLISH/SUBSCRIBE/PSUBSCRIBE establishes the starting contract, aioredis async pub/sub changes how that contract is executed or represented, and GEOADD/GEOSEARCH for nearby locations exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Pub/Sub & Redis GEO
1async with redis.pipeline(transaction=True) as pipe:2 pipe.hset(f"publish_subscribe_psubscribe:{entity_id}", mapping=payload)3 pipe.expire(f"publish_subscribe_psubscribe:{entity_id}", ttl_seconds)4 await pipe.execute()This Pub/Sub & Redis GEO slice makes PUBLISH/SUBSCRIBE/PSUBSCRIBE observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward GEOADD/GEOSEARCH for nearby locations, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Pub/Sub & Redis GEO
| Risk | Why it matters |
|---|---|
| PUBLISH/SUBSCRIBE/PSUBSCRIBE | Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine. |
| aioredis async pub/sub | Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine. |
| GEOADD/GEOSEARCH for nearby locations | Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine. |
Data investigation: Pub/Sub & Redis GEO
- Foundation: implement or demonstrate PUBLISH/SUBSCRIBE/PSUBSCRIBE with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine PUBLISH/SUBSCRIBE/PSUBSCRIBE with aioredis async pub/sub. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for GEOADD/GEOSEARCH for nearby locations. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Expiry, eviction & transactions
The Expiry, eviction & transactions unit begins with EXPIRE/PEXPIRE/TTL and lazy plus active expiry: A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. Document key version, TTL jitter, negative caching, and source-of-truth behavior. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Expiry, eviction & transactions
| Concept | Meaning | Engineering decision |
|---|---|---|
| EXPIRE/PEXPIRE/TTL and lazy plus active expiry | A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies | Redis expiry removes stale keys while eviction chooses victims when maxmemory is exceeded; transactions queue commands for uninterrupted execution, WATCH provides optimistic conflict detection, and pipelines reduce network round trips without implying atomicity. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
| MULTI/EXEC queued atomic execution | Redis expiry removes stale keys while eviction chooses victims when maxmemory is exceeded; transactions queue commands for uninterrupted execution, WATCH provides optimistic conflict detection, and pipelines reduce network round trips without implying atomicity. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
| WATCH optimistic compare-and-set | Redis expiry removes stale keys while eviction chooses victims when maxmemory is exceeded; transactions queue commands for uninterrupted execution, WATCH provides optimistic conflict detection, and pipelines reduce network round trips without implying atomicity. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
| pipeline batching vs transaction atomicity | Redis expiry removes stale keys while eviction chooses victims when maxmemory is exceeded; transactions queue commands for uninterrupted execution, WATCH provides optimistic conflict detection, and pipelines reduce network round trips without implying atomicity. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
| maxmemory sizing and eviction telemetry | Redis expiry removes stale keys while eviction chooses victims when maxmemory is exceeded; transactions queue commands for uninterrupted execution, WATCH provides optimistic conflict detection, and pipelines reduce network round trips without implying atomicity. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
Storage, planning, and execution: Expiry, eviction & transactions
EXPIRE/PEXPIRE/TTL and lazy plus active expiry. Cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses.
noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies. EXEC runs queued commands sequentially but does not roll back earlier command errors. WATCH aborts EXEC if watched keys changed. Approximate LRU/LFU samples candidates rather than maintaining perfect global order.
MULTI/EXEC queued atomic execution. EXEC runs queued commands sequentially but does not roll back earlier command errors. WATCH aborts EXEC if watched keys changed. Approximate LRU/LFU samples candidates rather than maintaining perfect global order.
WATCH optimistic compare-and-set. EXEC runs queued commands sequentially but does not roll back earlier command errors. WATCH aborts EXEC if watched keys changed. Approximate LRU/LFU samples candidates rather than maintaining perfect global order.
pipeline batching vs transaction atomicity. EXEC runs queued commands sequentially but does not roll back earlier command errors. WATCH aborts EXEC if watched keys changed. Approximate LRU/LFU samples candidates rather than maintaining perfect global order.
maxmemory sizing and eviction telemetry. EXEC runs queued commands sequentially but does not roll back earlier command errors. WATCH aborts EXEC if watched keys changed. Approximate LRU/LFU samples candidates rather than maintaining perfect global order.
Read these as one system: EXPIRE/PEXPIRE/TTL and lazy plus active expiry establishes the starting contract, noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies changes how that contract is executed or represented, and maxmemory sizing and eviction telemetry exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Expiry, eviction & transactions
1async with redis.pipeline(transaction=True) as pipe:2 pipe.hset(f"expire_pexpire_ttl_and_lazy_plus_active_ex:{entity_id}", mapping=payload)3 pipe.expire(f"expire_pexpire_ttl_and_lazy_plus_active_ex:{entity_id}", ttl_seconds)4 await pipe.execute()This Expiry, eviction & transactions slice makes EXPIRE/PEXPIRE/TTL and lazy plus active expiry observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward maxmemory sizing and eviction telemetry, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Expiry, eviction & transactions
| Risk | Why it matters |
|---|---|
| EXPIRE/PEXPIRE/TTL and lazy plus active expiry | Delete/update races can repopulate stale values; cache correctness is a protocol. |
| noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. |
| MULTI/EXEC queued atomic execution | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. |
| WATCH optimistic compare-and-set | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. |
| pipeline batching vs transaction atomicity | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. |
| maxmemory sizing and eviction telemetry | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. |
Data investigation: Expiry, eviction & transactions
- Foundation: implement or demonstrate EXPIRE/PEXPIRE/TTL and lazy plus active expiry with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine EXPIRE/PEXPIRE/TTL and lazy plus active expiry with noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for maxmemory sizing and eviction telemetry. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1import secrets2from redis.asyncio import Redis3
4async def cached(redis: Redis, key: str, loader):5 if value := await redis.get(key):6 return decode(value)7 lock_key = f"lock:{key}"8 token = secrets.token_hex(16)9 if await redis.set(lock_key, token, nx=True, px=5_000):10 try:11 value = await loader()12 await redis.set(key, encode(value), ex=300 + secrets.randbelow(30))13 return value14 finally:15 await redis.eval(COMPARE_DELETE, 1, lock_key, token)16 await asyncio.sleep(0.05)17 return await cached(redis, key, loader)Expected result
1A cache miss is coalesced behind a token-owned lease and the stored value receives jittered expiry.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | import secrets | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from redis.asyncio import Redis | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | async def cached(redis: Redis, key: str, loader): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 5 | if value := await redis.get(key): | Evaluates the condition and enters this branch only when it is truthy. |
| 6 | return decode(value) | Returns the observable result to the caller and ends this invocation. |
| 7 | lock_key = f"lock:{key}" | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 8 | token = secrets.token_hex(16) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | if await redis.set(lock_key, token, nx=True, px=5_000): | Evaluates the condition and enters this branch only when it is truthy. |
| 10 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 11 | value = await loader() | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 12 | await redis.set(key, encode(value), ex=300 + secrets.randbelow(30)) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 13 | return value | Returns the observable result to the caller and ends this invocation. |
| 14 | finally: | Defines failure translation or cleanup that must run around the protected operation. |
| 15 | await redis.eval(COMPARE_DELETE, 1, lock_key, token) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 16 | await asyncio.sleep(0.05) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 17 | return await cached(redis, key, loader) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Step-by-step execution
- The client borrows a bounded connection, encodes the command, and sends it to the node responsible for the key or hash slot.
- Redis executes the command atomically in its core event-loop order; transactions queue commands and Lua scripts perform one bounded server-side decision.
- Expiry, persistence, replication, eviction, and failover policy determine how long the result remains available and what loss window is possible.
- The client decodes the reply, handles redirection or timeout according to bounded retry policy, and releases the connection.
- Tests cover TTL boundaries, races, stale lease owners, failover, resharding, pending work, and memory pressure with latency and error metrics.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Data structures | Large aggregate keys create latency spikes, replication cost, and difficult resharding. | Choose the type that performs the needed update in one bounded command. |
| Caching strategies | Delete/update races can repopulate stale values; cache correctness is a protocol. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| Distributed locking | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| Pub/Sub & Redis GEO | Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine. | Use Streams or Kafka when replay is required and model location freshness separately. |
| Expiry, eviction & transactions | Delete/update races can repopulate stale values; cache correctness is a protocol. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Ride-Hailing Backend Service project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Data structures: String: SET/GET/INCR/SETEX
- To do: Data structures: Hash: HSET/HGET/HGETALL for objects
- To do: Data structures: List: LPUSH/RPUSH/BLPOP for queues
- To do: Data structures: Set: SADD/SINTER/SUNION/SDIFF
- To do: Data structures: Sorted Set: ZADD/ZRANGEBYSCORE for leaderboards
- To do: Data structures: HyperLogLog and Bitmaps
- To do: Caching strategies: cache-aside (lazy) with TTL
- To do: Caching strategies: write-through: cache + DB simultaneously
- To do: Caching strategies: write-behind (async DB writes)
- To do: Caching strategies: cache stampede prevention: mutex lock + probabilistic expiry
- To do: Distributed locking: Redlock algorithm
- To do: Distributed locking: Python redlock-py implementation
- To do: Distributed locking: SET NX PX pattern
- To do: Distributed locking: fencing tokens for safety
- To do: Pub/Sub & Redis GEO: PUBLISH/SUBSCRIBE/PSUBSCRIBE
- To do: Pub/Sub & Redis GEO: aioredis async pub/sub
- To do: Pub/Sub & Redis GEO: GEOADD/GEOSEARCH for nearby locations
- To do: Expiry, eviction & transactions: EXPIRE/PEXPIRE/TTL and lazy plus active expiry
- To do: Expiry, eviction & transactions: noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies
- To do: Expiry, eviction & transactions: MULTI/EXEC queued atomic execution
- To do: Expiry, eviction & transactions: WATCH optimistic compare-and-set
- To do: Expiry, eviction & transactions: pipeline batching vs transaction atomicity
- To do: Expiry, eviction & transactions: maxmemory sizing and eviction telemetry
Quick revision
- Data structures: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Caching strategies: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Distributed locking: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Pub/Sub & Redis GEO: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Expiry, eviction & transactions: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?