Learnings

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

Why and where

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.

Each layer answers if it can, and passes the request down if it cannot.
LayerScopeYou invalidate it by
BrowserOne userYou cannot: only headers and new URLs
CDN, reverse proxyAll usersPurge API, short s-maxage
App memoryOne processTTL, or an event sent to every process
RedisAll app serversDEL, 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

Why and where

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 ratioAverage readReads reaching the database
0% (no cache)200 ms100%
90%21 ms10%
99%3 ms1%
  • 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

Why and where

Cache what is read often, changes rarely and can be a little old. Leave the rest alone.

Do not cacheWhy
The balance check inside a transferA stale read moves money that is not there
Permissions and revoked sessions, for longA 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

Read and write patterns

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)

Read and write patterns

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.

Only what is asked for gets cached, and the first reader pays.
  • 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

Read and write patterns

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.

One place holds the loading logic, so stampede protection can live there too.

Write-through

Read and write patterns

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.

Database first, then cache: a failed database write must not leave a value in the cache.
  • The two writes are not atomic. A crash between them leaves the cache old, so keep a TTL.

Write-behind

Read and write patterns

The write lands in the cache and returns at once. The database is updated later, in batches.

Fast writes, paid for with a window where only the cache has the data.
  • 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

Read and write patterns

Writes go only to the database and the cached copy is deleted. The next read reloads it with cache-aside.

Cache-aside reads plus delete-on-write: the combination most services run.

The five patterns compared

Read and write patterns

PatternConsistencyComplexityFailure mode
Cache-asideStale up to the TTL unless writes invalidateLow, but repeated at every call siteStampede on a cold or expired key
Read-throughSame as cache-asideMedium: a cache layer with loadersCache layer down means reads fail unless it falls back
Write-throughFresh after every writeMedium: every write path must use itCrash between the two writes, slower writes
Write-behindDatabase lags the cacheHigh: queue, batching, retries, orderingLost writes when the cache dies
Write-aroundFresh after the next readLowMiss 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 and eviction

Expiry is about time: the entry is too old. Eviction is about memory: the cache is full and something has to go.

The Stale state is the whole problem: the cache cannot tell it from Fresh.
DataStarting TTLReason
Interest rates, branch list, configMinutes to hoursChanges rarely, and a late change is harmless
Account summary shown on a dashboardSeconds to a minute, plus delete on writeUsers 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

Expiry and eviction

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:

PolicyEvictsUse when
noevictionNothing: writes fail with an OOM errorRedis holds data you cannot lose (queues, locks)
allkeys-lruLeast recently used, any keyA pure cache. The usual choice.
allkeys-lfuLeast frequently used, any keyA few keys are much hotter than the rest
allkeys-lrmLeast recently modified (newer Redis 8 releases)Reads should not keep an old entry alive
volatile-lru, -lfu, -lrmThe same, only among keys with a TTLCache and durable keys share one instance
volatile-ttlThe key closest to expiringThe TTL already encodes importance
LRULFU
KeepsWhat was touched latelyWhat is touched often
Fooled byOne full scan: every cold key looks recentYesterday's hot key, until its counter decays
In RedisBoth 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

Expiry and eviction

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 (and functools.cache) grows until the process is killed. On a method, the cache also keeps every self alive.
  • 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

Invalidation and consistency

WayHowStale forWeak point
TTL onlyDo nothing on writeUp to the TTLUsers see old data after their own change
Delete on writeWrite the database, then DELMillisecondsEvery write path must remember to do it
Versioned keyPut a version in the key and bump itZero for new readersOld keys stay until they expire
EventPublish "key changed", every holder drops itMilliseconds, if the event arrivesA 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

Invalidation and consistency

"Update the cache on write" breaks when two writers interleave: the one that wrote the database first can write the cache last.

Nothing fixes the cache until its TTL ends.

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 SET it after the DEL. It is rare, and the TTL bounds it.

Versioned keys

Invalidation and consistency

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 GET per 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

Invalidation and consistency

"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.

NeedWhat to do
Anyone may see data a few seconds oldTTL, nothing more
Read-your-writes: the user who deposited must see the new balanceDelete 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 revokedBypass, 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

Invalidation and consistency

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

Failure modes

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.

The slower the query, the wider the window and the bigger the herd.

Fix 1: a lock with SET NX EX

Failure modes

Only the request that wins a short Redis lock may rebuild the value. The rest wait briefly and read the cache again.

