

# Target groups for your Application Load Balancers
<a name="load-balancer-target-groups"></a>

Target groups route requests to individual registered targets, such as EC2 instances, using the protocol and port number that you specify. You can register a target with multiple target groups. You can configure health checks on a per target group basis. Health checks are performed on all targets registered to a target group that is specified in a listener rule for your load balancer.

Each target group is used to route requests to one or more registered targets. When you create each listener rule, you specify a target group and conditions. When a rule condition is met, traffic is forwarded to the corresponding target group. You can create different target groups for different types of requests. For example, create one target group for general requests and other target groups for requests to the microservices for your application. You can use each target group with only one load balancer. For more information, see [Application Load Balancer components](introduction.md#application-load-balancer-components).

You define health check settings for your load balancer on a per target group basis. Each target group uses the default health check settings, unless you override them when you create the target group or modify them later on. After you specify a target group in a rule for a listener, the load balancer continually monitors the health of all targets registered with the target group that are in an Availability Zone enabled for the load balancer. The load balancer routes requests to the registered targets that are healthy.

**Topics**
+ [Routing configuration](#target-group-routing-configuration)
+ [Target type](#target-type)
+ [IP address type](#target-group-ip-address-type)
+ [Protocol version](#target-group-protocol-version)
+ [Registered targets](#registered-targets)
+ [Target Optimizer](#target-optimizer)
+ [Target group attributes](#target-group-attributes)
+ [Target group health](#target-group-health)
+ [Create a target group](create-target-group.md)
+ [Configure health checks](target-group-health-checks.md)
+ [Edit target group attributes](edit-target-group-attributes.md)
+ [Register targets](target-group-register-targets.md)
+ [Use Lambda functions as targets](lambda-functions.md)
+ [Tag a target group](target-group-tags.md)
+ [Delete a target group](delete-target-group.md)

## Routing configuration
<a name="target-group-routing-configuration"></a>

By default, a load balancer routes requests to its targets using the protocol and port number that you specified when you created the target group. Alternatively, you can override the port used for routing traffic to a target when you register it with the target group.

Target groups support the following protocols and ports:
+ **Protocols**: HTTP, HTTPS
+ **Ports**: 1-65535

When a target group is configured with the HTTPS protocol or uses HTTPS health checks, if any HTTPS listener is using a TLS 1.3 security policy, the `ELBSecurityPolicy-TLS13-1-0-2021-06` security policy will be used for target connections. Otherwise, the `ELBSecurityPolicy-2016-08` security policy is used. The load balancer establishes TLS connections with the targets using certificates that you install on the targets. The load balancer does not validate these certificates. Therefore, you can use self-signed certificates or certificates that have expired. Because the load balancer, and its targets are in a virtual private cloud (VPC), traffic between the load balancer and the targets is authenticated at the packet level, so it is not at risk of man-in-the-middle attacks or spoofing even if the certificates on the targets are not valid. Traffic that leaves AWS will not have these same protections, and additional steps may be needed to secure traffic further.

## Target type
<a name="target-type"></a>

When you create a target group, you specify its target type, which determines the type of target you specify when registering targets with this target group. After you create a target group, you can't change its target type.

The following are the possible target types:

`instance`  
The targets are specified by instance ID.

`ip`  
The targets are IP addresses.

`lambda`  
The target is a Lambda function.

When the target type is `ip`, you can specify IP addresses from one of the following CIDR blocks:
+ The subnets of the VPC for the target group
+ 10.0.0.0/8 ([RFC 1918](https://tools.ietf.org/html/rfc1918))
+ 100.64.0.0/10 ([RFC 6598](https://tools.ietf.org/html/rfc6598))
+ 172.16.0.0/12 (RFC 1918)
+ 192.168.0.0/16 (RFC 1918)

**Important**  
You can't specify publicly routable IP addresses.

All of the supported CIDR blocks enable you to register the following targets with a target group: 
+ Instances in a VPC that is peered to the load balancer VPC (same Region or different Region).
+ AWS resources that are addressable by IP address and port (for example, databases).
+ On-premises resources linked to AWS through Direct Connect or a Site-to-Site VPN connection.

**Note**  
For Application Load Balancers deployed within a Local Zone, the `ip` targets must be in the same Local Zone to receive traffic.  
For more information, see [What is AWS Local Zones?](https://docs.aws.amazon.com/local-zones/latest/ug/getting-started.html)

If you specify targets using an instance ID, traffic is routed to instances using the primary private IP address specified in the primary network interface for the instance. If you specify targets using IP addresses, you can route traffic to an instance using any private IP address from one or more network interfaces. This enables multiple applications on an instance to use the same port. Each network interface can have its own security group.

If the target type of your target group is `lambda`, you can register a single Lambda function. When the load balancer receives a request for the Lambda function, it invokes the Lambda function. For more information, see [Use Lambda functions as targets of an Application Load Balancer](lambda-functions.md).

You can configure Amazon Elastic Container Service (Amazon ECS) as a target of your Application Load Balancer. For more information, see [Use an Application Load Balancer for Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/alb.html) in the *Amazon Elastic Container Service Developer Guide*.

## IP address type
<a name="target-group-ip-address-type"></a>

When creating a new target group, you can select the IP address type of your target group. This controls the IP version used to communicate with targets and check their health status.

Target groups for your Application Load Balancers support the following IP address types:

**`ipv4`**  
The load balancer communicates with targets using IPv4.

**`ipv6`**  
The load balancer communicates with targets using IPv6.

**Considerations**
+ The load balancer communicates with targets based on the IP address type of the target group. The targets of an IPv4 target group must accept IPv4 traffic from the load balancer and the targets of an IPv6 target group must accept IPv6 traffic from the load balancer.
+ You can't use an IPv6 target group with an `ipv4` load balancer.
+ You can't register a Lambda function with an IPv6 target group.

## Protocol version
<a name="target-group-protocol-version"></a>

By default, Application Load Balancers send requests to targets using HTTP/1.1. You can use the protocol version to send requests to targets using HTTP/2 or gRPC.

The following table summarizes the result for the combinations of request protocol and target group protocol version.


| Request protocol | Protocol version | Result | 
| --- | --- | --- | 
| HTTP/1.1 | HTTP/1.1 | Success | 
| HTTP/2 | HTTP/1.1 | Success | 
| gRPC | HTTP/1.1 | Error | 
| HTTP/1.1 | HTTP/2 | Error | 
| HTTP/2 | HTTP/2 | Success | 
| gRPC | HTTP/2 | Success if targets support gRPC | 
| HTTP/1.1 | gRPC | Error | 
| HTTP/2 | gRPC | Success if a POST request | 
| gRPC | gRPC | Success | 

**Considerations for the gRPC protocol version**
+ The only supported listener protocol is HTTPS.
+ The only supported action type for listener rules is `forward`.
+ The only supported target types are `instance` and `ip`.
+ The load balancer parses gRPC requests and routes the gRPC calls to the appropriate target groups based on the package, service, and method.
+ The load balancer supports unary, client-side streaming, server-side streaming, and bi-directional streaming.
+ You must provide a custom health check method with the format `/package.service/method`.
+ You must specify the gRPC status codes to use when checking for a successful response from a target.
+ You can't use Lambda functions as targets.

**Considerations for the HTTP/2 protocol version**
+ The only supported listener protocol is HTTPS.
+ The only supported action type for listener rules is `forward`.
+ The only supported target types are `instance` and `ip`.
+ The load balancer supports unary, client-side streaming, server-side streaming, and bi-directional streaming. The maximum number of streams per client HTTP/2 connection is 128.

## Registered targets
<a name="registered-targets"></a>

Your load balancer serves as a single point of contact for clients and distributes incoming traffic across its healthy registered targets. You can register each target with one or more target groups.

If demand on your application increases, you can register additional targets with one or more target groups in order to handle the demand. The load balancer starts routing traffic to a newly registered target as soon as the registration process completes and the target passes the first initial health check, irrespective of the configured threshold.

If demand on your application decreases, or you need to service your targets, you can deregister targets from your target groups. Deregistering a target removes it from your target group, but does not affect the target otherwise. The load balancer stops routing requests to a target as soon as it is deregistered. The target enters the `draining` state until in-flight requests have completed. You can register the target with the target group again when you are ready for it to resume receiving requests.

If you are registering targets by instance ID, you can use your load balancer with an Auto Scaling group. After you attach a target group to an Auto Scaling group, Auto Scaling registers your targets with the target group for you when it launches them. For more information, see [Attaching a load balancer to your Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html) in the *Amazon EC2 Auto Scaling User Guide*.

**Limits**
+ You can't register the IP addresses of another Application Load Balancer in the same VPC. If the other Application Load Balancer is in a VPC that is peered to the load balancer VPC, you can register its IP addresses.
+ You can't register instances by instance ID if they are in a VPC that is peered to the load balancer VPC (same Region or different Region). You can register these instances by IP address.

## Target Optimizer
<a name="target-optimizer"></a>

 You can enable target optimizer on a target group. Target optimizer lets you accurately enforce a maximum number of concurrent requests on a target. It works with the help of an agent that you install and configure on targets. To enable target optimizer, you specify a target control port for the target group. This port is used for management traffic between the agents and load balancer. Target optimizer can only be enabled during target group creation. Target control port once specified cannot be modified. For more information, see [Target Optimizer](target-group-register-targets.md#register-targets-target-optimizer). 

## Target group attributes
<a name="target-group-attributes"></a>

You can configure a target group by editing its attributes. For more information, see [Edit target group attributes](edit-target-group-attributes.md).

The following target group attributes are supported if the target group type is `instance` or `ip`:

`deregistration_delay.timeout_seconds`  
The amount of time for Elastic Load Balancing to wait before deregistering a target. The range is 0–3600 seconds. The default value is 300 seconds.

`load_balancing.algorithm.type`  
The routing algorithm determines how the load balancer selects targets when routing requests. The value is `round_robin`, `least_outstanding_requests`, or `weighted_random`. The default is `round_robin`.

`load_balancing.algorithm.anomaly_mitigation`  
Only available when `load_balancing.algorithm.type` is `weighted_random`. Indicates whether anomaly mitigation is enabled. The value is `on` or `off`. The default is `off`.

`load_balancing.cross_zone.enabled`  
Indicates whether cross zone load balancing is enabled. The value is `true`, `false` or `use_load_balancer_configuration`. The default is `use_load_balancer_configuration`.

`slow_start.duration_seconds`  
The time period, in seconds, during which the load balancer sends a newly registered target a linearly increasing share of the traffic to the target group. The range is 30–900 seconds (15 minutes). The default is 0 seconds (disabled).

`stickiness.enabled`  
Indicates whether sticky sessions are enabled. The value is `true` or `false`. The default is `false`.

`stickiness.app_cookie.cookie_name`  
The name of the application cookie. The application cookie name can't have the following prefixes: `AWSALB`, `AWSALBAPP`, or `AWSALBTG`; they're reserved for use by the load balancer.

`stickiness.app_cookie.duration_seconds`  
The application-based cookie expiration period, in seconds. After this period, the cookie is considered stale. The minimum value is 1 second and the maximum value is 7 days (604800 seconds). The default value is 1 day (86400 seconds).

`stickiness.lb_cookie.duration_seconds`  
The duration-based cookie expiration period, in seconds. After this period, the cookie is considered stale. The minimum value is 1 second and the maximum value is 7 days (604800 seconds). The default value is 1 day (86400 seconds).

`stickiness.type`  
The type of stickiness. The possible values are `lb_cookie` and `app_cookie`.

`target_group_health.dns_failover.minimum_healthy_targets.count`  
The minimum number of targets that must be healthy. If the number of healthy targets is below this value, mark the node as unhealthy in DNS, so that traffic is routed only to healthy nodes. The possible values are `off` or an integer from 1 to the maximum number of targets. When `off`, DNS fail away is disabled, meaning that even if all targets in the target group are unhealthy, the node is not removed from DNS. The default is 1.

`target_group_health.dns_failover.minimum_healthy_targets.percentage`  
The minimum percentage of targets that must be healthy. If the percentage of healthy targets is below this value, mark the node as unhealthy in DNS, so that traffic is routed only to healthy nodes. The possible values are `off` or an integer from 1 to 100. When `off`, DNS fail away is disabled, meaning that even if all targets in the target group are unhealthy, the node is not removed from DNS. The default is `off`.

`target_group_health.unhealthy_state_routing.minimum_healthy_targets.count`  
The minimum number of targets that must be healthy. If the number of healthy targets is below this value, send traffic to all targets, including unhealthy targets. The range is 1 to the maximum number of targets. The default is 1.

`target_group_health.unhealthy_state_routing.minimum_healthy_targets.percentage`  
The minimum percentage of targets that must be healthy. If the percentage of healthy targets is below this value, send traffic to all targets, including unhealthy targets. The possible values are `off` or an integer from 1 to 100. The default is `off`.

The following target group attribute is supported if the target group type is `lambda`:

`lambda.multi_value_headers.enabled`  
Indicates whether the request and response headers exchanged between the load balancer and the Lambda function include arrays of values or strings. The possible values are `true` or `false`. The default value is `false`. For more information, see [Multi-value headers](lambda-functions.md#multi-value-headers).

## Target group health
<a name="target-group-health"></a>

By default, a target group is considered healthy as long as it has at least one healthy target. If you have a large fleet, having only one healthy target serving traffic is not sufficient. Instead, you can specify a minimum count or percentage of targets that must be healthy, and what actions the load balancer takes when the healthy targets fall below the specified threshold. This improves the availability of your application.

**Topics**
+ [Unhealthy state actions](#unhealthy-state-actions)
+ [Requirements and considerations](#target-group-health-considerations)
+ [Monitoring](#target-group-health-monitoring)
+ [Example](#target-group-health-examples)
+ [Using Route 53 DNS failover for your load balancer](#r53-dns-failover)

### Unhealthy state actions
<a name="unhealthy-state-actions"></a>

You can configure healthy thresholds for the following actions:
+ **DNS failover** – When the healthy targets in a zone fall below the threshold, we mark the IP addresses of the load balancer node for the zone as unhealthy in DNS. Therefore, when clients resolve the load balancer DNS name, the traffic is routed only to healthy zones.
+ **Routing failover** – When the healthy targets in a zone fall below the threshold, the load balancer sends traffic to all targets that are available to the load balancer node, including unhealthy targets. This increases the chances that a client connection succeeds, especially when targets temporarily fail to pass health checks, and reduces the risk of overloading the healthy targets.

### Requirements and considerations
<a name="target-group-health-considerations"></a>
+ If you enable target optimizer on the target group, we recommend you set the health check port of the target group to be the same as the port in TARGET\$1CONTROL\$1DATA\$1ADDRESS. This ensures that the target will fail health checks if the agent is unhealthy. For more information, see [Target Optimizer](target-group-register-targets.md#register-targets-target-optimizer).
+ You can't use this feature with target groups where the target is a Lambda function. If the Application Load Balancer is the target of a Network Load Balancer or Global Accelerator, do not configure a threshold for DNS failover.
+ If you specify both types of thresholds for an action (count and percentage), the load balancer takes the action when either threshold is breached.
+ If you specify thresholds for both actions, the threshold for DNS failover must be greater than or equal to the threshold for routing failover, so that DNS failover occurs either with or before routing failover.
+ If you specify the threshold as a percentage, we calculate the value dynamically, based on the total number of targets that are registered with the target groups.
+ The total number of targets is based on whether cross-zone load balancing is off or on. If cross-zone load balancing is off, each node sends traffic only to the targets in its own zone, which means that the thresholds apply to the number of targets in each enabled zone separately. If cross-zone load balancing is on, each node sends traffic to all targets in all enabled zones, which means that the specified thresholds apply to the total number targets in all enabled zones. For more information, see [Cross-zone load balancing](edit-target-group-attributes.md#modify-cross-zone).
+ When DNS failover occurs, it impacts all target groups associated with the load balancer. Ensure that you have enough capacity in your remaining zones to handle this additional traffic, especially if cross-zone load balancing is off.
+ With DNS failover, we remove the IP addresses of the unhealthy zones from the DNS hostname for the load balancer. However, the local client DNS cache might contain these IP addresses until the time-to-live (TTL) in the DNS record expires (60 seconds).
+ With DNS failover, if there are multiple target groups attached to an Application Load Balancer and one target group is unhealthy in a zone, DNS health checks succeed if at least one other target group is healthy in that zone.
+ With DNS failover, if all load balancer zones are considered unhealthy, the load balancer sends traffic to all zones, including the unhealthy zones.
+ There are factors other than whether there are enough healthy targets that might lead to DNS failover, such as the health of the zone.

### Monitoring
<a name="target-group-health-monitoring"></a>

To monitor the health of your target groups, see [CloudWatch metrics for target group health](load-balancer-cloudwatch-metrics.md#target-group-health-metric-table).

### Example
<a name="target-group-health-examples"></a>

The following example demonstrates how target group health settings are applied.

**Scenario**
+ A load balancer that supports two Availability Zones, A and B
+ Each Availability Zone contains 10 registered targets
+ The target group has the following target group health settings:
  + DNS failover - 50%
  + Routing failover - 50%
+ Six targets fail in Availability Zone B

![\[A load balancer enabled for two zones. AZ A has 10 healthy targets and AZ B has 4 healthy targets and 6 unhealthy targets.\]](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/images/tg-health-example.png)


**If cross-zone load balancing is off**
+ The load balancer node in each Availability Zone can send traffic only to the 10 targets in its Availability Zone.
+ There are 10 healthy targets in Availability Zone A, which meets the required percentage of healthy targets. The load balancer continues to distribute traffic between the 10 healthy targets.
+ There are only 4 healthy targets in Availability Zone B, which is 40% of the targets for the load balancer node in Availability Zone B. Because this is less than the required percentage of healthy targets, the load balancer takes the following actions:
  + DNS failover - Availability Zone B is marked as unhealthy in DNS. Because clients can't resolve the load balancer name to the load balancer node in Availability Zone B, and Availability Zone A is healthy, clients send new connections to Availability Zone A.
  + Routing failover - When new connections are sent explicitly to Availability Zone B, the load balancer distributes traffic to all targets in Availability Zone B, including the unhealthy targets. This prevents outages among the remaining healthy targets.

**If cross-zone load balancing is on**
+ Each load balancer node can send traffic to all 20 registered targets across both Availability Zones.
+ There are 10 healthy targets in Availability Zone A and 4 healthy targets in Availability Zone B, for a total of 14 healthy targets. This is 70% of the targets for the load balancer nodes in both Availability Zones, which meets the required percentage of healthy targets.
+ The load balancer distributes traffic between the 14 healthy targets in both Availability Zones.

### Using Route 53 DNS failover for your load balancer
<a name="r53-dns-failover"></a>

If you use Route 53 to route DNS queries to your load balancer, you can also configure DNS failover for your load balancer using Route 53. In a failover configuration, Route 53 checks the health of the target group targets for the load balancer to determine whether they are available. If there are no healthy targets registered with the load balancer, or if the load balancer itself is unhealthy, Route 53 routes traffic to another available resource, such as a healthy load balancer or a static website in Amazon S3.

For example, suppose that you have a web application for `www.example.com`, and you want redundant instances running behind two load balancers residing in different Regions. You want the traffic to be primarily routed to the load balancer in one Region, and you want to use the load balancer in the other Region as a backup during failures. If you configure DNS failover, you can specify your primary and secondary (backup) load balancers. Route 53 directs traffic to the primary load balancer if it is available, or to the secondary load balancer otherwise.

**How evaluate target health works**
+ If evaluate target health is set to `Yes` on an alias record for an Application Load Balancer, Route 53 evaluates the health of the resource specified by the `alias target` value. Route 53 uses the target group health checks.
+ If all target groups attached to an Application Load Balancer are healthy, Route 53 marks the alias record as healthy. If you configured a threshold for a target group and it meets its threshold, it passes health checks. Otherwise, if a target group contains at least one healthy target, it passes health checks. If health checks pass, Route 53 returns records according to your routing policy. If a failover routing policy is used, Route 53 returns the primary record.
+ If any of the target groups attached to an Application Load Balancer are unhealthy, the alias record fails the Route 53 health check (fail-open). If using evaluate target health, the failover routing policy redirects traffic to the secondary resource.
+ If all target groups attached to an Application Load Balancer are empty (no targets), Route 53 considers the record unhealthy (fail-open). If using evaluate target health, the failover routing policy redirects traffic to the secondary resource.

For more information, see [Using load balancer target group health thresholds to improve availability](https://aws.amazon.com/blogs/networking-and-content-delivery/using-load-balancer-target-group-health-thresholds-to-improve-availability/) in the AWS Blog and [Configuring DNS failover](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring.html) in the *Amazon Route 53 Developer Guide*.

# Create a target group for your Application Load Balancer
<a name="create-target-group"></a>

You register your targets with a target group. By default, the load balancer sends requests to registered targets using the port and protocol that you specified for the target group. You can override this port when you register each target with the target group.

After you create a target group, you can add tags.

To route traffic to the targets in a target group, specify the target group in an action when you create a listener or create a rule for your listener. For more information, see [Listener rules for your Application Load Balancer](listener-rules.md). You can specify the same target group in multiple listeners, but these listeners must belong to the same Application Load Balancer. To use a target group with a load balancer, you must verify that the target group is not in use by a listener for any other load balancer.

You can add or remove targets from your target group at any time. For more information, see [Register targets with your Application Load Balancer target group](target-group-register-targets.md). You can also modify the health check settings for your target group. For more information, see [Update the health check settings of an Application Load Balancer target group](modify-health-check-settings.md).

------
#### [ Console ]

**To create a target group**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose **Create target group**.

1. For **Choose a target type**, select **Instances** to register targets by instance ID, **IP addresses** to register targets by IP address, or **Lambda function** to register a Lambda function as a target.

1. For **Target group name**, type a name for the target group. This name must be unique per region per account, can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens, and must not begin or end with a hyphen.

1. (Optional) For **Protocol** and **Port**, modify the default values as needed.

1. If the target type is **Instances** or **IP addresses**, choose **IPv4** or **IPv6** as the **IP address type**, otherwise skip to the next step.

   Note that only targets that have the selected IP address type can be included in this target group. The IP address type can't be changed after the target group is created.

1. For **VPC**, select a virtual private cloud (VPC). Note that for **IP addresses** target types, the VPCs available for selection are those that support the **IP address type** that you chose in the previous step. 

1. (Optional) For **Protocol version**, modify the default value as needed. For more information, see [Protocol version](load-balancer-target-groups.md#target-group-protocol-version).

1. (Optional) In the **Health checks** section, modify the default settings as needed. For more information, see [Health check settings](target-group-health-checks.md#health-check-settings).

1. If the target type is **Lambda function**, you can enable health checks by selecting **Enable** in the **Health checks** section.

1.  (Optional) To enable ** Target optimizer ** on the target group, specify a target control port. The port cannot be modified after target group creation. Target optimizer works with the help of an agent that you install on targets. For more information, see [Target Optimizer](target-group-register-targets.md#register-targets-target-optimizer). 

1. (Optional) Add one or more tags as follows:

   1. Expand the **Tags** section.

   1. Choose **Add tag**.

   1. Enter the tag key and the tag value.

1. Choose **Next**.

1. (Optional) Add one or more targets as follows:
   + If the target type is **Instances**, select one or more instances, enter one or more ports, and then choose **Include as pending below**.

     **Note: **The instances must have an assigned primary IPv6 address to be registered with a IPv6 target group.
   + If the target type is **IP addresses**, do the following:

     1. Select a network **VPC** from the list, or choose **Other private IP addresses**.

     1. Enter the IP address manually, or find the IP address using instance details. You can enter up to five IP addresses at a time.

     1. Enter the ports for routing traffic to the specified IP addresses. 

     1. Choose **Include as pending below**. 
   + If the target type is a **Lambda function**, specify a single Lambda function or omit this step and specify a Lambda function later.

1. Choose **Create target group**.

------
#### [ AWS CLI ]

**To create a target group**  
Use the [create-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-target-group.html) command. The following example creates a target group with the HTTP protocol, targets registered by IP address, one tag, and default health check settings.

```
aws elbv2 create-target-group \
    --name my-target-group \
    --protocol HTTP \
    --port 80 \
    --target-type ip \
    --vpc-id vpc-1234567890abcdef0 \
    --tags Key=department,Value=123
```

**To register targets**  
Use the [register-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/register-targets.html) command to register targets with the target group. For examples, see [Register targets](target-group-register-targets.md#register-targets).

------
#### [ CloudFormation ]

**To create a target group**  
Define a resource of type [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html). The following example creates a target group with the HTTP protocol, targets registered by IP address, one tag, default health check settings, and two registered targets.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      Tags: 
        - Key: 'department'
          Value: '123'
      Targets:
        - Id: 10.0.50.10
          Port: 80
        - Id: 10.0.50.20
          Port: 80
```

------

# Health checks for Application Load Balancer target groups
<a name="target-group-health-checks"></a>

Your Application Load Balancer periodically sends requests to its registered targets to test their status. These tests are called *health checks*.

Each load balancer node routes requests only to the healthy targets in the enabled Availability Zones for the load balancer. Each load balancer node checks the health of each target, using the health check settings for the target groups with which the target is registered. After your target is registered, it must pass one health check to be considered healthy. After each health check is completed, the load balancer node closes the connection that was established for the health check.

If a target group contains only unhealthy registered targets, the load balancer routes requests to all those targets, regardless of their health status. This means that if all targets fail health checks at the same time in all enabled Availability Zones, the load balancer fails open. The effect of the fail-open is to allow traffic to all targets in all enabled Availability Zones, regardless of their health status, based on the load balancing algorithm.

Health checks do not support WebSockets.

For more information, see [Target group health](load-balancer-target-groups.md#target-group-health).

You can use health check logs to capture detailed information about the health checks made to your registered targets for your load balancer and store them as log files in Amazon S3. You can use these health check logs to troubleshoot issues with your targets. For more information, see [Health check logs](load-balancer-health-check-logs.md).

**Topics**
+ [Health check settings](#health-check-settings)
+ [Target health status](#target-health-states)
+ [Health check reason codes](#target-health-reason-codes)
+ [Check target health](check-target-health.md)
+ [Update health check settings](modify-health-check-settings.md)

## Health check settings
<a name="health-check-settings"></a>

You configure health checks for the targets in a target group as described in the following table. The setting names used in the table are the names used in the API. The load balancer sends a health check request to each registered target every **HealthCheckIntervalSeconds** seconds, using the specified port, protocol, and health check path. Each health check request is independent and the result lasts for the entire interval. The time that it takes for the target to respond does not affect the interval for the next health check request. If the health checks exceed **UnhealthyThresholdCount** consecutive failures, the load balancer takes the target out of service. When the health checks exceed **HealthyThresholdCount** consecutive successes, the load balancer puts the target back in service.

Note that when you deregister a target, this decreases **HealthyHostCount** but does not increase **UnhealthyHostCount**.


| Setting | Description | 
| --- | --- | 
| **HealthCheckProtocol** |  The protocol the load balancer uses when performing health checks on targets. For Application Load Balancers the possible protocols are HTTP and HTTPS. The default is the HTTP protocol. These protocols use the HTTP GET method to send health check requests.  | 
| **HealthCheckPort** |  The port the load balancer uses when performing health checks on targets. The default is to use the port on which each target receives traffic from the load balancer.  | 
| **HealthCheckPath** |  The destination for health checks on the targets. If the protocol version is HTTP/1.1 or HTTP/2, specify a valid URI (/*path*?*query*). The default is /. If the protocol version is gRPC, specify the path of a custom health check method with the format `/package.service/method`. The default is `/AWS.ALB/healthcheck`.  | 
| **HealthCheckTimeoutSeconds** |  The amount of time, in seconds, during which no response from a target means a failed health check. The range is 2–120 seconds. The default is 5 seconds if the target type is `instance` or `ip` and 30 seconds if the target type is `lambda`.  | 
| **HealthCheckIntervalSeconds** |  The approximate amount of time, in seconds, between health checks of an individual target. The range is 5–300 seconds. The default is 30 seconds if the target type is `instance` or `ip` and 35 seconds if the target type is `lambda`.  | 
| **HealthyThresholdCount** |  The number of consecutive successful health checks required before considering an unhealthy target healthy. The range is 2–10. The default is 5.  | 
| **UnhealthyThresholdCount** |  The number of consecutive failed health checks required before considering a target unhealthy. The range is 2–10. The default is 2.  | 
| **Matcher** |  The codes to use when checking for a successful response from a target. These are called **Success codes** in the console. If the protocol version is HTTP/1.1 or HTTP/2, the possible values are from 200 to 499. You can specify multiple values (for example, "200,202") or a range of values (for example, "200-299"). The default value is 200. If the protocol version is gRPC, the possible values are from 0 to 99. You can specify multiple values (for example, "0,1") or a range of values (for example, "0-5"). The default value is 12.  | 

## Target health status
<a name="target-health-states"></a>

Before the load balancer sends a health check request to a target, you must register it with a target group, specify its target group in a listener rule, and ensure that the Availability Zone of the target is enabled for the load balancer. Before a target can receive requests from the load balancer, it must pass the initial health checks. After a target passes the initial health checks, its status is `Healthy`.

The following table describes the possible values for the health status of a registered target.


| Value | Description | 
| --- | --- | 
| `initial` |  The load balancer is in the process of registering the target or performing the initial health checks on the target. Related reason codes: `Elb.RegistrationInProgress` \$1 `Elb.InitialHealthChecking`  | 
| `healthy` |  The target is healthy. Related reason codes: None  | 
| `unhealthy` |  The target did not respond to a health check or failed the health check. Related reason codes: `Target.ResponseCodeMismatch` \$1 `Target.Timeout` \$1 `Target.FailedHealthChecks` \$1 `Elb.InternalError`  | 
| `unused` |  The target is not registered with a target group, the target group is not used in a listener rule, the target is in an Availability Zone that is not enabled, or the target is in the stopped or terminated state. Related reason codes: `Target.NotRegistered` \$1 `Target.NotInUse` \$1 `Target.InvalidState` \$1 `Target.IpUnusable`  | 
| `draining` |  The target is deregistering and connection draining is in process. Related reason code: `Target.DeregistrationInProgress`  | 
| `unavailable` |  Health checks are disabled for the target group. Related reason code: `Target.HealthCheckDisabled`  | 

## Health check reason codes
<a name="target-health-reason-codes"></a>

If the status of a target is any value other than `Healthy`, the API returns a reason code and a description of the issue, and the console displays the same description. Reason codes that begin with `Elb` originate on the load balancer side and reason codes that begin with `Target` originate on the target side. For more information about possible causes for health check failures, see [Troubleshooting](load-balancer-troubleshooting.md#target-not-inservice).


| Reason code | Description | 
| --- | --- | 
| `Elb.InitialHealthChecking` |  Initial health checks in progress  | 
| `Elb.InternalError` |  Health checks failed due to an internal error  | 
| `Elb.RegistrationInProgress` |  Target registration is in progress  | 
| `Target.DeregistrationInProgress` |  Target deregistration is in progress  | 
| `Target.FailedHealthChecks` |  Health checks failed  | 
| `Target.HealthCheckDisabled` |  Health checks are disabled  | 
| `Target.InvalidState` |  Target is in the stopped state Target is in the terminated state Target is in the terminated or stopped state Target is in an invalid state  | 
| `Target.IpUnusable` |  The IP address cannot be used as a target, as it is in use by a load balancer  | 
| `Target.NotInUse` |  Target group is not configured to receive traffic from the load balancer Target is in an Availability Zone that is not enabled for the load balancer  | 
| `Target.NotRegistered` |  Target is not registered to the target group  | 
| `Target.ResponseCodeMismatch` |  Health checks failed with these codes: [*code*]  | 
| `Target.Timeout` |  Request timed out  | 

# Check the health of your Application Load Balancer targets
<a name="check-target-health"></a>

You can check the health status of the targets registered with your target groups. For help with health check failures, see [Troubleshooting: A registered target is not in service](load-balancer-troubleshooting.md#target-not-inservice).

You can use health check logs to capture detailed information about the health checks made to your registered targets for your load balancer and store them as log files in Amazon S3. You can use these health check logs to troubleshoot issues with your targets. For more information, see [Health check logs](load-balancer-health-check-logs.md).

------
#### [ Console ]

**To check the health of your targets**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. The **Details** tab displays the total number of targets, plus the number of targets for each health status.

1. On the **Targets** tab, the **Status** column indicates the status of each target.

1. If the status is any value other than `Healthy`, the **Status details** column contains more information.

**To receive email notifications about unhealthy targets**  
Use CloudWatch alarms to trigger a Lambda function to send details about unhealthy targets. For step-by-step instructions, see the following blog post: [Identifying unhealthy targets of your load balancer](https://aws.amazon.com/blogs/networking-and-content-delivery/identifying-unhealthy-targets-of-elastic-load-balancer/).

------
#### [ AWS CLI ]

**To check the health of your targets**  
Use the [describe-target-health](https://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-target-health.html) command. This example filters the output to include only targets that are not healthy. For targets that are not healthy, the output includes a reason code.

```
aws elbv2 describe-target-health \
    --target-group-arn target-group-arn \
    --query "TargetHealthDescriptions[?TargetHealth.State!='healthy'].[Target.Id,TargetHealth.State,TargetHealth.Reason]" \
    --output table
```

The following is example output.

```
----------------------------------------------
|            DescribeTargetHealth            |
+--------------+---------+-------------------+
|  172.31.0.57 |  unused |  Target.NotInUse  |
|  172.31.0.50 |  unused |  Target.NotInUse  |
+--------------+---------+-------------------+
```

------

## Target states and reason codes
<a name="target-states-reason-codes"></a>

The following list shows the possible reason codes for each target state.

**Target state is healthy**  
A reason code is not provided.

**Target state is initial**  
+  `Elb.RegistrationInProgress` - The target is in the process of being registered with the load balancer.
+  `Elb.InitialHealthChecking` - The load balancer is still sending the target the minimum number of health checks required to determine its health status.

**Target state is unhealthy**  
+ `Target.ResponseCodeMismatch` - The health checks did not return an expected HTTP code.
+ `Target.Timeout` - The health check requests timed out.
+ `Target.FailedHealthChecks` - The load balancer received an error while establishing a connection to the target or the target response was malformed.
+ `Elb.InternalError` - The health checks failed due to an internal error.

**Target state is unused**  
+ `Target.NotRegistered` - The target is not registered with the target group.
+ `Target.NotInUse` - The target group is not used by any load balancer or the target is in an Availability Zone that is not enabled for its load balancer.
+ `Target.InvalidState` - The target is in the stopped or terminated state.
+ `Target.IpUnusable` - The target IP address is reserved for use by a load balancer.

**Target state is draining**  
+ `Target.DeregistrationInProgress` - The target is in the process of being deregistered and the deregistration delay period has not expired.

**Target state is unavailable**  
+ `Target.HealthCheckDisabled` - Health checks are disabled for the target group.

# Update the health check settings of an Application Load Balancer target group
<a name="modify-health-check-settings"></a>

You can update the health check settings for your target group at any time. For the list of health check settings, see [Health check settings](target-group-health-checks.md#health-check-settings).

------
#### [ Console ]

**To update the health check settings**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Health checks** tab, choose **Edit**.

1. On the **Edit health check settings** page, modify the settings as needed.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update the health check settings**  
Use the [modify-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group.html) command. The following example updates the **HealthyThresholdCount** and **HealthCheckTimeoutSeconds** settings.

```
aws elbv2 modify-target-group \
    --target-group-arn target-group-arn \
    --healthy-threshold-count 3 \
    --health-check-timeout-seconds 20
```

------
#### [ CloudFormation ]

**To update the health check settings**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the updated health check settings. The following example updates the **HealthyThresholdCount** and **HealthCheckTimeoutSeconds** settings.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: instance
      VpcId: !Ref myVPC
      HealthyThresholdCount: 3
      HealthCheckTimeoutSeconds: 20
```

------

# Edit target group attributes for your Application Load Balancer
<a name="edit-target-group-attributes"></a>

After you create a target group for you Application Load Balancer, you can edit its target group attributes.

**Topics**
+ [Deregistration delay](#deregistration-delay)
+ [Routing algorithm](#modify-routing-algorithm)
+ [Slow start mode](#slow-start-mode)
+ [Health settings](#modify-target-group-health-settings)
+ [Cross-zone load balancing](#modify-cross-zone)
+ [Automatic Target Weights (ATW)](#automatic-target-weights)
+ [Sticky sessions](#sticky-sessions)

## Deregistration delay
<a name="deregistration-delay"></a>

Elastic Load Balancing stops sending requests to targets that are deregistering. By default, Elastic Load Balancing waits 300 seconds before completing the deregistration process, which can help in-flight requests to the target to complete. To change the amount of time that Elastic Load Balancing waits, update the deregistration delay value.

The initial state of a deregistering target is `draining`. After the deregistration delay elapses, the deregistration process completes and the state of the target is `unused`. If the target is part of an Auto Scaling group, it can be terminated and replaced.

If a deregistering target has no in-flight requests and no active connections, Elastic Load Balancing immediately completes the deregistration process, without waiting for the deregistration delay to elapse. However, even though target deregistration is complete, the status of the target is displayed as `draining` until the deregistration delay timeout expires. After the timeout expires, the target transitions to an `unused` state.

If a deregistering target terminates the connection before the deregistration delay elapses, the client receives a 500-level error response.

------
#### [ Console ]

**To update the deregistration delay value**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. In the **Target deregistration management** pane, enter a new value for **Deregistration delay**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update the deregistration delay value**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `deregistration_delay.timeout_seconds` attribute.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=deregistration_delay.timeout_seconds,Value=60"
```

------
#### [ CloudFormation ]

**To update the deregistration delay value**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `deregistration_delay.timeout_seconds` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "deregistration_delay.timeout_seconds"
          Value: "60"
```

------

## Routing algorithm
<a name="modify-routing-algorithm"></a>

A routing algorithm is a method used by the load balancer when determining which targets will receive requests. The **round robin** routing algorithm is used by default to route requests at the target group level. The **least outstanding requests** and **weighted random** routing algorithms are also available based on the needs of your application. A target group can only have one active routing algorithm at a time, however the routing algorithm can be updated whenever needed.

If you enable sticky sessions, the selected routing algorithm is used for the initial target selection. Future requests from the same client will be forwarded to the same target, bypassing the selected routing algorithm. If you have enabled target optimizer, the routing algorithm can only be round robin.

**Round robin**
+ The round robin routing algorithm routes requests evenly across healthy targets in the target group, in a sequential order.
+ This algorithm is commonly used when the requests being received are similar in complexity , the registered targets are similar in processing capability, or if you need to distribute requests equally among targets. 

**Least outstanding requests**
+ The least outstanding requests routing algorithm routes requests to the targets with the lowest number of in progress requests.
+ This algorithm is commonly used when the requests being received vary in complexity, the registered targets vary in processing capability.
+ When a load balancer that supports HTTP/2 is using targets that only support HTTP/1.1, it converts the request to multiple HTTP/1.1 requests. In this configuration the least outstanding requests algorithm will treat each HTTP/2 request as multiple requests.
+ When using WebSockets, the target is selected using the least outstanding requests algorithm. After the target is selected, the load balancer creates a connection to the target and sends all messages over this connection.
+ The least outstanding requests routing algorithm can not be used with slow start mode.

**Weighted random**
+ The weighted random routing algorithm routes requests evenly across healthy targets in the target group, in a random order.
+ This algorithm supports Automatic Target Weights (ATW) anomaly mitigation.
+ The weighted random routing algorithm can not be used with slow start mode.
+ The weighted random routing algorithm can not be used with sticky sessions.

------
#### [ Console ]

**To update the routing algorithm**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. In the **Traffic configuration** pane, for **Load balancing algorithm**, choose **Round robin**, **Least outstanding requests**, or **Weighted random**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update the routing algorithm**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `load_balancing.algorithm.type` attribute.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=load_balancing.algorithm.type,Value=least_outstanding_requests"
```

------
#### [ CloudFormation ]

**To update the routing algorithm**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `load_balancing.algorithm.type` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "load_balancing.algorithm.type"
          Value: "least_outstanding_requests"
```

------

## Slow start mode
<a name="slow-start-mode"></a>

By default, a target starts to receive its full share of requests as soon as it is registered with a target group and passes an initial health check. Using slow start mode gives targets time to warm up before the load balancer sends them a full share of requests.

After you enable slow start for a target group, its targets enter slow start mode when they are considered healthy by the target group. A target in slow start mode exits slow start mode when the configured slow start duration period elapses or the target becomes unhealthy. The load balancer linearly increases the number of requests that it can send to a target in slow start mode. After a healthy target exits slow start mode, the load balancer can send it a full share of requests.

**Considerations**
+ When you enable slow start for a target group, the healthy targets registered with the target group do not enter slow start mode.
+ When you enable slow start for an empty target group and then register targets using a single registration operation, these targets do not enter slow start mode. Newly registered targets enter slow start mode only when there is at least one healthy target that is not in slow start mode.
+ If you deregister a target in slow start mode, the target exits slow start mode. If you register the same target again, it enters slow start mode when it is considered healthy by the target group.
+ If a target in slow start mode becomes unhealthy, the target exits slow start mode. When the target becomes healthy, it enters slow start mode again.
+ You can't enable slow start mode when using the **least outstanding requests** or **weighted random** routing algorithms.

------
#### [ Console ]

**To update the slow start duration value**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. In the **Traffic configuration** pane, enter a new value for **Slow start duration**. To disable slow start mode, enter 0.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update the slow start duration value**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `slow_start.duration_seconds` attribute.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=slow_start.duration_seconds,Value=30"
```

------
#### [ CloudFormation ]

**To update the slow start duration value**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `slow_start.duration_seconds` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "slow_start.duration_seconds"
          Value: "30"
```

------

## Health settings
<a name="modify-target-group-health-settings"></a>

By default, Application Load Balancers monitor the health of targets and route requests to healthy targets. However, if the load balancer doesn't have enough healthy targets, it automatically sends traffic to all registered targets (fail open). You can modify the target group health settings for your target group to define the thresholds for DNS failover and routing failover. For more information, see [Target group health](load-balancer-target-groups.md#target-group-health).

------
#### [ Console ]

**To modify target group health settings**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. Check whether cross-zone load balancing is turned on or turned off. Update this setting as needed to ensure that you have enough capacity to handle the additional traffic if a zone fails.

1. Expand **Target group health requirements**.

1. For **Configuration type**, we recommend that you choose **Unified configuration**, which sets the same threshold for both actions.

1. For **Healthy state requirements**, do one of the following:
   + Choose **Minimum healthy target count**, and then enter a number from 1 to the maximum number of targets for your target group.
   + Choose **Minimum healthy target percentage**, and then enter a number from 1 to 100.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To modify target group health settings**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command. The following example sets the healthy threshold for both unhealthy state actions to 50%.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes \
        "Key=target_group_health.dns_failover.minimum_healthy_targets.percentage,Value=50" \
        "Key=target_group_health.unhealthy_state_routing.minimum_healthy_targets.percentage,Value=50"
```

------
#### [ CloudFormation ]

**To modify target group health settings**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource. The following example sets the healthy threshold for both unhealthy state actions to 50%.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "target_group_health.dns_failover.minimum_healthy_targets.percentage"
          Value: "50"
        - Key: "target_group_health.unhealthy_state_routing.minimum_healthy_targets.percentage"
          Value: "50"
```

------

## Cross-zone load balancing
<a name="modify-cross-zone"></a>

The nodes for your load balancer distribute requests from clients to registered targets. When cross-zone load balancing is on, each load balancer node distributes traffic across the registered targets in all registered Availability Zones. When cross-zone load balancing is off, each load balancer node distributes traffic only across the registered targets in its Availability Zone. This could be if zonal failure domains are preferred over regional, ensuring that a healthy zone isn't impacted by an unhealthy zone, or for overall latency improvements.

With Application Load Balancers, cross-zone load balancing is always turned on at the load balancer level, and cannot be turned off. For target groups, the default is to use the load balancer setting, but you can override the default by explicitly turning cross-zone load balancing off at the target group level.

**Considerations**
+ Target stickiness is not supported when cross-zone load balancing is off.
+ Lambda functions as targets are not supported when cross-zone load balancing is off.
+ Attempting to turn off cross-zone load balancing through the `ModifyTargetGroupAttributes` API if any targets have parameter `AvailabilityZone` set to `all` results in an error.
+ When registering targets, the `AvailabilityZone` parameter is required. Specific Availability Zone values are only allowed when cross-zone load balancing is off. Otherwise, the parameter is ignored and treated as `all`.

**Best practices**
+ Plan for enough target capacity across all Availability Zones that you expect to utilize, per target group. If you can't plan for enough capacity across all participating Availability Zones, we recommend that you keep cross-zone load balancing on.
+ When configuring your Application Load Balancer with multiple target groups, ensure all target groups are participating in the same Availability Zones, within the configured Region. This is to avoid an Availability Zone being empty while cross-zone load balancing is off, as this triggers a 503 error for all HTTP requests that enter the empty Availability Zone.
+ Avoid creating empty subnets. Application Load Balancers expose zonal IP addresses through DNS for the empty subnets, which triggers 503 errors for HTTP requests.
+ There can be occurrences where a target group with cross-zone load balancing turned off has enough planned target capacity per Availability Zone, but all targets in an Availability Zone become unhealthy. When there is at least one target group with all unhealthy targets, the IP addresses of the load balancer nodes are removed from DNS. After the target group has at least one healthy target, the IP addresses are restored to DNS.

### Turn off cross-zone load balancing
<a name="cross_zone_console_disable"></a>

You can turn off cross-zone load balancing for your Application Load Balancer target groups at any time.

------
#### [ Console ]

**To turn off cross-zone load balancing**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, select **Edit**.

1. In the **Target selection configuration** pane, choose **Off** for **Cross-zone load balancing**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To turn off cross-zone load balancing**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command and set the `load_balancing.cross_zone.enabled` attribute to `false`.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=load_balancing.cross_zone.enabled,Value=false"
```

------
#### [ CloudFormation ]

**To turn off cross-zone load balancing**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `load_balancing.cross_zone.enabled` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "load_balancing.cross_zone.enabled"
          Value: "false"
```

------

### Turn on cross-zone load balancing
<a name="cross_zone_console_enable"></a>

You can turn on cross-zone load balancing for your Application Load Balancer target groups at any time. The cross-zone load balancing setting at the target group level overrides the setting at the load balancer level.

------
#### [ Console ]

**To turn off cross-zone load balancing**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, select **Edit**.

1. In the **Target selection configuration** pane, choose **On** for **Cross-zone load balancing**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To turn on cross-zone load balancing**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command and set the `load_balancing.cross_zone.enabled` attribute to `true`.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=load_balancing.cross_zone.enabled,Value=true"
```

------
#### [ CloudFormation ]

**To turn on cross-zone load balancing**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `load_balancing.cross_zone.enabled` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "load_balancing.cross_zone.enabled"
          Value: "true"
```

------

## Automatic Target Weights (ATW)
<a name="automatic-target-weights"></a>

Automatic Target Weights (ATW) constantly monitors the targets running your applications, detecting significant performance deviations, known as anomalies. ATW provides the ability to dynamically adjust the amount of traffic routed to targets, through real time data anomaly detection.

Automatic Target Weights (ATW) performs anomaly detection on every Application Load Balancer in your account automatically. When anomalous targets are identified, ATW can automatically attempt to stabilize them by reducing the amount of traffic they're routed, known as anomaly mitigation. ATW continuously optimizes traffic distribution to maximize per-target success rates while minimizing target group failure rates.

**Considerations:**
+ Anomaly detection currently monitors HTTP 5xx response codes coming from, and connection failures to, your targets. Anomaly detection is always on and can't be turned off.
+ ATW is not supported when using Lambda as a target.

**Contents**
+ [Anomaly detection](#anomaly-detection)
+ [Anomaly mitigation](#anomaly-mitigation)

### Anomaly detection
<a name="anomaly-detection"></a>

ATW anomaly detection monitors for any targets that are displaying a significant deviation in behavior from other targets in their target group. These deviations, called anomalies, are determined by comparing the percent errors of one target with the percent errors of other targets in the target group. These errors can be both connection errors and HTTP error codes. Targets reporting significantly higher than their peers are then considered anomalous.

Anomaly detection requires a minimum of three healthy targets in the target group. When a target is registered to a target group it must pass the health checks before receiving traffic. After the target starts receiving traffic, ATW begins monitoring the target and continuously publishes the anomaly result. For targets without anomalies, the anomaly result is `normal`. For targets with anomalies, the anomaly result is `anomalous`.

ATW anomaly detection works independently from target group health checks. A target can be passing all target group health checks, but still be marked anomalous due to an elevated error rate. Targets becoming anomalous does not affect their target group health check status.

**Anomaly detection status**

You can view the current anomaly detection status. The following are the possible values:
+ `normal` – No anomalies were detected.
+ `anomalous` – Anomalies were detected.

------
#### [ Console ]

**To view the anomaly detection status**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. Choose the **Targets** tab.

1. Within the **Registered targets** table, the **Anomaly detection result** column displays the anomaly status of each target.

------
#### [ AWS CLI ]

**To view the anomaly detection status**  
Use the [describe-target-health](https://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-target-health.html) command. The following example displays the status for every target in the specified target group.

```
aws elbv2 describe-target-health \
    --target-group-arn target-group-arn \
    --include AnomalyDetection
```

------

### Anomaly mitigation
<a name="anomaly-mitigation"></a>

ATW anomaly mitigation routes traffic away from anomalous targets automatically, giving them an opportunity to recover.

**Requirement**  
The anomaly mitigation function of ATW is only available when using the **Weighted random** routing algorithm.

**During mitigation:**
+ ATW periodically adjusts the amount of traffic routed to anomalous targets. Currently, the period is every five seconds.
+ ATW reduces the amount of traffic routed to anomalous targets to the minimum amount required to perform anomaly mitigation.
+ Targets which are no longer detected as anomalous will gradually have more traffic routed to them until they reach parity with other normal targets in the target group.

------
#### [ Console ]

**To turn on anomaly mitigation**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. In the **Traffic configuration** pane, verify that the selected value for **Load balancing algorithm** is **Weighted random**.

   When the weighted random algorithm is initially selected, anomaly detection is on by default.

1. Under **Anomaly mitigation**, ensure that **Turn on anomaly mitigation** is selected.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To turn on anomaly mitigation**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `load_balancing.algorithm.anomaly_mitigation` attribute.

```
aws elbv2 
```

------

**Mitigation status**

You can check whether ATW is performing mitigation on a target. The following are the possible values:
+ `yes` – Mitigation is in progress.
+ `no` – Mitigation is not in progress.

------
#### [ Console ]

**To view the anomaly mitigation status**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. Choose the **Targets** tab.

1. Within the **Registered targets** table, you can view the anomaly mitigation status of each target in the **Mitigation in effect** column.

------
#### [ AWS CLI ]

**To view the anomaly mitigation status**  
Use the [describe-target-health](https://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-target-health.html) command. The following example displays the status for every target in the specified target group.

```
aws elbv2 describe-target-health \
    --target-group-arn target-group-arn \
    --include AnomalyDetection
```

------

## Sticky sessions
<a name="sticky-sessions"></a>

By default, an Application Load Balancer routes each request independently to a registered target based on the chosen load-balancing algorithm. However, you can use the sticky session feature (also known as session affinity) to enable the load balancer to bind a user's session to a specific target. This ensures that all requests from the user during the session are sent to the same target. This feature is useful for servers that maintain state information in order to provide a continuous experience to clients. To use sticky sessions, the client must support cookies.

Application Load Balancers support both duration-based cookies and application-based cookies. Sticky sessions are enabled at the target group level. You can use a combination of duration-based stickiness, application-based stickiness, and no stickiness across your target groups.

The key to managing sticky sessions is determining how long your load balancer should consistently route the user's request to the same target. If your application has its own session cookie, then you can use application-based stickiness and the load balancer 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 use duration-based stickiness to generate a load balancer session cookie with a duration that you specify.

The content of load balancer generated cookies are encrypted using a rotating key. You can't decrypt or modify load balancer generated cookies. 

For both stickiness types, the Application Load Balancer resets the expiry of the cookies it generates after every request. If a cookie expires, the session is no longer sticky and the client should remove the cookie from its cookie store.

**Requirements**
+ An HTTP/HTTPS load balancer.
+ At least one healthy instance in each Availability Zone.

**Considerations**
+ Sticky sessions are not supported if [cross-zone load balancing](#modify-cross-zone) is disabled. Attempts to enable sticky sessions while cross-zone load balancing is disabled fail.
+ For application-based cookies, cookie names have to be specified individually for each target group. However, for duration-based cookies, `AWSALB` is the only name used across all target groups.
+ If you are using multiple layers of Application Load Balancers, you can enable sticky sessions across all layers with application-based cookies. However, with duration-based cookies, you can enable sticky sessions only on one layer, because `AWSALB` is the only name available.
+ If the Application Load Balancer receives both an `AWSALBCORS` and an `AWSALB` duration-based stickiness cookie, the value in `AWSALBCORS` will take precedence.
+ Application-based stickiness does not work with weighted target groups.
+ If you have a [forward action](rule-action-types.md#forward-actions) with multiple target groups, and sticky sessions are enabled for one or more of the target groups, you must enable stickiness at the target group level.
+ WebSocket connections are inherently sticky. If the client requests a connection upgrade to WebSockets, the target that returns an HTTP 101 status code to accept the connection upgrade is the target used in the WebSockets connection. After the WebSockets upgrade is complete, cookie-based stickiness is not used.
+ Application Load Balancers use the `Expires` attribute in the cookie header instead of the `Max-Age` attribute.
+ Application Load Balancers do not support cookie values that are URL encoded.
+ If the Application Load Balancer receives a new request while the target is draining due to deregistration, the request is routed to a healthy target.
+ Sticky sessions are not supported if target optimizer is enabled.

**Topics**
+ [Duration-based stickiness](#duration-based-stickiness)
+ [Application-based stickiness](#application-based-stickiness)

### Duration-based stickiness
<a name="duration-based-stickiness"></a>

Duration-based stickiness routes requests to the same target in a target group using a load balancer generated cookie (`AWSALB`). The cookie is used to map the session to the target. If your application does not have its own session cookie, you can specify your own stickiness duration and manage how long your load balancer should consistently route the user's request to the same target. 

When a load balancer first receives a request from a client, it routes the request to a target (based on the chosen algorithm), and generates a cookie named `AWSALB`. It encodes information about the selected target, encrypts the cookie, and includes the cookie in the response to the client. The load balancer generated cookie has its own expiry of 7 days which is non-configurable.

In subsequent requests, the client should include the `AWSALB` cookie. When the load balancer receives a request from a client that contains the cookie, it detects it and routes the request to the same target. If the cookie is present but can't be decoded, or if it refers to a target that was deregistered or is unhealthy, the load balancer selects a new target and updates the cookie with information about the new target.

For cross-origin resource sharing (CORS) requests, some browsers require `SameSite=None; Secure` to enable stickiness. To support these browsers the load balancer always generates a second stickiness cookie, `AWSALBCORS`, which includes the same information as the original stickiness cookie, as well as the `SameSite` attribute. Clients receive both cookies, including non CORS requests.

------
#### [ Console ]

**To enable duration-based stickiness**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. Under **Target selection configuration**, do the following:

   1. Select **Turn on stickiness**.

   1. For **Stickiness type**, select **Load balancer generated cookie**.

   1. For **Stickiness duration**, specify a value between 1 second and 7 days.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To enable duration-based stickiness**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `stickiness.enabled` and `stickiness.lb_cookie.duration_seconds` attributes.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes \
        "Key=stickiness.enabled,Value=true" \
        "Key=stickiness.lb_cookie.duration_seconds,Value=300"
```

------
#### [ CloudFormation ]

**To enable duration-based stickiness**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `stickiness.enabled` and `stickiness.lb_cookie.duration_seconds` attributes.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "stickiness.enabled"
          Value: "true" 
        - Key: "stickiness.lb_cookie.duration_seconds"
          Value: "300"
```

------

### Application-based stickiness
<a name="application-based-stickiness"></a>

Application-based stickiness gives you the flexibility to set your own criteria for client-target stickiness. When you enable application-based stickiness, the load balancer routes the first request to a target within the target group based on the chosen algorithm. The target is expected to set a custom application cookie that matches the cookie configured on the load balancer to enable stickiness. This custom cookie can include any of the cookie attributes required by the application.

When the Application Load Balancer receives the custom application cookie from the target, it automatically generates a new encrypted application cookie to capture stickiness information. This load balancer generated application cookie captures stickiness information for each target group that has application-based stickiness enabled. 

The load balancer generated application cookie does not copy the attributes of the custom cookie set by the target. It has its own expiry of 7 days which is non-configurable. In the response to the client, the Application Load Balancer only validates the name with which the custom cookie was configured at the target group level and not the value or the expiry attribute of the custom cookie. As long as the name matches, the load balancer sends both cookies, the custom cookie set by the target, and the application cookie generated by the load balancer, in the response to the client. 

In subsequent requests, clients have to send back both cookies to maintain stickiness. The load balancer decrypts the application cookie, and checks whether the configured duration of stickiness is still valid. It then uses the information in the cookie to send the request to the same target within the target group to maintain stickiness. The load balancer also proxies the custom application cookie to the target without inspecting or modifying it. In subsequent responses, the expiry of the load balancer generated application cookie and the duration of stickiness configured on the load balancer are reset. To maintain stickiness between client and target, the expiry of the cookie, and the duration of stickiness should not elapse.

If a target fails or becomes unhealthy, the load balancer stops routing requests to that target, and chooses a new healthy target based on the chosen load balancing algorithm. The load balancer treats the session as now being "stuck" to the new healthy target, and continues routing requests to the new healthy target even if the failed target comes back.

With cross-origin resource sharing (CORS) requests, to enable stickiness, the load balancer adds the `SameSite=None; Secure` attributes to the load balancer generated application cookie only if the user-agent version is Chromium80 or above.

Because most browsers limit cookies to 4K in size, the load balancer shards application cookies greater than 4K into multiple cookies. Application Load Balancers support cookies up to 16K in size and can therefore create up to 4 shards that it sends to the client. The application cookie name that the client sees begins with “AWSALBAPP-" and includes a fragment number. For example, if the cookie size is 0-4K, the client sees AWSALBAPP-0. If the cookie size is 4-8k, the client sees AWSALBAPP-0 and AWSALBAPP-1, and so on.

------
#### [ Console ]

**To enable application-based stickiness**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. Under **Target selection configuration**, do the following:

   1. Select **Turn on stickiness**.

   1. For **Stickiness type**, select **Application-based cookie**.

   1. For **Stickiness duration**, specify a value between 1 second and 7 days.

   1. For **App cookie name**, enter a name for your application-based cookie.

      Do not use `AWSALB`, `AWSALBAPP`, or `AWSALBTG` for the cookie name; they're reserved for use by the load balancer.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To enable application-based stickiness**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the following attributes:
+ `stickiness.enabled`
+ `stickiness.type`
+ `stickiness.app_cookie.cookie_name`
+ `stickiness.app_cookie.duration_seconds`

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes \
        "Key=stickiness.enabled,Value=true" \
        "Key=stickiness.type,Value=app_cookie" \
        "Key=stickiness.app_cookie.cookie_name,Value=my-cookie-name" \
        "Key=stickiness.app_cookie.duration_seconds,Value=300"
```

------
#### [ CloudFormation ]

**To enable application-based stickiness**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the following attributes:
+ `stickiness.enabled`
+ `stickiness.type`
+ `stickiness.app_cookie.cookie_name`
+ `stickiness.app_cookie.duration_seconds`

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      TargetGroupAttributes: 
        - Key: "stickiness.enabled"
          Value: "true" 
        - Key: "stickiness.type"
          Value: "app_cookie" 
        - Key: "stickiness.app_cookie.cookie_name"
          Value: "my-cookie-name" 
        - Key: "stickiness.app_cookie.duration_seconds"
          Value: "300"
```

------

**Manual rebalancing**

When scaling up, if the number of targets increase considerably, there is potential for unequal distribution of load due to stickiness. In this scenario, you can rebalance the load on your targets using the following two options:
+ Set an expiry on the cookie generated by the application that is prior to the current date and time. This prevents clients from sending the cookie to the Application Load Balancer, which will restart the process of establishing stickiness.
+ Set a short duration on the load balancer's application-based stickiness configuration; for example, 1 second. This forces the Application Load Balancer to reestablish stickiness even if the cookie set by the target is not expired.

# Register targets with your Application Load Balancer target group
<a name="target-group-register-targets"></a>

You register your targets with a target group. When you create a target group, you specify its target type, which determines how you register its targets. For example, you can register instance IDs, IP addresses, or Lambda functions. For more information, see [Target groups for your Application Load Balancers](load-balancer-target-groups.md).

If demand on your currently registered targets increases, you can register additional targets in order to handle the demand. When your target is ready to handle requests, register it with your target group. The load balancer starts routing requests to the target as soon as the registration process completes and the target passes the initial health checks.

If demand on your registered targets decreases, or you need to service a target, you can deregister it from your target group. The load balancer stops routing requests to a target as soon as you deregister it. When the target is ready to receive requests, you can register it with the target group again.

When you deregister a target, the load balancer waits until in-flight requests have completed. This is known as *connection draining*. The status of a target is `draining` while connection draining is in progress.

When you deregister a target that was registered by IP address, you must wait for the deregistration delay to complete before you can register the same IP address again.

If you are registering targets by instance ID, you can use your load balancer with an Auto Scaling group. After you attach a target group to an Auto Scaling group and the group scales out, the instances launched by the Auto Scaling group are automatically registered with the target group. If you detach the target group from the Auto Scaling group, the instances are automatically deregistered from the target group. For more information, see [Attaching a load balancer to your Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html) in the *Amazon EC2 Auto Scaling User Guide*.

When shutting down an application on a target you must first deregister the target from its target group and allow time for existing connections to drain. You can monitor deregistration status using the describe-target-health CLI command, or by refreshing the target group view in the AWS Management Console. After confirming the target is deregistered you can proceed with stopping or terminating the application. This sequence prevents users from experiencing 5XX errors when applications are terminated while still processing traffic.

## Target security groups
<a name="target-security-groups"></a>

When you register EC2 instances as targets, you must ensure that the security groups for your instances allow the load balancer to communicate with your instances on both the listener port and the health check port.


**Recommended rules**  

| 
| 
| **Inbound** | 
| --- |
|  Source  |  Port Range  |  Comment  | 
| load balancer security group | instance listener | Allow traffic from the load balancer on the instance listener port | 
| load balancer security group | health check | Allow traffic from the load balancer on the health check port | 

We also recommend that you allow inbound ICMP traffic to support Path MTU Discovery. For more information, see [Path MTU Discovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/network_mtu.html#path_mtu_discovery) in the *Amazon EC2 User Guide*.

## Target Optimizer
<a name="register-targets-target-optimizer"></a>

Target optimizer lets you enforce strict concurrency on targets in a target group. It works with the help of an agent that you install and configure on targets. The agent serves as an inline proxy between the load balancer and your application. You configure the agent to enforce a maximum number of concurrent requests that the load balancer can send to the target. The agent tracks the number of requests the target is processing. When the number falls below the configured maximum value, the agent sends a signal to the load balancer letting it know that the target is ready to process another request.

To enable target optimizer, you specify a target control port when creating the target group. The load balancer establishes control channels with agents on this port for management traffic. This port is different from the port on which the load balancer sends application traffic. Targets registered with the target group must have the agent running on them. 

 ** Note: Target optimizer can only be enabled during target group creation. Target control port cannot be modified after creation.** 

The agent is available as a Docker image at: ` public.ecr.aws/aws-elb/target-optimizer/target-control-agent:latest`. You configure the following environment variables when running the agent container:

`TARGET_CONTROL_DATA_ADDRESS`  
The agent receives application traffic from the load balancer on this socket (IP:port). The port in this socket is the application traffic port you configure for the target group. By default, the agent can accept both plaintext and TLS connections.

`TARGET_CONTROL_CONTROL_ADDRESS`  
The agent receives management traffic from the load balancer on this socket (IP:port). The port in the socket is the target control port you configure for the target group. 

`TARGET_CONTROL_DESTINATION_ADDRESS`  
The agent proxies application traffic to this socket (IP:port). Your application should be listening on this socket.

(Optional) `TARGET_CONTROL_MAX_CONCURRENCY`  
The maximum number of concurrent requests that the target will receive from the load balancer. It can be between 0-1000. The default is 1.

(Optional) `TARGET_CONTROL_TLS_CERT_PATH`  
The location of the TLS certificate that the agent provides to the load balancer during TLS handshake. By default, the agent generates a self-signed certificate in-memory.

(Optional) `TARGET_CONTROL_TLS_KEY_PATH`  
The location of the private key corresponding to the TLS certificate that the agent provides to the load balancer during TLS handshake. By default, the agent generates a private key in-memory. 

(Optional) `TARGET_CONTROL_TLS_SECURITY_POLICY`  
The ELB security policy that you configure for the target group. The default is `ELBSecurityPolicy-2016-08`.

(Optional) `TARGET_CONTROL_PROTOCOL_VERSION`  
The protocol through which the load balancer communicates with the agent. Possible values are ` HTTP1`, ` HTTP2`, ` GRPC`. The default is ` HTTP1`.

(Optional) `RUST_LOG`  
The log level of the agent process. The agent software is written in Rust. Possible values are ` debug`, ` info`,and ` error` . The default is ` info`. 

 To modify the value for any environment variable, you have to restart the agent with the new value. You can monitor target optimizer with the following metrics: `TargetControlRequestCount`, `TargetControlRequestRejectCount`, `TargetControlActiveChannelCount`, `TargetControlNewChannelCount`, `TargetControlChannelErrorCount`,` TargetControlWorkQueueLength`, `TargetControlProcessedBytes`. For more information, see [Target optimizer metrics](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html#target-optimizer-metric-table) For troubleshooting information, see [Troubleshooting target optimizer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html#troubleshoot-target-optimizer) 

## Shared subnets
<a name="register-targets-shared-subnets"></a>

Participants can create an Application Load Balancer in a shared VPC. Participants can't register a target that runs in a subnet that is not shared with them.

## Register targets
<a name="register-targets"></a>

Each target group must have at least one registered target in each Availability Zone that is enabled for the load balancer.

The target type of your target group determines how you register targets with that target group. For more information, see [Target type](load-balancer-target-groups.md#target-type).

**Requirements and considerations**
+ An instance must be in the `running` state when you register it.
+ A target instance must be in the virtual private cloud (VPC) that you specified for the target group.
+ When registering targets by instance ID for a IPv6 target group, the targets must have an assigned primary IPv6 address. To learn more, see [ IPv6 addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#ipv6-addressing) in the *Amazon EC2 User Guide*
+ When registering targets by IP address for an IPv4 target group, the IP addresses that you register must be from one of the following CIDR blocks:
  + The subnets of the target group VPC
  + 10.0.0.0/8 (RFC 1918)
  + 100.64.0.0/10 (RFC 6598)
  + 172.16.0.0/12 (RFC 1918)
  + 192.168.0.0/16 (RFC 1918)
+ When registering targets by IP address for an IPv6 target group, the IP addresses that you register must be within the VPC IPv6 CIDR block or within the IPv6 CIDR block of a peered VPC.
+ You can't register the IP addresses of another Application Load Balancer in the same VPC. If the other Application Load Balancer is in a VPC that is peered to the load balancer VPC, you can register its IP addresses.

------
#### [ Console ]

**To register targets**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. Choose the **Targets** tab.

1. Choose **Register targets**.

1. If the target type of the target group is `instance`, select available instances, override the default port if needed, and then choose **Include as pending below**.

1. If the target type of the target group is `ip`, for each IP address, select the network, enter the IP addresses and ports, and choose **Include as pending below**.

1. If the target type of the target group is `lambda`, select the Lambda function or enter its ARN. For more information, see [Use Lambda functions as targets](lambda-functions.md).

1. Choose **Register pending targets**.

------
#### [ AWS CLI ]

**To register targets**  
Use the [register-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/register-targets.html) command. The following example registers targets by instance ID. Because the port is not specified, the load balancer uses the target group port.

```
aws elbv2 register-targets \
    --target-group-arn target-group-arn \
    --targets Id=i-1234567890abcdef0 Id=i-0abcdef1234567890
```

The following example registers targets by IP address. Because the port is not specified, the load balancer uses the target group port.

```
aws elbv2 register-targets \
    --target-group-arn target-group-arn \
    --targets Id=10.0.50.10 Id=10.0.50.20
```

The following example registers a Lambda function as a target.

```
aws elbv2 register-targets \
    --target-group-arn target-group-arn \
    --targets Id=lambda-function-arn
```

------
#### [ CloudFormation ]

**To register targets**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the new targets. The following example registers two targets by instance ID.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: instance
      VpcId: !Ref myVPC
      Targets:
        - Id: !GetAtt Instance1.InstanceId
          Port: 80
        - Id: !GetAtt Instance2.InstanceId
          Port: 80
```

------

## Deregister targets
<a name="deregister-targets"></a>

If demand on your application decreases, or if you need to service your targets, you can deregister targets from your target groups. Deregistering a target removes it from your target group, but does not affect the target otherwise.

------
#### [ Console ]

**To deregister targets**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Targets** tab, select the targets to remove.

1. Choose **Deregister**.

1. When prompted for confirmation, choose **Deregister**.

------
#### [ AWS CLI ]

**To deregister targets**  
Use the [deregister-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/deregister-targets.html) command. The following example deregisters two targets that were registered by instance ID.

```
aws elbv2 deregister-targets \
    --target-group-arn target-group-arn \
    --targets Id=i-1234567890abcdef0 Id=i-0abcdef1234567890
```

------

# Use Lambda functions as targets of an Application Load Balancer
<a name="lambda-functions"></a>

You can register your Lambda functions as targets and configure a listener rule to forward requests to the target group for your Lambda function. When the load balancer forwards the request to a target group with a Lambda function as a target, it invokes your Lambda function and passes the content of the request to the Lambda function, in JSON format.

The load balancer invokes the Lambda function directly instead of using a network connection. Therefore, there are no requirements for the outbound rules of the Application Load Balancer security groups.

**Limits**
+ The Lambda function and target group must be in the same account and in the same Region.
+ The maximum size of the request body that you can send to a Lambda function is 1 MB. For related size limits, see [HTTP header limits](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/how-elastic-load-balancing-works.html#http-header-limits).
+ The maximum size of the response JSON that the Lambda function can send is 1 MB.
+ WebSockets are not supported. Upgrade requests are rejected with an HTTP 400 code.
+ Local Zones are not supported.
+ Automatic Target Weights (ATW) is not supported.

**Topics**
+ [Prepare the Lambda function](#prepare-lambda-function)
+ [Create a target group for the Lambda function](#create-lambda-target-group)
+ [Receive events from the load balancer](#receive-event-from-load-balancer)
+ [Respond to the load balancer](#respond-to-load-balancer)
+ [Multi-value headers](#multi-value-headers)
+ [Enable health checks](#enable-health-checks-lambda)
+ [Register the Lambda function](#register-lambda-function)
+ [Deregister the Lambda function](#deregister-lambda-function)

For a demo, see [Lambda target on Application Load Balancer](https://exampleloadbalancer.com/lambda_demo.html).

## Prepare the Lambda function
<a name="prepare-lambda-function"></a>

The following recommendations apply if you are using your Lambda function with an Application Load Balancer.

**Permissions to invoke the Lambda function**  
If you create the target group and register the Lambda function using the AWS Management Console, the console adds the required permissions to your Lambda function policy on your behalf. Otherwise, after you create the target group and register the function using the AWS CLI, you must use the [add-permission](https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html) command to grant Elastic Load Balancing permission to invoke your Lambda function. We recommend that you use the `aws:SourceAccount` and `aws:SourceArn` condition keys to restrict function invocation to the specified target group. For more information, see [The confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) in the *IAM User Guide*,

```
aws lambda add-permission \
    --function-name lambda-function-arn-with-alias-name \ 
    --statement-id elb1 \
    --principal elasticloadbalancing.amazonaws.com \
    --action lambda:InvokeFunction \
    --source-arn target-group-arn \
    --source-account target-group-account-id
```

**Lambda function versioning**  
You can register one Lambda function per target group. To ensure that you can change your Lambda function and that the load balancer always invokes the current version of the Lambda function, create a function alias and include the alias in the function ARN when you register the Lambda function with the load balancer. For more information, see [AWS Lambda function aliases](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) in the *AWS Lambda Developer Guide*.

**Function timeout**  
The load balancer waits until your Lambda function responds or times out. We recommend that you configure the timeout of the Lambda function based on your expected run time. For information about the default timeout value and how to change it, see [Configure Lambda function timeout](https://docs.aws.amazon.com/lambda/latest/dg/configuration-timeout.html). For information about the maximum timeout value that you can configure, see [AWS Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html).

## Create a target group for the Lambda function
<a name="create-lambda-target-group"></a>

Create a target group, which is used in request routing. If the request content matches a listener rule with an action to forward it to this target group, the load balancer invokes the registered Lambda function.

------
#### [ Console ]

**To create a target group and register the Lambda function**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose **Create target group**.

1. For **Choose a target type**, select **Lambda function**.

1. For **Target group name**, enter a name for the target group.

1. (Optional) To enable health checks, choose **Enable** in the **Health checks** section.

1. (Optional) Expand **Tags**. For each tag, choose **Add new tag** and enter a tag key and a tag value.

1. Choose **Next**.

1. If you are ready to register the Lambda function, choose **Select a Lambda function** and choose the Lambda function from the list, or choose **Enter a Lambda function ARN** and enter the ARN of the Lambda function,

   If you are not ready to register the Lambda function, choose **Register Lambda function later** and register the target later on. For more information, see [Register targets](target-group-register-targets.md#register-targets).

1. Choose **Create target group**.

------
#### [ AWS CLI ]

**To create a target group of type lambda**  
Use the [create-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-target-group.html) command.

```
aws elbv2 create-target-group \
    --name my-target-group \
    --target-type lambda
```

**To register the Lambda function**  
Use the [register-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/register-targets.html) command.

```
aws elbv2 register-targets \
    --target-group-arn target-group-arn \
    --targets Id=lambda-function-arn
```

------
#### [ CloudFormation ]

**To create a target group and register the Lambda function**  
Define a resource of type [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html). If you aren't ready to register the Lambda function now, you can omit the `Targets` property and add it later on.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      TargetType: lambda
      Tags: 
        - Key: 'department'
          Value: '123'
      Targets:
        - Id: !Ref myLambdaFunction
```

------

## Receive events from the load balancer
<a name="receive-event-from-load-balancer"></a>

The load balancer supports Lambda invocation for requests over both HTTP and HTTPS. The load balancer sends an event in JSON format. The load balancer adds the following headers to every request: `X-Amzn-Trace-Id`, `X-Forwarded-For`, `X-Forwarded-Port`, and `X-Forwarded-Proto`.

If the `content-encoding` header is present, the load balancer Base64 encodes the body and sets `isBase64Encoded` to `true`.

If the `content-encoding` header is not present, Base64 encoding depends on the content type. For the following types, the load balancer sends the body as is and sets `isBase64Encoded` to `false`: text/\$1, application/json, application/javascript, and application/xml. Otherwise, the load balancer Base64 encodes the body and sets `isBase64Encoded` to `true`.

The following is an example event.

```
{
    "requestContext": {
        "elb": {
            "targetGroupArn": "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09"
        }
    },
    "httpMethod": "GET",
    "path": "/",
    "queryStringParameters": {parameters},
    "headers": {
        "accept": "text/html,application/xhtml+xml",
        "accept-language": "en-US,en;q=0.8",
        "content-type": "text/plain",
        "cookie": "cookies",
        "host": "lambda-846800462-us-east-2.elb.amazonaws.com",
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)",
        "x-amzn-trace-id": "Root=1-5bdb40ca-556d8b0c50dc66f0511bf520",
        "x-forwarded-for": "72.21.198.66",
        "x-forwarded-port": "443",
        "x-forwarded-proto": "https"
    },
    "isBase64Encoded": false,
    "body": "request_body"
}
```

## Respond to the load balancer
<a name="respond-to-load-balancer"></a>

The response from your Lambda function must include the Base64 encoding status, status code, and headers. You can omit the body.

To include a binary content in the body of the response, you must Base64 encode the content and set `isBase64Encoded` to `true`. The load balancer decodes the content to retrieve the binary content and sends it to the client in the body of the HTTP response.

The load balancer does not honor hop-by-hop headers, such as `Connection` or `Transfer-Encoding`. You can omit the `Content-Length` header because the load balancer computes it before sending responses to clients.

The following is an example response from a **nodejs** based Lambda function.

```
{
    "isBase64Encoded": false,
    "statusCode": 200,
    "statusDescription": "200 OK",
    "headers": {
        "Set-cookie": "cookies",
        "Content-Type": "application/json"
    },
    "body": "Hello from Lambda (optional)"
}
```

For Lambda function templates that work with Application Load Balancers, see [application-load-balancer-serverless-app](https://github.com/aws/elastic-load-balancing-tools/tree/master/application-load-balancer-serverless-app) on github. Alternatively, open the [Lambda console](https://console.aws.amazon.com/lambda), choose **Applications**, **Create a application**, and select one of the following from the AWS Serverless Application Repository:
+ ALB-Lambda-Target-UploadFiletoS3
+ ALB-Lambda-Target-BinaryResponse
+ ALB-Lambda-Target-WhatisMyIP

## Multi-value headers
<a name="multi-value-headers"></a>

If requests from a client or responses from a Lambda function contain headers with multiple values or contains the same header multiple times, or query parameters with multiple values for the same key, you can enable support for multi-value header syntax. After you enable multi-value headers, the headers and query parameters exchanged between the load balancer and the Lambda function use arrays instead of strings. If you do not enable multi-value header syntax and a header or query parameter has multiple values, the load balancer uses the last value that it receives.

**Topics**
+ [Requests with multi-value headers](#multi-value-headers-request)
+ [Responses with multi-value headers](#multi-value-headers-response)
+ [Enable multi-value headers](#enable-multi-value-headers)

### Requests with multi-value headers
<a name="multi-value-headers-request"></a>

The names of the fields used for headers and query string parameters differ depending on whether you enable multi-value headers for the target group.

The following example request has two query parameters with the same key:

```
http://www.example.com?&myKey=val1&myKey=val2
```

With the default format, the load balancer uses the last value sent by the client and sends you an event that includes query string parameters using `queryStringParameters`. For example:

```
"queryStringParameters": { "myKey": "val2"},
```

If you enable multi-value headers, the load balancer uses both key values sent by the client and sends you an event that includes query string parameters using `multiValueQueryStringParameters`. For example:

```
"multiValueQueryStringParameters": { "myKey": ["val1", "val2"] },
```

Similarly, suppose that the client sends a request with two cookies in the header:

```
"cookie": "name1=value1",
"cookie": "name2=value2",
```

With the default format, the load balancer uses the last cookie sent by the client and sends you an event that includes headers using `headers`. For example:

```
"headers": {
    "cookie": "name2=value2",
    ...
},
```

If you enable multi-value headers, the load balancer uses both cookies sent by the client and sends you an event that includes headers using `multiValueHeaders`. For example:

```
"multiValueHeaders": {
    "cookie": ["name1=value1", "name2=value2"],
    ...
},
```

If the query parameters are URL-encoded, the load balancer does not decode them. You must decode them in your Lambda function.

### Responses with multi-value headers
<a name="multi-value-headers-response"></a>

The names of the fields used for headers differ depending on whether you enable multi-value headers for the target group. You must use `multiValueHeaders` if you have enabled multi-value headers and `headers` otherwise.

With the default format, you can specify a single cookie:

```
{
  "headers": {
      "Set-cookie": "cookie-name=cookie-value;Domain=myweb.com;Secure;HttpOnly",
      "Content-Type": "application/json"
  },
}
```

If you enable multi-value headers, you must specify multiple cookies as follows:

```
{
  "multiValueHeaders": {
      "Set-cookie": ["cookie-name=cookie-value;Domain=myweb.com;Secure;HttpOnly","cookie-name=cookie-value;Expires=May 8, 2019"],
      "Content-Type": ["application/json"]
  },
}
```

The load balancer might send the headers to the client in a different order than the order specified in the Lambda response payload. Therefore, do not count on headers being returned in a specific order.

### Enable multi-value headers
<a name="enable-multi-value-headers"></a>

You can enable or disable multi-value headers for a target group with the target type `lambda`.

------
#### [ Console ]

**To enable multi-value headers**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Attributes** tab, choose **Edit**.

1. Enable **Multi value headers**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To enable multi-value headers**  
Use the [modify-target-group-attributes](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group-attributes.html) command with the `lambda.multi_value_headers.enabled` attribute.

```
aws elbv2 modify-target-group-attributes \
    --target-group-arn target-group-arn \
    --attributes "Key=lambda.multi_value_headers.enabled,Value=true"
```

------
#### [ CloudFormation ]

**To enable multi-value headers**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `lambda.multi_value_headers.enabled` attribute.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      TargetType: lambda
      Tags: 
        - Key: 'department'
          Value: '123'
      Targets:
        - Id: !Ref myLambdaFunction
      TargetGroupAttributes:
        - Key: "lambda.multi_value_headers.enabled"
          Value: "true"
```

------

## Enable health checks
<a name="enable-health-checks-lambda"></a>

By default, health checks are disabled for target groups of type `lambda`. You can enable health checks in order to implement DNS failover with Amazon Route 53. The Lambda function can check the health of a downstream service before responding to the health check request. If the response from the Lambda function indicates a health check failure, the health check failure is passed to Route 53. You can configure Route 53 to fail over to a backup application stack.

You are charged for health checks as you are for any Lambda function invocation.

The following is the format of the health check event sent to your Lambda function. To check whether an event is a health check event, check the value of the user-agent field. The user agent for health checks is `ELB-HealthChecker/2.0`.

```
{
    "requestContext": {
        "elb": {
            "targetGroupArn": "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09"
        }
    },
    "httpMethod": "GET",  
    "path": "/",  
    "queryStringParameters": {},  
    "headers": {
        "user-agent": "ELB-HealthChecker/2.0"
    },  
    "body": "",  
    "isBase64Encoded": false
}
```

------
#### [ Console ]

**To enable health checks for a lambda target group**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Health checks** tab, choose **Edit**.

1. For **Health checks**, select **Enable**.

1. (Optional) Update the health check settings as needed.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To enable health checks for a lambda target group**  
Use the [modify-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-target-group.html) command.

```
aws elbv2 modify-target-group \
    --target-group-arn target-group-arn \
    --health-check-enabled
```

------
#### [ CloudFormation ]

**To enable health checks for a lambda target group**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      TargetType: lambda
      HealthCheckEnabled: true
      Tags: 
        - Key: 'department'
          Value: '123'
      Targets:
        - Id: !Ref myLambdaFunction
```

------

## Register the Lambda function
<a name="register-lambda-function"></a>

You can register a single Lambda function with each target group. To replace a Lambda function, we recommend that you create a new target group, register the new function with the new target group, and update the listener rules to use the new target group.

------
#### [ Console ]

**To register a Lambda function**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Targets** tab, if there is no Lambda function registered, choose **Register target**.

1. Select the Lambda function or enter its ARN.

1. Choose **Register**.

------
#### [ AWS CLI ]

**To register a Lambda function**  
Use the [register-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/register-targets.html) command.

```
aws elbv2 register-targets \
    --target-group-arn target-group-arn \
    --targets Id=lambda-function-arn
```

------
#### [ CloudFormation ]

**To register a Lambda function**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      TargetType: lambda
      Tags: 
        - Key: 'department'
          Value: '123'
      Targets:
        - Id: !Ref myLambdaFunction
```

------

## Deregister the Lambda function
<a name="deregister-lambda-function"></a>

If you no longer need to send traffic to your Lambda function, you can deregister it. After you deregister a Lambda function, in-flight requests fail with HTTP 5XX errors.

To replace a Lambda function, we recommend that you create a new target group, register the new function with the new target group, and update the listener rules to use the new target group.

------
#### [ Console ]

**To deregister a Lambda function**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Targets** tab, select the target and choose **Deregister**.

1. When prompted for confirmation, choose **Deregister**.

------
#### [ AWS CLI ]

**To deregister a Lambda function**  
Use the [deregister-targets](https://docs.aws.amazon.com/cli/latest/reference/elbv2/deregister-targets.html) command.

```
aws elbv2 deregister-targets \
    --target-group-arn target-group-arn \
    --targets Id=lambda-function-arn
```

------

# Tags for your Application Load Balancer target group
<a name="target-group-tags"></a>

Tags help you to categorize your target groups in different ways, for example, by purpose, owner, or environment.

You can add multiple tags to each target group. Tag keys must be unique for each target group. If you add a tag with a key that is already associated with the target group, it updates the value of that tag.

When you are finished with a tag, you can remove it.

**Restrictions**
+ Maximum number of tags per resource—50
+ Maximum key length—127 Unicode characters
+ Maximum value length—255 Unicode characters
+ Tag keys and values are case-sensitive. Allowed characters are letters, spaces, and numbers representable in UTF-8, plus the following special characters: \$1 - = . \$1 : / @. Do not use leading or trailing spaces.
+ Do not use the `aws:` prefix in your tag names or values because it is reserved for AWS use. You can't edit or delete tag names or values with this prefix. Tags with this prefix do not count against your tags per resource limit. 

------
#### [ Console ]

**To manage the tags for a target group**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Choose the name of the target group to open its details page.

1. On the **Tags** tab, choose **Manage tags** and do one or more of the following:

   1. To update a tag, enter new values for **Key** and **Value**.

   1. To add a tag, choose **Add tag** and enter values for **Key** and **Value**.

   1. To delete a tag, choose **Remove** next to the tag.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To add tags**  
Use the [add-tags](https://docs.aws.amazon.com/cli/latest/reference/elbv2/add-tags.html) command. The following example adds two tags.

```
aws elbv2 add-tags \
    --resource-arns target-group-arn \
    --tags "Key=project,Value=lima" "Key=department,Value=digital-media"
```

**To remove tags**  
Use the [remove-tags](https://docs.aws.amazon.com/cli/latest/reference/elbv2/remove-tags.html) command. The following example removes the tags with the specified keys.

```
aws elbv2 remove-tags \
    --resource-arns target-group-arn \
    --tag-keys project department
```

------
#### [ CloudFormation ]

**To add tags**  
Update the [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-targetgroup.html) resource to include the `Tags` property.

```
Resources:
  myTargetGroup:
    Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
    Properties:
      Name: my-target-group
      Protocol: HTTP
      Port: 80
      TargetType: ip
      VpcId: !Ref myVPC
      Tags: 
        - Key: 'project'
          Value: 'lima'
        - Key: 'department'
          Value: 'digital-media'
```

------

# Delete an Application Load Balancer target group
<a name="delete-target-group"></a>

You can delete a target group if it is not referenced by the forward actions of any listener rules. Deleting a target group does not affect the targets registered with the target group. If you no longer need a registered EC2 instance, you can stop or terminate it.

------
#### [ Console ]

**To delete a target group**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, under **Load Balancing**, choose **Target Groups**.

1. Select the target group and choose **Actions**, **Delete**.

1. Choose **Delete**.

------
#### [ AWS CLI ]

**To delete a target group**  
Use the [delete-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/delete-target-group.html) command.

```
aws elbv2 delete-target-group \
    --target-group-arn target-group-arn
```

------