Summary#
A caching strategy decides who loads data into the cache and what happens on writes. For reads: cache-aside (the application checks the cache, loads from the database on a miss and fills the cache; the most common choice) and read-through (the cache itself loads from the database). For writes: write-through (write to cache and database together, so the cache is always fresh), write-behind / write-back (write to the cache now, the database later, fast but can lose data), and write-around (write only to the database and let reads fill the cache). Refresh-ahead reloads popular entries before they expire. Each gives different freshness, latency and failure behaviour, so choose per workload, and usually combine a read strategy with a write strategy.
Why It Exists#
Adding a cache creates two copies of the same data. Every design must answer: when the cache misses, who fetches the data? When data changes, which copy is updated first, and what happens if one update fails? A wrong answer leads to stale pages, lost writes or a database stampede. The standard strategies are well-understood answers with known trade-offs, so you can pick one deliberately instead of inventing one under pressure. This page builds on Caching Fundamentals.
How It Works#
Cache-aside (lazy loading)#
The application talks to both the cache and the database. On a read it checks the cache first; on a miss it reads the database and writes the result into the cache with a TTL. On a write it updates the database and deletes the cache entry so the next read reloads fresh data.
get_product(id):
v = cache.get("product:" + id)
if v != null: return v
v = db.query("SELECT ... WHERE id = ?", id)
cache.set("product:" + id, v, ttl = 3600)
return v
update_product(id, fields):
db.update(id, fields)
cache.delete("product:" + id) # delete, don't set: avoids racing writers- Only requested data is cached, so memory holds the working set.
- If the cache is down, the app still works (reads go to the database, slower).
- The first read of each key is a miss (cold start), and many concurrent misses on one hot key can stampede the database.
- Small staleness windows exist (see consistency below).
Cache-aside, in depth#
Why it is the default. Cache-aside keeps the cache entirely optional. The database stays the source of truth, the cache holds only copies that someone asked for, and the application is the only component that knows both exist. If you remember one pattern for interviews and for production, make it this one. Memcached was designed to be used exactly this way: it has no idea a database exists, and that ignorance is a feature. You can flush it, restart it or lose a node, and the system still returns correct answers, just more slowly.
The cost of a miss: three trips. A hit costs one network round trip to the cache (about 0.2 to 1 ms in the same data centre). A miss costs three sequential steps: the cache lookup that fails, the database query, and the write that fills the cache. With a 0.5 ms cache round trip and a 10 ms query, a miss takes about 11 ms against 0.5 ms for a hit. The average latency is therefore driven by the miss ratio, not the hit latency:
average latency = hit_ratio x 0.5 ms + (1 - hit_ratio) x 11 ms
hit ratio 99% -> 0.6 ms
hit ratio 95% -> 1.0 ms
hit ratio 80% -> 2.6 msThe fill write can be done asynchronously (fire and forget) so the caller does not wait for it, which brings a miss down to roughly the cost of the database query plus one lookup.
Cold nodes. When a cache node fails and is replaced, or when you add nodes and keys move, the new node starts empty. Every key it now owns misses once. With consistent hashing only about 1/N of the keys move when one of N nodes changes, but those misses arrive all at once and land on the database. Warming strategies (copying hot keys from a replica, or shadow-reading from the old node for a while) and miss throttling are covered in Cache Failure Modes and Distributed Caching.
Why delete rather than set on write. After a database update, the application has two choices: write the new value into the cache, or delete the key and let the next read reload it. Deleting is preferred for three reasons:
- Racing writers. If two writers update the same row, the database applies them in one order (W1 then W2), but their cache sets can arrive in the other order (W2 then W1). The cache then holds W1's older value indefinitely. A delete is idempotent and order-free: whichever delete lands last, the key ends up absent.
- Derived values. A cached object is often assembled from several rows (a product with its price, stock and reviews summary). The writer that changed the price may not have the other pieces to build a correct cached object. Deleting forces a full, consistent rebuild.
- Wasted work. Setting the cache on every write fills memory with values that may never be read before the next change.
Why the database first. If you delete the key first and then write the database, a reader can slip in between: it misses, reads the old row and refills the cache with the old value, and the cache stays stale after your write commits. Writing the database first and deleting second shrinks the window to the race described below.
The stale-set race, step by step. Even with database-first, delete-second ordering, one interleaving still leaves stale data. It needs a read miss whose database read happens before a write, and whose cache fill happens after that write's delete:
The window is narrow, because the reader's fill must take longer than the writer's whole update-and-delete. But at high QPS on a hot key it does happen, often enough that large operators built specific defences. The defences, from cheapest to strongest:
- TTL as a safety net. Every cache-aside entry should have a TTL, so any stale value heals within a bounded time. Pick the TTL from your staleness budget: if a product price may be stale for at most 5 minutes, the TTL is at most 5 minutes.
- Delayed double delete. The writer deletes the key, then schedules a second delete after a short delay (for example 500 ms to 2 s, longer than a typical miss-and-fill). The second delete removes any stale value that a racing reader put back. It is cheap and catches most races, but the delay is a guess.
- Versioned or conditional sets. Store the row version with the value and set only if the cached version is older. Old readers can never overwrite newer data (see the snippet in How to Implement It).
- Leases. The cache hands out a token on a miss and rejects a set whose token was invalidated by a delete. This is Meta's approach, described in the Deep Dive.
- CDC-driven invalidation. Delete keys from the database's change stream instead of from application code, so every committed write, from any service or script, triggers invalidation.
When the delete fails. The database commit succeeded but the DEL timed out. Now the cache is stale until the TTL. Options: retry the delete a few times with backoff, put the key on a local retry queue, write an invalidation event to a transactional outbox (a table written in the same transaction as the data, then relayed to the cache invalidator), or rely on CDC so that invalidation does not depend on the request path at all. For most product data, retry plus TTL is enough. For data where staleness causes real harm, use the outbox or CDC.
Negative caching. If many requests ask for keys that do not exist (a deleted product, a mistyped URL, a scraper probing IDs), every one of them misses and queries the database. Caching the "not found" result with a short TTL (30 to 60 seconds) stops that. Remember to delete the negative entry when the item is created, or creation will look broken for up to a minute.
Serialisation and size. Cache-aside stores whatever the application serialises. JSON is easy to debug but large and slow to parse; MessagePack, Protocol Buffers or compressed JSON cut size and CPU. Store what the hot read needs, not the whole ORM object graph. Large values (over about 100 KB in Redis) hurt latency for everyone sharing that node, because Redis processes commands on a single thread. Split them or keep them in object storage and cache a pointer.
Read-through#
The application asks only the cache. On a miss, the cache (or a cache library) loads the data from the database using a loader you register, stores it and returns it. It is cache-aside moved into the cache layer: application code is simpler and the loading logic lives in one place. Libraries such as Caffeine and Guava (LoadingCache), NCache, and DAX for DynamoDB work this way; plain Redis does not load data itself, so with Redis you implement cache-aside in code or a wrapper. A good read-through cache also coalesces concurrent misses for the same key into one database load.
Read-through, in depth#
The cache as a smart proxy. In read-through, the application never talks to the database for cached data. It calls cache.get(key), and the cache layer, through a loader function you register, fetches from the database on a miss, stores the value and returns it. Read-through is the read-side twin of write-through: in both, the cache sits between the application and the database and performs the database operation on the application's behalf. Systems often combine the two into a single "cache layer" that owns all access to a dataset.
Where you actually meet it.
- In-process libraries. Caffeine and Guava's
LoadingCachein Java, or a memoisation layer in any language. You pass a loader once, and everygeteither returns the cached value or calls the loader. - Data grids. Hazelcast (
MapLoader), Apache Ignite and Ehcache (CacheLoaderWriter) let you plug database access code into the grid, so the grid loads on a miss. - Managed services. Amazon DAX sits in front of DynamoDB and speaks the DynamoDB API, so the application points its client at DAX instead of DynamoDB.
- CDNs and reverse proxies. A CDN is the most common read-through cache in the world. On a miss, the edge fetches from your origin, caches the response according to its headers and returns it. Varnish and Nginx proxy caching work the same way.
- Database gateways. Meta's ZGateway, which sits in front of the ZippyDB key-value store, checks a local in-memory cache first and, on a miss, fetches from ZippyDB and keeps a copy for later requests.
Plain Redis and Memcached do not load data themselves. With them, "read-through" means a wrapper library in your application that hides the cache-aside steps behind one call. The behaviour is the same; the difference is where the code lives.
Request coalescing comes for free (if the library does it). The biggest practical win of a good read-through layer is that it can collapse concurrent misses for one key into a single database load. When a popular entry expires, or when a celebrity profile suddenly gets traffic, thousands of callers can miss in the same millisecond. A naive cache-aside implementation sends all of them to the database. A read-through layer can keep a per-key fill lock or an "in-flight" table: the first caller loads, the rest wait on the same future and receive the same result. ZGateway does exactly this on each gateway host, which is the same idea as request coalescing, with the result kept afterwards. Caffeine does it by computing a missing entry once per key while other callers block on that computation.
Coalescing has limits. It works only among callers that reach the same process (or the same cache node). Ten application servers each with their own read-through cache will still send up to ten loads for one key. And while a slow load is in progress, waiting callers pile up, so the layer needs a cap on waiters and a timeout, otherwise a slow database turns into memory exhaustion in the cache layer.
Freshness with read-through. Read-through alone only describes how misses are filled. Staleness depends on how the cache learns about writes: a TTL, a paired write-through path, or an external invalidation stream. ZGateway's answer is a change data capture stream that invalidates or refreshes cached entries, with an agreed bound on how far cached reads may lag behind writes. That pattern, read-through for loads plus CDC for invalidation, scales well because no writer has to remember which keys to delete.
The cache is now on the critical path. With cache-aside, a cache outage degrades latency but reads still work. With read-through, the application asks only the cache, so a cache outage can mean no reads at all unless the client has a fallback that goes straight to the database. In-process read-through caches avoid this problem (they fail with the process), but a remote read-through tier needs the same availability as the database behind it, plus a plan for what clients do when it is down.
When to propose it in an interview. Read-through rarely needs to be named for application caching with Redis; cache-aside is what people expect, and saying "a small wrapper does cache-aside for us" is clear. Name read-through when you discuss CDNs, in-process loading caches, DAX, or a gateway or data-access layer that owns caching for many teams. In those cases, mention coalescing and how invalidation reaches the layer.
Write-through#
Every write goes to the cache and the database as part of the same operation: the cache layer writes to the database synchronously and updates its own copy, and the write is acknowledged only when both succeed.
- Reads after writes hit the cache and see fresh data.
- Writes are slower (two writes on the path).
- The cache fills with data that may never be read (combine with TTLs).
- If the two writes are not truly atomic, a failure between them can leave them inconsistent; well-built systems write the database first, then the cache, and treat cache failures by deleting the key.
Write-through pairs naturally with read-through. DAX (DynamoDB Accelerator) is a managed example: writes pass through DAX to DynamoDB and update the item cache.
Write-through, in depth#
The contract. The application writes to the cache layer, and the cache layer writes the database synchronously before it acknowledges. The write is not complete until both copies hold the new value. Subsequent reads of just-written data hit the cache and are fresh. Users usually tolerate a slower save more than a slower page load, so moving cost from reads to writes is often a good trade for read-heavy data.
It needs infrastructure that supports it. Redis does not write to your database for you. Write-through in practice means one of:
- a data grid or caching library with a store plugin, such as Hazelcast
MapStoreconfigured with zero write delay, Ehcache'sCacheLoaderWriter, or Apache Ignite with write-through enabled; - a managed cache that speaks the database's API, such as DAX for DynamoDB;
- a data-access layer in your own code that performs "write database, then update cache" as one function every caller must use.
The third option is the most common. It works only if every write path goes through that layer. A batch job, a migration script or another service that writes the table directly leaves the cache stale, which is why write-through is often combined with a TTL or CDC invalidation as a backstop.
It still has a dual-write problem. Two separate systems are being written, and there is no transaction spanning them. The failure cases:
| Step that fails | Result | Mitigation |
|---|---|---|
| Database write fails | Nothing changed. Return an error, do not touch the cache | None needed if the cache is updated only after the database commits |
| Database commits, cache update fails | Cache holds the old value | Delete the key (or mark it invalid), retry, TTL as backstop |
| Cache updated first, database fails | Cache shows a value that was never stored | Do not order it this way, or roll back the cache entry |
| Process crashes between the two | Same as the second row | TTL, CDC invalidation, or an outbox event |
The safe ordering is database first, then cache. Even then, perfect agreement between cache and database needs either a distributed transaction (rarely worth it) or acceptance of a short, bounded inconsistency window.
Racing writers still need ordering. If W1 and W2 update the same key, the database orders them, but their cache updates can arrive in the opposite order, the same problem described for "set on write" under cache-aside. A write-through cache that is itself the coordinator (all writes to a key pass through one cache node that serialises them, as in a data grid that owns a partition) avoids this. A library-level write-through spread across many application servers needs versioned sets: store the row version and refuse to overwrite a newer value.
Cache pollution and cold nodes. Every written item lands in the cache whether or not anyone reads it. If most writes are never read (audit records, rarely viewed settings), memory fills with dead weight. A TTL on write-through entries limits the damage. The opposite problem also exists: a node that joins the cluster after a failure or a scale-out holds nothing until items are written again, and items that are read but rarely written may never reach it. The fix is to combine write-through with cache-aside reads, so a miss loads from the database as usual.
Latency maths. A write-through write costs the database write plus the cache update, sequentially. With a 5 ms database commit and a 0.5 ms cache set, the write takes about 5.5 ms instead of 5 ms. That 10% is usually invisible. The real cost is availability: if the cache tier is unavailable, writes either fail or must fall back to "database only, then invalidate later", which you need to design explicitly.
A landmark example. Meta's TAO (Bronson and colleagues, USENIX ATC 2013) is a write-through cache for the social graph. Reads are served from follower cache tiers. Writes are forwarded to a leader cache for the shard, which writes to MySQL and updates its own copy, then followers are invalidated or refreshed asynchronously. A follower that forwarded a write also updates its own copy right away, which gives the writing user read-your-writes behaviour while other users see the change slightly later.
Write-behind (write-back)#
The application writes to the cache only and gets an immediate acknowledgement; the cache flushes changes to the database asynchronously, often in batches every few hundred milliseconds or seconds.
- Very fast writes and big savings when the same key is updated many times (only the latest value is flushed, and batches are efficient).
- Data loss risk: if the cache node dies before flushing, acknowledged writes are lost, unless the cache itself is replicated and persistent.
- The database lags behind the cache, so anything reading the database directly (reports, other services) sees old data.
- Ordering and failure handling of flushes are tricky.
Fits: counters, view counts, likes, game state, rate limits, metrics aggregation: high-rate writes where losing a second of data is acceptable. Not for payments or orders. A durable variant uses a log (Kafka) as the buffer instead of the cache's memory.
Write-behind, in depth#
The idea comes from hardware. CPU caches have used write-back for decades. A store instruction updates the cache line and sets a dirty bit. The line goes to main memory only when it is evicted, so ten writes to the same line cost one memory write. Write-behind caching applies the same trick to databases: the cache absorbs writes, tracks which entries are dirty and flushes them later, coalesced and batched.
Where the savings come from. Two effects multiply:
- Coalescing. If a key is written many times between flushes, only the last value is written. A video's view counter incremented 2,000 times in five seconds becomes one
UPDATE. - Batching. Dirty entries are flushed in groups, such as one multi-row
INSERT ... ON CONFLICT DO UPDATEof 500 rows, which costs far less than 500 single-row statements, because the database amortises round trips, parsing and log flushes.
A worked example: 50,000 like and view increments per second spread over 10,000 active posts. Writing each increment to PostgreSQL directly means 50,000 transactions per second, which needs a large, carefully tuned primary. With write-behind flushing every 5 seconds, each flush writes at most 10,000 rows, about 2,000 rows per second, in batches of 500: 4 statements per second. That is a 25 times reduction in rows and a 10,000 times reduction in statements.
What you give up.
- Durability. Acknowledged writes live only in the cache until flushed. If the cache node dies, they are gone. Redis with append-only file persistence and
appendfsync everyseccan lose up to about one second of writes on a crash, and async replication to a replica can lose a little more on failover. Memcached has no persistence at all. - A lagging database. Anything that reads the database directly (reports, other services, search indexers, CDC consumers) sees data that is seconds or minutes old. All reads that need the latest value must go through the cache.
- Ordering and failure handling. If a flush fails halfway, which entries were written? If the database is down for ten minutes, dirty entries pile up in memory and may push out clean data or exhaust memory. If flushes are retried, they must be idempotent (set absolute values, or apply increments keyed by a flush ID), otherwise a retry double-counts.
- Eviction becomes dangerous. A dirty entry must be flushed before it can be evicted. A cache under memory pressure therefore has to stall writers or flush synchronously, which removes the speed advantage just when load is highest.
The durable variant: a log as the buffer. For most production systems, the safer form of write-behind puts a durable log between the fast path and the database:
The application writes the event to a replicated log (Kafka with acks=all), which acknowledges in a few milliseconds, and updates the cache for fast reads. A consumer aggregates events and writes batches to the database. A cache crash now loses nothing: counters can be rebuilt from the database plus the unflushed part of the log. This is what "write-behind" usually means in analytics and metrics pipelines, and it is the version to propose in an interview when the data matters at all.
Grid-native write-behind. Data grids implement write-behind directly. Hazelcast's MapStore with a non-zero write delay queues dirty entries per partition, coalesces repeated updates to the same key and flushes them in batches of a configured size. Its backups hold copies of the queue, so losing one member does not lose the queued writes. That shows the general requirement: write-behind is only as durable as the replication of its pending-write queue.
Good fits and bad fits.
- Good: view counts, likes, play counts, rate-limit counters, leaderboards, game state checkpoints, IoT telemetry aggregation, "last seen" timestamps. Losing or delaying a second of these is harmless.
- Bad: payments, orders, bookings, inventory decrements, anything audited or anything another system reads from the database to make decisions.
Write-around#
Writes go directly to the database, bypassing the cache (and invalidating any cached copy). The cache is filled only by reads, as in cache-aside.
- Avoids filling the cache with data that is written but rarely read (logs, bulk imports, archives).
- A read soon after a write will miss and go to the database.
- In practice, "cache-aside with delete on write" is a form of write-around.
Write-around, in depth#
What it protects. Cache memory is the scarce resource. Write-through puts every written item into the cache. Write-around puts none: writes go straight to the database, any cached copy is invalidated, and only items that are actually read get cached, through the normal cache-aside miss path. The cache keeps holding the read working set instead of whatever was written most recently.
When writes and reads are different sets. Write-around shines when much of what is written is read rarely or never soon:
- Bulk imports and backfills. Loading 50 million product rows overnight through a write-through cache would evict the entire hot set and replace it with data nobody is reading.
- Logs, audit trails, events and time-series data. Written once, read occasionally, usually by analytics queries that should not use the application cache anyway.
- Archives and cold content. Old orders and old messages are written when created and rarely revisited.
The cost. A read that follows a write closely misses and pays the database round trip. For a user who edits their profile and immediately views it, that is one extra 5 to 20 ms. If that matters, pair write-around with a short read-your-writes rule (route that user's next read to the database, or set the cache for that one key on write) rather than switching the whole system to write-through.
Relationship to cache-aside. Cache-aside with "update the database, then delete the key" is write-around for writes plus lazy loading for reads. Most Redis deployments run exactly this combination, even if they never call it write-around. The term is useful mainly to contrast with write-through when you explain why you are not caching on write.
Refresh-ahead#
The cache reloads popular entries before they expire: for example, when an entry is read in the last 10-20% of its TTL, it triggers an asynchronous refresh while still returning the current value.
- Hot keys never expire under load, so users never wait for a miss and there is no stampede at expiry.
- Wasted work if the refreshed entries are not read again; needs a good guess of what is hot.
- Caffeine's
refreshAfterWriteand CDNs' stale-while-revalidate (Cache-Control: max-age=60, stale-while-revalidate=30) work this way.
See Cache Failure Modes for stampede protection.
Refresh-ahead, in depth#
The problem it solves. With plain TTL expiry, a hot key behaves badly at the moment it expires. The entry disappears, the next request misses, and so does every other request that arrives before the reload finishes. If the reload takes 200 ms and the key gets 5,000 reads per second, about 1,000 requests miss at once. Refresh-ahead keeps hot entries warm by reloading them before expiry, while still serving the current value.
Three ways to trigger a refresh.
- Access-triggered, with a refresh threshold. When a read finds an entry that is older than a refresh age (for example 80% of its TTL), it returns the cached value and starts an asynchronous reload. Caffeine's
refreshAfterWriteworks like this: after the refresh duration, the next access triggers a background reload and callers keep getting the old value until the new one arrives. Oracle Coherence calls the threshold the refresh-ahead factor. Only entries that are actually read near expiry get refreshed, so cold entries simply expire. - Scheduled refresh. A background job rebuilds known hot keys on a timer, such as the home page every 30 seconds or the trending list every minute. This is simple and predictable, and it works well for a small, known set of expensive keys. The cost is fixed: keys times refresh rate, whether or not anyone reads them.
- Probabilistic early expiration. Each reader independently decides to refresh early with a probability that rises as expiry approaches. Vattani, Chierichetti and Lowenstein (VLDB 2015, "Optimal Probabilistic Cache Stampede Prevention") proposed the XFetch rule:
# delta = how long the last recompute took, beta >= 1 (1.0 is a good default)
should_refresh = now - delta * beta * ln(random()) >= expiry
# ln(random()) is negative, so this fires earlier for slow recomputes and higher betaNo coordination is needed, refreshes spread out naturally, and the expected number of concurrent recomputes stays close to one even at very high read rates. The slower the recompute, the earlier refreshes start, which is exactly what you want.
HTTP's version: stale-while-revalidate. RFC 5861 (Mark Nottingham, 2010) defines stale-while-revalidate and stale-if-error. With Cache-Control: max-age=60, stale-while-revalidate=30, a CDN or browser serves the response fresh for 60 seconds, then for the next 30 seconds serves the stale copy immediately while revalidating in the background. stale-if-error=86400 lets it keep serving stale content for a day if the origin returns errors, which turns an origin outage into slightly old pages instead of error pages.
Cost model. Access-triggered refresh adds at most one extra load per key per TTL period, and only for keys read late in their life. Scheduled refresh costs (number of keys) / (refresh interval) loads per second. For 200 hot keys refreshed every 30 seconds, that is about 7 loads per second, trivial. For 2 million keys refreshed every minute, it is about 33,000 loads per second, probably more than the database serves today. That is why refresh-ahead is a tool for a few hot keys, not a whole dataset.
Failure behaviour. If a background refresh fails, keep the old value and retry with backoff instead of deleting it. Serving a value that is 70 seconds old instead of 60 is better than turning a transient database error into a stampede. Set a hard maximum age after which stale data is no longer served, so a broken refresh cannot serve day-old prices forever.
Consistency of each strategy#
| Strategy | Read path | Write path | Freshness after write | Write latency | Data loss risk | Cache outage |
|---|---|---|---|---|---|---|
| Cache-aside | App: cache, then DB on miss, fill cache | App: DB, then delete key | Fresh on next read (small race window) | DB only | None | Reads fall to DB |
| Read-through | Cache loads on miss | (paired with another write strategy) | Same as its write strategy | N/A | None | App cannot read unless it falls back |
| Write-through | Cache (hit) | Cache layer writes DB + cache synchronously | Fresh immediately | DB + cache | None (DB is written) | Writes fail or fall back |
| Write-behind | Cache | Cache now, DB asynchronously | Cache fresh; DB lags | Cache only (fastest) | Yes, unflushed writes | Possible loss |
| Write-around | Cache-aside style | DB only, invalidate cache | Next read is a miss, then fresh | DB only | None | Reads fall to DB |
| Refresh-ahead | Cache, async refresh near expiry | (any) | Bounded by TTL; hot keys refreshed | N/A | None | Reads fall to DB |
The cache-aside race. With delete-on-write, a rare race remains: reader A misses and reads the old row; writer B updates the database and deletes the key; reader A then writes the old value into the cache, which stays stale until its TTL. Defences: short TTLs as a safety net, delayed double delete (delete again a second or so after the write), versioned values (only set if newer), or invalidation driven by the database's change log (CDC). Updating the cache on write instead of deleting makes concurrent-writer races worse, which is why deleting is preferred. See Cache Eviction and Invalidation.
Consistency, in depth#
A cache is an asynchronously maintained replica. Thinking of the cache this way makes its guarantees easier to reason about. Like a database read replica, it holds copies that lag the primary by some amount. Unlike a replica, it does not receive an ordered log of changes (unless you feed it one through CDC), so its lag is not bounded by replication delay. It is bounded by whichever invalidation mechanism fires first.
What bounds the staleness.
| Mechanism | Worst-case staleness after a write |
|---|---|
| TTL only | The TTL (a write just after a fill stays invisible for the full TTL) |
| Delete on write | Delete latency, plus the stale-set race (then bounded by the TTL) |
| Delete on write plus delayed double delete | The double-delete delay, for most races |
| Versioned sets or leases | Delete latency. Stale sets are rejected |
| CDC invalidation | Log-to-invalidation lag, typically tens of milliseconds to a few seconds |
| Write-through with a single owner per key | Effectively zero for reads through the cache. Direct database writers still need a backstop |
Strong consistency is not on the menu. Linearizable reads through a cache (every read sees the latest committed write) would need the write to wait until every cache that might hold the key has confirmed the invalidation, and readers to coordinate with writers. That is a distributed protocol with the cost of a database read, which defeats the purpose. Design instead around the weaker guarantees that users actually notice:
- Read-your-writes. A user must see their own change immediately. Options: write-through for that key, set the cache for that key on the writer's request path, route that user's reads to the primary for a few seconds after a write (keep a "last write" timestamp in their session), or pass a version token with the request and treat older cached versions as misses.
- Monotonic reads. A user should not see a new value and then an older one. This breaks when different requests hit caches with different lag, such as two application servers with their own in-process caches. Sticky routing or a single shared cache tier solves it.
- Bounded staleness for everyone else. Most data only needs "everyone sees the change within N seconds". Write that N down per data type, since it determines TTLs and invalidation design.
Multi-tier caches multiply the problem. With an in-process L1 cache on each of 50 application servers in front of a shared Redis L2, a delete in Redis does not touch the 50 local copies. Common fixes: very short L1 TTLs (1 to 10 seconds) so local staleness is bounded, an invalidation broadcast over Redis pub/sub or a message bus that each server subscribes to, or Redis client-side caching (Redis 6 and later can track the keys a client has read and push invalidation messages when they change).
Measure it. Staleness is invisible unless you look. Sample a small fraction of cache hits (for example 0.1%), read the same key from the database asynchronously, and record mismatches and their age. A dashboard of "stale reads per million" by key prefix turns consistency from a belief into a number, and it catches bugs such as a write path that forgot to invalidate.
Choosing per workload#
| Workload | Recommended | Why |
|---|---|---|
| General read-heavy app data (products, profiles) | Cache-aside + delete on write + TTL | Simple, resilient, caches only what is read |
| Read-after-write must be fresh (user settings shown right after save) | Write-through (or cache-aside plus read-your-writes from DB) | Cache updated on the write path |
| Very high write rate, loss of a few seconds acceptable (likes, views) | Write-behind, or a durable log + batch writer | Absorbs writes, batches DB updates |
| Bulk writes rarely read soon (logs, imports) | Write-around | Keeps the cache for hot reads |
| A few very hot keys with expensive loads (home page, trending) | Refresh-ahead / stale-while-revalidate | No expiry misses, no stampedes |
| Many app teams reading the same data | Read-through library or service | Loading logic in one place |
Combining is normal: read-through with write-through (a full cache layer), or cache-aside reads with write-around writes (the common Redis setup).
Choosing a strategy, in depth#
Decide reads and writes separately. A strategy is really two choices: how misses are filled (cache-aside, read-through, refresh-ahead) and what writes do (delete, write-through, write-behind, write-around). Ask the questions in this order:
Worked example 1: an e-commerce catalogue. 20 million products, 30,000 product-page reads per second at peak, a few hundred price or description edits per minute, and prices allowed to be stale for 60 seconds on product pages (checkout always reads the database). Choice: cache-aside in Redis with key product:{id}:v3, TTL 10 minutes with 10% jitter, update the database then delete the key, and CDC-based invalidation because the pricing service and a nightly import job also write the table. With a 98% hit ratio the database sees about 600 reads per second instead of 30,000. The home page and top-category pages use refresh-ahead every 30 seconds because they are expensive to assemble and get thousands of reads per second.
Worked example 2: a social like counter. 100,000 likes per second during peaks, displayed counts may lag by a few seconds, and the exact total must eventually be correct. Choice: write-behind through a log. Each like is appended to Kafka and applied to a Redis counter with INCRBY. A consumer aggregates per post and upserts every few seconds. The "has this user liked this post" check, which must be exact for the user, is stored in the database and served by cache-aside with set-on-write for the acting user's key.
Worked example 3: event search results (the Ticketmaster pattern). Search queries are expensive (a search engine or database with filters), and popular searches repeat heavily when a big tour goes on sale. Choice: cache-aside of whole result pages in Redis or Memcached. The key must include every parameter that can change the result: keyword, date range, location, sort order, page and any filters, for example search:keyword=taylor swift&start=2025-01-01&end=2025-12-31&page=1. Normalise parameters (lowercase, sorted, trimmed) so equivalent queries share an entry. The TTL is chosen per freshness need, from minutes up to a day for slow-changing event listings. The hard part is invalidation: when a new event is added, which cached searches should now include it? Exact answers are impossible for fuzzy search, so combine TTLs with cache tags: tag each cached result with the performers, venues and cities it covers, and when an event changes, delete all entries carrying its tags. Watch the miss rate during on-sale peaks, since a wave of novel queries will all miss and land on the search tier.
Worked example 4: user sessions. Sessions are read on every request and written on login, logout and occasional updates. Here the cache is the store: Redis with persistence and replication holds sessions with a sliding TTL, and nothing backs them in a relational database. None of the six strategies applies, because there is no second copy. This is worth saying in an interview, because treating Redis as a primary store changes the durability discussion completely.
Common combinations.
| Combination | Typical use |
|---|---|
| Cache-aside reads, delete on write, TTL | The default for application data in Redis or Memcached |
| Read-through plus write-through | Data grids, DAX, a dedicated data-access service |
| Cache-aside plus refresh-ahead for the top keys | Catalogues and feeds with a few very hot pages |
| Write-behind via log, cache-aside for reads | Counters, metrics, activity aggregates |
| Read-through plus CDC invalidation | Gateways and platform caches shared by many teams (ZGateway) |
Implementation snippets#
Versioned set with a Lua script. The value is stored as a hash with a version field. The script writes only if the incoming version is newer, so a slow reader can never overwrite a fresher value. Redis runs Lua scripts atomically.
-- KEYS[1] = cache key, ARGV[1] = version, ARGV[2] = payload, ARGV[3] = ttl seconds
local cur = redis.call('HGET', KEYS[1], 'v')
if cur and tonumber(cur) >= tonumber(ARGV[1]) then
return 0 -- cached copy is same or newer: skip
end
redis.call('HSET', KEYS[1], 'v', ARGV[1], 'd', ARGV[2])
redis.call('EXPIRE', KEYS[1], ARGV[3])
return 1Deletes defeat version checks (once the key is gone, any version wins). To keep protection after a delete, write a short-lived tombstone that records the deleted version instead of removing the key entirely.
Cache-aside with in-process coalescing (TypeScript).
const inflight = new Map<string, Promise<Product | null>>();
async function getProduct(id: string): Promise<Product | null> {
const key = `product:${id}:v3`;
const hit = await redis.get(key);
if (hit !== null) return hit === "NULL" ? null : JSON.parse(hit);
let p = inflight.get(key);
if (!p) {
p = (async () => {
const row = await db.products.findById(id);
const ttl = 600 + Math.floor(Math.random() * 60); // TTL with jitter
await redis.set(key, row ? JSON.stringify(row) : "NULL", "EX", row ? ttl : 30);
return row;
})().finally(() => inflight.delete(key));
inflight.set(key, p);
}
return p;
}This coalesces only within one process and caches "not found" for 30 seconds. For cross-process protection, add a short Redis lock (SET lock:key token NX PX 3000) around the load, and have losers briefly retry the cache.
Invalidation through an outbox. In the same transaction as the update, insert a row into cache_invalidations(key, created_at). A relay process reads new rows, issues the deletes and marks them done. The delete can no longer be lost to a crash between commit and DEL, because the intent to invalidate was committed with the data.
Operating and changing strategies#
Metrics that tell you a strategy is working. Each strategy fails in its own way, so each needs its own signal:
| Strategy | Watch | Warning sign |
|---|---|---|
| Cache-aside | Misses per second by key prefix, fill latency, sampled stale-read rate | Misses per second approaching database read capacity |
| Read-through | Waiters per in-flight load, loader timeouts | Waiter count growing while the database slows |
| Write-through | Write latency split into database and cache parts, failed cache updates | Rising cache-update failures, because each one is a stale key |
| Write-behind | Dirty entries, flush lag (age of the oldest unflushed write), flush errors | Flush lag growing steadily, which means the database cannot keep up |
| Refresh-ahead | Refreshes per second, share of refreshed entries read again | Most refreshed entries never read, so the work is wasted |
Flush lag deserves an alert of its own. A write-behind system whose lag grows from 5 seconds to 5 minutes is one cache crash away from losing 5 minutes of data, and nothing user-visible shows it.
Testing the races. Stale-set races and dual-write failures rarely show up in unit tests, because they need precise timing. Ways to flush them out: a test harness that injects delays between a reader's database read and its cache fill, a fault injector that fails a fraction of cache deletes in staging, and a consistency checker that compares cache and database for every key touched in a load test. Run the checker after every change to a write path, since a new endpoint that forgets to invalidate is the most common cache bug in practice.
Changing strategy safely. Moving from one strategy to another is a data migration in miniature:
- Version the keys. New logic writes
product:{id}:v4while old servers still usev3. Both run side by side during a rolling deploy without reading each other's format. - Add the new invalidation path before relying on it. For example, start the CDC invalidator in shadow mode, logging which keys it would delete, and compare with the deletes the application sends.
- Warm before the switch. Pre-load the hottest keys of the new key version (from logs of the last hour of requests) so the switch does not start at a zero hit ratio.
- Let old keys expire. Do not run a mass delete on a production cache, which costs CPU and can block a single-threaded Redis node. TTLs clean up the old version within one TTL period.
Choosing TTLs per strategy. Under cache-aside with reliable invalidation, the TTL is a safety net, so it can be long (an hour or a day) and should match how long you could tolerate a missed invalidation. Under TTL-only caching, the TTL is the freshness guarantee, so it equals the staleness budget. Under write-through, a TTL mainly limits pollution by write-only data. Under refresh-ahead, the TTL is the hard maximum age, and the refresh point sits well before it. Getting this right per data type removes most arguments about whether the cache is "too stale".
Plan the degraded mode. Decide in advance what each strategy does when the cache tier is unavailable. Cache-aside falls back to the database, so check that the database can survive the full read load for a few minutes, or shed low-priority traffic with a circuit breaker. Read-through needs an explicit bypass path. Write-through must choose between failing writes and writing the database only while recording keys to invalidate later. Write-behind must stop accepting writes or switch to writing the database directly, slowly. Writing these choices into the runbook turns a cache outage from an improvisation into a known procedure.
When to Use It#
- Every time you introduce a cache, choose and document both a read and a write strategy.
- When stale data, write latency or data-loss risk becomes a requirement discussion.
- When a hot key or cold start causes database spikes (refresh-ahead, coalescing).
When NOT to Use It#
- Write-behind for money, orders or anything that must not be lost.
- Write-through when most written data is never read (fills memory for nothing).
- Refresh-ahead for long-tail keys; it wastes database work.
- Any cache strategy for data that must be exact at read time (stock at checkout); read the source of truth.
How to Implement It#
- Default to cache-aside with delete on write and TTLs (minutes to an hour).
- Write the database first, then delete the cache key; never the other way round.
- Add TTL jitter and request coalescing for hot keys.
- Use write-through where read-after-write freshness matters and writes are moderate.
- Use write-behind only with durable buffering (replicated cache with persistence, or Kafka) and idempotent flushes.
- Consider CDC-based invalidation (Debezium to a cache invalidator) when many services write the same tables.
- Monitor hit ratio, stale-read rates (by sampling) and flush lag for write-behind.
| Technology | Fits when |
|---|---|
| Redis / Memcached with app code | Cache-aside, write-around, custom strategies |
| Caffeine, Guava LoadingCache | In-process read-through, refresh-ahead |
| Amazon DAX | Read-through and write-through for DynamoDB |
| CDN stale-while-revalidate | Refresh-ahead for HTTP responses |
| Kafka + batch writer | Durable write-behind |
Trade-offs#
| Strategy | Gain | Cost | Pick when |
|---|---|---|---|
| Cache-aside | Simple, resilient to cache failure | Miss latency; race windows | Default for read-heavy data |
| Read-through | Simpler app code, coalesced loads | Cache layer must know the DB | Shared loaders, in-process caches |
| Write-through | Fresh reads after writes | Slower writes; caches unread data | Read-after-write freshness |
| Write-behind | Fastest writes, batching | Data loss, DB lag | High-rate, loss-tolerant writes |
| Write-around | Cache not polluted by writes | Miss after write | Write-heavy, rarely re-read data |
| Refresh-ahead | No expiry misses | Wasted refreshes | Few hot keys |
| CDC-driven invalidation | Catches every writer, replayable | A pipeline to run, seconds of lag | Many services or jobs write the same tables |
| Versioned sets or leases | Closes the stale-set race | Extra metadata and script logic | Hot keys where stale fills are visible |
Common Pitfalls#
- Updating the cache (instead of deleting) on write, causing stale values when writers race.
- Deleting the cache key before the database write, so a reader reloads the old value.
- Write-behind on non-replicated, non-persistent memory for important data.
- No TTL on cache-aside entries, so a missed invalidation lasts forever.
- Assuming Redis does read-through by itself.
- Write-behind without idempotent flushes, so a retried batch double-counts increments.
- Letting a batch import run through a write-through path and evict the whole hot set.
- Refreshing ahead every key on a schedule, turning a small hot-key fix into a database-wide load.
- Multi-tier caches with long in-process TTLs and no invalidation broadcast.
Real-World Examples#
Meta's memcache paper describes a cache-aside "demand-filled look-aside cache" where web servers delete keys after database updates, plus leases to prevent stale sets and stampedes.
Amazon DynamoDB Accelerator (DAX) provides a read-through and write-through cache in front of DynamoDB with microsecond read latency for cached items.
Meta's TAO (USENIX ATC 2013) is a write-through graph cache in which leader caches write MySQL and followers are refreshed asynchronously. Meta's ZGateway uses read-through caching with per-key fill locks in front of ZippyDB and keeps entries fresh with a CDC stream.
In the Interview#
Talking about strategies in an interview#
Name both halves. "Cache-aside for reads, delete on write" is a complete answer. "We'll use Redis" is not. As soon as a cache appears on your diagram, say how misses are filled and what happens on writes, and give a TTL with a reason ("prices may be 60 seconds stale on the product page, so TTL 60 seconds, and checkout reads the database").
Match strategy to each data type, not to the whole system. Strong answers often use two or three strategies: cache-aside for profiles, write-behind through a log for counters, refresh-ahead for the home feed. Interviewers listen for whether you know which data can be stale and which cannot.
Pre-empt the classic follow-ups.
- Delete or update on write? Delete, because concurrent writers can apply cache sets out of order and derived objects need a full rebuild.
- Which order? Database first, then delete. Deleting first lets a reader reload the old row.
- What if the delete fails? Retry, TTL as a safety net, and for important data an outbox or CDC-driven invalidation.
- Write-behind and durability? Only with a replicated buffer (a log or a replicated grid), idempotent flushes, and only for loss-tolerant data.
- Hot key expiry? Coalescing on misses, plus refresh-ahead or probabilistic early expiration for the few hottest keys.
Avoid over-engineering. Proposing write-through or read-through with Redis implies infrastructure that Redis does not provide. Unless you are talking about a CDN, DAX or a data grid, cache-aside plus a clear invalidation story is the answer interviewers expect, and the time saved is better spent on the database or the hot-key discussion.
Deep Dive: Leases, versioned sets and CDC invalidationShow
Leases (Meta). On a miss, the cache gives the client a lease token. Only the holder of a valid token may set the key; a delete invalidates outstanding leases. This blocks the stale-set race (an old reader's set is rejected) and limits stampedes, because other clients are told to wait briefly instead of all hitting the database.
Versioned sets. Store a version (row version or update timestamp) with the cached value, and use a compare-and-set or Lua script to write only if the new version is higher. Old reads can never overwrite newer data.
CDC-driven invalidation. Instead of every writer remembering to delete keys, tail the database log and delete or update keys for each changed row. It catches writes from all services, batch jobs and manual fixes. The cost is a little delay (log to invalidation is usually tens of milliseconds to seconds) and a pipeline to run. Meta's mcsqueal daemon does this for MySQL commits. See Change Data Capture.
Deep Dive: How Meta keeps a look-aside cache consistent at scaleShow
The setting. "Scaling Memcache at Facebook" (Nishtala and colleagues, NSDI 2013) describes a demand-filled look-aside cache, which is cache-aside under another name, serving billions of requests per second in front of sharded MySQL. Web servers read memcache, query MySQL on a miss and fill the cache. Writers update MySQL and then delete the key, never set it, because deletes are idempotent.
Leases fix two problems with one mechanism. On a miss, memcached returns a 64-bit lease token bound to that key. The client must present the token when it sets the value. If a delete for that key arrives in the meantime, memcached invalidates the token, and the late set is rejected. That closes the stale-set race described earlier on this page. The same token rations reloads: memcached hands out a token for a given key at most once every 10 seconds, and other clients that miss during that window are told to wait briefly and retry, by which time the token holder has usually filled the cache. The paper reports that leases cut peak database query rates for a hot workload from about 17,000 per second to about 1,300 per second. Some clients can also accept a value marked as slightly stale (kept briefly after a delete) instead of waiting, which is a deliberate freshness-for-latency trade.
Invalidation from the commit log. Rather than trusting every writer to send deletes to every cache cluster, Meta runs invalidation daemons (mcsqueal) on the database hosts. They tail the MySQL commit log, extract the keys to delete from each committed transaction and broadcast the deletes, batched through the mcrouter proxy layer, to every cache cluster in the region. Because invalidation follows the commit log, it covers all writers and can be replayed after failures. This is the same principle as CDC-based invalidation on this page.
Cross-region read-your-writes. With one primary region for writes and replica regions that receive MySQL replication, a user in a replica region could write, then immediately read a stale value refilled from the lagging local replica. Meta's remedy is a remote marker: before the write, the web server sets a marker key in the local region. Reads that find the marker go to the primary region until replication catches up and the marker is deleted. The trade is extra cross-region latency for a short time after a write, only for keys that were just written.
Measuring consistency. Meta's later engineering writing on TAO cache consistency (2022) described a monitoring service, Polaris, that observes invalidation events and checks whether replicas of a cached value converge, reporting inconsistencies with their age. Using it to find and fix rare race bugs, Meta reported improving the measured share of consistent cache writes from about six nines to about ten nines. The lesson for any team: cache consistency improves when it is measured continuously, not argued about.
What to copy. You probably do not need memcache at Meta's scale, but the pieces carry over: delete instead of set, a token or version check on fills, invalidation driven by the commit log, a marker or session rule for read-your-writes, and continuous sampling of stale reads.
Key Takeaways#
- Cache-aside (app loads on miss, deletes on write) is the default: simple and resilient.
- Read-through moves loading into the cache layer; write-through keeps the cache fresh on every write at the cost of write latency.
- Write-behind gives the fastest writes but can lose data and lets the database lag.
- Write-around keeps write-only data out of the cache; refresh-ahead keeps hot keys from ever expiring.
- Write the database first, then delete the key, keep TTLs as a safety net, and pick strategies per workload.
- A strategy is two choices: how misses are filled and what writes do. State both, with a TTL and its reason.
- The stale-set race survives database-first deletes. Bound it with TTLs and close it with versioned sets, leases or CDC.
- Write-behind is only as durable as its pending-write buffer, so use a replicated log for anything that matters.
- Use refresh-ahead or probabilistic early expiration for a few hot keys, never for the whole dataset.