Skip to content
System design on Kubernetes · Chapter 7 of 20 Day 5: Cache with Valkey via an operator

Day 5: Cache with Valkey via an operator

Goal: Run a Valkey cluster with three shards via an operator, connect kurz to it, measure the hit rate and database load, fail a primary under load and see what a wrongly sized cache does · Duration: approx. 90 min · Prerequisite: Day 4

Briefing

  • In the predecessor course, a single Valkey ran on s3, with a password, set up by hand. kurz asks the cache first and the database only on a miss (cache-aside). The code is the same; only the address changes.
  • Today an operator takes over operations: the Valkey Operator from the Valkey project. It knows a ValkeyCluster resource and builds Pods, configuration, users and failover from it.

Caution: The Valkey Operator is young (version 0.9.0 from November 2026, API v1alpha1). The developers themselves write “not ready for production use”. It can only do Valkey Cluster with shards, no single server and no Sentinel. For a course that shows how an operator works, that is good enough; for production, check the current state before you commit.

  • A Valkey Cluster divides the keys into 16,384 slots, and each shard owns part of them. Each shard has a primary and, here, one replica. The client in kurz (valkey-go) detects cluster mode on its own and asks the right shard for each key.

Drill 1: Installing the operator

# on s1
# Helm repository of the Valkey project
helm repo add valkey https://valkey.io/valkey-helm
helm repo update valkey
# Which versions are there?
helm search repo valkey/valkey-operator --versions | head -4
# Install the operator into its own namespace
helm install valkey-operator valkey/valkey-operator --version 0.9.0 \
  -n valkey-operator-system --create-namespace
# Wait until it is running
kubectl -n valkey-operator-system rollout status deploy/valkey-operator
# The new resource types
kubectl get crd | grep valkey
# Which default images does the operator work with?
kubectl -n valkey-operator-system get deploy valkey-operator -o jsonpath='{.spec.template.spec.containers[0].args}{"\n"}'

Expected (abridged):

NAME                    CHART VERSION   APP VERSION DESCRIPTION
valkey/valkey-operator  0.9.0           v0.9.0      A Helm chart for the Valkey Operator
valkey/valkey-operator  0.8.0           v0.8.0      A Helm chart for the Valkey Operator
STATUS: deployed
deployment "valkey-operator" successfully rolled out
valkeyclusters.valkey.io     Namespaced   v1alpha1(storage)     2026-11-25T08:21:22Z
valkeynodes.valkey.io        Namespaced   v1alpha1(storage)     2026-11-25T08:21:22Z
["--leader-elect","--health-probe-bind-address=:8081","--metrics-bind-address=:8443","--metrics-secure=false","--default-valkey-image=valkey/valkey:9.0.0","--default-exporter-image=oliver006/redis_exporter:v1.88.0"]

The operator uses Valkey 9.0.0 if you specify nothing. The current version is 9.2.0; you set the version explicitly in the ValkeyCluster. A fixed image tag has a second advantage: the operator recognizes the version and checks whether every configuration line fits it.

Save your progress? Sign up for free

Drill 2: A cluster with three shards

kurz authenticates to Valkey with only a password, without a username. Valkey then uses the user default. The operator disables it unless you create it explicitly. So you create it, with a password from a Secret:

# on s1
# Working directory
mkdir -p ~/sdk/tag05 && cd ~/sdk/tag05
# Password for the Valkey user default (key = username)
kubectl -n kurz create secret generic cache-users --from-literal=default=lab-valkey-123
# The cluster: 3 shards, 1 replica each, 64 MB per node, LRU eviction
cat > cache.yaml <<EOF
apiVersion: valkey.io/v1alpha1
kind: ValkeyCluster
metadata:
  name: cache
  namespace: kurz
