Application caching Operating a cache

Application caching

Operating a cache

Deep diveAbout 11 minutes AI-generated

A cache is helping while it saves useful work and still returns answers the application may use. A running server does not establish either. Requests can wait in the client, found entries can be unusable, and a recovered cache can bring back an old price.

Operating a cache means following those effects through the request path, then changing the part the evidence points to. We will follow the shop’s product-card service through a slow lookup, rising source demand, a failover and a format change. Redis supplies concrete observations and deployment choices; the questions apply to other caches too.

The examples follow the same mug and public product card as the rest of the collection. Timings and operating limits are illustrative; they are not measurements of Redis capacity.

Measure what the application receives

Start at the branch where the application decides whether it has an answer. A lookup can find a usable card, find no key, find an unusable value, or fail without establishing what is stored. Only the first saves the following source read in this simple path.

Lookup outcomeNext decision
Valid hitReturn the accepted answer.
No keySeek admission to the source.
Found but unusableRecord why it was rejected; seek source admission.
Cache errorClassify it before choosing a fallback or surfacing a fault.
Figure 1. Count lookup outcomes separately from final responses. A refused source attempt starts no read; a failed optional fill can follow a successful source read.

Record the lookup outcome separately from the final request result. An unusable hit might lead to a successful source answer. A failed fill might leave this caller satisfied while forcing the next caller to read the source again. Combining both into a single “cache success” count hides the work.

Redis’s INFO reports keyspace_hits and keyspace_misses. These count successful and failed key lookups inside Redis. They do not know whether the returned bytes match the requested format, context or freshness rule. Count valid hits in the application, after those checks.

Compare counters over the same interval. Suppose Redis hits rise from 8,000 to 8,900 and misses from 2,000 to 2,100. That interval contains 900 hits and 100 misses: a 90% server hit ratio. If the application rejects fifty found values, it has only 850 valid hits among these 1,000 requests.

That arithmetic assumes one lookup per request and no other traffic. In a real deployment, separate request types and account for retries or multi-key calls. A restart or counter reset also breaks subtraction across the boundary. Keep the instance identity and reset history with the samples rather than interpreting a negative difference as falling traffic.

Beside the outcomes, record request latency, lookup and fill durations, source attempts, admitted reads and refusals. Keep latency distributions: the median describes an ordinary request, while a high percentile exposes the slow tail. Then break those observations down by outcome. A fast majority of hits can conceal a much slower miss path.

Follow a slow request

Suppose cache lookups now take thirty milliseconds. That number names the caller’s wait, not where the time went. The client may wait for its own execution time or a connection. Connection setup, the network, command execution and decoding add further work.

Figure 2. Each bar accounts for one complete lookup. Communication combines outward and return travel; these bands are not a chronological trace. Redis’s slow log measures command execution, not the whole bar.

Redis’s slow log times command execution and excludes client communication. A quiet slow log therefore does not clear the complete cache path. Its configured threshold and retained history also determine what it can show.

Use a request trace to locate the wait, then compare server and client observations from that interval. If the command itself is slow, inspect its work and the server’s latency evidence. If the delay comes before sending, inspect application scheduling, connection churn and any pool wait. Some pools reject immediately when full; the ordinary redis-py pool in Caching with Redis does this.

If reply transfer or decoding dominates, compare payload sizes and client resource use. A tiny command can return a large value. If many commands pause together, inspect the network and server environment as well as individual command timings. Redis’s latency guide separates these causes.

Preserve the request deadline while diagnosing. Increasing every timeout can turn brief failures into a large population of waiting requests. Bound pending work, and let any fallback use the time and source allowance that remain.

Explain the extra source work

A steady hit ratio can accompany a source overload. When traffic doubles, an unchanged miss fraction can mean twice as much source work. The percentage tells us about reuse; the rate tells us what the source must carry.

Two invented intervals, each one second long
ObservationBeforeAfter traffic grows
Card requests1,0002,000
Valid hits9001,800
Valid-hit ratio90%90%
Source reads100200

Keep rates beside ratios. In a coalesced path, several misses may share one read; retries and refreshes can add reads that the miss count does not explain. Measure actual source work and source latency rather than deriving capacity from a hit ratio alone.

When the ratio falls, identify which requests stopped finding useful copies. A new namespace starts cold. A promotion can make previously rare products popular. More locale or currency variants divide reuse among more keys. Expiry removes old entries, while eviction removes entries to make room. A fill rejected for lack of memory creates no new reusable copy.

