Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 429 of 8026. Kubernetes Traffic and ScalingFree lesson

Implementing Session Affinity for Statefull Workloads

Enable client IP-based session stickiness to ensure that requests from the same user are consistently routed to the same pod instance.

In this lesson, you will learn how to use Kubernetes Service configuration to ensure a client’s requests consistently reach the same backend pod, a technique known as "session affinity."

Why Session Affinity Matters

In a typical stateless web application, any request can be handled by any pod. However, stateful workloads—like an application that caches user data in local memory or maintains a temporary shopping session on the pod itself—require "stickiness." Without this, a user might bounce between different pods, losing their session state every time they are routed to a new instance.

Configuring Session Affinity

In Kubernetes, you can enforce this behavior by setting the sessionAffinity field in your Service definition to ClientIP. When this is enabled, Kubernetes will use the client's IP address to create a hash, ensuring that all subsequent requests from that specific IP are directed to the same pod for as long as that pod remains healthy.

Here is how you define it in your service manifest:

apiVersion: v1
kind: Service
metadata:
  name: stateful-app-service
spec:
  selector:
    app: my-stateful-workload
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10800 # Session stickiness lasts for 3 hours
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

Important Considerations

  • Sticky Time: The timeoutSeconds field allows you to control how long the mapping remains active. If the user stops sending traffic and the timeout expires, the session affinity is cleared.
  • Load Balancing Limitations: Because ClientIP affinity forces requests to a specific pod, it can lead to uneven traffic distribution across your replicas. If a large number of users are behind a single corporate NAT (sharing one public IP), all of those users will be "stuck" to the same single pod, potentially creating a bottleneck.
  • Infrastructure dependencies: This configuration relies on the standard Kubernetes Service proxy. If you are using an Ingress controller for routing, you may need to configure affinity at the Ingress level instead, as the Service proxy might be bypassed by certain load-balancing configurations.

Key Takeaway: Setting sessionAffinity: ClientIP in your Kubernetes Service ensures that traffic from a single source IP is consistently routed to the same pod, maintaining state for applications that cannot easily share data across replicas.