Pin a Client to the Same Pod Using Service Session Affinity
Scenario
The whoami application is deployed in the sticky-app namespace with 4
replicas behind a ClusterIP Service. A persistent client pod is already
running in the same namespace.
Right now, every request to the Service gets load-balanced across all 4 Pods — which is a problem for any client that needs to keep talking to the same backend across multiple requests (for example, an app relying on in-memory session state).
Confirm the current behavior — exec into the client pod and send
several requests:
kubectl exec -it -n sticky-app client -- sh
curl -s http://whoami-svc | grep Hostname
curl -s http://whoami-svc | grep Hostname
curl -s http://whoami-svc | grep Hostname
You will likely see a different Hostname (Pod name) on each call:
Hostname: whoami-76bdff8f74-qhtzd
Hostname: whoami-76bdff8f74-lcgqb
Hostname: whoami-76bdff8f74-qhtzd
Exit the shell when done:
exit
Task
Configure the whoami-svc Service so that requests from the same client
IP are always routed to the same Pod for 1 hour, using sessionAffinity.
Hint 1 — Enable ClientIP Session Affinity
Kubernetes Services support a sessionAffinity field under spec. It has
two valid values: None (default — no stickiness) and ClientIP (route all
requests from the same source IP to the same Pod).
Use kubectl edit or kubectl patch to update the Service in-place.
Documentation
Hint 2 — Set the Affinity Timeout
When ClientIP affinity is active, you can control how long the sticky
mapping lasts using a nested config block under spec. The path is
sessionAffinityConfig.clientIP.timeoutSeconds — it accepts an integer
number of seconds.
The default if unset is 10800. The task requires a different value — convert
the required duration to seconds yourself.
Documentation
Hint 3 — Verify Sticky Behavior
Use the client pod that is already running in the sticky-app namespace
to send repeated requests from a consistent source IP:
kubectl exec -n sticky-app client -- sh -c \
'for i in $(seq 1 20); do curl -s http://whoami-svc | grep "Hostname"; done'
All 20 requests should show the same Hostname value, proving that
session affinity is routing this client consistently to one Pod.
Documentation