Sub topic 17
Choosing a Strategy for Your Workload
This chapter assumes you know the patterns from earlier chapters: cache-aside, read-through, write-through, write-around and write-back. It also assumes you know TTL, eviction, invalidation and stampedes. Here you combine them. The goal is a repeatable way to pick a design, instead of a favorite pattern applied everywhere.
Start with the workload, not the pattern
Every caching decision comes down to a few measurable facts. Collect them before you choose anything.
- Read/write ratio. How many reads happen per write? A ratio near 1 gives a cache little to work with, because every write invalidates or updates an entry.
- Access skew. Do a few keys get most of the traffic? Skewed traffic gives high hit ratios from a small cache. Uniform traffic over a huge key space does not.
- Staleness tolerance. How old may a value be before it causes harm? A product description can be an hour old. An account balance usually cannot.
- Cost of a miss. How slow or expensive is the source read? A 2 ms indexed lookup rarely justifies a cache. A 900 ms aggregate query does.
- Durability of writes. Can you lose the most recent writes if a node crashes?
- Re-read after write. Is freshly written data read again soon, or mostly never?
Cheap, fast sources and tight consistency requirements both argue against caching. Complexity is a cost too.
Matching patterns to workloads
| Workload shape | Good fit | Main risk |
|---|---|---|
| Read-heavy, tolerates some staleness | Cache-aside with TTL | Stale reads, stampede on hot expiry |
| Read-heavy, many services need the same loading logic | Read-through | Cache library becomes a hard dependency |
| Read-after-write must be fresh, moderate writes | Write-through | Slower writes, cache filled with data never read |
| Writes are rarely re-read (logs, bulk imports) | Write-around | First read after a write is always a miss |
| Very high write rate, can lose a little data | Write-back | Data loss if the cache fails before flushing |
| Low read/write ratio, fast source | No cache | None, which is the point |
Two of these deserve a closer look. Write-through and cache-aside with delete-on-write both keep reads fresh. The first pays at write time and may cache data nobody reads. The second pays on the next read. Choose by asking whether written data is usually read again soon.
Write-back is the only pattern here that can lose acknowledged writes. Use it only when the data is counters, telemetry or something else you can rebuild. Never use it for payments or orders.
A decision flow
The diagram shows the order in which to ask the questions. Cheap, disqualifying questions come first.
Encoding the decision
The function below turns the workload facts into recommendations. It is a teaching aid, not a replacement for judgment. Its value is that it forces you to write the facts down.
from dataclasses import dataclass
@dataclass
class Workload:
reads_per_write: float # read/write ratio
max_staleness_s: float # 0 means reads must be exact
reread_after_write: bool # is written data read again soon?
can_lose_writes: bool # is losing recent writes acceptable?
miss_cost_ms: float # latency of reading the source
def recommend(w: Workload) -> list[str]:
notes = []
if w.miss_cost_ms < 5 or w.reads_per_write < 2:
notes.append("Cache may not pay off: fast source or low read/write ratio.")
if w.max_staleness_s > 0:
notes.append(f"Cache-aside with TTL near {int(w.max_staleness_s)}s.")
elif w.reread_after_write:
notes.append("Write-through, or cache-aside with delete on write.")
else:
notes.append("Write-around; reads fill the cache on demand.")
if w.can_lose_writes and w.reads_per_write < 1:
notes.append("Write-heavy and loss-tolerant: write-back is an option.")
return notes
catalog = Workload(50, 300, False, False, 400)
for line in recommend(catalog):
print(line)For the catalog workload, the output is a single line: Cache-aside with TTL near 300s.
Worked examples
Product catalog
Reads outnumber writes by about 50 to 1. A price may be five minutes stale. The database query joins several tables and takes about 400 ms. Cache-aside with a 300-second TTL fits. Add per-key locking for the hottest products, because a popular product expiring causes many simultaneous misses.
User profile with read-after-write
A user edits their profile and expects to see the change on the next page load. A short TTL alone breaks this, so on every write, update the database and then delete the cache entry. If many services write profiles, move the logic behind a write-through layer so no writer can forget the invalidation.
Page-view counters
Millions of increments arrive per minute, and losing a few seconds of counts is fine. Accumulate increments in the cache and flush them to the database in batches. That is write-back. Accept that a crash loses the unflushed batch.
Reports generated nightly
The data changes once a day, and many users request the same report. Skip the application cache logic and send HTTP caching headers with max-age and an ETag. Browsers and CDNs absorb the load.
Combining layers
Real systems use several caches at once. A common stack is a CDN for public assets, an application cache for query results, and the database's own buffer cache. Each layer adds its own staleness. If the CDN holds a response for 10 minutes and the application cache holds its data for 5 minutes, a reader can see data up to 15 minutes old. Sum the TTLs along the path when you state a freshness guarantee.
Prefer caching the layer closest to the user for data that is identical for everyone. Cache closer to the source for data that depends on the user or needs controlled invalidation.
Common errors
- Choosing by habit. Using cache-aside everywhere, including data that must be exact.
- Caching without measuring. Ship the cache with hit ratio, latency and eviction counters from day one. If the hit ratio stays low, the design is wrong or the keys are badly shaped.
- Ignoring skew. A cache sized for 10% of the data helps only if that 10% holds most of the traffic.
- Tuning TTL by guess. Set TTL from the staleness tolerance you wrote down, not from a round number.
- Forgetting failure. Decide what happens when the cache is down. Reads should fall back to the source, and the source must survive the extra load.
Starting simple
Begin with cache-aside and a TTL. It is the easiest pattern to reason about, and a failed cache only costs speed. Move to a more complex pattern only when a measured problem justifies it. Examples are stale reads after writes, slow writes, or a write rate the database cannot sustain. Each step up adds a failure mode, so move one step at a time and measure after each change.
Exercise
An order-status page shows data that must reflect a customer's latest change on the very next load. Writes are moderate, and the status is re-read often after each write. Which pattern do you choose, and which pattern do you reject?
Show answer
Choose write-through, or cache-aside with delete-on-write, because both keep the next read fresh and the data is re-read soon. Reject cache-aside with only a TTL, since a stale value could be served until expiry, and reject write-back, since losing an acknowledged order update is unacceptable.
Exercise
A CDN caches a page for 10 minutes, and your application cache holds the underlying data for 5 minutes. What is the worst-case staleness a reader can see, and how would you reduce it?
Show answer
Up to 15 minutes, since the CDN can fetch the page just before the application cache refreshes and hold it for its full TTL. Reduce it by shortening one TTL, by purging the CDN entry on writes, or by using ETag validation so the CDN revalidates instead of waiting for expiry.