Sub topic 7
Target groups and registering targets
This chapter assumes you know what an EC2 instance, a security group and a VPC subnet are, and that you have read the previous chapter on listeners and routing rules. You should be able to run AWS CLI commands.
What a target group is
A target group is the set of destinations that a load balancer sends requests to. A listener rule points at a target group, and the load balancer picks one registered, healthy target from that group for each request (Application Load Balancer) or each connection (Network Load Balancer).
A target group holds three kinds of settings:
- Routing settings: the protocol and port used to reach the targets, and the target type.
- Health check settings: how the load balancer decides whether a target can receive traffic. The next chapter covers these in detail.
- Attributes: behavior such as deregistration delay, load balancing algorithm and stickiness.
One load balancer can use many target groups, for example one for /api/* and one for /images/*. One target group can also be used by more than one rule.
Target types
The target type is fixed when you create the target group. You cannot change it later.
| Target type | What you register | Typical use |
|---|---|---|
| `instance` | EC2 instance IDs | Standard EC2 fleets and Auto Scaling groups |
| `ip` | Private IP addresses | Containers with their own network interface, on-premises servers reachable over VPN or Direct Connect, targets in peered VPCs |
| `lambda` | A single Lambda function | Serverless backends behind an Application Load Balancer |
| `alb` | An Application Load Balancer | A Network Load Balancer placed in front of an ALB |
With instance targets, traffic arrives at the primary private IP address of the instance's primary network interface. With ip targets, traffic goes to the address you give, and the address must come from the target group's VPC or from an RFC 1918 or RFC 6598 range. Public IP addresses cannot be registered.
Protocol and port
A target group has a protocol and a default port. The protocol describes how the load balancer talks to the target, and it does not have to match the listener. A common pattern is an HTTPS listener that terminates TLS and a target group that uses HTTP on port 80 or 8080.
You can override the port for each target when you register it. This matters when several copies of an application run on one instance, each on a different port. It is also how Amazon ECS registers containers that use dynamic host ports.
The protocol choices depend on the load balancer type:
- Application Load Balancer: HTTP and HTTPS. Protocol versions HTTP/1.1, HTTP/2 and gRPC are available.
- Network Load Balancer: TCP, UDP, TCP_UDP and TLS.
Creating a target group and registering targets
The topic's earlier example created a target group with create-target-group. This version adds a few settings you will often need, and then registers two instances.
TG_ARN=$(aws elbv2 create-target-group \
--name web-tg \
--protocol HTTP \
--port 80 \
--vpc-id vpc-0123456789abcdef0 \
--target-type instance \
--health-check-path /health \
--query 'TargetGroups[0].TargetGroupArn' \
--output text)
aws elbv2 register-targets \
--target-group-arn "$TG_ARN" \
--targets Id=i-0aaa1111bbbb2222c Id=i-0ddd3333eeee4444f,Port=8080The first instance uses the target group's default port 80. The second overrides it with port 8080. The same instance can be registered more than once with different ports, and each pair is treated as a separate target with its own health state.
To remove a target, call deregister-targets with the same ID and port:
aws elbv2 deregister-targets \
--target-group-arn "$TG_ARN" \
--targets Id=i-0ddd3333eeee4444f,Port=8080Deregistering does not terminate the instance. It only stops new requests from being sent to it.
Registration is a lifecycle
A newly registered target does not receive traffic immediately. It moves through states, and you can read them with describe-target-health.
initial: registration is in progress and the first health checks are running.healthy: the target passes checks and receives traffic.unhealthy: the target fails checks and receives no traffic, unless every target in the group is unhealthy (see the callout below).draining: the target is being deregistered. In-flight requests can finish, but no new ones arrive. The wait is the deregistration delay, 300 seconds by default.unused: the target is not registered, or its Availability Zone is not enabled on the load balancer.
This function prints the state of each target, along with the reason when the target is not healthy:
import boto3
elbv2 = boto3.client("elbv2")
def print_target_health(target_group_arn):
response = elbv2.describe_target_health(TargetGroupArn=target_group_arn)
for description in response["TargetHealthDescriptions"]:
target = description["Target"]
health = description["TargetHealth"]
line = f'{target["Id"]}:{target.get("Port", "-")} {health["State"]}'
if "Reason" in health:
line += f' ({health["Reason"]})'
print(line)The Reason field is the quickest clue when something is wrong. Values such as Target.Timeout, Target.ResponseCodeMismatch and Target.NotInUse point to different causes.
Attributes worth knowing
You change attributes with modify-target-group-attributes.
- Deregistration delay (
deregistration_delay.timeout_seconds): from 0 to 3600 seconds. Lower it for short requests so scale-in and deployments finish sooner. Raise it for long downloads or uploads. - Slow start (
slow_start.duration_seconds): ramps up traffic to a new target over 30 to 900 seconds, so a cold application is not flooded. It is available for ALB target groups. - Load balancing algorithm (
load_balancing.algorithm.type):round_robinis the default, andleast_outstanding_requestsfavors targets with fewer open requests. The second one helps when request durations vary a lot. - Stickiness (
stickiness.enabled): keeps a client on the same target using a cookie (ALB) or source IP (NLB). It reduces the evenness of load, so use it only when the application keeps state on the instance.
aws elbv2 modify-target-group-attributes \
--target-group-arn "$TG_ARN" \
--attributes \
Key=deregistration_delay.timeout_seconds,Value=60 \
Key=load_balancing.algorithm.type,Value=least_outstanding_requestsSecurity groups and network access
The target must accept traffic from the load balancer on the target port and on the health check port. For an ALB, the cleanest rule allows the target's security group to accept inbound traffic from the load balancer's security group, instead of a CIDR range. With ip targets in a peered VPC or on premises, you may need to allow the load balancer's subnet CIDR ranges, because the source address is the load balancer's private address in that subnet.
Common errors
- Wrong VPC. A target group belongs to one VPC, and
instancetargets must be in that VPC. Registration fails otherwise. - Registering and then waiting. A new target stays
initialuntil it passes the configured number of consecutive checks. Plan for this time in deployment scripts. - Blocked health check port. If the security group allows port 80 but the health check uses a different port, the target stays unhealthy with
Target.Timeout. - Manual registration on an Auto Scaling group. When an Auto Scaling group is attached to a target group, the group registers and deregisters its own instances. Manual changes to those instances get overwritten.
- Unused target group. A target group that no listener rule references shows its targets as
unusedwith the reasonTarget.NotInUse.
Exercise
A target group uses the default deregistration delay. An instance is deregistered while it serves a 20-second file download. What state does the instance show right after the deregister call, and what happens to the download?
Show answer
The instance shows draining. The load balancer sends it no new requests, and the in-flight download is allowed to finish, because the 20 seconds is well below the 300-second default delay. The target is removed once its requests complete or the delay expires, whichever comes first.
Exercise
You run two copies of an application on one EC2 instance, on ports 8080 and 8081, behind one target group. How do you register them, and how many health states will describe-target-health report for that instance?
Show answer
Register the same instance ID twice with different ports, for example Id=i-0aaa1111bbbb2222c,Port=8080 Id=i-0aaa1111bbbb2222c,Port=8081. Each instance and port pair is a separate target, so describe-target-health reports two health states.