In this lesson, you will learn how to configure session affinity to ensure that a user’s requests are consistently routed to the same pod instance during complex deployment cycles.
Why Session Affinity Matters
In a standard Kubernetes Service, the load balancer typically uses a round-robin approach, distributing incoming requests across all available pods. While this is great for scaling, it creates a problem for applications that maintain local state (like a shopping cart or a multi-step form) or those undergoing "Canary" rollouts. If a user is routed to a pod running v1 of your app and their next request hits a pod running v2, they might lose their session data or encounter unexpected errors due to mismatched application versions.
Implementing Client IP Affinity
To solve this, Kubernetes allows you to enable Session Affinity (also known as "sticky sessions") at the Service level. By setting the sessionAffinity field to ClientIP, Kubernetes will ensure that all requests originating from the same IP address are directed to the same pod instance for the duration of the session.
You can enable this in your Service manifest like this:
apiVersion: v1
kind: Service
metadata:
name: my-web-app
spec:
selector:
app: web-server
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP:
timeoutSeconds: 10800 # 3 hours
ports:
- protocol: TCP
port: 80
targetPort: 8080
Constraints to Keep in Mind
When using ClientIP affinity, keep in mind that the "stickiness" is tied to the source IP. If multiple users are behind a corporate NAT or a proxy, they will all share the same source IP and consequently be routed to the same pod, potentially defeating the purpose of your load balancer. Additionally, if the specific pod selected for that user is terminated (due to scaling or a node failure), the affinity is broken, and the user will be routed to a new pod. For highly stateful, long-lived sessions, consider offloading state to an external store like Redis rather than relying solely on infrastructure-level routing.
Key Takeaway: By setting sessionAffinity to ClientIP, you force Kubernetes to pin traffic from a specific source to a single pod, ensuring a consistent user experience during phased deployments.