Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 291 of 8024. Kubernetes Architecture and Core ObjectsFree lesson

Implementing Session Affinity for State-Dependent Traffic

Learners will configure client IP-based session affinity to ensure requests from a single client are consistently routed to the same Pod.

In this lesson, you will learn how to use session affinity to ensure that requests from a specific client are consistently routed to the same Pod.

The Challenge of State

In previous lessons, we learned that Services distribute traffic across multiple Pods using a round-robin approach. While this is great for performance, it poses a problem for stateful applications. If a user logs into a web application and their session data is stored locally in the memory of "Pod A," they will be logged out immediately if the Service routes their next request to "Pod B."

Implementing Client IP Affinity

To solve this, Kubernetes allows you to configure Session Affinity. By setting the sessionAffinity field in your Service definition to ClientIP, Kubernetes instructs the Service to "stick" a client to a specific Pod based on their source IP address.

Once a client makes an initial request, the Service records their IP and ensures that all subsequent requests from that same IP are routed to the same Pod, provided the Pod remains healthy and the session has not expired.

Configuring Your Service

You can enable this in your Service manifest under the spec section:

apiVersion: v1
kind: Service
metadata:
  name: stateful-service
spec:
  selector:
    app: my-app
  sessionAffinity: ClientIP
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

By default, the sessionAffinity is set to None, meaning the Service behaves as a standard load balancer. When you change it to ClientIP, the Service creates a mapping table in the background. It is important to remember that this affinity is not permanent; if the target Pod is deleted or scaled down, the client’s session will eventually be directed to a new Pod, and any local application state held in the old Pod will be lost. This is why session affinity is a "best effort" approach—always aim to move critical state out of Pod memory and into external databases or distributed caches for truly reliable state management.

Key Takeaway: Setting sessionAffinity: ClientIP in your Service spec ensures consistent routing for state-dependent traffic by binding requests to a specific Pod based on the client's source IP address.