Senior engineering skills
Caching Strategies
A cache trades freshness for speed, and every pattern here is a different way of making that trade: where the copy lives, who fills it, when it dies and what happens when it is wrong. Each pattern gets one diagram, and the failure modes are reproduced with small Python programs (redis-py 7, Python 3.9, a local Redis 8.10.3, a slow pretend database) whose output is pasted from real runs.
Why and where
Part 1 of 6 · the layers, and what a hit is worth
The layers a request passes
A request can be answered by any layer that holds a copy. The earlier the hit, the cheaper it is and the harder it is to invalidate.
| Layer | Scope | You invalidate it by |
|---|---|---|
| Browser | One user | You cannot: only headers and new URLs |
| CDN, reverse proxy | All users | Purge API, short s-maxage |
| App memory | One process | TTL, or an event sent to every process |
| Redis | All app servers | DEL, TTL, a versioned key |
Related: the same layers at system-design level, with CDNs and replicas, are in Building Blocks. This page stays with the app and Redis.
Hit ratio, and what it buys
Hit ratio is hits / (hits + misses). With a 1 ms cache and a 200 ms query, the average read costs 1 + miss ratio × 200 ms.
| Hit ratio | Average read | Reads reaching the database |
|---|---|---|
| 0% (no cache) | 200 ms | 100% |
| 90% | 21 ms | 10% |
| 99% | 3 ms | 1% |
- 90% to 99% looks like 9 points, and it cuts database load ten times.
- The reverse is the danger: a cache that drops from 99% to 90% sends the database ten times the traffic.
What not to cache
Cache what is read often, changes rarely and can be a little old. Leave the rest alone.
| Do not cache | Why |
|---|---|
| The balance check inside a transfer | A stale read moves money that is not there |
| Permissions and revoked sessions, for long | A revoked user keeps access until the TTL ends |
| Results with endless key variety (free-text search) | Memory fills with keys nobody asks for twice |
Interview point: a cache hides a slow query, it does not fix it. Fix the query first, then cache what is still hot.
Read and write patterns
Part 2 of 6 · who fills the cache, and when
The project: a slow database
Every example imports this module: a dict that takes 200 ms to read and counts its calls, plus a Redis client on database 15. All keys start with bank:, and reset() removes them.
Cache-aside (lazy loading)
The application owns both steps: look in the cache, and on a miss load from the database and store the result. It is the default, because the cache can die and reads still work.
- The millisecond figures will differ on your machine. The shape will not: one slow miss, then hits.
- Always set a TTL, even with explicit invalidation. It is the safety net for every bug below.
Read-through
The same flow, moved behind the cache: the application asks only the cache, and the cache layer (a library or a proxy) calls a loader on a miss.
Write-through
Every write goes to the cache and the database together, before the caller gets an answer. Reads after a write are always hits and always fresh.
- The two writes are not atomic. A crash between them leaves the cache old, so keep a TTL.
Write-behind
The write lands in the cache and returns at once. The database is updated later, in batches.
- Good for counters, view counts, last-seen times: loss of a few seconds is acceptable.
- Never for money: if the cache node dies before the flush, the deposit is gone.
Write-around
Writes go only to the database and the cached copy is deleted. The next read reloads it with cache-aside.
The five patterns compared
| Pattern | Consistency | Complexity | Failure mode |
|---|---|---|---|
| Cache-aside | Stale up to the TTL unless writes invalidate | Low, but repeated at every call site | Stampede on a cold or expired key |
| Read-through | Same as cache-aside | Medium: a cache layer with loaders | Cache layer down means reads fail unless it falls back |
| Write-through | Fresh after every write | Medium: every write path must use it | Crash between the two writes, slower writes |
| Write-behind | Database lags the cache | High: queue, batching, retries, ordering | Lost writes when the cache dies |
| Write-around | Fresh after the next read | Low | Miss after every write, and the reader/writer race below |
Default answer: cache-aside reads, delete on write, a TTL on everything. Move away from it only with a reason you can name.
Expiry and eviction
Part 3 of 6 · how an entry dies
TTLs and the life of an entry
Expiry is about time: the entry is too old. Eviction is about memory: the cache is full and something has to go.
| Data | Starting TTL | Reason |
|---|---|---|
| Interest rates, branch list, config | Minutes to hours | Changes rarely, and a late change is harmless |
| Account summary shown on a dashboard | Seconds to a minute, plus delete on write | Users notice a wrong balance |
Jitter: never give a batch of keys the same TTL. Add a random 10% so they do not all expire in the same second (shown in Cache avalanche).
Redis eviction policies, LRU and LFU
When memory reaches maxmemory, Redis applies maxmemory-policy. The owner's server here has neither set, which is the default and is wrong for a cache:
| Policy | Evicts | Use when |
|---|---|---|
noeviction | Nothing: writes fail with an OOM error | Redis holds data you cannot lose (queues, locks) |
allkeys-lru | Least recently used, any key | A pure cache. The usual choice. |
allkeys-lfu | Least frequently used, any key | A few keys are much hotter than the rest |
allkeys-lrm | Least recently modified (newer Redis 8 releases) | Reads should not keep an old entry alive |
volatile-lru, -lfu, -lrm | The same, only among keys with a TTL | Cache and durable keys share one instance |
volatile-ttl | The key closest to expiring | The TTL already encodes importance |
| LRU | LFU | |
|---|---|---|
| Keeps | What was touched lately | What is touched often |
| Fooled by | One full scan: every cold key looks recent | Yesterday's hot key, until its counter decays |
| In Redis | Both are approximate: a few keys are sampled and the worst of the sample goes | |
Trap: with a volatile-* policy and no keys carrying a TTL, nothing can be evicted and writes fail as with noeviction.
functools.lru_cache and its traps
The standard library's in-process cache is the fastest layer there is: no network and no serialisation. It has no TTL and three traps.
- Mutable results: return tuples or frozen objects, or copy on the way out.
- No bound:
maxsize=None(andfunctools.cache) grows until the process is killed. On a method, the cache also keeps everyselfalive. - Per process: eight workers hold eight separate copies, and
cache_clear()clears only the one it runs in.
Invalidation and consistency
Part 4 of 6 · keeping the copy honest
Four ways to invalidate
| Way | How | Stale for | Weak point |
|---|---|---|---|
| TTL only | Do nothing on write | Up to the TTL | Users see old data after their own change |
| Delete on write | Write the database, then DEL | Milliseconds | Every write path must remember to do it |
| Versioned key | Put a version in the key and bump it | Zero for new readers | Old keys stay until they expire |
| Event | Publish "key changed", every holder drops it | Milliseconds, if the event arrives | A lost event means stale until the TTL |
- Events are how in-process caches on many servers are cleared: see example 5 on the Redis Pub/Sub page.
- Whichever you choose, keep the TTL as the backstop.
The race between two writers
"Update the cache on write" breaks when two writers interleave: the one that wrote the database first can write the cache last.
The script runs those four steps in that order, then the same order with DEL as step 2.
- Delete, do not update: deletes commute, so any order leaves the cache empty and the next read correct.
- Database first, then delete. Deleting first lets a reader refill the old value before the write lands.
- One race remains: a reader that loaded the old row before the write can
SETit after theDEL. It is rare, and the TTL bounds it.
Versioned keys
Put a version number in the key name. Changing the number makes every old entry unreachable in one write, with no scan and no mass delete.
- Cost: one extra
GETper read for the version, unless it is held in memory for a second or two. - Old keys must have a TTL, or they stay forever.
How consistent a cache can be
"Eventual" here means: with no new writes, readers see the latest value once the TTL or the invalidation has run. Until then different readers can see different values.
| Need | What to do |
|---|---|
| Anyone may see data a few seconds old | TTL, nothing more |
| Read-your-writes: the user who deposited must see the new balance | Delete on write in the same request, or serve that user's next read from the primary |
| The value decides something (enough money for a transfer?) | Bypass the cache: read the database inside the transaction |
| Access was revoked | Bypass, or delete the session key at revoke time |
Rule: a cache is for showing, the database is for deciding.
Per-user or shared: key design
The key must contain everything the answer depends on. Leave the user out of a per-user answer and the cache serves one customer's data to another.
- The usual cause is a key built from the URL (
/me/balance) by a generic decorator or a proxy.
Failure modes
Part 5 of 6 · how caches take a service down
Cache stampede
A popular key expires and every request in flight misses together. Also called thundering herd or dogpile: each of them runs the same slow query.
Fix 1: a lock with SET NX EX
Only the request that wins a short Redis lock may rebuild the value. The rest wait briefly and read the cache again.
- The re-check matters. Without it this script made 2 database calls in 14 runs out of 40: a thread that missed early won the lock just after the first winner released it.
EXfrees the lock if the winner crashes. Set it longer than the slowest query.
Fix 2: request coalescing, and early refresh
Coalescing (single flight) does the same inside one process with no Redis lock: the first caller loads, the others wait on its result.
| Fix | Database calls for N servers | Note |
|---|---|---|
| Redis lock | 1 | Losers poll, so they wait a little longer than needed |
| Single flight | Up to N, one per process | No polling. Go has it as singleflight. |
| Early probabilistic refresh | About 1 | Each reader refreshes with a small chance that grows near expiry, so the key never goes cold. Not run for this page. |
| Serve stale while one refreshes | 1 | Keep the old value past its soft TTL. Nobody waits. |
Cache penetration and negative caching
A key that does not exist in the database can never be a hit, so every request for it reaches the database. A bug or an attacker cycling through made-up ids turns that into steady load.
- Random ids make a new sentinel each time and fill memory. Validate the id format first, then rate limit, then consider a Bloom filter of existing ids (not run for this page).
Cache avalanche
Many keys die at once: a batch loaded with one TTL, a cache restart, or a deploy that warms everything in the same minute. It is a stampede on a thousand keys together.
- Jitter spreads the expiries over a minute, so no single second loses the cache.
- After a cache restart, jitter does not help: warm the hot keys first, and limit concurrent database loads.
Hot keys and big values
A hot key is one key taking a large share of all reads, so one Redis shard carries the load however many shards exist. A big value makes every read slow, and Redis runs commands on one thread.
| Problem | Find it | Fix |
|---|---|---|
| Hot key | redis-cli --hotkeys (needs an LFU policy), per-key metrics in the app | Local cache in front, read from replicas, or split into key:1 .. key:N copies |
| Big value | redis-cli --bigkeys, --memkeys, MEMORY USAGE key | Cache the fields you read, not the whole object. Paginate lists, compress, or use a hash and HGET one field. |
Trap: deleting a huge key with DEL blocks the server while memory is freed. UNLINK frees it in the background.
A deploy that changes the value format
The cache outlives the code that wrote it. Release 2 reads what release 1 stored, and during a rolling deploy both releases read and write the same keys.
- Put a schema version in the key (
bank:v2:...) and bump it with the format. Old and new code then never share an entry. - Expect a cold cache for the new version right after the deploy: that is a small avalanche, so roll out gradually.
HTTP caching and operating
Part 6 of 6 · headers, numbers to watch, and a decision table
Cache-Control
One response header tells every cache between the server and the user what it may keep and for how long.
| Directive | Meaning |
|---|---|
max-age=60 | Fresh for 60 seconds in any cache |
s-maxage=300 | Overrides max-age for shared caches (CDN, proxy) |
public | Shared caches may store it |
private | Only the user's browser may store it. Use for anything per user. |
no-cache | May be stored, but must be revalidated before every use |
no-store | Must not be stored at all |
immutable | Will never change: do not revalidate even on reload |
stale-while-revalidate=30 | Serve the stale copy for 30 more seconds while refreshing in the background |
| Response | Header |
|---|---|
| Asset with a hash in its name | public, max-age=31536000, immutable |
| HTML page | no-cache |
| Public API data (rates) | public, max-age=60, s-maxage=300 |
| A user's balance | private, no-cache, or no-store |
Trap: no-cache does not mean "do not cache". That is no-store.
ETag and conditional requests
An ETag is a fingerprint of the response body. The client sends it back in If-None-Match, and the server answers 304 with no body when nothing changed.
Trap: this server still builds the whole body to compute the ETag. To save the work as well, derive the ETag from a version column or updated_at.
Vary, and CDN versus browser
Vary names the request headers that are part of the cache key. It is the HTTP form of the per-user key rule.
| Header | Effect |
|---|---|
Vary: Accept-Encoding | Separate copies for gzip and brotli. Always safe. |
Vary: Cookie or Authorization | One copy per user: the shared cache stops being useful. Send private instead. |
| Browser cache | CDN | |
|---|---|---|
| Serves | One user | Everyone |
| Honours | max-age, private | s-maxage first, then max-age. Does not store private responses. |
| Purge | Not possible | By URL or tag, through the provider's API |
The serious bug: a per-user response sent with public, or with no Cache-Control through a CDN set to cache everything. One user's page is then served to all.
What to measure
A cache you do not measure is a guess. Redis counts hits and misses for the whole server, and the script reads the counters before and after 20 reads.
| Metric | From | Worry when |
|---|---|---|
| Hit ratio | keyspace_hits, keyspace_misses, better per key prefix in the app | It drops suddenly: a deploy, an eviction storm, a bad key |
| Latency | p50 and p99 of cache calls and of loader calls, in the app | Cache p99 nears the query time |
| Memory | used_memory against maxmemory | It sits at the limit and evictions climb |
| Evictions | evicted_keys | Above zero on an instance that also holds locks or queues |
Trap: the INFO counters cover every database and every client since the last restart. Compute rates from deltas, as the script does.
Key names and sizing
A key name is the cache's whole schema: app:version:entity:id, for example bank:v2:balance:ACC-1001.
- Overhead: a 4-digit balance costs 48 bytes, an 8 KB statement about 100 bytes more than its length.
- Sizing: keys in the hot set × average
MEMORY USAGE, plus 30% or more headroom. Size for what is read, not for the whole table. - Namespacing: a prefix per service and environment,
SCANand neverKEYSin production, a separate instance for durable data.
Choosing a serialisation
Redis stores bytes. The format decides size, speed and who else can read the value.
| Format | Good | Bad |
|---|---|---|
| JSON | Readable in redis-cli, any language | Large, no dates or decimals, int keys become strings and tuples become lists (last line above) |
| pickle | Any Python object | Python only, breaks when classes change, runs code on load: never unpickle from a cache others can write to |
| MessagePack, Protobuf | Compact binary, many languages, Protobuf has a schema | A dependency, not readable by eye (not run for this page) |
| + zlib | 8 times smaller here, on repetitive data | CPU on every read and write. Worth it above about a kilobyte. |
Default: JSON, compressed when values are large. Go services reading the same keys is the common reason pickle has to go.
Which pattern for which situation
| I have this situation | Use this |
|---|---|
| Read-heavy data, a little staleness is fine | Cache-aside with a TTL |
| Users must see their own change at once | Delete on write (write-around), database first |
| Read immediately after every write, and often | Write-through |
| Very frequent small writes that may be lost | Write-behind |
| The value drives a decision about money or access | No cache: read the database |
| One expensive key, many concurrent readers | Lock or single flight, plus serve-stale |
| Requests for ids that do not exist | Negative caching, validation, Bloom filter |
| A batch of keys loaded together | TTL with jitter |
| One key far hotter than the rest | Short local cache in front of Redis |
| Invalidate a whole group at once | Versioned keys |
| In-process copies on many servers | Event-based invalidation, TTL as backstop |
| Per-user answers | User id in the key, private over HTTP |
Back to Senior Skills.