liveBook · Manning

Session affinity

As explained in Kubernetes in Action, Second Edition

Cookie-based session affinity is a traffic-routing policy that uses an HTTP cookie to keep a client associated with the same backend instance.

Session affinity keeps repeated requests from one client associated with the same backend instance. Cookie-based affinity does this with an HTTP cookie, so it requires an application-layer HTTP component rather than a transport-layer Service. section 12.4.1 section 11.1.3

Distinguish the two Kubernetes mechanisms:

  • A Service defaults to None, distributing connections without guaranteeing the destination pod; ClientIP instead keeps connections from one IP on the same pod for a configurable period. section 11.1.3
  • An Ingress operates at HTTP layer 7 and can read cookies, but its affinity annotations are specific to the chosen controller. section 12.4.1

Enable affinity in an Nginx Ingress

Add nginx.ingress.kubernetes.io/affinity: cookie to enable cookie routing and nginx.ingress.kubernetes.io/session-cookie-name: SESSION_COOKIE to choose the cookie name. An initial request returns Set-Cookie; send that value in a subsequent Cookie header, and repeated requests are forwarded to the same pod. section 12.4.1

$ kubectl exec -it quote-001 -c nginx -- sh
/ #

Use the manifest listing to inspect the complete networking.k8s.io/v1 Ingress configuration, including both affinity annotations. section 12.4.1

/ # curl http://10.96.136.190      #1
This is the quiz service running in pod quiz

/ # curl http://10.96.74.151       #2
This is the quote service running in pod quote-canary

Use the request listings to see the returned session cookie and replay it through the Cookie header. section 12.4.1

How Kubernetes in Action, Second Edition covers it

How deep it goes
Explains layer boundaries, annotations, cookie naming, manifest configuration, and curl verification without developing controller internals.
Examples
Uses Nginx annotations, a named SESSION_COOKIE, Set-Cookie output, and repeated curl requests.
What it assumes
Builds on Kubernetes Service routing and HTTP requests while introducing why transport-layer Services cannot read cookies.
What you can do after
Operate/configure cookie affinity by applying an Nginx Ingress manifest and replaying the returned Cookie header.
How it connects
Contrasts Kubernetes Services with Ingress and connects HTTP cookies to OSI layer 7.

Also explained in

Compare how 2 books explain session affinity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kubernetes in Action, Second Edition. The section links point to the parts of the book it draws on.