Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Cloud Container Engine/ User Guide (ME-Abu Dhabi Region)/ Best Practices/ Networking/ Implementing Sticky Session Through Load Balancing

Implementing Sticky Session Through Load Balancing

Updated on 2024-01-04 GMT+08:00

Concepts

Session persistence is one of the most common while complex problems in load balancing.

Session persistence is also called sticky sessions. After the sticky session function is enabled, requests from the same client are distributed to the same backend ECS by the load balancer for better continuity.

In load balancing and sticky session, connection and session are two key concepts. When only load balancing is concerned, session and connection refer to the same thing.

Simply put, if a user needs to log in, it can be regarded as a session; otherwise, a connection.

The sticky session mechanism fundamentally conflicts with the basic functions of load balancing. A load balancer forwards requests from clients to multiple backend servers to avoid overload on a single server. However, sticky session requires that some requests be forwarded to the same server for processing. Therefore, select a proper sticky session mechanism based on the application environment.

Layer-4 Load Balancing (Service)

In layer-4 load balancing, source IP address-based sticky session (Hash routing based on the client IP address) can be enabled. To enable source IP address-based sticky session on Services, the following conditions must be met:
  1. Service Affinity of the Service is set to Node level (that is, the value of the externalTrafficPolicy field of the Service is Local).
    NOTE:

    You do not need to set this parameter for CCE Turbo clusters.

  2. Enable the source IP address-based sticky session in the load balancing configuration of the Service.
    apiVersion: v1
    kind: Service
    metadata:
      name: svc-example
      namespace: default
      annotations:
        kubernetes.io/elb.class: union
        kubernetes.io/elb.id: 56dcc1b4-8810-480c-940a-a44f7736f0dc
        kubernetes.io/elb.lb-algorithm: ROUND_ROBIN
        kubernetes.io/elb.session-affinity-mode: SOURCE_IP
    spec:
      selector: 
        app: nginx
      externalTrafficPolicy: Local   # You do not need to configure this parameter for CCE Turbo clusters.
      ports:
        - name: cce-service-0
          targetPort: 80
          nodePort: 32633
          port: 80
          protocol: TCP
      type: LoadBalancer
  3. Anti-affinity is enabled for the backend application corresponding to the Service.

Layer-7 Load Balancing (Ingress)

In layer-7 load balancing, sticky session based on HTTP cookies and app cookies can be enabled. To enable such sticky session, the following conditions must be met:

  1. The application (workload) corresponding to the ingress is enabled with workload anti-affinity.
  2. Node affinity is enabled for the Service corresponding to the ingress.

Procedure

  1. Create an Nginx workload.

    Set the number of pods to 3 and set the podAntiAffinity.
    kind: Deployment
    apiVersion: apps/v1
    metadata:
      name: nginx
      namespace: default
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
            - name: container-0
              image: 'nginx:perl'
              resources:
                limits:
                  cpu: 250m
                  memory: 512Mi
                requests:
                  cpu: 250m
                  memory: 512Mi
          imagePullSecrets:
            - name: default-secret
          affinity:
            podAntiAffinity:                   # Pod anti-affinity.
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: app
                        operator: In
                        values:
                          - nginx
                  topologyKey: kubernetes.io/hostname

  2. Creating a NodePort Service

    Configure the sticky session in a Service. An ingress can connect to multiple Services, and each Service can have different sticky sessions.
    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      namespace: default
      annotations:
        kubernetes.io/elb.lb-algorithm: ROUND_ROBIN
        kubernetes.io/elb.session-affinity-mode: HTTP_COOKIE      # HTTP cookie type.
        kubernetes.io/elb.session-affinity-option: '{"persistence_timeout":"1440"}'   # Session stickiness duration, in minutes. The value ranges from 1 to 1440.
    spec:
      selector:
        app: nginx
      ports:
        - name: cce-service-0
          protocol: TCP
          port: 80
          targetPort: 80
          nodePort: 32633            # Node port number.
      type: NodePort
      externalTrafficPolicy: Local   # Node-level forwarding.

    You can also select APP_COOKIE.

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      namespace: default
      annotations:
        kubernetes.io/elb.lb-algorithm: ROUND_ROBIN
        kubernetes.io/elb.session-affinity-mode: APP_COOKIE     # Select APP_COOKIE.
        kubernetes.io/elb.session-affinity-option: '{"app_cookie_name":"test"}'  # Application cookie name.
    ...

  3. Create an ingress and associate it with a Service.

    apiVersion: networking.k8s.io/v1
    kind: Ingress 
    metadata: 
      name: ingress-test
      namespace: default
      annotations: 
        kubernetes.io/elb.class: union
        kubernetes.io/elb.port: '80'
        kubernetes.io/elb.autocreate: 
          '{
              "type":"public",
              "bandwidth_name":"cce-bandwidth-test",
              "bandwidth_chargemode":"traffic",
              "bandwidth_size":1,
              "bandwidth_sharetype":"PER",
              "eip_type":"5_bgp"
            }'
    spec:
      rules: 
      - host: 'www.example.com'
        http: 
          paths: 
          - path: '/'
            backend: 
              service:
                name: nginx     #Service name
                port: 
                  number: 80
            property:
              ingress.beta.kubernetes.io/url-match-mode: STARTS_WITH
            pathType: ImplementationSpecific
      ingressClassName: cce

  4. Log in to the ELB console, access the load balancer details page, and check whether the sticky session feature is enabled.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback