Subscribe

Caching strategies: cache-aside, write-through, TTLs and the thundering herd

Where to cache, how cache-aside and write-through differ, and how to stop a cache stampede in Go with singleflight, jittered TTLs and negative caching, tested with 1000 concurrent misses on shorty.

Caching strategies: cache-aside, write-through, TTLs and the thundering herd

A cache makes the fast path faster and adds a new way for everything to fall over. The fast part is easy. The hard parts are deciding what goes stale, for how long, and what happens in the second after a popular key expires and a thousand requests all go to the database at once. In this blog we will look at the common caching strategies, then write the redirect lookup for shorty in Go with cache-aside, singleflight, jittered TTLs and negative caching, and test it with a real stampede.

Level: intermediate. You should be comfortable with goroutines and context. I used Go 1.27.3, golang.org/x/sync v0.25.0, go-redis v9.23.0 and Redis 8.10 in Docker. shorty is the URL shortener from Designing a URL shortener from requirements to scale, and the numbers below come from System design basics: latency, throughput and back-of-the-envelope estimates.

Requirements

What the cache has to do for shorty:

  • GET /{code} should not touch Postgres for popular links.
  • A deleted link must stop redirecting within a minute or so. Exact is nice, but not required.
  • Bots that try random codes should not hit Postgres on every try.
  • When a hot link expires from the cache, Postgres should see one query for it. Not one per waiting request.
  • If Redis is down, redirects still work, just slower.

Estimates

From the SD-1 post: about 2,000 redirects a second at peak, reads to writes at 100:1, and a million or so hot links taking roughly 200 MB in Redis. Links never change once created. That last fact matters more than any number, because the classic cache problem is keeping a changing value in sync, and shorty mostly doesn't have one. The only change is a delete.

Where to cache

There are more layers than people think. In order, from the user inward:

browser / CDN       301 is cached by browsers forever, 302 is not
load balancer       usually nothing
shorty process      in-memory map, fastest, but one per instance
Redis               shared by every instance, ~75 µs a lookup on my Mac
Postgres            shared_buffers keeps hot rows in memory anyway

I'd skip the browser for shorty: a 301 would save us traffic but we would lose every click count and could never delete a link for real, because browsers keep it. A per-process cache is tempting, but with two or more instances a delete only clears it on one of them. Redis in the middle is the usual answer, and it's what shorty already does.

High-level picture

   GET /Ab3dE9x
        |
        v
  +------------+   1. GET shorty:link:Ab3dE9x   +---------+
  |  shorty    |------------------------------->|  Redis  |
  |  Resolve() |<-------------------------------|         |
  +-----+------+        hit: return URL         +---------+
        |                                            ^
        | miss: singleflight.DoChan(code)            | 3. SET with jittered TTL
        v                                            |
  +------------+   2. SELECT url FROM links ...      |
  |  Postgres  |-------------------------------------+
  +------------+   (one query per code, however many waiters)

Cache-aside, write-through and the others

Cache-aside (lazy loading) is what the picture shows. The app reads the cache, on a miss reads the database and fills the cache. The cache only ever holds what someone asked for. It's simple and survives a cache outage, which is why it's the default almost everywhere.

Write-through means every write goes to the database and the cache together. The first read after a write is a hit. The cost is that you cache things nobody reads, and you have two writes that can half fail.

Write-behind writes to the cache and flushes to the database later. Fast, but you can lose data. I wouldn't use it for links. shorty does something like it for click counts though, it adds them up in memory and flushes every 5 seconds, and losing a few clicks on a crash is fine there.

For shorty I use cache-aside for reads plus a small bit of write-through: when a link is created we put it in Redis straight away, because people usually click their new link within seconds to test it.

The stampede, shown

First I wanted to see the problem with my own eyes. The test store pretends to be Postgres under load, every query takes 50 ms, and counts its calls.

type slowStore struct {
    calls atomic.Int64
    urls  map[string]string
}

func (s *slowStore) GetURL(ctx context.Context, code string) (string, error) {
    s.calls.Add(1)
    select {
    case <-time.After(50 * time.Millisecond):
    case <-ctx.Done():
        return "", ctx.Err()
    }
    u, ok := s.urls[code]
    if !ok {
        return "", ErrNotFound
    }
    return u, nil
}

Then 1000 goroutines ask for the same cold code, once with plain cache-aside and once with the resolver below.

=== RUN   TestStampede
    linkcache_test.go:82: 1000 concurrent misses: naive=1000 database calls, singleflight=1
--- PASS: TestStampede (0.11s)

A thousand queries for one row. That is the thundering herd, and honestly it looked worse in numbers then I expected. In production it shows up as a spike of identical queries right after a deploy, a Redis restart or a hot key expiring.

The resolver in Go

This is the whole deep dive, so here is all of it. The Cache interface is the same one shorty has in internal/cache.

package linkcache

import (
    "context"
    "errors"
    "log/slog"
    "math/rand/v2"
    "time"

    "golang.org/x/sync/singleflight"
)

type Cache interface {
    Get(ctx context.Context, code string) (url string, ok bool, err error)
    Set(ctx context.Context, code, url string, ttl time.Duration) error
    Delete(ctx context.Context, code string) error
}

type Store interface {
    GetURL(ctx context.Context, code string) (string, error)
}

var ErrNotFound = errors.New("link not found")

// notFound is cached for unknown codes so bots scanning random codes
// don't reach Postgres every time.
const notFound = "\x00notfound"

