Elastic Load Balancing
Developer Guide (API Version 2012-06-01)
Did this page help you?  Yes | No |  Tell us about it...
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.

Sticky Sessions

By default, a load balancer routes each request independently to the application instance with the smallest load. However, you can use the sticky session feature (also known as session affinity), which enables the load balancer to bind a user's session to a specific application instance. This ensures that all requests from the user during the session are sent to the same application instance.

The key to managing sticky sessions is to determine how long your load balancer should consistently route the user's request to the same application instance. If your application has its own session cookie, then you can set up Elastic Load Balancing so that the session cookie follows the duration specified by the application's session cookie. If your application does not have its own session cookie, then you can set up Elastic Load Balancing to create a session cookie by specifying your own stickiness duration.

Requirements

  • An HTTP/HTTPS load balancer.

  • At least one healthy application instance in each Availability Zone.

Duration-Based Session Stickiness

The load balancer uses a special load balancer-generated cookie to track the application instance for each request. When the load balancer receives a request, it first checks to see if this cookie is present in the request. If so, the request is sent to the application instance specified in the cookie. If there is no cookie, the load balancer chooses an application instance based on the existing load balancing algorithm. A cookie is inserted into the response for binding subsequent requests from the same user to that application instance. The stickiness policy configuration defines a cookie expiration, which establishes the duration of validity for each cookie. The cookie is automatically updated after its duration expires.

If an application instance fails or becomes unhealthy, the load balancer stops routing request to that instance, instead chooses a new instance based on the existing load balancing algorithm. The request is routed to the new instance as if there is no cookie and the session is no longer sticky.

The following examples show you how to enable duration-based sticky sessions for a load balancer with load balancer-generated HTTP cookies. For information about setting up a HTTPS/SSL load balancer, see Create a HTTPS/SSL Load Balancer .

Enabling Duration-Based Sticky Sessions Using the AWS Management Console

To enable duration-based sticky sessions for a load balancer

  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. In the navigation pane, under NETWORK & SECURITY, click Load Balancers.

  3. Select your load balancer.

  4. In the bottom pane, click (edit) in the Port Configuration: row.

    Enable Duration Based Stickiness
  5. On the Edit Stickiness page, click Enable Load Balancer Generated Cookie Stickiness.

  6. In the Expiration Period box, enter the cookie expiration period, in seconds, and then click Save.

    Specify Expiration Period

The Port Configuration row in the Description pane shows the newly created cookie stickiness policy.

Enabling Duration-Based Sticky Sessions Using the AWS CLI

Before you get started, you must install and configure your AWS CLI environment. For more information, see Getting Set Up with the AWS Command Line Interface.

