Cache-aside with jitter and singleflight

You can combine cache-aside, jitter and singleflight so concurrent menu reads share a rebuild instead of stampeding MySQL.

Learning outcomes

  • Explain how cache-aside serves assembled restaurant menus from Redis while keeping MySQL authoritative.
  • Calculate jittered TTLs and distinguish expiration spikes from concurrent misses for the same key.
  • Explain how singleflight coordinates concurrent cache rebuilds within one Go process.
  • Apply fail-open behaviour, loader error handling and delete-based invalidation to keep cached menu data correct.

The restaurant menu endpoint assembles items, sizes, option groups, options and prices from MySQL. Every request currently repeats that work, even when the menu has not changed. You need a cache that avoids those repeated reads without allowing customers to see outdated stock information.

The menu read path

Cache-aside is a caching pattern in which your application checks Redis before loading data from its original source. Your application controls both cache population and invalidation. Redis does not decide when your database should be queried.

For a restaurant menu, the read path has four parts:

  1. Build a cache key using the restaurant ID.
  2. Request the cached value using Redis GET.
  3. On a cache miss, assemble the menu from MySQL.
  4. Store the successfully loaded menu in Redis using SET with an expiration.

A useful key is menu:42 for restaurant 42. The exercise uses the pattern menu:{restaurant_id} so each restaurant has a separate cached menu.

A cache hit avoids the database queries used to assemble that menu. A cache miss follows the existing database loading path and stores the resulting menu for subsequent requests.

The following fragment shows the important distinction between returning a cached menu and loading a fresh one:

go
data, err := rdb.Get(ctx, key).Bytes()
if err == nil && json.Unmarshal(data, &menu) == nil {
    return menu, true, nil
}

menu, err = loadMenu(ctx)
if err != nil {
    return nil, false, err
}

The second return value indicates whether the result came from Redis. A successful database load after a cache miss is still a miss, even though the caller receives a valid menu.

Notice that the cache helper does not need to understand restaurant menus. It needs a key, a destination for the result and a loader function. The restaurant service supplies the loading logic.

Redis values and expiration

Redis stores bytes, so your application needs JSON encoding in Go to convert structured Go values into a representation that Redis can store.

A restaurant menu contains nested data. For example, an item has sizes and option groups, and an option can contain prices for different sizes. Storing the fully assembled menu means the next request can retrieve the complete structure with one Redis read.

The storage operation follows this shape:

go
encoded, err := json.Marshal(menu)
if err == nil {
    _ = rdb.Set(ctx, key, encoded, ttl).Err()
}

When reading, decode the stored JSON into the expected Go type. If the cached JSON is invalid, treat it as a cache miss and load a fresh value. Returning corrupted cached data would make a serialization problem visible to customers.

Redis supports automatic expiration through a time to live (TTL). The application supplies the duration when writing a value.

For example:

go
ttl := 10 * time.Minute

err := rdb.Set(ctx, "menu:42", encoded, ttl).Err()

After the TTL expires, Redis removes the key automatically. The next request must rebuild the menu from MySQL.

Expiration limits how long an unchanged cache entry can survive. However, a fixed TTL creates another problem when many entries are populated around the same time.

TTL jitter

Jitter adds a random duration to the base TTL of each cache entry.

Imagine that a deployment or a traffic spike causes many restaurant menus to enter Redis during the same period. If every menu receives exactly ten minutes of TTL, those entries can expire together.

The next wave of requests encounters many cache misses at approximately the same time. MySQL then receives a burst of menu-loading queries.

Jitter spreads those expiration times across an interval instead of synchronizing them.

Suppose your base TTL is 600 seconds and your maximum jitter is 120 seconds. Each successful cache write receives a duration between 600 seconds and 720 seconds.

You can calculate the additional duration with math/rand/v2:

go
extra := time.Duration(0)

if maxJitter > 0 {
    n := rand.Int64N(int64(maxJitter) + 1)
    extra = time.Duration(n)
}

ttl := baseTTL + extra

The zero-jitter check matters because rand.Int64N requires a positive upper bound. A cache configured without jitter must still work.

For the menu cache in the exercise, the configuration uses a ten-minute base TTL with up to 60 seconds of jitter. The restaurant-list cache uses a 60-second TTL without jitter.

The cache tests also exercise a smaller configuration: a 100-second base TTL with 20 seconds of jitter. They create 40 keys and check that their observed TTLs stay within the expected bounds and are not all equal.

Jitter does not guarantee that two entries will never expire together. It only makes synchronized expiration less likely.

