StackPractices
intermediate By Mathias Paulenko

Cache Strategy Decision Template

Fill-in template for choosing and documenting a cache strategy per service: decision matrix, TTL rules, invalidation plan, and rationale record.

Topics: caching

Overview

Teams that add caching ad hoc end up with five services using five different strategies and no written reason for any of them — and the first incident review turns into “who picked write-back for billing data?” This template gives each service a single decision record: you fill in the workload facts, walk the decision tree, and commit the rationale where the next engineer can find it.

Use it when introducing caching to a service, when a hot path outgrows its current strategy, or when an incident review asks why a key behaves the way it does. Skip it for a single hot endpoint — the caching strategies recipe covers implementation patterns once you know which strategy you picked.

Decision flowchart for choosing a cache strategy: fast-changing data goes to no-cache; write-heavy workloads split into write-back or write-through depending on loss tolerance; predictable access goes to refresh-ahead; everything else defaults to cache-aside.

1. Decision Record

Copy this block into your service docs (or the ADR) and fill it in. Every field is there to force a fact, not a preference.

CACHE STRATEGY DECISION RECORD
──────────────────────────────────────────────────────
Service / endpoint : <service-name> — <cacheable resource>
Data owner         : <team>
Date / author      : <YYYY-MM-DD> / <name>

WORKLOAD FACTS (measured, not guessed)
  Read:write ratio       : <e.g., 95:5>
  Peak QPS on resource   : <measured>
  p95 latency budget     : <ms added by cache miss>
  Data change frequency  : <how often the row changes>
  Staleness tolerance    : <seconds/minutes acceptable>
  Loss tolerance         : <can a lost write be reconstructed?>

DECISION
  Strategy               : <no-cache | cache-aside | read-through |
                            write-through | write-back | refresh-ahead>
  TTL                    : <seconds> + jitter <±%>
  Invalidation           : <explicit delete | TTL | tags | pub/sub | versioned>
  Stampede protection    : <none | lock | single-flight | SWR>
  Fallback on cache down : <serve stale | fail open to DB | fail closed>

RATIONALE
  Why this strategy      : <one sentence tied to the facts above>
  Rejected alternatives  : <what you ruled out and why>
  Review trigger         : <metric/date that should reopen this decision>

Two fields do most of the work: staleness tolerance and loss tolerance. If a stale answer is harmless, almost any strategy works and you optimize for simplicity. If it isn’t, you narrow to write-through or no-cache almost immediately. Loss tolerance is the write-back gate — if a crashed cache node would permanently drop a write, write-back is off the table no matter how attractive the throughput looks.

2. Decision Matrix and Tree

2.1 Strategy Comparison

Strategy       | Read perf | Write perf | Consistency | Complexity | Use when
───────────────┼───────────┼────────────┼─────────────┼────────────┼──────────────────
No-cache       | Baseline  | Baseline   | Strong      | None       | Data changes fast
Cache-aside    | Fast      | Baseline   | Eventual    | Low        | General purpose
Read-through   | Fast      | Baseline   | Eventual    | Medium     | Read-heavy
Write-through  | Fast      | Slower     | Strong      | Medium     | Read + write parity
Write-back     | Fastest   | Fast       | Weak        | High       | Write-heavy, tolerate loss
Refresh-ahead  | Fast      | Baseline   | Eventual    | High       | Predictable access

2.2 Decision Tree

1. Does data change faster than the cache fills?
   YES → No-cache. Stop here.
   NO  → Continue.

2. Is the workload write-heavy (>70% writes)?
   YES → Can you tolerate lost writes on a cache crash?
         YES → Write-back
         NO  → Write-through
   NO  → Continue.

3. Is the access pattern predictable (known hot keys)?
   YES → Refresh-ahead
   NO  → Continue.

4. Do you need strong consistency on writes?
   YES → Write-through
   NO  → Continue.

5. Default:
   → Cache-aside (simplest, most flexible)

The tree is deliberately biased toward the simplest adequate strategy. Every step past question 1 adds operational cost — background refreshers, pub/sub invalidation, lock coordination — that has to be earned by the workload facts from section 1.

3. Strategy Reference

3.1 No-Cache

Skip caching when data changes so fast the hit rate would be near zero anyway (live counters, in-flight order state) or when a stale answer is worse than a slow one (authorization checks, pricing at checkout). A query that takes 8 ms and changes every second isn’t a cache problem.

3.2 Cache-Aside (Lazy Loading)

The application owns the cache: read-through on miss, populate, invalidate on write. It’s the default because failure modes are benign — a broken cache means slow queries, not wrong ones.

