Configure session affinity for Knative services

更新时间:
复制 MD 格式

In stateful services, such as AI inference applications and agents, routing requests from the same client to different pods can lead to context loss or session disconnection. Knative session affinity ensures that requests from the same client are always routed to the same pod by using a unique session key extracted from a cookie, header, or token.

Combined with Knative's native autoscaling capabilities, session affinity provides complete, session-aware lifecycle management:

  • On-demand scale-out: Automatically creates a pod when a new session begins.

  • Precise scale-in: Automatically deletes the corresponding pod after a session expires.

  • Directs each session to a dedicated pod.

How it works

Session affinity provides three core capabilities for Knative services:

Capability

Description

Consistent routing

Ensures that requests from the same client are always forwarded to the same pod, maintaining context continuity for stateful services.

View details

  • First request: Knative assigns a pod to the session. Subsequent requests with the same session key are routed to this pod.

  • Session timeout: If a session is idle for longer than the specified session-timeout, the pod is automatically scaled in. The next request from the client is assigned to a new pod.

  • Autoscaling basis: When you use metric: session, autoscaling is based on the number of active sessions instead of concurrent requests. A setting of target: "1" means each pod handles only one session.

Session-aware autoscaling

Supports autoscaling based on the number of active sessions. A new session triggers pod creation, and session expiration triggers pod scale-in.

Multiple storage modes

Supports in-memory storage (default) and Redis storage to meet different scale and reliability requirements.

Knative session affinity supports multiple ways to configure a session key, providing flexibility for different client access patterns.

Key

Use case

Description

Custom cookie

Web-based chat applications

Automatically generates a UUID and sets a cookie on the first request.

Authorization header

API Key or OAuth access

Uses the SHA-256 digest of the Bearer token as the key.

X-Session-Key header

Custom integrations

The client explicitly specifies the key, which is suitable for internal systems.

Prerequisites

Procedure

1. Create a Knative service with session affinity

The following steps demonstrate a configuration that maps each session to a dedicated pod, and the pod is automatically scaled in after 5 minutes of inactivity. This is suitable for short-term stateful tasks, such as API debugging or short-lived inference sessions.

For long-running AI inference sessions, we recommend setting session-timeout to 30m or longer to prevent premature session termination.
  1. Log on to the ACS console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the name of the target cluster. In the left navigation pane, choose Applications > Knative.

  3. On the Services page, select default for Namespace, click Create from Template, select Custom for Sample Template, and use the following YAML to deploy the service.

    This example uses the recommended default values for the corresponding annotations. To customize the timeout, cookie name, or number of sessions per pod, see Annotation parameters.
    apiVersion: serving.knative.dev/v1
    kind: Service
    metadata:
      name: my-sessions-per-pod
    spec:
      template:
        metadata:
          annotations:
            # Enable session affinity.
            serving.knative.dev/session-affinity: "true"
            # The idle timeout period for a session. The pod is automatically scaled in after the timeout.
            serving.knative.dev/session-timeout: "5m"
            # The name of the cookie used for session identification.
            serving.knative.dev/session-affinity-cookie: "demo"
            # Use the number of sessions as the metric for autoscaling.
            autoscaling.knative.dev/metric: "session"
            # The maximum number of sessions that each pod can handle.
            autoscaling.knative.dev/target: "1"
        spec:
          containers:
            - image: registry-cn-hangzhou-vpc.ack.aliyuncs.com/acs/knative-samples-helloworld-go-session:v1.0-bfdce98
  4. After the my-sessions-per-pod deployment is complete, on the Services page, obtain the Gateway address and the service's Default Domain.

  5. Verify session routing.

    Requests with different cookie values should be routed to different pods.

    • Accessing with Cookie demo=11 routes the request to Pod A.

      curl -i -H "Host: my-sessions-per-pod.default.example.com" http://47.xx.xx.xx \
        -H "Cookie: demo=11"

      Expected output from pod A:

      HTTP/1.1 200 OK
      Date: Tue, 21 Apr 2026 09:57:44 GMT
      Content-Type: text/plain; charset=utf-8
      Content-Length: 77
      Connection: keep-alive
      
      Hello World!
      
      Cookies:
        Name:  demo
        Value: 11
      
      Raw Cookie Header: demo=11
    • A request with Cookie demo=22 is routed to Pod B.

      curl -i -H "Host: my-sessions-per-pod.default.example.com" http://47.xx.xx.xx \
        -H "Cookie: demo=22"
    • Expected output from pod B:

      HTTP/1.1 200 OK
      Date: Tue, 21 Apr 2026 11:27:15 GMT
      Content-Type: text/plain; charset=utf-8
      Content-Length: 77
      Connection: keep-alive
      
      Hello World!
      
      Cookies:
        Name:  demo
        Value: 22
      
      Raw Cookie Header: demo=22
  6. Confirm that pods for both sessions have been created.

    kubectl get pods -l serving.knative.dev/service=my-sessions-per-pod

    The expected output shows two pods in the Running state, handling the sessions for Cookie demo=11 and demo=22. The number of pods matches the number of active sessions, which indicates that session-aware autoscaling has taken effect.

