Course contentsShow
← Cloud and Infrastructure
Lesson 1215 of 2,98924. Kubernetes NetworkingFree lesson

Session Affinity

Configuring ClientIP-based session affinity to route repeat requests to the same Pod.

Session Affinity

What you'll learn: How to configure Kubernetes Services to route repeat requests from the same client back to the same Pod every time.

The Problem

By default, a Kubernetes Service distributes traffic randomly across all healthy backend Pods. Each new request might land on a different Pod. This works great for stateless applications, but what if a user's session data is stored in memory on one specific Pod? If their next request goes to a different Pod, their session is lost.

What is Session Affinity?

Session affinity (also called "sticky sessions") tells the Service to remember which client sent a request and always route that client's future requests to the same Pod. Kubernetes supports this through ClientIP-based affinity.

When you enable sessionAffinity: ClientIP, the Service uses the client's IP address as a key. All requests from that IP get routed to the same Pod for a configurable duration (default: 10,800 seconds / 3 hours).

How to Configure It

In your Service manifest, add two fields:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
    - port: 80
      targetPort: 8080
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 3600  # 1 hour

Now all requests from the same client IP stick to the same Pod for one hour.

Think of It Like...

Imagine a coffee shop where each barista remembers your order. Session affinity is like always sending you to the same barista so they recognize you and know your preferences—no need to re-explain every time.

Key Takeaway: Session affinity with ClientIP ensures repeat requests from the same client reach the same Pod, useful for applications that store session state locally.