type Resolver struct {
    Cache       Cache
    Store       Store
    TTL         time.Duration // e.g. 24h
    Jitter      float64       // 0.1 means TTL +/- 10%
    NotFoundTTL time.Duration // e.g. 1m; 0 disables negative caching
    DBTimeout   time.Duration // limit for the shared database call
    Log         *slog.Logger

    group singleflight.Group
}

func (r *Resolver) jittered(ttl time.Duration) time.Duration {
    if r.Jitter <= 0 {
        return ttl
    }
    f := 1 + r.Jitter*(2*rand.Float64()-1) // between 1-j and 1+j
    return time.Duration(float64(ttl) * f)
}

func (r *Resolver) Resolve(ctx context.Context, code string) (string, error) {
    u, ok, err := r.Cache.Get(ctx, code)
    if err != nil {
        r.Log.WarnContext(ctx, "cache get failed, using the database", "code", code, "err", err)
    }
    if ok {
        if u == notFound {
            return "", ErrNotFound
        }
        return u, nil
    }

    ch := r.group.DoChan(code, func() (any, error) {
        // Not the caller's ctx: if the first caller hangs up, the other
        // waiters still want the answer. Bound it with our own timeout.
        dbctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.DBTimeout)
        defer cancel()

        u, err := r.Store.GetURL(dbctx, code)
        if errors.Is(err, ErrNotFound) && r.NotFoundTTL > 0 {
            r.set(dbctx, code, notFound, r.NotFoundTTL)
            return "", err
        }
        if err != nil {
            return "", err
        }
        r.set(dbctx, code, u, r.jittered(r.TTL))
        return u, nil
    })

    select {
    case res := <-ch:
        if res.Err != nil {
            return "", res.Err
        }
        return res.Val.(string), nil
    case <-ctx.Done():
        return "", ctx.Err() // this caller gave up; the load carries on for the others
    }
}

func (r *Resolver) set(ctx context.Context, code, u string, ttl time.Duration) {
    if err := r.Cache.Set(ctx, code, u, ttl); err != nil {
        r.Log.WarnContext(ctx, "cache set failed", "code", code, "err", err)
    }
}

// Created is the write-through half.
func (r *Resolver) Created(ctx context.Context, code, u string) {
    r.set(ctx, code, u, r.jittered(r.TTL))
}

// Deleted runs after the database delete.
func (r *Resolver) Deleted(ctx context.Context, code string) error {
    r.group.Forget(code)
    return r.Cache.Delete(ctx, code)
}

A Redis error is logged and treated as a miss, so Redis being down means slower redirects and not failed ones.

Why not the caller's context

The obvious way to write this is group.Do with the caller's ctx passed straight into the query. It is what I would write without thinking. I wanted to see what it does, so I changed that one line to context.WithTimeout(ctx, r.DBTimeout) and ran the test where one impatient caller with a 5 ms timeout starts the load and a second, patient caller joins it.

    linkcache_test.go:114: want exactly one error (the impatient caller), got context deadline exceeded and context deadline exceeded
FAIL

The first caller's timeout cancelled the query for everybody who was waiting on it. Under load that means one client with a short timeout can fail requests for a hundred others. context.WithoutCancel plus our own DBTimeout fixes the shared part, and DoChan with a select lets each caller still give up on their own deadline.

Jittered TTLs

Singleflight protects one key. It doesn't help when ten thousand keys were cached in the same minute, for example after a Redis restart when cache is empty, and so they all expire in the same minute 24 hours later. Spreading the TTL by plus or minus 10% fixes that. The test caches 10k keys at once and counts how many expire in each hour.

10k keys cached at once with 24h +/- 10%, expiring per hour:
map[21:826 22:2078 23:2097 24:2046 25:2073 26:880]

Without jitter all 10,000 expire in the same second. With it, about 2,000 an hour, which Postgres won't even notice.

Negative caching

A missing code is cached for one minute as a special value. Five lookups of a code that doesn't exist made one database call in the test. Keep that TTL short, a link created right after a miss would otherwise look missing for too long. This is also why I use a sentinel string and not an empty one: an empty URL is a bug, and I want to be able to tell them apart.

Running it against real Redis

The in-memory cache is good for tests, but I wanted to see it on Redis too. The test runs only when REDIS_ADDR is set.

docker run -d --name cache-demo-redis -p 127.0.0.1:6379:6379 redis:8-alpine
REDIS_ADDR=127.0.0.1:6379 go test -race -v ./...
docker rm -f cache-demo-redis
=== RUN   TestRedisStampede
    linkcache_test.go:146: redis: database calls=1, key TTL=24h14m0s
--- PASS: TestRedisStampede (0.24s)

One database call for 500 concurrent misses, and the key got a TTL of 24h14m, so the jitter is doing its job.

Trade-offs

Singleflight only works inside one process. With four shorty instances a cold hot key can still cause four queries. That's fine for us. If it wasn't, the next step is a short Redis lock (SET key NX PX 3000) around the load, but then you have to handle the lock holder dying and I'd avoid it until the numbers say you need it.

Cache-aside can also put back a stale value: a reader loads a link, a delete happens and clears Redis, then the reader writes the old value back. For shorty the TTL limits that window and a deleted link redirecting for a bit longer is acceptable. For data like balances or permissions it is not, and there I'd keep the value out of the cache or version the keys.

Last tip: put a metric on cache hits and misses from day one. Without it you only find out the cache stopped working when Postgres CPU goes up.