# Caching: patterns, and the hard part, invalidation

> A cache trades freshness for speed. Cache-aside, write-through and TTLs cover most needs, and invalidation is where the bugs live.

Published 2026-11-20 · Language: en · Tags: architecture, caching

A cache stores the result of expensive work so the next request is fast. It always costs something: the data may be out of date. Good caching is deciding how stale is acceptable.

 

## Cache-aside

 

The application checks the cache first. On a miss it loads from the source, stores the result and returns it. This is the most common pattern because the cache is optional: if it is empty or down, the app still works.

 

```python
cache = {}

def get_user(user_id, load):
    if user_id in cache:
        return cache[user_id]
    value = load(user_id)      # slow source of truth
    cache[user_id] = value
    return value

print(get_user(1, lambda uid: {"id": uid, "name": "Ada"}))
```

 

## Write-through and write-behind

 

**Write-through** updates the cache and the source together, so reads are fresh but writes are slower. **Write-behind** writes to the cache first and to the source later, which is fast but can lose data if the cache fails before flushing.

 

## Expiry with TTL

 

A time to live removes entries after a fixed time. It is the simplest safety net: even if you forget to invalidate, the data heals itself. Choose the TTL from how stale the business can tolerate.

 

## Invalidation

 

There is a famous joke that cache invalidation is one of the two hard problems in computing. The practical approaches are:

 

- **Delete on write**: when a record changes, remove its cache entry.
- **Versioned keys**: include a version or an updated timestamp in the key, such as `user:42:v7`. Old entries are simply never read again.
- **Short TTL** where exactness matters less than simplicity.

 

## Stampedes

 

When a popular key expires, hundreds of requests may recompute it at once and overload the source. Reduce the risk with a lock so only one request recomputes, by adding random jitter to TTLs, or by refreshing before expiry.

 

**What not to cache.** Personalised data under a shared key, anything that must be strongly consistent such as account balances, and responses that vary by a header you forgot to include in the key.

 

## Takeaway

 

Cache with a clear freshness rule, set a TTL as a safety net, and treat invalidation as part of the feature rather than an afterthought.

Source: https://tdphat.io.vn/blog/caching-patterns-and-invalidation
