Application caching
Caching with Redis
Redis can hold the product card, but the application still decides how to obtain it, whether to use it and what to do when a command fails. A cache client turns GET and SET into ordinary function calls. The useful integration is the control flow around those calls.
We will add Redis to the shop’s public catalogue. The server still owns the request: it validates a saved card or reads the source when no usable copy exists. Checkout continues to use the source’s transaction and stock checks. Redis is the implementation used here; the same boundaries matter with other shared caches.
The downloadable adapter uses Python’s asynchronous redis-py client, version 8.1.0. It was exercised against Redis 8.10.3 with Python 3.14.5. The source is an explicitly labelled dictionary model. The Redis commands are real; the exercise does not measure a production database or service.
Follow a product request
A cache fill is optional work after the server has obtained an answer. If Redis refuses the copy, this request can still succeed. The consequence falls on later requests, which have no saved answer to reuse.
On a miss, the application reads the source, encodes the returned card and tries to save it. This code shows that successful path. The sections below add validation, admission and deadlines; the downloadable adapter includes them.
raw = await redis.get(context.key)
# If there is no usable entry:
product = await source.read(context)
await redis.set(context.key, encode(context, product), ex=30)
return product await means that this request waits for a result while the event loop can run other requests. It does not make the work disappear or move it into a durable job. Redis receives no source connection and never calls source.read.
The ex=30 option stores the value and its 30-second expiry in one SET. Sending SET and then a separate expiry command would leave a gap in which the value exists without its intended lifetime. A plain replacement SET also clears an existing expiry, unless an option preserves it. Every ordinary fill here supplies its own expiry.
Reuse one client through the application
Open the client when the application starts and close it when the application shuts down. Pass it to requests through the adapter. The client’s pool lends connections to commands and reuses them when those commands finish. Creating a client for each lookup would repeatedly pay for connection setup.
from redis.asyncio import Redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
redis = Redis(
unix_socket_path=owned.path,
decode_responses=False,
max_connections=4,
socket_connect_timeout=0.020,
socket_timeout=0.020,
retry=Retry(NoBackoff(), 0),
protocol=2,
)
try:
# Pass this client to the application's ProductCache.
...
finally:
await redis.aclose() This configuration uses the practice runner’s owned Unix socket. The runner starts a disposable Redis with TCP disabled and verifies its identity before writing data. For a deployed service, supply the endpoint, authentication and TLS settings appropriate to that deployment. Operating a cache explains those choices.
The four-connection limit is an example, not a capacity recommendation. With this client’s ordinary pool, a fifth command that finds every connection occupied raises MaxConnectionsError. It does not wait for a free slot. Connection setup can still take time after a slot is obtained, so pool size alone does not bound the whole operation.
A connection limit also does not limit how many application requests are waiting elsewhere. The adapter admits at most 64 concurrent calls and eight concurrent source operations on one event loop. A full gate raises Busy immediately. It creates no queue of pending fills. These local limits must fit the source budget across all application instances; Handling cache misses develops that wider decision.
Decide whether a value can be used
A successful GET returns bytes. Those bytes still need to describe the answer this request expects. The adapter uses an envelope, a small object that names the format, request context and kind of result alongside the product.
{
"schema": 1,
"context": {
"shop": "north", "id": "P7",
"locale": "en-GB", "currency": "GBP"
},
"kind": "product",
"product": {
"id": "P7", "name": "Blue mug", "price_pence": 2000,
"currency": "GBP", "revision": 1
}
} schema: 1 and the key’s v1 name the representation format. revision: 1 names the source product version. Raising the mug’s price changes its revision; it need not change the format. Cache keys explains how the context determines safe sharing.
The decoder checks the schema, context, result tag and product fields. It also imposes a 4 KiB example value limit before parsing. It rejects a card for another shop, a string where integer pence is expected, malformed JSON and unsupported formats. The byte limit bounds parsing of ordinary responses after receipt; it does not stop an oversized Redis reply travelling over the connection.
Rejected content becomes a miss and an observation for repair. The adapter does not delete it immediately: another request might have replaced it with a valid value between this read and a later delete. A successful source read can provide the next ordinary fill.
value = decode(raw, context)
if value is not MISS:
return value # A product, or the cached not-found result None.
with self.sources.slot():
value = await self.source.read(context)
raw = encode(context, value) MISS is a unique object, tested by identity. A truthiness test such as if value would mix valid empty values with misses. Here None has a different meaning: the source successfully established that the requested product is absent, or a valid cached envelope retained that answer.
The example saves absence for five seconds and products for thirty. Both are illustrative insertion lifetimes. If that product is created during those five seconds, its old absence can remain reusable until expiry or invalidation. A source timeout never establishes absence and is never saved as a not-found result.
Keep the source result when a fill fails
The source branch has a clear boundary. Before it returns, the request has no answer. After it returns a valid representation, the request can answer even if saving the optional copy fails.
ttl = self.negative_ttl if value is None else self.positive_ttl
await self.optional_write(
lambda: self.redis.set(context.key, raw, ex=ttl),
deadline, "fill",
)
return value optional_write records a failed Redis command and returns without discarding value. The driver checks this with a real Redis memory rejection: the server refuses SET, the key remains absent and the caller still receives GBP 20.00.
Failures before the source read need more care. A temporary connection failure, timeout or exhausted Redis pool can lead to the bounded source path. An authentication or command fault raises CacheFault instead. It needs repair; treating it as an ordinary miss would hide a persistent problem.
The distinction matters in redis-py because authentication errors inherit from ConnectionError. The adapter classifies them before general connection failures. If such a fault happens during an optional fill, it is still reported, but the successful source answer survives.
A source failure propagates to the caller. No catch-all handler converts it into a product or an absence. A full source gate also propagates Busy. The surrounding service must turn that outcome into controlled refusal, rather than immediately repeating the same request.
Fit the cache inside the request deadline
A timeout on each command is not a request deadline. Time spent obtaining a connection, reconnecting, reading the source and filling Redis all belongs to the same caller. The adapter accepts an absolute deadline from the event loop’s monotonic clock.
deadline = asyncio.get_running_loop().time() + 0.200
product = await cache.read(Context(), deadline=deadline) This standalone call starts with 200 ms. Inside an existing request, pass the deadline already in force; do not grant a fresh budget after earlier work has spent part of it. A slow source read leaves less room for the optional copy.
The GET wrapper limits the whole lookup to 25 ms, including acquiring and preparing a connection. The client also limits connection setup and socket waits to 20 ms each. The source read must finish by the overall deadline. After that read succeeds, the optional fill gets at most 20 ms and less when the deadline is close.
The fill leaves five milliseconds for returning the result. If that allowance has already gone, it is skipped. These numbers make the branches visible in the example. Choose actual limits from the caller’s requirements and measured behaviour; they do not promise that every event loop runs precisely on time.
Retries are explicitly set to zero. A failed fill is not queued for replay after reconnection, when its saved payload may already be old. The adapter also creates no detached background task. A later request can obtain a new source result through the normal path.
Cancellation stops this request’s wait. It cannot retract a command Redis has already received. In the pinned client, cancellation while reading a reply disconnects that connection and releases it back to the pool; a later command can reconnect. The driver checks recovery with a genuinely blocked Redis command, then performs a successful PING and GET using the same one-slot client.
Python’s deadlines are cooperative: they cancel asynchronous work at points where it can yield. They cannot forcibly stop blocking source code or a coroutine that suppresses cancellation. A real source adapter must preserve cancellation and release its own connections. External cancellation also propagates during a fill; the cache wrapper must not turn an abandoned request into more source work.
Change the source, then invalidate
Raise the source price to GBP 22.00 and advance the revision to 2. The adapter waits for the source’s successful commit result, then deletes the product key. The next read misses and fills from revision 2.
updated, invalidated = await cache.change_price(Context(), 2200)
# updated: price_pence 2200, revision 2
# invalidated: whether DEL completed successfully
card = await cache.read(Context()) The returned flag says whether the invalidation completed successfully. If deletion fails, revision 2 remains committed at the source. The driver’s injected deletion failure leaves revision 1 in Redis, so a later cached read returns GBP 20.00. The update caller can see both the committed result and the failed invalidation.
A real source mutation can time out after committing. The adapter does not blindly repeat it or claim that a timeout means rollback. The source integration needs its own way to resolve uncertain outcomes. The dictionary model has only an assignment as its commit point and does not test database transactions.
Even a successful deletion leaves the familiar late-fill race. A reader takes revision 1, pauses, then fills it after another request commits revision 2 and deletes the key. The command lab reproduces that order. A new 30-second TTL does not make the old snapshot current.
This adapter therefore implements the baseline cache-aside policy, not a stronger freshness guarantee. Freshness and invalidation develops the promise the application can make, and Versioned cache fills examines rejecting older work. Reads requiring authoritative current state must use the source path appropriate to that operation.
Exercise the complete adapter
Download these files into one directory: cache_adapter.py, adapter_demo.py, cache_lab.py and requirements.txt. The practice instructions describe the branches and their limits. Install a local Redis server, then run the driver with Python 3.14:
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python adapter_demo.py --redis-server /path/to/redis-server
# Change one source fact and inspect the returned prices and source-call counts:
.venv/bin/python adapter_demo.py --initial-price-pence 1800 The runner creates its own Redis process, private socket and temporary directory. It accepts a Redis executable, not an existing server address. The exact downloaded files produced the recorded results. Use --json adapter-results.json to retain the version, file hashes and scenario outcomes from your run.
| Exercise | Expected observation |
|---|---|
| Miss, hit and actual expiry | Two initial reads call the source once. Expiry makes the next read call it again. |
| Malformed, obsolete and mismatched values | Seven unusable variants lead to source reads. Zero and empty fields remain valid. |
| Cached absence, then a source failure | The absence hit saves a read. A failed source lookup writes no negative entry. |
| Real rejected fill and exhausted pool | The successful source result survives. Source and request gates still limit admission. |
| Injected slow GET, source and SET | A GET timeout may fall back; a source timeout propagates; a fill timeout retains the result. |
| Cancellation and source changes | No fill is detached. The native client recovers. A failed invalidation leaves a visible old copy. |
The simulated faults occur at the client or dictionary boundary. They do not reproduce packet loss, database failure or fleet-wide load. The blocked-command cancellation check uses real Redis; it is a client lifecycle test, not a claim that an ordinary GET normally blocks like that.
To adapt this code, supply a source that returns the agreed representation, commits changes with its own transaction rules and respects deadlines. Then choose the freshness allowance, source admission budget, client pool and deployment access settings for that application. Observe valid hits, unusable entries, errors and source work separately: a successful request can still reveal a cache that has stopped saving work.
Sources and further reading
Checked on 28 October 2026. The runnable driver records Redis 8.10.3, redis-py 8.1.0 and Python 3.14.5. The figures illustrate its control flow; their time limits are example configuration, not observed service latency.
- Redis, SET: combined value and expiry writes, replacement and expiry preservation.
- Redis, Asynchronous operations: shared clients, pool ownership and explicit shutdown.
- redis-py 8.1.0, Connection API and connection source: limits, ordinary-pool exhaustion and cancellation cleanup.
- redis-py 8.1.0, client source and retry source: connection release and explicit retry counts.
- Redis, Error handling and Production usage: distinguish failure classes and configure bounded waits.
- Python 3.14, Timeouts and task cancellation: absolute deadlines, cooperative cancellation and propagation.