More importantly, jitter does not solve every cache miss problem. Two hundred requests can still miss the same popular menu key at the same moment.

Concurrent cache misses

A popular restaurant can receive many menu requests at nearly the same time. If its menu key expires, each request may independently start assembling the same menu from MySQL.

Go handles concurrent requests using separate goroutines. Without coordination, each goroutine can perform the same database work.

This is a thundering herd. It can happen even when your cache has a reasonable TTL.

Consider a menu key requested by 20 concurrent goroutines:

  • Every goroutine calls Redis GET.
  • Every request observes a cache miss.
  • Every request starts loading the same menu.
  • The requests compete for database connections and execute duplicate queries.

Your database receives work that only one request needed to perform.

A Mutex can protect shared state from concurrent access. However, one mutex around all cache rebuilds can also serialize requests for unrelated restaurant IDs. A request rebuilding restaurant 42 would block another request rebuilding restaurant 75.

You need coordination based on the cache key.

Singleflight coordination

The Go package golang.org/x/sync/singleflight provides singleflight for this problem.

A singleflight.Group coordinates concurrent function calls using a key. When multiple goroutines call Do with the same key while an execution is in progress, one function runs and the other callers receive its result.

A simplified example:

go
var group singleflight.Group

value, err, _ := group.Do(key, func() (any, error) {
    menu, err := loadMenu(ctx)
    if err != nil {
        return nil, err
    }
    return menu, nil
})

The key identifies the work being coordinated. Requests for menu:42 share one execution, while requests for menu:75 can load independently.

For a cache rebuild, the coordinated operation should cover the expensive loading and successful cache population. Otherwise, you may still perform unnecessary work outside the coordinated operation.

There is an important distinction between singleflight and a mutex.

A mutex controls access to a critical section. Singleflight controls duplicate function execution and shares its result with waiting callers. You do not need every caller to execute the loading function after the first caller finishes.

The cache test launches 20 concurrent requests for the same key. The expected loader count is exactly one. After those requests finish, another read should be a cache hit without running the loader again.

Result ownership

Singleflight returns one result to all callers. That does not mean every handler should freely modify the same mutable Go object.

Consider what happens when the loaded value is a pointer to a menu structure. If every waiting caller receives the same pointer, one handler could accidentally change data another handler is reading.

Keep caller-owned results separate. For cached JSON, each caller can decode the bytes into its own destination. When singleflight returns a loaded value, copy or decode it into the destination supplied by that caller.

The generic cache API in the exercise exposes two loading functions:

  • GetOrLoad returns an error when loading fails.
  • GetOrLoadResult also reports whether the result was a cache hit.

That boolean is useful because the HTTP handlers need to distinguish a cache hit from a successful rebuild.

Loader errors

A failed database load is not a valid cached result.

Suppose a menu loader encounters context.DeadlineExceeded. If the cache stores an error response or an empty menu as though it were valid data, subsequent customers may receive that result even after MySQL recovers.

The correct behaviour is to return the loader error and leave the key uncached.

On the next request, the application should attempt the load again.

The same rule applies to the singleflight operation. If the shared loader fails, waiting callers receive the error. The failure must not become a successful cache entry.

Context and Redis failures

Pass the request's context through the cache operations and loader. The context carries cancellation and deadline information. If the request is cancelled, the work using that context can stop instead of continuing unnecessarily.

For example:

go
data, err := rdb.Get(ctx, key).Bytes()
if err != nil {
    // Continue through the loader path.
}

menu, err := loadMenu(ctx)
if err != nil {
    return nil, false, err
}

A missing key is a normal cache miss. With go-redis, Redis reports this using redis.Nil.

A different class of problem occurs when the Redis connection is unavailable or an operation times out. Redis may be down while MySQL is still healthy.

The menu endpoint should not become unavailable because an optimization has failed.

This is called Fail-open behavior behaviour. The application uses MySQL to load the menu even when Redis cannot serve the cached value.

For this exercise, the Redis fail-open behaviour covers both sides of the cache operation:

  • If Redis cannot return a cached value, continue to the loader.
  • If Redis cannot store a successfully loaded value, return the loaded value anyway.

The loader's own errors remain real errors. Failing open does not mean ignoring a MySQL failure or inventing a successful menu response.

A test creates a Redis client pointing to 127.0.0.1:1. The cache must still return the loader's menu with ID: 9 and no error. Another test verifies that an ordinary loader failure returns an error and that the next read tries loading again.

Cache invalidation

A menu can change before its TTL expires. For example, restaurant staff can mark an item out of stock.