Join those application observations to Redis’s interval counters. expired_keys and evicted_keys distinguish two reasons keys disappear. Command rejection counts, application fill errors and memory measurements help explain why replacement entries never arrive. These are clues to test against the affected keys and deployment changes, not a unique diagnosis from one counter.

For example, suppose useful hits fall just after a release. Evictions stay flat, but the new readers use v2 keys that have never been filled. Extra cache memory does not create those answers. Hold the rollout, rebuild through the existing source allowance, and check whether useful hits return before sending more traffic.

If instead larger new values displace frequently used cards, inspect the entry sizes and resident set. Cache memory develops that retention decision. Handling cache misses supplies the coalescing and admission controls. After a change, check source work and user outcomes together: fewer source reads achieved by refusing more users is a different result from more useful hits.

Check the answers as well as their speed

Now the merchant raises the mug’s price to GBP 22.00, revision 2. The cache continues returning revision 1 in a millisecond. Both latency and the server hit ratio look healthy. Neither observation establishes whether that answer is allowed.

Record the information needed to test the reader’s actual promise. For a maximum observation age, retain the source observation time and evaluate age when the answer is returned. For a request requiring revision 2 or newer, record the required and returned revisions. For invalidation, observe pending work and progress, including changes the consumer can no longer replay.

A sampled source comparison can reveal drift, but its timing matters. A source read made after the response may see an update that occurred after the cached answer was returned. The difference alone does not prove a violation. Compare against the promised age or revision at the relevant point, with the clock and source-read assumptions that promise requires.

Trace every affected answer. The mug’s price appears in its card and determines whether it belongs in the list below GBP 21.00. The new price removes it from that list. Checking the card alone can miss the stale membership. For restricted results, also check current access through the required authorisation path.

Freshness and invalidation builds these contracts and their repair paths. The baseline thirty-second insertion TTL is not a thirty-second source-age guarantee. An observation can already be old before it enters Redis.

Choose the failure you can recover from

Start the deployment decision with a loss: the shared cache disappears. Can the bounded source path still deliver an acceptable service while useful entries rebuild? If it can, one replaceable instance may be sufficient. If too much traffic must be refused, a replicated deployment can reduce exposure to a single instance failing.

Replication changes which copies survive; it does not turn the cache into the source of truth. Redis normally replicates asynchronously. Suppose its primary deletes the old £20 card and acknowledges the command, then fails before a replica receives that deletion. Promoting that replica makes its retained £20 card available again.

Figure 3. An illustrative failure order under asynchronous replication. A request requiring revision 2 must reject the recovered revision 1 value. Promotion does not establish freshness.

The source still holds GBP 22.00. The old cached value has returned because the surviving copy never applied the deletion. A reader requiring revision 2 must reject it. A reader with a bounded age allowance must evaluate that allowance; promotion neither renews it nor proves it expired.

Choose the recovery rule before the incident. If the application cannot establish that recovered entries still satisfy its contract, bypass that namespace and rebuild under source admission. Replayable invalidation can help repair copies, but needs retained history and cannot alone prevent a delayed fill. Protocols in Versioned cache fills must also account for losing their remembered ordering information.

The client needs a way to find the current endpoint. For non-clustered Redis, Sentinel coordinates failover and provides the current primary’s address to compatible clients. A managed service may expose discovery differently. Test the chosen client during the transition: reconnection, request deadlines and pending-work limits all still matter.

Ask a managed provider what its endpoint and data guarantees mean during failover. Delegating deployment work does not establish that an application’s freshness contract survives. Rehearse both a lost connection and a responding endpoint whose entries must be treated as untrusted.

Memory, restart and scale

Persistence can retain a useful working set across restarts. Redis offers snapshots and an append-only log. Loading them takes time and consumes resources, so compare the saved source load with the cost of recovery. Restored entries still need the application’s validity checks; persistence is not a new observation of the source.

An empty restart can be simpler when rebuilding is already affordable. But a replica does not automatically protect that working set: Redis documents that an empty restarted primary can cause its replicas to synchronise to the empty dataset. Choose restart and persistence behaviour as part of the deployment, then test the resulting request path.

If one node cannot hold or serve the useful set, Redis Cluster distributes keys among hash slots on different nodes. Use a cluster-aware client that handles MOVED and ASK redirections. One hot key still belongs to one slot owner; adding shards does not divide that key’s work among them.