To enable duration-based sticky sessions for a load balancer

  1. Enter the create-lb-cookie-stickiness-policy command to create a load balancer-generated cookie stickiness policy with a cookie expiration period of 60 seconds. Use the following options:

    • load-balancer-name = my-test-loadbalancer

    • policy-name = MyDurationStickyPolicy

    • cookie-expiration-period = 60

    Your command should look like the following example:

    aws elb create-lb-cookie-stickiness-policy --load-balancer-name my-test-loadbalancer --policy-name  MyDurationStickyPolicy --cookie-expiration-period 60
  2. Enter the set-load-balancer-policies-of-listener command to enable session stickiness for a load balancer using the following options:

    Note

    The set-load-balancer-policies-of-listener command replaces the current set of policies associated with the specified load balancer port. Every time you use this command to enable the policies, use the --policy-names option to list all the policies you want to enable for the port.

    • load-balancer-name = my-test-loadbalancer

    • load-balancer-port = 443

    • policy-names = MyDurationStickyPolicy

      To enable multiple policies for the port, list the policy names separated by a space, as follows:

      policy-names = MyDurationStickyPolicy MyPolicy2 MyPolicy3

    Your command should look like the following example:

    aws elb set-load-balancer-policies-of-listener  --load-balancer-name my-test-loadbalancer --load-balancer-port 443 --policy-names MyDurationStickyPolicy
  3. Enter the describe-load-balancers command to verify that the sticky policy is enabled.

    aws elb describe-load-balancers --load-balancer-name my-test-loadbalancer
  4. Elastic Load Balancing responds as in the following example.

    {
        "LoadBalancerDescriptions": [
            {
                "Subnets": [], 
                "CanonicalHostedZoneNameID": "Z3DZXE0Q79N41H", 
                "CanonicalHostedZoneName": "my-test-loadbalancer-521886987.us-east-1.elb.amazonaws.com", 
                "ListenerDescriptions": [
                    {
                        "Listener": {
                            "InstancePort": 443, 
                            "SSLCertificateId": "arn:aws:iam::55555555:server-certificate/production/myservercert", 
                            "LoadBalancerPort": 443, 
                            "Protocol": "HTTPS", 
                            "InstanceProtocol": "HTTPS"
                        }, 
                        "PolicyNames": [
                             "MyDurationStickyPolicy", 
                            "ELBSecurityPolicy-2015-03"
                        ]
                    }, 
                    {
                        "Listener": {
                            "InstancePort": 80, 
                            "LoadBalancerPort": 80, 
                            "Protocol": "TCP", 
                            "InstanceProtocol": "TCP"
                        }, 
                        "PolicyNames": []
                    }
                ], 
                "HealthCheck": {
                    "HealthyThreshold": 10, 
                    "Interval": 30, 
                    "Target": "TCP:443", 
                    "Timeout": 5, 
                    "UnhealthyThreshold": 2
                }, 
                "BackendServerDescriptions": [], 
                "Instances": [], 
                "DNSName": "my-test-loadbalancer-521886987.us-east-1.elb.amazonaws.com", 
                "SecurityGroups": [], 
                "Policies": {
                    "LBCookieStickinessPolicies": [
                     {
                            "PolicyName": "MyDurationStickyPolicy", 
                            "CookieExpirationPeriod": 60
                        }
    
                    ], 
                    "AppCookieStickinessPolicies": [], 
                    "OtherPolicies": [
                        "ELBSecurityPolicy-2015-03", 
                        "MySSLNegotiationPolicy", 
                        "EnableProxyProtocol"
                    ]
                }, 
                "LoadBalancerName": "my-test-loadbalancer", 
                "CreatedTime": "2014-08-03T02:43:43.860Z", 
                "AvailabilityZones": [
                    "us-east-1a"
                ], 
                "Scheme": "internet-facing", 
                "SourceSecurityGroup": {
                    "OwnerAlias": "amazon-elb", 
                    "GroupName": "amazon-elb-sg"
                }
            }
        ]
    }

    The PolicyNames field of the Listener 443 lists the new MyDurationStickyPolicy policy confirming that the policy is enabled

Enabling Duration-Based Sticky Sessions Using the Query API

To enable duration-based sticky sessions for a load balancer

  1. Use the CreateLBCookieStickinessPolicy action with the following parameters to create a load balancer-generated cookie stickiness policy with a cookie expiration period of 60 seconds.

    • LoadBalancerName = my-test-loadbalancer

    • PolicyName = MyLoadBalancerPolicy

    • CookieExpirationPeriod = 60

  2. Use the SetLoadBalancerPoliciesOfListener action with the following parameters to enable session stickiness for a load balancer using the MyLoadBalancerPolicy policy.

    • LoadBalancerName = my-test-loadbalancer

    • LoadBalancerPort = 80

    • PolicyNames = MyLoadBalancerPolicy

Application-Controlled Session Stickiness

The load balancer uses a special cookie to associate the session with the original server that handled the request, but follows the lifetime of the application-generated cookie corresponding to the cookie name specified in the policy configuration. The load balancer only inserts a new stickiness cookie if the application response includes a new application cookie. The load balancer stickiness cookie does not update with each request. If the application cookie is explicitly removed or expires, the session stops being sticky until a new application cookie is issued.

If an application instance fails or becomes unhealthy, the load balancer stops routing request to that instance, instead chooses a new healthy application instance based on the existing load balancing algorithm. The load balancer will treat the session as now "stuck" to the new healthy instance and continue routing requests to that instance even if the failed application instance comes back. However, it is up to the new application instance whether and how to respond to a session which it has not previously seen.

The following examples show you how to enable application-controlled sticky sessions for your load balancer. For information on how to set up a HTTPS/SSL load balancer, see Create a HTTPS/SSL Load Balancer .

To enable application-controlled session stickiness

  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. In the navigation pane, under NETWORK & SECURITY, click Load Balancers.

  3. Select your load balancer.

  4. In the bottom pane, click (edit) in the Port Configuration: row.

    Enable Duration Based Stickiness
  5. On the Edit Stickiness page, click Enable Application Generated Cookie Stickiness.

  6. In the Cookie Name box, enter the name for your cookie and then click Save.

    Cookie Name

The Port Configuration row in the Description pane shows the newly created cookie stickiness policy.