spec:
  image: valkey/valkey:9.2.0
  shards: 3
  replicasPerShard: 1
  config:
    maxmemory: 64mb
    maxmemory-policy: allkeys-lru
  resources:
    requests:
      cpu: 100m
      memory: 96Mi
    limits:
      memory: 128Mi
  scheduling:
    node:
      spread:
        shard:
          mode: Required
        primaries:
          mode: Preferred
  acl:
    users:
    - name: default
      password:
        secret:
          name: cache-users
          keys: [default]
      permissions: "~* &* +@all"
EOF
# Create
kubectl apply -f cache.yaml
# Wait until the operator reports Ready (at most 5 minutes)
for i in $(seq 60); do
  [ "$(kubectl -n kurz get valkeycluster cache -o jsonpath='{.status.state}')" = Ready ] && break; sleep 5
done
# State, Pods and Service
kubectl -n kurz get valkeycluster cache
kubectl -n kurz get pods -l app.kubernetes.io/name=valkey -o wide | awk '{print $1, $2, $3, $7}'
kubectl -n kurz get svc valkey-cache

Expected:

secret/cache-users created
valkeycluster.valkey.io/cache created
NAME    STATE   REASON           AGE
cache   Ready   ClusterHealthy   7m50s
NAME READY STATUS NODE
valkey-cache-0-0-0 2/2 Running s3
valkey-cache-0-1-0 2/2 Running s1
valkey-cache-1-0-0 2/2 Running s2
valkey-cache-1-1-0 2/2 Running s1
valkey-cache-2-0-0 2/2 Running s3
valkey-cache-2-1-0 2/2 Running s1
NAME           TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
valkey-cache   ClusterIP   None         <none>        6379/TCP   7m51s

Pod names: valkey-cache-<shard>-<node>-0. Node 0 is the primary at startup, node 1 the replica. The two rules under scheduling.node.spread:

Rule Effect Here
shard: Required primary and replica of a shard never on the same node hard: a node failure never takes both copies
primaries: Preferred the primaries on different nodes if possible soft

Happened during testing: With primaries: Required, the cluster was still Degraded with PodUnschedulable after seven minutes: the three replicas had been scheduled first and all sat on s1. The primary of shard 2 was not allowed next to its replica on s1 (anti-affinity), but the hard spread rule demanded exactly s1, because s2 and s3 already had a primary. Two hard rules that contradict each other depending on the order are a trap. After switching to Preferred, the cluster was Ready in 45 seconds. The primaries now sit on s2 and twice on s3; that is the price of the soft rule.

valkey-cache is a headless Service without a ClusterIP: its DNS name resolves to the Pod addresses. A cluster client needs only any one node; it learns the rest from the cluster itself.

Save your progress? Sign up for free

Drill 3: Looking into the cluster

# on s1
# valkey-cli in the "server" container of the first Pod, logged in as default
V="kubectl -n kurz exec valkey-cache-0-0-0 -c server -- valkey-cli -a lab-valkey-123 --no-auth-warning"
# State of the cluster
$V cluster info | grep -E 'cluster_state|cluster_slots_ok|cluster_known_nodes|cluster_size'
# Who is primary (master) and which slots does it have?
$V cluster nodes | awk '{print $2, $3, $9}' | sed 's/@[0-9]*//' | sort -k2
# Eviction policy
$V config get maxmemory-policy

Expected:

cluster_state:ok
cluster_slots_ok:16384
cluster_known_nodes:6
cluster_size:3
10.42.4.28:6379 master 10923-16383
10.42.2.39:6379 master 5462-10922
10.42.4.27:6379 myself,master 0-5461
10.42.0.53:6379 slave
10.42.0.54:6379 slave
10.42.0.55:6379 slave
maxmemory-policy
allkeys-lru

Three primaries share all 16,384 slots in equal parts; three replicas (slave) follow them. allkeys-lru: when memory is full, the least recently used key goes. For a cache, that is the right choice; the default noeviction would reject new writes.

Save your progress? Sign up for free

Drill 4: The baseline without a cache

As in the predecessor course, you measure with skewed load: 95 % redirects, and a few links are clicked very often. Math.pow(Math.random(), 3) makes small indexes much more likely.