Check multi-key operations before changing topology. Atomic operations involving a payload and its ordering metadata must fit the chosen placement rules, commonly by sharing a hash slot. Cluster is a deployment change that reaches the application protocol, not merely extra memory behind an unchanged endpoint.

Limit access to the cache

Keep the shared store reachable only from the systems that need it. Configure authentication and TLS for the chosen deployment, including certificate verification by clients. Network reachability, encrypted transport and permission to run a command protect different boundaries.

Give the application only the commands and key patterns it needs. Keep administration under a separate identity. In Redis, a prefix rule such as ~product:* limits named keys; it does not restrict a whole-store command such as FLUSHALL. Command permissions must exclude that operation too.

On a disposable deployment, verify an allowed product read and fill, a denied key outside the application’s scope, and a denied administrative operation. Check permissions with the exact client: connection preparation can require commands beyond the visible GET and SET. Rotate credentials through a tested reconnection path, so existing connections do not hide a failure that new ones will encounter.

Store permissions identify the application connecting to Redis. They do not decide which person may see a product view. That decision remains in the request’s authorisation path, including when the content comes from a cache.

Rehearse the change and the recovery

Suppose a new product-card format cannot be decoded by the old application. Either deploy readers that understand every format they can encounter, or separate the formats into namespaces. Here the new reader uses product:v2:north:P7:en-GB:GBP. The v2 names the representation format; it does not identify the product’s source revision.

Separate namespaces avoid mixing incompatible values, but the new one begins cold and needs space alongside the old one. Moving more traffic before it warms can create more source demand than the service can admit.

Figure 4. Two alternative traffic splits over the same 100-request interval. v1 hits 90%; every v2 request here misses. The bars show demand before admission, not permission to exceed the source limit.

Prepare for the next increase using representative demand, with warm-up inside the same source allowance as user requests. Warming a few popular keys says little about the next group’s long tail. Increase traffic only while latency, source work, errors and answer validity remain within the declared limits.

Rollback has a data requirement as well as a code requirement. While v1 remains a possible destination, source changes must still invalidate its affected answers. If that stopped, old code successfully decoding old bytes proves little. Restore a trustworthy repair path or use a fresh namespace generation, and treat rebuilding as a cold recovery.

Expiry also continues during the rollback window. Even with correct invalidation, a rarely used v1 namespace may lose its useful entries before traffic returns. Test the resulting misses; do not assume rollback will be warm merely because old keys were retained earlier.

After the rollback window closes and no old readers or fills remain, retire the old namespace. Let bounded expiry or a controlled cleanup release its space. Keep cleanup targeted to that namespace; deleting unrelated cache data would create a second recovery problem.

Bring a cold cache back gradually

Use the same bounded source path when the cache is empty, unavailable or deliberately bypassed. Demand fills rebuild useful answers; a small warm-up can help where recent requests identify them. Both consume the same source allowance, including work from every application instance.

A successful PING establishes that Redis responds. It does not establish that product requests can finish in time. Exercise the full application read, watch useful hits return, and increase traffic only while the source remains healthy. Keep room for uncached work such as checkout, whose authoritative transaction and stock checks still decide whether a sale can proceed.

A worked rollout can begin with 10% of traffic on v2 and an allowance of thirty source starts per observation interval. Demand and warm-up share that allowance. These are invented limits for the following change record; a real record uses tested limits, defines its interval and states who can stop the rollout.

A worked record for the v2 change
DecisionRecorded condition
First changeMove 10% of requests to v2. Keep v1 invalidation active.
Permit the next increaseUseful v2 hits return, answers meet their contract, and demand plus warm-up stays below 30 source starts per interval.
StopSource allowance is exhausted, requests miss their deadline, unexpected errors appear, or an answer fails its validity rule.
Return or recoverUse v1 only after checking its freshness path and likely miss load. Otherwise rebuild gradually with the same source limit.
FinishClose the rollback window, remove old readers and fills, then reclaim v1 space.

Rehearse that record with an empty cache and with the cache unreachable. Then repeat the price change during recovery. The useful result is evidence that the application still bounds its work and honours its answer contract while the cache changes underneath it.

Sources and further reading

Checked on 28 October 2026. The incident traces, traffic intervals and rollout budgets are illustrative. The collection’s native Redis 8.10.3 lab tests commands and client branches with a dictionary source; it supplies no failover, topology, TLS or production-capacity measurement for this article.

← Back to application caching