Skip to content
System design · Chapter 8 of 21 Day 6: When the Cache Causes Trouble

Day 6: When the Cache Causes Trouble

Goal: Experience a cache’s cold start under load, coalesce concurrent misses, stop a cascade via health checks, and test what an outage of the cache itself costs · Duration: approx. 75 min · Prerequisite: Day 5

Briefing

  • Yesterday the cache took 93% of the load off the database and, with an expensive query, sped up the system by a factor of 200. But that means the system now depends on the cache, even if the code calls it “optional”.
  • Anyone who runs a cache knows three problems:
Problem What happens
Cold start empty cache, all requests hit the database at once
Stampede many requests miss the same key at the same time and all ask the database
Cache gone “the cache may fail” is only true if the database can carry the full load
  • The expensive query from Day 5 (84 ms) stays on today, and k6 sends 500 requests per second. It goes away at the end of the day.

Drill 1: The Cold Start

Fill the cache, start the load, and flush the cache after ten seconds, as with a restart of Valkey or a big deploy:

# on s1
mkdir -p ~/sd/tag06 && cd ~/sd/tag06 && cp ~/sd/tag05/codes.txt ~/sd/tag05/schief.js .
sed -i 's/rate<0.01/rate<1/' schief.js
V="valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning"
for c in $(cat codes.txt); do curl -s -o /dev/null http://localhost/$c; done
(ZIEL=http://localhost RATE=500 DAUER=40s k6 run --quiet schief.js > k6-kalt.txt 2>&1 &)
sleep 10; $V flushall
for i in $(seq 1 10); do
  echo "$(date +%T) $(echo 'show stat' | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18 \
    | sed -n 3,4p | tr '\n' ' ') cache=$($V dbsize)"
  sleep 2
done
sleep 25
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped' k6-kalt.txt | sed 's/  */ /g'

Expected:

OK
21:15:48 s1,UP s2,UP  cache=0
21:15:50 s1,UP s2,UP 2/3  cache=51
21:15:55 s1,UP 1/3 s2,UP 1/3  cache=181
21:15:57 s1,UP 1/3 s2,DOWN  cache=246
21:15:59 s1,DOWN s2,DOWN  cache=304
21:16:07 s1,DOWN s2,DOWN  cache=476
 http_req_duration..............: avg=727.36ms min=234.53µs med=1.71ms max=11.69s p(90)=1.65s p(95)=7.42s
 http_req_failed................: 38.49% 6276 out of 16305
 http_reqs......................: 16305 334.232066/s
 dropped_iterations.............: 3696 75.763368/s

Expected shows only some of the loop’s lines. 38% errors. The cache fills at about 30 keys per second; the database cannot manage more at 84 ms per query. Much worse: after eleven seconds, HAProxy takes both instances out. From then on nobody answers anymore, not even for the half of the links that are already back in the cache.

Save your progress? Sign up for free

Drill 2: Coalescing Concurrent Misses

After the flush, a popular link is missed not once but by dozens of requests at the same time, and each one asks the database. Go’s singleflight package coalesces concurrent calls with the same key: one asks, all the others wait for its result.

# on s1
cd ~/kurz && cp cache.go /tmp/cache.go.alt
perl -0pi -e 's/\t"github.com\/valkey-io\/valkey-go"\n/\t"github.com\/valkey-io\/valkey-go"\n\t"golang.org\/x\/sync\/singleflight"\n/; s/\tcacheTTL = 10 \* time.Minute\n/\tcacheTTL = 10 * time.Minute\n\tladen   singleflight.Group \/\/ fasst gleichzeitige Fehltreffer pro Code zusammen\n/; s/\tvar ziel string\n\terr := db.QueryRow\(ctx, "SELECT url FROM links WHERE code = \$1", code\).Scan\(&ziel\)\n\tif err != nil \{\n\t\treturn "", err\n\t\}\n/\tv, err, _ := laden.Do(code, func() (any, error) {\n\t\tvar ziel string\n\t\terr := db.QueryRow(ctx, "SELECT url FROM links WHERE code = \$1", code).Scan(&ziel)\n\t\treturn ziel, err\n\t})\n\tif err != nil {\n\t\treturn "", err\n\t}\n\tziel := v.(string)\n/' cache.go
gofmt -w cache.go
diff /tmp/cache.go.alt cache.go
go mod tidy && go vet . && go build -o kurz .

Expected:

10a11
>   "golang.org/x/sync/singleflight"
17a19
>   laden    singleflight.Group // fasst gleichzeitige Fehltreffer pro Code zusammen
52,53c54,58
<   var ziel string
<   err := db.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
---
>   v, err, _ := laden.Do(code, func() (any, error) {
>       var ziel string
>       err := db.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
>       return ziel, err
>   })
56a62
>   ziel := v.(string)

Roll out with the loop from Day 4 and repeat the test from Drill 1:

Expected (abridged):

21:18:25 s1,DOWN s2,DOWN  cache=315
21:18:34 s1,DOWN 1/2 s2,DOWN 1/2  cache=552
21:18:36 s1,UP s2,UP  cache=590
 http_req_duration..............: avg=461.54ms min=221.16µs med=1.72ms max=8.61s p(90)=641.32ms p(95)=4.68s
 http_req_failed................: 37.84% 6698 out of 17697
 http_reqs......................: 17697 434.593943/s

Barely better: 37.8 instead of 38.5% errors. singleflight helps with the popular links, but most of the 1000 codes are missed by only a few requests, and each one still needs its 84 ms. And the instances keep getting kicked out. That is the real damage.

Save your progress? Sign up for free

Drill 3: The Health Check as Fire Accelerant

/readyz asks PostgreSQL with a one-second timeout. Under load, the ping waits for a free one of the four connections and arrives too late. HAProxy considers the instance dead, even though it could answer every link from the cache immediately. Being ready here means: the cache or the database answers.

# on s1
cat >> cache.go <<'EOF'

// cacheBereit meldet, ob der Cache antwortet. Dann kann die Instanz beliebte Links
// auch bei überlasteter Datenbank weiterleiten und bleibt im Load Balancer.
func cacheBereit(ctx context.Context) bool {
    return cache != nil && cache.Do(ctx, cache.B().Ping().Build()).Error() == nil
}
EOF
perl -0pi -e 's/\tif err := db.Ping\(ctx\); err != nil \{\n/\tif err := db.Ping(ctx); err != nil && !cacheBereit(ctx) {\n/' main.go
go vet . && go build -o kurz .

Roll out, repeat the test:

Expected (abridged):

21:20:29 s1,UP 1/3 s2,UP 1/3  cache=309
21:20:31 s1,DOWN s2,DOWN  cache=374
 http_req_failed................: 34.33% 5870 out of 17095

Still out. A thinking error that happens often in practice: both checks share ctx with a one-second timeout. The ping to the overloaded database uses up the whole second, after which the context has expired, and the cache check fails right along with it. First the fast check, then the slow one:

# on s1
perl -0pi -e 's/\tif err := db.Ping\(ctx\); err != nil && !cacheBereit\(ctx\) \{/\tif !cacheBereit(ctx) && db.Ping(ctx) != nil {/' main.go
sed -n 92,100p main.go
go vet . && go build -o kurz .

Expected:

func bereit(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := context.WithTimeout(r.Context(), time.Second)
    defer cancel()
    if !cacheBereit(ctx) && db.Ping(ctx) != nil {
        http.Error(w, "Datenbank nicht erreichbar", http.StatusServiceUnavailable)
        return
    }
    w.Write([]byte("bereit\n"))
}

Roll out, repeat the test:

Expected:

21:22:15 s1,UP s2,UP  cache=0
21:22:23 s1,UP s2,UP  cache=310
21:22:33 s1,UP s2,UP  cache=647
 http_req_duration..............: avg=980.42ms min=865.1µs med=2.54ms max=9.43s p(90)=5.53s p(95)=7.5s
 http_req_failed................: 0.00% 0 out of 14084
 http_reqs......................: 14084 338.089412/s
 dropped_iterations.............: 5917 142.038842/s

0 errors. Both instances stay in the whole time. Half of the requests are fast (median 2.5 ms, from the cache); the misses wait for the database, hence p95 of 7.5 s and dropped requests in k6. During the cold start the system is slow instead of broken. That is exactly the goal.

Save your progress? Sign up for free

Drill 4: And If Valkey Fails?

finde treats a broken cache like a miss. That sounds robust:

# on s1
for c in $(cat codes.txt); do curl -s -o /dev/null http://localhost/$c; done
(ZIEL=http://localhost RATE=500 DAUER=40s k6 run --quiet schief.js > k6-valkey.txt 2>&1 &)
sleep 10; ssh s3 "sudo systemctl stop valkey"
sleep 20; ssh s3 "sudo systemctl start valkey"
sleep 18
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped' k6-valkey.txt | sed 's/  */ /g'

Expected:

 http_req_duration..............: avg=2.12s min=929.37µs med=2.24ms max=28.79s p(90)=8.34s p(95)=19.52s
 http_req_failed................: 0.00% 0 out of 7333
 http_reqs......................: 7333 152.93568/s
 dropped_iterations.............: 12668 264.201445/s

No errors, but throughput drops from 500 to 153 per second, and p95 is at 20 seconds. Two thirds of the planned requests never even arrive. For users, that is an outage. And after the restart, Valkey is empty: the outage is followed by the cold start from Drill 1. A cache that takes 93% of the load off the database is no longer an optimization but load-bearing. Either the database can carry the load without it, or the cache needs the same fault tolerance as the database.

Save your progress? Sign up for free

Drill 5: Back to the Cheap Query

# on s1
export PGPASSWORD=lab-kurz-123
psql -h s3 -U kurz -d kurz -c "ALTER ROLE kurz RESET enable_indexscan" \
  -c "ALTER ROLE kurz RESET enable_bitmapscan" -c "ALTER ROLE kurz RESET enable_indexonlyscan"
for s in s1 s2; do ssh $s "sudo systemctl restart kurz"; done
psql -h s3 -U kurz -d kurz -tAc "select setting from pg_settings where name = 'enable_indexscan'"

Expected:

ALTER ROLE
ALTER ROLE
ALTER ROLE
on

Save your progress? Sign up for free

Exercise: Speed drills

  1. Show how many keys are in the cache and how many of them expire within the next minute. Target time: 2 min
  2. Check /readyz on both instances directly, without HAProxy. Target time: 30 s
  3. Show how often kurz on s1 logged a cache error in the last 10 minutes. Target time: 1 min

Solution

# on s1
$V dbsize
for k in $($V --scan --pattern 'link:*'); do $V ttl $k; done | awk '$1 < 60' | wc -l
for s in s1 s2; do curl -s http://$s:8080/readyz; done
journalctl -u kurz --since -10min --no-pager | grep -c 'cache get'

Save your progress? Sign up for free

Checkpoint

# on s1
grep -c 'singleflight\|cacheBereit' ~/kurz/cache.go

Expected: 3 or more

# on s1
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18 | sed -n 3,4p

Expected: s1,UP and s2,UP

Challenge

After the outage in Drill 4, the cache refilled in about 20 seconds. All these keys have the same TTL. What happens ten minutes later? Check the expiry times and make sure it doesn’t happen.

Hint: valkey-cli ttl shows a key’s remaining lifetime.

Solution

# on s1
for k in $($V --scan --pattern 'link:*' | head -400); do $V ttl $k; done | sort -n \
  | awk 'NR==1 {min=$1} {a[NR]=$1} END {print "min", min, "max", a[NR], "n", NR}'

Expected:

min 542 max 562 n 400

400 keys expire within 20 seconds, again every ten minutes: a scheduled cold start. The fix: add jitter to the TTL.

# on s1
cd ~/kurz
perl -0pi -e 's/Ex\(cacheTTL\)/Ex(streuen(cacheTTL))/; s/\t"log"\n/\t"log"\n\t"math\/rand\/v2"\n/' cache.go
cat >> cache.go <<'EOF'

// streuen verteilt die Ablaufzeiten zufällig auf 80–120 % der TTL, damit Schlüssel,
// die gleichzeitig gefüllt wurden, nicht alle gleichzeitig ablaufen.
func streuen(ttl time.Duration) time.Duration {
    return ttl*8/10 + rand.N(ttl*4/10)
}
EOF
go vet . && go build -o kurz .

Roll out, flush the cache, fetch 400 codes and measure again:

# on s1
$V flushall >/dev/null
for c in $(head -400 ~/sd/tag06/codes.txt); do curl -s -o /dev/null http://localhost/$c; done
for k in $($V --scan --pattern 'link:*'); do $V ttl $k; done | sort -n \
  | awk 'NR==1 {min=$1} {a[NR]=$1} END {print "min", min, "max", a[NR], "n", NR}'

Expected:

min 473 max 715 n 400

Now the expirations are spread over four minutes.

Save your progress? Sign up for free

Clean-up

# on s1
rm -f ~/sd/tag06/k6-*.txt

singleflight, the new readiness check and the jittered TTL stay. The indexes are allowed again.

Interview note

  • What is a cache stampede, and what helps? Many concurrent misses on the same key. Fixes: coalesce requests (singleflight, request coalescing), locks per key, refresh values in the background before they expire, add jitter to the TTL.
  • May a health check test a dependency? Only if the instance truly cannot work without it. An instance that can answer from the cache is ready, even if the database is slow.
  • Is a cache optional? Only as long as the system carries the load without it. Otherwise it is part of capacity planning and needs fault tolerance.

Enterprise note

  • Large systems warm caches before switching over (cache warming) or shift traffic gradually, so that a completely empty cache never faces full load.
  • An overloaded service should rather reject quickly than keep clients waiting for a long time. How that works is shown on Day 12 (backpressure) and Day 13 (circuit breaker).

Contents

More