Works across processes and servers, because the lock lives in Redis.
  • 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.
  • EX frees the lock if the winner crashes. Set it longer than the slowest query.

Fix 2: request coalescing, and early refresh

Failure modes

Coalescing (single flight) does the same inside one process with no Redis lock: the first caller loads, the others wait on its result.

FixDatabase calls for N serversNote
Redis lock1Losers poll, so they wait a little longer than needed
Single flightUp to N, one per processNo polling. Go has it as singleflight.
Early probabilistic refreshAbout 1Each 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 refreshes1Keep the old value past its soft TTL. Nobody waits.

Cache penetration and negative caching

Failure modes

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.

Two guards: a Bloom filter in front, and a cached "not found" behind it.
  • 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

Failure modes

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

Failure modes

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.

A very short in-process layer absorbs most reads of a hot key.
ProblemFind itFix
Hot keyredis-cli --hotkeys (needs an LFU policy), per-key metrics in the appLocal cache in front, read from replicas, or split into key:1 .. key:N copies
Big valueredis-cli --bigkeys, --memkeys, MEMORY USAGE keyCache 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

Failure modes

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

HTTP caching and operating

One response header tells every cache between the server and the user what it may keep and for how long.

DirectiveMeaning
max-age=60Fresh for 60 seconds in any cache
s-maxage=300Overrides max-age for shared caches (CDN, proxy)
publicShared caches may store it
privateOnly the user's browser may store it. Use for anything per user.
no-cacheMay be stored, but must be revalidated before every use
no-storeMust not be stored at all
immutableWill never change: do not revalidate even on reload
stale-while-revalidate=30Serve the stale copy for 30 more seconds while refreshing in the background
ResponseHeader
Asset with a hash in its namepublic, max-age=31536000, immutable
HTML pageno-cache
Public API data (rates)public, max-age=60, s-maxage=300
A user's balanceprivate, no-cache, or no-store

Trap: no-cache does not mean "do not cache". That is no-store.

ETag and conditional requests

HTTP caching and operating

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.

Revalidation saves the transfer, not the round trip.

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

HTTP caching and operating

Vary names the request headers that are part of the cache key. It is the HTTP form of the per-user key rule.

HeaderEffect
Vary: Accept-EncodingSeparate copies for gzip and brotli. Always safe.
Vary: Cookie or AuthorizationOne copy per user: the shared cache stops being useful. Send private instead.
Browser cacheCDN
ServesOne userEveryone
Honoursmax-age, privates-maxage first, then max-age. Does not store private responses.
PurgeNot possibleBy 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

HTTP caching and operating

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.

MetricFromWorry when
Hit ratiokeyspace_hits, keyspace_misses, better per key prefix in the appIt drops suddenly: a deploy, an eviction storm, a bad key
Latencyp50 and p99 of cache calls and of loader calls, in the appCache p99 nears the query time
Memoryused_memory against maxmemoryIt sits at the limit and evictions climb
Evictionsevicted_keysAbove 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

HTTP caching and operating

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, SCAN and never KEYS in production, a separate instance for durable data.

Choosing a serialisation

HTTP caching and operating

Redis stores bytes. The format decides size, speed and who else can read the value.

FormatGoodBad
JSONReadable in redis-cli, any languageLarge, no dates or decimals, int keys become strings and tuples become lists (last line above)
pickleAny Python objectPython only, breaks when classes change, runs code on load: never unpickle from a cache others can write to
MessagePack, ProtobufCompact binary, many languages, Protobuf has a schemaA dependency, not readable by eye (not run for this page)
+ zlib8 times smaller here, on repetitive dataCPU 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

HTTP caching and operating

I have this situationUse this
Read-heavy data, a little staleness is fineCache-aside with a TTL
Users must see their own change at onceDelete on write (write-around), database first
Read immediately after every write, and oftenWrite-through
Very frequent small writes that may be lostWrite-behind
The value drives a decision about money or accessNo cache: read the database
One expensive key, many concurrent readersLock or single flight, plus serve-stale
Requests for ids that do not existNegative caching, validation, Bloom filter
A batch of keys loaded togetherTTL with jitter
One key far hotter than the restShort local cache in front of Redis
Invalidate a whole group at onceVersioned keys
In-process copies on many serversEvent-based invalidation, TTL as backstop
Per-user answersUser id in the key, private over HTTP

Back to Senior Skills.