(Optional) 2. Configure Redis storage mode

In a production environment with multiple Activator replicas, you must use Redis storage mode to ensure session consistency. Set the Redis address in the config-defaults ConfigMap in the knative-serving namespace.

For a detailed comparison of the two modes, see Comparison of session storage modes.
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-defaults
  namespace: knative-serving
data:
  # Replace this with the connection address of your Redis instance.
  session-storage-redis-addr: "r-xxxxxxxxxxxx.redis.rds.aliyuncs.com:6379"

Configuration reference

Annotation parameters

The following are all the annotations for session affinity. You can configure them as needed in the spec.template.metadata.annotations field of a Knative service.

Annotation

Description

Default

Example

serving.knative.dev/session-affinity

Enables session affinity.

false

"true"

serving.knative.dev/session-affinity-cookie

Specifies the name of a custom cookie.

Auto-detection

"my-session-id"

serving.knative.dev/session-timeout

Session idle timeout.

30m

"15m", "1h"

autoscaling.knative.dev/metric

The metric type for autoscaling.

concurrency

"session"

autoscaling.knative.dev/target

The target number of sessions per pod.

1 (in session mode)

"1", "5"

Comparison of session storage modes

In-memory mode works out of the box and is suitable for development and testing. Redis mode supports multiple Activator replicas and is better suited for production environments.

Aspect

In-memory mode (default)

Redis mode

Deployment complexity

Zero dependencies; works out of the box.

Requires an ApsaraDB for Tair instance.

Multiple Activator replicas

Not supported

Fully supported

Consistency

Eventual consistency

Strong consistency

Session state after Activator restart

May be lost

Immediately restored

Use Case

Single Activator; environments where some session loss is acceptable.

Production environments (recommended)

Use case: AI inference sessions (1-to-1 isolation)

Each inference session exclusively occupies one GPU pod, and the pod is not released during the session. The session-timeout: 30m setting specifies that the GPU pod is released only after 30 minutes of user inactivity. This prevents frequent cold starts from affecting response speed and avoids unnecessary costs caused by idle GPU resources.

apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: ai-inference
spec:
  template:
    metadata:
      annotations:
        serving.knative.dev/session-affinity: "true"
        # The GPU pod is automatically scaled in after 30 minutes of session inactivity.
        serving.knative.dev/session-timeout: "30m"
        # The name of the cookie used for session identification.
        serving.knative.dev/session-affinity-cookie: "demo"
        autoscaling.knative.dev/metric: "session"
        # Each GPU pod handles only one inference session.
        autoscaling.knative.dev/target: "1"
    spec:
      containers:
      - image: registry-vpc.cn-hangzhou.aliyuncs.com/knative-sample/helloworld-go:73fbdd56
        resources:
          limits:
            nvidia.com/gpu: "1"

FAQ

Choosing between in-memory and Redis modes

Choose the appropriate storage mode based on your deployment scale and reliability requirements.

Scenario

Recommended mode

Development and testing

In-memory mode

Production environments and 1-to-1 isolation

Redis mode

Multiple Activator replicas

Redis mode

Session persistence is required

Redis mode

Troubleshooting session affinity

Check the following:

  1. Whether serving.knative.dev/session-affinity: "true" is set in the spec.template.metadata.annotations field of the Revision.

  2. Ensure that the request carries a recognizable session key.

  3. Determines whether the value of session-affinity-cookie is the same as the request cookie name when you use a custom cookie.

  4. View the Activator logs: kubectl -n knative-serving logs -l app=activator -c activator

Can a Knative service simultaneously use session and concurrency metrics?

No. The session, concurrency, and RPS scaling metrics are mutually exclusive. A service can be configured with only one of them.

Session affinity and canary releases

The two features are orthogonal. Traffic is first distributed to different revisions based on the configured percentages. Within each revision, session affinity is maintained independently.

Feature

Scope

Purpose

Traffic splitting

Across revisions

Controls traffic distribution for canary releases.

Session affinity

Within a revision

Ensures that requests from the same client are consistently routed to the same pod within a single revision.