import json
import redis

r = redis.Redis(host="localhost", port=6379, db=0)

def get_user(user_id: str) -> dict:
    cached = r.get(f"user:{user_id}")
    if cached is not None:
        return json.loads(cached)

    user = db.query("SELECT * FROM users WHERE id = %s", user_id)
    r.setex(f"user:{user_id}", 3600, json.dumps(user))
    return user

def update_user(user_id: str, data: dict) -> dict:
    user = db.update("users", user_id, data)
    r.delete(f"user:{user_id}")  # invalidate, don't update — avoids write races
    return user

Strengths: caches only what’s actually read; survives cache restarts gracefully. Weaknesses: every miss costs a round trip plus a query; a window of staleness exists between the DB write and the invalidate. When that window becomes a thundering herd on a hot key, the cache stampede prevention pattern is the fix — locks, single-flight or stale-while-revalidate depending on your latency tolerance.

3.3 Read-Through

Same flow as cache-aside, but the cache layer owns the loader. Application code calls get and never sees the miss logic — useful when many callers share one data source and you want the read path uniform.

import json
from typing import Any, Callable

def read_through_get(key: str, loader: Callable[[str], Any], ttl: int = 3600) -> Any:
    cached = r.get(key)
    if cached is not None:
        return json.loads(cached)

    data = loader(key)
    if data is not None:
        r.setex(key, ttl, json.dumps(data))
    return data

user = read_through_get(
    f"user:{user_id}",
    loader=lambda k: db.query("SELECT * FROM users WHERE id = %s", k.split(":")[1]),
    ttl=3600,
)

In real deployments this lives inside the cache client (Guava’s LoadingCache, a Redis module, or a thin wrapper like the one above). Strengths: identical read semantics everywhere, no duplicated miss logic. Weaknesses: the first request after expiry still pays full latency, and the loader becomes a hidden dependency worth logging.

3.4 Write-Through

Every write hits the database and the cache synchronously; reads only touch the cache. The cache is never stale — at the price of doubling write latency and making writes depend on cache availability.

def write_through_update(user_id: str, data: dict) -> dict:
    user = db.update("users", user_id, data)
    r.setex(f"user:{user_id}", 3600, json.dumps(user))
    return user

Strengths: strong consistency, warm cache at all times, no stale reads. Weaknesses: every write waits on two systems; if Redis is down you either buffer writes (reintroducing write-back complexity) or fail. Pick it when reads vastly outnumber writes and a stale answer is a real bug — permissions, entitlements, inventory counts.

3.5 Write-Back (Write-Behind)

Writes land in the cache and flush to the database asynchronously. It’s the fastest path and the only one that absorbs write bursts — and the only one that can silently lose data.

import json
import threading
import time
from collections import deque

write_queue: deque[tuple[str, dict]] = deque(maxlen=10_000)

def write_back_update(user_id: str, data: dict) -> dict:
    r.setex(f"user:{user_id}", 3600, json.dumps(data))
    write_queue.append((f"user:{user_id}", data))
    return data

def flush_writes() -> None:
    while True:
        while write_queue:
            key, data = write_queue.popleft()
            db.update("users", data["id"], data)
        time.sleep(0.1)

threading.Thread(target=flush_writes, daemon=True).start()

The deque(maxlen=) bound matters: an unbounded queue silently becomes a memory leak under sustained load. Even with the bound, a full queue drops writes — decide in the decision record whether that’s acceptable, and persist the queue (Redis list, WAL) if it isn’t. Strengths: fastest writes, natural batching, smooths spikes. Weaknesses: a cache crash loses the unflushed window; recovery and ordering get complicated fast. Reserve it for telemetry, view counters and other data you can lose or rebuild.

3.6 Refresh-Ahead

Instead of waiting for expiry, the cache refreshes popular keys before they miss — usually when the remaining TTL crosses a threshold. The refresh-ahead cache pattern covers dedicated implementations; the sketch shows the trigger logic.

import json
import threading

def refresh_ahead_get(key: str, loader, ttl: int = 3600) -> dict:
    cached = r.get(key)
    if cached is not None:
        if r.ttl(key) < ttl * 0.2:
            threading.Thread(
                target=lambda: r.setex(key, ttl, json.dumps(loader(key))),
                daemon=True,
            ).start()
        return json.loads(cached)

    data = loader(key)
    r.setex(key, ttl, json.dumps(data))
    return data

