Skip to content
System design · Chapter 7 of 21 Day 5: Caching with Valkey

Day 5: Caching with Valkey

Goal: Answer redirects from Valkey using the cache-aside pattern, measure the hit rate, and find out when a cache makes the system faster and when it only takes load off the database · Duration: approx. 75 min · Prerequisite: Day 4

Briefing

  • A URL shortener reads a lot and writes little, and most reads go to a few popular links. That is the ideal case for a cache: a copy of the frequently read data in a fast store in front of the database.
  • Cache-aside (also “lazy loading”): the app asks the cache first. On a hit, it is done. On a miss, it asks the database and stores the result in the cache with an expiry time (TTL).
  GET /<code> ──▶ kurz ──GET link:<code>──▶ Valkey ── hit ──▶ 302
                   │                          │
                   │                         miss
                   └───── SELECT url ─────▶ PostgreSQL ──▶ SET link:<code> EX 600 ──▶ 302
  • You measure two things today: how much load the cache takes off the database, and whether users notice anything.

Drill 1: The cache in the code

Valkey has an official Go client, valkey-go. The cache goes into its own file. If KURZ_CACHE is not set, everything stays as before:

# on s1
cd ~/kurz
cat > cache.go <<'EOF'
package main

import (
    "context"
    "errors"
    "log"
    "strconv"
    "time"

    "github.com/valkey-io/valkey-go"
)

// cache ist nil, wenn KURZ_CACHE nicht gesetzt ist.
// Dann geht jede Anfrage an PostgreSQL.
var (
    cache    valkey.Client
    cacheTTL = 10 * time.Minute
)

func initCache() {
    addr := env("KURZ_CACHE", "")
    if addr == "" {
        return
    }
    if s, err := strconv.Atoi(env("KURZ_CACHE_TTL", "600")); err == nil {
        cacheTTL = time.Duration(s) * time.Second
    }
    c, err := valkey.NewClient(valkey.ClientOption{
        InitAddress: []string{addr},
        Password:    env("KURZ_CACHE_PASSWORT", ""),
    })
    if err != nil {
        log.Fatalf("cache: %v", err)
    }
    cache = c
    log.Printf("%s: Cache %s, TTL %s", instanz, addr, cacheTTL)
}

// finde liefert die Zieladresse zu einem Code: erst aus dem Cache, sonst aus der
// Datenbank, und legt sie dann für cacheTTL im Cache ab (Cache-Aside).
func finde(ctx context.Context, code string) (string, error) {
    key := "link:" + code
    if cache != nil {
        ziel, err := cache.Do(ctx, cache.B().Get().Key(key).Build()).ToString()
        if err == nil {
            return ziel, nil
        }
        if !valkey.IsValkeyNil(err) {
            log.Printf("cache get: %v", err) // Cache gestört: weiter mit der Datenbank
        }
    }
    var ziel string
    err := db.QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
    if err != nil {
        return "", err
    }
    if cache != nil {
        set := cache.B().Set().Key(key).Value(ziel).Ex(cacheTTL).Build()
        err := cache.Do(ctx, set).Error()
        if err != nil && !errors.Is(err, context.Canceled) {
            log.Printf("cache set: %v", err)
        }
    }
    return ziel, nil
}
EOF

In main.go, weiterleiten now calls finde instead of asking the database itself, and main starts the cache:

# on s1
perl -0pi -e 's/\tvar ziel string\n\terr := db.QueryRow\(r.Context\(\), "SELECT url FROM links WHERE code = \$1",\n\t\tr.PathValue\("code"\)\).Scan\(&ziel\)\n/\tziel, err := finde(r.Context(), r.PathValue("code"))\n/; s/\tserve\(handler\)\n/\tinitCache()\n\tserve(handler)\n/' main.go
grep -n 'finde(r.Context\|initCache' main.go
go get github.com/valkey-io/valkey-go@latest && go mod tidy
go vet . && go build -o kurz . && grep valkey go.mod

Expected (abridged):

79: ziel, err := finde(r.Context(), r.PathValue("code"))
126:    initCache()
    github.com/valkey-io/valkey-go v1.0.80

Three decisions are built into finde:

Decision Why
Key link:<code> one prefix per kind of data, so that keys can be told apart later
Cache errors are not app errors if Valkey is impaired, kurz asks the database. The cache is allowed to fail
TTL 10 minutes a link never changes; the TTL only limits memory. For mutable data, it determines how long stale values remain visible

Roll out with the loop from Day 4, still without the cache:

# on s1
for s in s1 s2; do
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  scp -q kurz $s:/tmp/kurz
  ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done

Save your progress? Sign up for free

Drill 2: Realistic load

So far, k6 has called all 1000 codes equally often. In reality, a few links are clicked very often. Math.pow(Math.random(), 3) makes small values much more likely: the first 10% of the codes get almost half of the calls. Plus 95% reads instead of 90:

# on s1
mkdir -p ~/sd/tag05 && cd ~/sd/tag05 && cp ~/sd/tag01/codes.txt .
sed -e 's/Math.random() < 0.9/Math.random() < 0.95/' \
  -e 's/codes\[Math.floor(Math.random() \* codes.length)\]/codes[Math.floor(Math.pow(Math.random(), 3) * codes.length)]/' \
  ~/sd/tag01/mix.js > schief.js
grep -n 'pow\|0.95' schief.js | cut -c1-90

Expected:

21:  if (Math.random() < 0.95) {
22:    const code = codes[Math.floor(Math.pow(Math.random(), 3) * codes.length)];

From now on, you also measure how much work PostgreSQL has: xact_commit counts the completed transactions, read before and after:

# on s1
export PGPASSWORD=lab-kurz-123
Q="select xact_commit from pg_stat_database where datname = 'kurz'"
X0=$(psql -h s3 -U kurz -d kurz -tAc "$Q")
ZIEL=http://localhost RATE=1500 DAUER=30s k6 run --quiet schief.js \
  | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
X1=$(psql -h s3 -U kurz -d kurz -tAc "$Q"); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"

Expected:

 http_req_duration..............: avg=6.54ms min=906.39µs med=3.73ms max=162.7ms p(90)=13.93ms p(95)=22.4ms
 http_req_failed................: 0.00% 0 out of 44907
 http_reqs......................: 44907 1496.695168/s
DB-Transaktionen: 1472/s

Without a cache: every request is a transaction, 1472 per second.

Save your progress? Sign up for free

Drill 3: Cache on

The cache comes in via a drop-in, so that it can be switched off again with one command:

# on s1
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=KURZ_CACHE=s3:6379\nEnvironment=KURZ_CACHE_PASSWORT=lab-valkey-123\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/cache.conf >/dev/null && sudo systemctl daemon-reload"
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  ssh $s "sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
journalctl -u kurz --no-pager -n 3 | grep Cache | cut -c1-80

Expected:

Nov 22 21:03:28 s1 kurz[14955]: 2026/11/22 21:03:28 s1: Cache s3:6379, TTL 10m0s

Empty cache, counters at zero, the same measurement:

# on s1
V="valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning"
$V flushall >/dev/null; $V config resetstat >/dev/null
X0=$(psql -h s3 -U kurz -d kurz -tAc "$Q")
ZIEL=http://localhost RATE=1500 DAUER=30s k6 run --quiet schief.js \
  | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
X1=$(psql -h s3 -U kurz -d kurz -tAc "$Q"); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"
$V info stats | grep -E 'keyspace_(hits|misses)'
$V dbsize

Expected:

 http_req_duration..............: avg=5.99ms min=917.03µs med=3.58ms max=211.28ms p(90)=11.42ms p(95)=18.21ms
 http_req_failed................: 0.00% 0 out of 44875
 http_reqs......................: 44875 1495.707929/s
DB-Transaktionen: 109/s
keyspace_hits:41605
keyspace_misses:1023
1000
Without cache With cache
p95 22 ms 18 ms
Transactions in PostgreSQL 1472/s 109/s
Hit rate – 41,605 / 42,628 = 97.6%

The database has 93% less work. The remaining 109 per second are almost only the new links (5% of 1500 = 75/s) plus the 1023 misses, one per code on its first call. The users, on the other hand, barely notice anything: p95 drops from 22 to 18 ms. A second run right afterwards was even at 74 ms. No wonder: a cache hit is also a network call, to a machine that shares Valkey with PostgreSQL. As long as the database is not the bottleneck, a cache does not make the system faster. It makes it less loaded.

Save your progress? Sign up for free

Drill 4: When the query is expensive

Our query takes 0.1 ms because it goes via the primary key. Real queries are often more expensive: joins across several tables, calculations, calls to other services. You reproduce this by forbidding PostgreSQL to use indexes for the role kurz:

# on s1
psql -h s3 -U kurz -d kurz -c "ALTER ROLE kurz SET enable_indexscan = off" \
  -c "ALTER ROLE kurz SET enable_bitmapscan = off" -c "ALTER ROLE kurz SET enable_indexonlyscan = off"
psql -h s3 -U kurz -d kurz -c "explain analyze select url from links where code = 'MPKfz5D'" \
  | grep -E 'Seq Scan|Execution' | cut -c1-90
for s in s1 s2; do ssh $s "sudo systemctl restart kurz"; done

Expected:

ALTER ROLE
ALTER ROLE
ALTER ROLE
   ->  Parallel Seq Scan on links  (cost=0.00..3516.82 rows=1 width=31) (actual time=27.700..63.684 r
 Execution Time: 84.131 ms

84 ms instead of 0.1 ms: PostgreSQL now reads all 100,000 rows. The setting applies to new connections of the role, hence the restart. Now fill the cache once with all codes and measure at 500 requests per second:

# on s1
$V flushall >/dev/null
for c in $(cat codes.txt); do curl -s -o /dev/null http://localhost/$c; done
$V dbsize; $V config resetstat >/dev/null
ZIEL=http://localhost RATE=500 DAUER=30s k6 run --quiet schief.js \
  | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
$V info stats | grep -E 'keyspace_(hits|misses)'

Expected:

1000
 http_req_duration..............: avg=2.49ms min=947.39µs med=2.06ms max=59.28ms p(90)=3.72ms p(95)=4.73ms
 http_req_failed................: 0.00% 0 out of 15000
 http_reqs......................: 15000 499.980881/s
keyspace_hits:14283
keyspace_misses:0

Filling takes a good minute (1000 × 84 ms). After that: p95 4.7 ms, no errors, not a single miss. And without the cache?

# on s1
for s in s1 s2; do ssh $s "sudo mv /etc/systemd/system/kurz.service.d/cache.conf /tmp/ \
  && sudo systemctl daemon-reload && sudo systemctl restart kurz"; done
sleep 3
for r in 500 50; do
  echo "== ohne Cache $r/s"
  ZIEL=http://localhost RATE=$r DAUER=20s k6 run --quiet schief.js \
    | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
done

Expected:

== ohne Cache 500/s
 http_req_duration..............: avg=1.58s min=228.58µs med=547.96µs max=11.81s p(90)=8.77s p(95)=11.28s
 http_req_failed................: 79.33% 6628 out of 8354
 http_reqs......................: 8354 201.765258/s
== ohne Cache 50/s
 http_req_duration..............: avg=1.18s min=349.59µs med=949.6ms max=2.49s p(90)=2.34s p(95)=2.39s
 http_req_failed................: 18.19% 171 out of 940
 http_reqs......................: 940 45.161945/s

Without a cache, the system already fails at 50 requests per second. Little’s Law explains it: 50/s × 84 ms gives 4.2 concurrent queries, each wants two cores for the parallel scan, and s3 has two. With the cache, 500/s is no problem. Here the cache makes the system faster, by a factor of 200 at p95. The “without cache 500/s” measurement ran for 30 instead of 20 seconds, hence the different number.

Cache back on:

# on s1
for s in s1 s2; do ssh $s "sudo mv /tmp/cache.conf /etc/systemd/system/kurz.service.d/ \
  && sudo systemctl daemon-reload && sudo systemctl restart kurz"; done

Save your progress? Sign up for free

Exercise: Speed drills

  1. Show whether a specific code is in the cache and for how much longer. Target time: 1 min
  2. Calculate the hit rate from Valkey’s counters. Target time: 1 min
  3. Show how much memory Valkey uses. Target time: 30 s

Solution

# on s1
$V get link:MPKfz5D; $V ttl link:MPKfz5D
$V info stats | awk -F: '/keyspace_hits/ {h=$2} /keyspace_misses/ {m=$2} END {printf "%.1f %%\n", 100*h/(h+m)}'
$V info memory | grep used_memory_human

Save your progress? Sign up for free

Checkpoint

# on s1
ssh s2 systemctl show kurz -p Environment | grep -o 'KURZ_CACHE=[^ ]*'

Expected: KURZ_CACHE=s3:6379

# on s1
psql -h s3 -U kurz -d kurz -tAc "select setting from pg_settings where name = 'enable_indexscan'"

Expected: off (the expensive query stays for Day 6)

Challenge

With the cache, there is a new kind of error: a link is deleted in PostgreSQL, for example because it points to a phishing site. How long does kurz keep redirecting, and how do you fix that without emptying the whole cache?

Hint: Who knows that something has changed?

Solution

Up to 10 minutes (TTL), because the cache knows nothing about the deletion. Try it:

# on s1
C=$(curl -s -X POST http://localhost/api/links -d '{"url":"https://example.org/phishing"}' | jq -r .code)
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/$C
psql -h s3 -U kurz -d kurz -c "delete from links where code = '$C'"
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/$C
$V del link:$C
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/$C

Expected:

302
DELETE 1
302
1
404

After the deletion in the database, kurz keeps redirecting (302) until the key in the cache is deleted. Whoever changes something must change the cache too (“invalidation”). In a real app, that belongs in the same code that deletes: first the database, then DEL in the cache.

Save your progress? Sign up for free

Clean-up

Nothing. The cache and the expensive query stay for Day 6.

Interview note

  • When is a cache worth it? With many reads of a small set of rarely changed data and expensive sources. It always takes load off the source; it only gets faster if the source is slower than the path to the cache.
  • Cache-aside, read-through, write-through? With cache-aside, the app itself queries cache and database. With read-/write-through, a layer between the two does that. Cache-aside is the most common, because the cache is allowed to fail.
  • What is the hit rate, and what is a good one? Hits / (hits + misses). What is good depends on how expensive a miss is. At 84 ms per miss, every percent counts.

Enterprise note

  • In front of the Valkey cache there is often a CDN or a cache in the app itself (a few seconds, in memory). Each layer catches a part. A URL shortener can even answer redirects directly in the CDN.
  • Valkey is a single process. For high availability, there are replicas with Sentinel or Valkey Cluster with sharding. A cache that is allowed to fail (as here) often does not need that.

Contents

More