To enable application-controlled session stickiness

  1. Enter the create-app-cookie-stickiness-policy command to create an application-generated cookie stickiness policy. Use the following options:

    • load-balancer-name = my-test-loadbalancer

    • policy-name = MyAppStickyPolicy

    • cookie-name = MyAppCookie

    Your command should look like the following example:

    aws elb create-app-cookie-stickiness-policy --load-balancer-name my-test-loadbalancer --policy-name  MyAppStickyPolicy --cookie-name MyAppCookie
  2. Enter the set-load-balancer-policies-of-listener command to enable session stickiness for a load balancer using the following options:

    Note

    The set-load-balancer-policies-of-listener command replaces the current set of policies associated with the specified load balancer port. Every time you use this command to enable the policies, use the --policy-names option to list all the policies you want to enable for the port.

    • load-balancer-name = my-test-loadbalancer

    • load-balancer-port = 443

    • policy-names = MyAppStickyPolicy

      To enable multiple policies for the port, list the policy names separated by a space, as follows:

      policy-names = MyDurationStickyPolicy MyPolicy2 MyPolicy3

    Your command should look like the following example:

    aws elb set-load-balancer-policies-of-listener  --load-balancer-name my-test-loadbalancer --load-balancer-port 443 --policy-names MyAppStickyPolicy
  3. Enter the describe-load-balancers command to verify that the sticky policy is enabled.

    aws elb describe-load-balancers --load-balancer-name my-test-loadbalancer
  4. Elastic Load Balancing responds as in the following example.

    {
        "LoadBalancerDescriptions": [
            {
                "Subnets": [], 
                "CanonicalHostedZoneNameID": "Z3DZXE0Q79N41H", 
                "CanonicalHostedZoneName": "my-test-loadbalancer-521886987.us-east-1.elb.amazonaws.com", 
                "ListenerDescriptions": [
                    {
                        "Listener": {
                            "InstancePort": 443, 
                            "SSLCertificateId": "arn:aws:iam::55555555:server-certificate/production/myservercert", 
                            "LoadBalancerPort": 443, 
                            "Protocol": "HTTPS", 
                            "InstanceProtocol": "HTTPS"
                        }, 
                        "PolicyNames": [
                            "MyAppStickyPolicy",  
                            "ELBSecurityPolicy-2015-03"
                        ]
                    }, 
                    {
                        "Listener": {
                            "InstancePort": 80, 
                            "LoadBalancerPort": 80, 
                            "Protocol": "TCP", 
                            "InstanceProtocol": "TCP"
                        }, 
                        "PolicyNames": []
                    }
                ], 
                "HealthCheck": {
                    "HealthyThreshold": 10, 
                    "Interval": 30, 
                    "Target": "TCP:443", 
                    "Timeout": 5, 
                    "UnhealthyThreshold": 2
                }, 
                "BackendServerDescriptions": [], 
                "Instances": [], 
                "DNSName": "my-test-loadbalancer-521886987.us-east-1.elb.amazonaws.com", 
                "SecurityGroups": [], 
                "Policies": {
                    "LBCookieStickinessPolicies": [], 
                    "AppCookieStickinessPolicies": [
                    {
                            "PolicyName": "MyAppStickyPolicy", 
                            "CookieName": "MyAppCookie"
                        }
    
                    ], 
                    "OtherPolicies": [
                        "ELBSecurityPolicy-2015-03", 
                        "MySSLNegotiationPolicy", 
                        "EnableProxyProtocol"
                    ]
                }, 
                "LoadBalancerName": "my-test-loadbalancer", 
                "CreatedTime": "2014-08-03T02:43:43.860Z", 
                "AvailabilityZones": [
                    "us-east-1a"
                ], 
                "Scheme": "internet-facing", 
                "SourceSecurityGroup": {
                    "OwnerAlias": "amazon-elb", 
                    "GroupName": "amazon-elb-sg"
                }
            }
        ]
    }

    The PolicyNames field of the Listener 443 lists the new MyAppStickyPolicy policy confirming that the policy is enabled

To enable application-controlled session stickiness

  1. Use the CreateAppCookieStickinessPolicy action with the following parameters to create an application-generated cookie stickiness policy.

    • LoadBalancerName = my-test-loadbalancer

    • PolicyName = my-app-cookie-lb-policy

    • CookieName = my-cookie

  2. Use the SetLoadBalancerPoliciesOfListener action with the following parameters to enable session stickiness.

    • LoadBalancerName = my-test-loadbalancer

    • LoadBalancerPort = 80

    • PolicyNames = my-app-cookie-lb-policy