Strengths: hot keys never miss. Weaknesses: you spend reloads on keys that may never be read again, and every “hot” judgment that’s wrong is wasted database work. Needs the same stampede protection as cache-aside if several instances race to refresh — the naive version above refreshes once per request inside the threshold window; in production gate it with a SET NX refresh lock or let a single-flight do the dedup.

4. TTL and Jitter

4.1 TTL Selection

Data type              | TTL         | Reasoning
───────────────────────┼─────────────┼──────────────────────────────
User profile           | 30-60 min   | Changes infrequently
Product catalog        | 5-15 min    | Changes occasionally
Search results         | 1-5 min     | New content appears
Session data           | 15-30 min   | Security timeout
Rate limit counters    | 1-60 sec    | Real-time accuracy
Configuration          | 1-5 min     | Quick rollout of changes
Computed aggregations  | 5-60 min    | Depends on update frequency
Reference data         | 24 hours    | Rarely changes

4.2 Rules

  • Never run without a TTL unless the entry has explicit invalidation wired up — an immortal key is a stale-read bug waiting for its moment.
  • Start at roughly 2x the expected update frequency, then let hit ratio tune it.
  • Add jitter of ±10% so a batch of keys written together doesn’t expire together — the second kind of stampede.
  • Shorter TTL plus explicit invalidation beats a long TTL plus hope.
import json
import random