# on s1
# Codes and manifest from yesterday
cp ../tag04/codes.txt ../tag04/kurz.yaml .
# schief.js: 95 % reads, codes unevenly distributed
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)]/' \
  ../tag04/mix.js > schief.js
# Check the two changed lines
grep -n 'pow\|0.95' schief.js | cut -c1-90
# Function xact: committed transactions of the database kurz
xact() { kubectl -n kurz exec db-1 -c postgres -- psql -d kurz -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
# Counter value, 30 s at 1500/s through the Gateway, counter value
X0=$(xact)
ZIEL=http://172.16.0.126 RATE=1500 DAUER=30s k6 run --quiet schief.js 2>/dev/null \
  | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
X1=$(xact); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"

Expected:

21:  if (Math.random() < 0.95) {
22:    const code = codes[Math.floor(Math.pow(Math.random(), 3) * codes.length)];
 http_req_duration..............: avg=43.06ms min=2.07ms med=28.94ms max=396.76ms p(90)=99.64ms p(95)=130.79ms
 http_req_failed................: 0.01% 6 out of 43617
 http_reqs......................: 43617 1451.508504/s
DB-Transaktionen: 1324/s

Without a cache, almost every request is a transaction (DB-Transaktionen = DB transactions).

Save your progress? Sign up for free

Drill 5: Cache on

Two settings: the address into the ConfigMap, the password from the cluster’s Secret:

# on s1
# KURZ_CACHE into the ConfigMap, KURZ_CACHE_PASSWORT from the Secret cache-users
python3 - <<'EOF'
s = open("kurz.yaml").read()
s = s.replace('  KURZ_CODELAENGE: "7"\n', '  KURZ_CODELAENGE: "7"\n  KURZ_CACHE: valkey-cache:6379\n', 1)
s = s.replace("        - name: KURZ_DB\n",
              "        - name: KURZ_CACHE_PASSWORT\n"
              "          valueFrom:\n"
              "            secretKeyRef:\n"
              "              name: cache-users\n"
              "              key: default\n"
              "        - name: KURZ_DB\n", 1)
open("kurz.yaml", "w").write(s)
EOF
# Difference from yesterday
diff ../tag04/kurz.yaml kurz.yaml
# Apply; the new environment variable changes the Pod template, so the Deployment rolls out again
kubectl apply -f kurz.yaml >/dev/null && kubectl -n kurz rollout status deploy/kurz | tail -1
# Do the new Pods report the cache?
kubectl -n kurz logs -l app=kurz --tail=-1 | grep Cache

Expected (abridged):

8a9
>   KURZ_CACHE: valkey-cache:6379
43a45,49
>         - name: KURZ_CACHE_PASSWORT
>           valueFrom:
>             secretKeyRef:
>               name: cache-users
>               key: default
deployment "kurz" successfully rolled out
2026/11/25 08:31:17 kurz-57d69c849d-fhc2f: Cache valkey-cache:6379, TTL 10m0s
2026/11/25 08:31:19 kurz-57d69c849d-vwxq5: Cache valkey-cache:6379, TTL 10m0s

A sed with multi-line inserts becomes unreadable here; the small Python script is clearer. Now the same measurement, plus hits and misses, summed over all six nodes. --cluster call sends a command to every node:

# on s1
# Reset the statistics of all nodes
$V --cluster call 127.0.0.1:6379 CONFIG RESETSTAT >/dev/null
# The same measurement as in Drill 4
X0=$(xact)
ZIEL=http://172.16.0.126 RATE=1500 DAUER=30s k6 run --quiet schief.js 2>/dev/null \
  | grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/  */ /g'
X1=$(xact); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"
# Sum hits and misses over all nodes
$V --cluster call 127.0.0.1:6379 INFO stats | grep -E 'keyspace_(hits|misses)' | tr -d '\r' \
  | awk -F: '{s[$1]+=$2} END {print "hits", s["keyspace_hits"], "misses", s["keyspace_misses"]}'
# Keys per node
$V --cluster call 127.0.0.1:6379 DBSIZE | tail -6

Expected:

 http_req_duration..............: avg=27.64ms min=1.73ms med=17.65ms max=333.05ms p(90)=63.82ms p(95)=85.02ms
 http_req_failed................: 0.00% 3 out of 44192
 http_reqs......................: 44192 1472.762985/s
DB-Transaktionen: 113/s
hits 40943 misses 1029
127.0.0.1:6379: 331
10.42.2.39:6379: 344
10.42.0.54:6379: 344
10.42.0.55:6379: 325
10.42.4.28:6379: 325
10.42.0.53:6379: 331
without cache with Valkey Cluster Predecessor course: without / with
p95 131 ms 85 ms 22 / 18 ms
Transactions in PostgreSQL 1324/s 113/s 1472 / 109/s
Hit rate – 40,943 / 41,972 = 97.5 % 97.6 %

The same hit rate as on the VMs, the same relief for the database of more than 90 %. The keys are spread evenly across the three shards, about 330 each, and every replica has exactly as many as its primary. That p95 is higher in the cluster than on the VMs is something you have known since Day 3: Gateway and overlay network cost their share.

Save your progress? Sign up for free

Drill 6: A primary fails

Under load, the primary of shard 0 disappears. The Valkey Cluster should promote its replica, and kurz should fall back to the database on cache errors.

# on s1
# valkey-cli on a Pod that does not get deleted
V="kubectl -n kurz exec valkey-cache-1-0-0 -c server -- valkey-cli -a lab-valkey-123 --no-auth-warning"
# 60 s load in the background
(ZIEL=http://172.16.0.126 RATE=1500 DAUER=60s k6 run --quiet schief.js > k6-failover.txt 2>&1 &)
# After 10 s, starting value of the transactions and time
sleep 10; X0=$(xact); date +%T
# Delete the primary of shard 0
kubectl -n kurz delete pod valkey-cache-0-0-0 --wait=false
# Ten times every 4 s: cluster state and transactions per second since the deletion
for i in $(seq 10); do
  sleep 4
  printf "%s %s xact/s=%s\n" $(date +%T) "$($V cluster info | grep cluster_state | tr -d '\r')" $(( ($(xact) - X0) / (i*4) ))
done
# Wait for the end of the load and show the result
sleep 12
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' k6-failover.txt | sed 's/  */ /g'
# New roles
$V cluster nodes | awk '{print $2, $3, $9}' | sed 's/@[0-9]*//' | sort -k2
# What did kurz log during that time? Addresses masked, counted
kubectl -n kurz logs -l app=kurz --since=90s --tail=-1 | cut -c21- \
  | sed -E 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+/ADDR/g' | sort | uniq -c | sort -rn | head -4

Expected (abridged):

08:32:28
pod "valkey-cache-0-0-0" deleted from kurz namespace
08:32:33 cluster_state:ok xact/s=130
08:32:46 cluster_state:ok xact/s=121
08:33:10 cluster_state:ok xact/s=136
08:33:27 cluster_state:ok xact/s=114
 http_req_duration..............: avg=32.92ms min=1.48ms med=19.97ms max=2.52s p(90)=73.82ms p(95)=99.95ms
 http_req_failed................: 0.02% 25 out of 89050
 http_reqs......................: 89050 1483.570036/s
10.42.0.53:6379 master 0-5461
10.42.4.28:6379 master 10923-16383
10.42.2.39:6379 myself,master 5462-10922
10.42.0.54:6379 slave
10.42.0.55:6379 slave
10.42.4.29:6379 slave
     25 weiterleiten: context deadline exceeded
     25 cache get: context deadline exceeded

Two pieces of good news and one bad:

  • cluster_state stayed ok throughout. The replica on s1 (10.42.0.53) took over slots 0–5461; the new Pod came back as a replica.
  • The database barely noticed anything (~130 instead of 113 transactions per second): the replica already had all keys, so the hit rate stayed high.
  • But: 25 errors, and each one has the same story. cache get waits for the vanished node until the timeout of the whole request (2 s from Day 1) has expired. After that, kurz would ask the database, but there is no time left for it (max=2.52s). (weiterleiten is the redirect handler.)

The fallback is there; it just comes too late. A cache must never wait longer than the query it is supposed to save. How to fix that is the Challenge.

Save your progress? Sign up for free

Drill 7: A cache that is too small

The operator can change maxmemory live, without restarting Pods. What happens at 1 MB?

# on s1
# How much memory does each node use right now?
$V --cluster call 127.0.0.1:6379 INFO memory | grep -E '^used_memory:' | tr -d '\r' | head -3
# Set the limit to 1 MB (live)
kubectl -n kurz patch valkeycluster cache --type merge -p '{"spec":{"config":{"maxmemory":"1mb"}}}'
# Wait briefly, reset statistics, measure
sleep 15; $V --cluster call 127.0.0.1:6379 CONFIG RESETSTAT >/dev/null
X0=$(xact)
ZIEL=http://172.16.0.126 RATE=1500 DAUER=30s k6 run --quiet schief.js 2>/dev/null \
  | grep -E 'http_req_duration\.|http_reqs\.' | sed 's/  */ /g'
X1=$(xact); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"
# Hits, misses, evicted keys
$V --cluster call 127.0.0.1:6379 INFO stats | grep -E 'keyspace_(hits|misses)|evicted_keys' | tr -d '\r' \
  | awk -F: '{s[$1]+=$2} END {print "hits", s["keyspace_hits"], "misses", s["keyspace_misses"], "evicted", s["evicted_keys"]}'

Expected:

used_memory:3782256
used_memory:3899328
used_memory:3756112
valkeycluster.valkey.io/cache patched
 http_req_duration..............: avg=193.91ms min=5.51ms med=168.23ms max=1.2s p(90)=351.17ms p(95)=388.65ms
 http_reqs......................: 41642 1370.864621/s
DB-Transaktionen: 693/s
hits 0 misses 39536 evicted 0

Zero hits, zero evictions, and at 389 ms p95 is three times as bad as with no cache at all. Each Valkey node already uses a good 3.7 MB for itself. The limit is below that, there is nothing left to evict, and every SET is rejected. Every request now pays for the trip to the cache, the trip to the database and a failed write attempt. The database still sees only 693 instead of 1324 transactions: kurz merges concurrent misses for the same code into one query (singleflight, predecessor course Day 6).

A wrongly sized cache is worse than none. Back to 64 MB:

# on s1
# Apply the manifest again (maxmemory 64mb)
kubectl apply -f cache.yaml
# After a short while, 64 MB on all six nodes?
sleep 15; $V --cluster call 127.0.0.1:6379 CONFIG GET maxmemory | grep -c 67108864

Expected:

valkeycluster.valkey.io/cache configured
6

Save your progress? Sign up for free

Exercise: Speed drills

  1. On which shard is the link: key of the first code from codes.txt? Target time: 2 min
  2. Why would maxmemory-policy: noeviction be wrong for this cache? Target time: 1 min
  3. What does kubectl -n kurz get valkeycluster cache show while a Pod is Pending? Target time: 1 min

Solution

# on s1
# Compute the key's slot and find the responsible node in cluster nodes
K="link:$(head -1 codes.txt)"
S=$($V cluster keyslot "$K" | tr -d '\r'); echo "$K -> Slot $S"
$V cluster nodes | awk -v s=$S '$3 ~ /master/ {split($9, r, "-"); if (s >= r[1] && s <= r[2]) print $2, $9}' | sed 's/@[0-9]*//'

The output depends on your code: a slot between 0 and 16383 and exactly one primary whose range contains it.

For 2: with noeviction, Valkey rejects writes as soon as memory is full. New links would never get into the cache again, and the hit rate would drop day by day. A cache needs allkeys-lru (or allkeys-lfu), a data store noeviction.

For 3: STATE Degraded, REASON PodUnschedulable, as in the “Happened during testing” from Drill 2. The message in .status.conditions names the Pod and the scheduler’s reason.

Save your progress? Sign up for free

Challenge

The 25 errors from Drill 6 happen because the cache query uses up the request’s entire time budget. Sketch the change in cache.go that prevents this, and name the number you choose for it, with reasoning from the measurements in this course.

Solution

The cache query gets its own short timeout, derived from the request’s context:

// eigenes Limit für den Cache, z. B. KURZ_TIMEOUT_CACHE=50ms
cctx, cancel := context.WithTimeout(ctx, cacheTimeout)
defer cancel()
ziel, err := cache.Do(cctx, cache.B().Get().Key(key).Build()).ToString()
// Bei Zeitüberschreitung: wie jeder andere Cache-Fehler weiter zur Datenbank

The comments say: a separate limit for the cache, e.g. KURZ_TIMEOUT_CACHE=50ms; on timeout, go on to the database like any other cache error.

The number: a cache hit takes a few milliseconds in the cluster (median 18 ms for the whole request through the Gateway in Drill 5, the cache share is a fraction of that), a database query by primary key about 3 ms holding time (Day 2, Little’s Law). 50 ms is generous for a healthy cache and, with a 2 s total budget, leaves almost everything for the trip to the database. kurz already has the same pattern for the read replica (KURZ_TIMEOUT_LESEN, 300 ms); the cache lacks it.

It also needs a counter for cache timeouts. Without it, from the outside you only see “cache disrupted, continuing with the database” and a database that suddenly has more to do.

Save your progress? Sign up for free

Checkpoint

# on s1
# Cluster ready, image version
kubectl -n kurz get valkeycluster cache -o jsonpath='{.status.state} {.spec.image}{"\n"}'
# Six Valkey Pods ready
kubectl -n kurz get pods -l app.kubernetes.io/name=valkey --no-headers | grep -c '2/2'
# kurz knows the cache
kubectl -n kurz get configmap kurz -o jsonpath='{.data.KURZ_CACHE}{"\n"}'
# Limit 64 MB on all nodes
kubectl -n kurz exec valkey-cache-1-0-0 -c server -- valkey-cli -a lab-valkey-123 --no-auth-warning \
  --cluster call 127.0.0.1:6379 CONFIG GET maxmemory | grep -c 67108864

Expected:

Ready valkey/valkey:9.2.0
6
valkey-cache:6379
6

Interview note

  • Cache-aside in the cluster: the cache is an optimization, not a dependency. If it fails, the application must get to the database fast enough; for that, every cache query needs its own short timeout. And the database must be able to carry the full load, or you need load shedding.
  • Valkey/Redis Cluster vs. one server with a replica: Cluster distributes keys across shards (more memory, more throughput) and fails over per shard on its own. Price: commands across several keys only work if the keys are in the same slot (hash tags {…}), and the client must be cluster-aware.
  • Cache size: memory limit = data volume of the hot keys plus the server’s base usage plus headroom. Too small is worse than no cache (Drill 7).

Enterprise note

  • For production, more mature options are common: a managed service, the Bitnami or Valkey Helm chart with Sentinel, or an established operator. The Valkey Operator is worth watching; it is built by the Valkey developers themselves.
  • The operator supports TLS, per-application users with key patterns (keys.readWrite: ["link:*"]) and a Prometheus exporter as a sidecar (the second container metrics-exporter in each Pod). A dedicated user per service instead of default belongs in every serious setup; for that, the client must be able to send a username.
  • persistence is unnecessary for a pure cache: after a restart it fills up on its own. Anyone using Valkey as a data store needs persistence, AOF and a backup concept; the operator cannot do backups yet.

Contents

More