The database is the source of truth. If MySQL changes but Redis still contains the old menu, customers can continue seeing the item as available.

Cache invalidation means removing the cached entry when a write changes the data represented by that entry.

The safe ordering for a stock update is:

  1. Verify that the authenticated restaurant staff member owns the restaurant.
  2. Update the item's stock in MySQL.
  3. After the database update succeeds, delete the restaurant's menu key.
  4. Let the next menu request rebuild the cached value.

The write and invalidation concern different systems. MySQL decides whether the stock update succeeded. Redis only holds a copy of the menu.

For example, the invalidation operation is a Redis DEL:

go
err := rdb.Del(ctx, menuKey).Err()

Deleting the key is preferable to modifying the cached JSON in place. An in-place modification can race with a concurrent request that already loaded an older menu from MySQL and is about to write that result to Redis.

There is also an important error rule in this exercise. A failed cache deletion must not turn an otherwise successful stock update into a failed stock update.

If MySQL accepted the change, the update succeeded. A Redis deletion failure can leave stale data until expiration, but it must not cause the handler to report that the database write failed.

Cache eligibility

Not every read is a good candidate for the same cache entry.

The assembled menu belongs to one restaurant. Its key can therefore identify the restaurant without including a particular customer.

The restaurant listing has a different structure. It supports cursor pagination, so the first page and a later page represent different results.

The exercise caches only the first page of the restaurant listing. A request with a cursor bypasses the cache entirely.

The resulting behaviour is:

RequestCache behaviour
First menu readCache miss, load and store menu
Second menu readCache hit
Menu read after stock invalidationCache miss, rebuild menu
First restaurant-list pageEligible for caching
Restaurant-list page with cursorBypass cache

For menu and first-page list responses, the handler reports the result through the X-Cache response header:

X-Cache: MISS

A subsequent read from Redis reports:

X-Cache: HIT

Cursor-page responses must not include X-Cache. They did not use the list cache, so reporting a cache hit or miss would be misleading.

Cache monitoring

Caching changes where your application spends its time. You need evidence to determine whether it is reducing repeated database work.

The cache hit rate measures the share of eligible reads served from Redis rather than rebuilt through the loader.

A basic calculation is:

cache hit rate = cache hits / (cache hits + cache misses)

For example, if 80 of 100 eligible reads are cache hits, the hit rate is 80%.

A low hit rate can indicate short TTLs, unsuitable cache keys or a frequently changing resource. A high hit rate does not prove that the cached data is correct. You still need reliable invalidation.

The next module, Metrics, logging and timeouts, gives you the instrumentation needed to observe cache hits and misses alongside the other API metrics.

Common failure patterns

Several mistakes can make a cache appear to work while violating the behaviour your application needs.

Treating every Redis error as a database error: A Redis connection failure should fall through to MySQL. If the cache returns an error instead, the unreachable-Redis test fails.

Caching loader failures: A failed loader must not populate the key. Otherwise, a second request can receive an invalid cached result instead of trying again.

Using jitter as concurrency control: Jitter spreads expiration times across different entries. It does not prevent multiple requests for the same expired key from starting identical loads. The concurrent-miss test exposes this mistake.

Using one global lock for every key: This can unnecessarily block independent restaurant menu rebuilds. Coordinate by cache key instead.

Invalidating before the database update succeeds: A concurrent reader could rebuild the cache using the old committed value and store it again. Update MySQL first, then delete the corresponding key.

Caching cursor pages as the first page: A cached first page cannot represent the result of a later cursor request. The list-cache test checks that cursor pages do not become cache hits.

Assuming a successful write guarantees successful invalidation: Redis can fail independently of MySQL. The stock update must remain successful after the database update, even when deleting the cache entry fails.

The menu cache boundary

The exercise, Menu cache and stock updater, brings these ideas together around the existing restaurant service.

You will work with two cache policies: a jittered menu cache and a first-page restaurant-list cache. The menu cache stores the complete assembled result, while the list cache bypasses requests that contain a cursor.

The generic cache helper handles Redis operations, JSON values, TTLs, loader execution and singleflight coordination. The restaurant service supplies the cache keys and database loaders. The stock update path changes MySQL before invalidating the affected menu.

Keep the distinction between a successful database load, a cache miss and a Redis failure clear. They represent different outcomes, even when the customer receives a valid menu in all three cases.

Check your understanding

Question 1 of 4

Twenty goroutines request menu:42 at the same time. All 20 Redis reads miss, and the menu loader succeeds. The requests share one singleflight group. What should happen?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go, Redis, go-redis v9).

Finished Lesson 6.1?