Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 686 of 80210. Deployment Strategies and GitOpsFree lesson

Handling Session Persistence During Traffic Shifts

Configure sticky sessions and connection draining to ensure users do not lose state during blue-green deployment transitions.

In this lesson, you’ll learn how to maintain user state continuity during blue-green deployment transitions by leveraging sticky sessions and connection draining.

When you shift traffic from a "Blue" environment to a "Green" environment, the biggest risk to user experience is the abrupt termination of active sessions. If a user is mid-transaction or logged into a stateful application, moving them to a new pod without context forces a re-authentication or data loss. To solve this, we combine two orchestration patterns: Session Affinity (Sticky Sessions) and Connection Draining.

Implementing Sticky Sessions

At the ingress or service mesh layer, you must configure the traffic controller to route a user's subsequent requests to the same pod they started on. Using Kubernetes Ingress annotations, you can enable cookie-based affinity. This ensures that even as the deployment controller marks the "Blue" pods for termination, the ingress controller continues to send existing users to their current pods until they naturally terminate or the session expires.

nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/session-cookie-name: "INGRESSCOOKIE"

Managing Connection Draining

Once you shift traffic to the "Green" environment, you cannot simply kill the "Blue" pods immediately. You must implement Connection Draining (or "Graceful Shutdown"). By configuring a preStop hook in your deployment, you instruct the pod to stop accepting new requests while allowing existing connections to finish processing their current task.

lifecycle:
  preStop:
    exec:
      command: ["/bin/sleep", "30"]

By adding a preStop delay, the Kubernetes Endpoint controller removes the pod from the service load balancer, but the pod remains "alive" for the duration of the sleep. During this window, the sticky session logic keeps the user locked to the Blue pod, while new users are routed exclusively to the Green pods. Once the preStop timer expires, the pod terminates cleanly, effectively handing off the session lifecycle to the new deployment.

Key Takeaway: By combining cookie-based affinity to pin users to their current instance and preStop delays to drain existing traffic, you prevent session drops during the critical transition phase of your blue-green release.