def set_cache_with_jitter(key: str, value: dict, base_ttl: int) -> None:
    ttl = base_ttl + random.randint(-base_ttl // 10, base_ttl // 10)
    r.setex(key, ttl, json.dumps(value))

5. Invalidation Plan

5.1 Methods

Method              | When to use                    | Complexity
────────────────────┼────────────────────────────────┼──────────
Explicit delete     | Write-through, cache-aside     | Low
TTL expiration      | All strategies                 | None
Tag-based           | Group invalidation             | Medium
Pub/sub invalidation| Multi-instance cache           | Medium
Version-based       | Schema or format changes       | Low

5.2 Tag-Based Invalidation

def cache_with_tags(key: str, value: str, tags: list[str], ttl: int = 3600) -> None:
    r.setex(key, ttl, value)
    for tag in tags:
        r.sadd(f"tag:{tag}", key)

def invalidate_tag(tag: str) -> None:
    keys = r.smembers(f"tag:{tag}")
    if keys:
        r.delete(*keys)
    r.delete(f"tag:{tag}")

cache_with_tags("user:123", user_data, tags=["users", "team:5"])
invalidate_tag("team:5")  # wipes every team-5 entry

The decision record’s Invalidation field should name the method and the trigger (“explicit delete on update_user” / “pub/sub on team.updated”), not just “TTL”. TTL-only invalidation means your staleness bound is the TTL itself — fine for reference data, lazy for anything user-facing. The cache eviction policy template covers what happens when memory pressure starts evicting keys before their TTL.

6. Common Pitfalls

6.1 Stampede on a Hot Key

A lock without an ownership check creates a second bug: the holder can time out, lose the lock to TTL expiry, then delete the new owner’s lock. Release with an atomic check-and-delete, and bound the retry loop — unbounded recursion or polling turns a slow load into a pile of stuck requests.

import json
import time
import uuid

def get_with_lock(key: str, loader, ttl: int = 3600) -> dict:
    cached = r.get(key)
    if cached is not None:
        return json.loads(cached)

    lock_key = f"lock:{key}"
    token = str(uuid.uuid4())
    if not r.set(lock_key, token, nx=True, ex=30):
        for _ in range(10):              # bounded poll, not recursion
            time.sleep(0.1)
            cached = r.get(key)
            if cached is not None:
                return json.loads(cached)
        return loader(key)               # give up waiting — load directly

    try:
        data = loader(key)
        r.setex(key, ttl, json.dumps(data))
        return data
    finally:
        # release only if we still own the lock
        r.eval(
            'if redis.call("get",KEYS[1])==ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end',
            1, lock_key, token,
        )

6.2 Cold Cache After Restart

A flush or deploy empties the cache and every request misses at once. The cache warmup runbook covers pre-heating; lazy strategies additionally need a loader that survives a burst of simultaneous misses (see 6.1).

6.3 Writes That Bypass the Cache Layer

Migrations, admin tools and batch jobs update the database without telling the application, so invalidation never fires. Either route those writes through the same invalidation channel (pub/sub, CDC trigger) or accept a staleness window and write it into the decision record.

7. Worked Example

A realistic record for a product-catalog service: read-heavy, prices updated by an admin tool, stock counts that can’t be stale.

CACHE STRATEGY DECISION RECORD
──────────────────────────────────────────────────────
Service / endpoint : catalog-api — GET /products/{id}
Data owner         : commerce-platform
Date / author      : 2026-10-14 / a.reyes

WORKLOAD FACTS
  Read:write ratio       : 97:3
  Peak QPS on resource   : 1,800
  p95 latency budget     : 40 ms (miss budget: 120 ms)
  Data change frequency  : prices ~daily; stock ~2/min
  Staleness tolerance    : prices 60 s; stock ~0 s
  Loss tolerance         : none — stock writes are final

DECISION
  Strategy               : split — cache-aside for product payload,
                           no-cache for /stock
  TTL                    : 300 s + jitter ±10%
  Invalidation           : pub/sub on product.updated; explicit
                           delete on price_changed
  Stampede protection    : single-flight on top-100 products
  Fallback on cache down : fail open to DB (read path) —
                           stock endpoints already bypass cache

RATIONALE
  Why this strategy      : 97:3 ratio and 60 s price tolerance make
                           cache-aside the cheapest adequate fit;
                           stock's zero staleness tolerance keeps it
                           uncached rather than adding write-through
                           complexity to every inventory write
  Rejected alternatives  : write-through (write path doesn't justify
                           it at 3%), refresh-ahead (catalog tail is
                           too cold for proactive reload)
  Review trigger         : hit ratio < 90% or stock queries joining
                           the cache path in any PR

Two things worth noticing in that record: the strategy isn’t one word — splitting the hot payload from the zero-tolerance stock field is a better answer than forcing write-through on everything — and the review trigger is a metric someone can actually check, not “revisit next quarter”. Split decisions like this are the rule in practice: a single endpoint rarely serves one homogeneous workload, and caching the product payload and the stock field identically would either make stock stale or make prices uncacheable. When two fields inside one resource have different tolerances, record them as two decisions — one row per workload, not per service.

8. When to Revisit the Decision

A cache strategy ages with the workload. Reopen the record when:

  • The read:write ratio drifts by an order of magnitude — a 95:5 service that becomes 60:40 may have outgrown cache-aside.
  • A new dependency bypasses the invalidation channel (new admin tool, new batch job).
  • Hit ratio drops below the trigger you wrote down for more than a few days.
  • The loader’s latency changes materially — a slow dependency behind a short TTL is a stampede setup, not a cache.
  • You’re about to scale horizontally — single-flight and in-memory assumptions change the moment a second instance exists.
  • Ownership moves: the team that wrote the record isn’t the team the on-call runbook now points at.

The record makes these reviews cheap: instead of re-deriving the choice from scratch, you check which facts changed and update just those fields. When nothing changed, that’s also a result — the review closes with a date stamp and the decision stands.

Further Reading

Frequently Asked Questions

When should I use write-back instead of write-through?

Only when write throughput is the bottleneck and a lost write can be rebuilt or doesn't matter — analytics events, view counters, non-critical telemetry. Write-back trades durability for speed, so it's a business decision as much as a technical one: if losing the last N seconds of writes is acceptable, the record should say so explicitly. Never use it for financial transactions, user data or anything that must survive a crash.

How do I handle invalidation when multiple services update the same data?

Pub/sub invalidation: services publish an invalidation message on update, and every instance subscribed to the channel drops its copy. That decouples producers from cache owners and keeps local caches consistent without direct calls. Keep the payload minimal — a key or tag name, not the whole row — and log misses on the subscriber side, because a dropped message means stale data until TTL.

What TTL should I use for frequently changing data?

Start at about twice the expected update frequency and add ±10% jitter so mass expirations don't synchronize. If updates arrive every 5 minutes, try a 10-minute TTL, then watch hit ratio and staleness metrics and adjust. For data that changes unpredictably, short TTLs (30-60 s) plus explicit invalidation on write paths usually beats any fixed number.

Should I cache at the application level or use a CDN?

Both — they cover different layers. A CDN caches HTTP responses at the edge for public, cacheable content; an application cache (Redis, Memcached) holds computed data, query results and session state. CDN rules belong in the CDN cache rules template; this template decides the application-side strategy.

How do I measure whether the cache is working?

Watch hit ratio (hits / total gets), miss rate, eviction count and the p95 latency of the load path. A healthy hot-key cache sits above ~90% hits; anything lower means the TTL is too short, the cache is too small, or the keys aren't actually hot. Track these per strategy so the decision record's review trigger has a number to fire on — Redis INFO and your metrics pipeline already expose most of it.