Load balancing and observability on AWS

ALB target groups and health checks, CloudWatch logs, metrics and alarms, and the cost line that surprises everyone.

15 min read☁️ AWS for Backend Engineers

The load balancer is where traffic enters, and CloudWatch is where the evidence of what happened to it ends up. Both are the AWS spellings of things earlier courses covered generically: the system-design course's load-balancing lesson, and the observability course's metrics and alerting. This lesson is the specifics:

  • what an ALB actually does to a request;
  • what a health check must be;
  • how the metrics and logs land in CloudWatch;
  • which alarms are worth having;
  • where the bill comes from.

The Application Load Balancer

An ALB is a layer-7 (HTTP) load balancer. It terminates TLS with a certificate from ACM (free, auto-renewed) and listens on 443. It evaluates rules by host, path, header or query, and forwards to a target group: a set of targets (EC2 instances, ECS tasks, IP addresses, a Lambda) with a health check.

It is nginx's routing from the CI/CD course as a managed service, doing the ingress controller's job on EKS. It adds the forwarded headers the same way (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Port), so Spring's forwarded-headers strategy applies unchanged.

What it does that nginx on one host could not:

  • It is itself multi-AZ and scales with traffic.
  • It does connection draining (deregistration delay), so a task being replaced finishes its requests.
  • It can do sticky sessions, which the Kubernetes lesson said not to need.
  • It integrates with WAF for rate-based and signature rules, and with Cognito or OIDC for authentication at the edge, which the microservices course's gateway lesson discussed.

The NLB is the layer-4 sibling: TCP, no HTTP awareness, millions of connections and a static IP. Use it for gRPC pass-through, non-HTTP protocols, or a fixed address a partner must allow-list.

Two settings that bite. The idle timeout (default 60 s) closes a connection with no bytes in flight. So a request the service takes 70 s to answer is a 504 from the ALB while the JVM works on. It is the nginx lesson's proxy_read_timeout, again. And HTTP/2 to the target is not the default: a gRPC target group is its own protocol version setting.

Health checks: what the ALB must be told

A target group's health check is an HTTP request to a path on each target, every N seconds. A threshold of failures marks the target unhealthy, and it stops receiving traffic. A threshold of successes brings it back.

The path must be the Actuator lesson's readiness endpoint, not liveness. An unhealthy target is removed from rotation, not restarted. So a check that fails when the database is slow does the right thing here (no traffic to a target that cannot serve), and would do the wrong thing on a Kubernetes liveness probe (a restart).

ECS adds the restart on top: a task whose target stays unhealthy is stopped and replaced. That is why the ECS health check grace period must cover a Spring Boot start.

The failure mode to design for is every target unhealthy at once, because the check's dependency is down. The ALB then fails open: it routes to all targets anyway. That is the least-bad choice. Knowing it means a dashboard showing "0 healthy targets" during a database incident does not send you looking at the wrong thing.

CloudWatch: metrics, logs, and the shape of each

Metrics arrive from two directions.

  • AWS services publish their own: the ALB's RequestCount, TargetResponseTime, HTTPCode_Target_5XX_Count and HealthyHostCount; RDS's CPUUtilization, DatabaseConnections, FreeStorageSpace and ReadLatency; ECS's CPU and memory per service.
  • Your JVM publishes through Micrometer's CloudWatch registry. A cheaper option, with histograms intact, is Prometheus and a managed Grafana. The reason: CloudWatch's custom metrics are billed per metric per month, and a Micrometer registry with a high-cardinality tag (the observability course's warning) becomes a bill before it becomes a dashboard.

Metrics have a namespace, dimensions (the tags) and a resolution. One-minute is standard, and one-second costs more.

Logs go to CloudWatch Logs through the ECS awslogs driver, the CloudWatch agent on EC2, or Fluent Bit on EKS. You get a log group per service and a stream per task or instance, with a retention you must set: the default is forever, and forever is billed.

Write JSON (the structured-logging lesson) and Logs Insights queries it: fields @timestamp, level, msg | filter level = "ERROR" and traceId = "..." | sort @timestamp desc. Metric filters turn a log pattern into a metric, such as a count of ERROR lines or of a specific exception, for the alarms below. A log group is not a long-term archive: export to S3 with a lifecycle rule for what must be kept.

X-Ray is the tracing half, with an OpenTelemetry collector as the modern path in. The distributed-tracing lesson's propagation applies. The ALB also adds its own X-Amzn-Trace-Id header to every request, which is a free correlation id if nothing else is set.

Alarms: symptoms, with a runbook attached

A CloudWatch alarm watches one metric (or a metric math expression across several) against a threshold for N of M periods. It changes state (OK, ALARM or INSUFFICIENT_DATA) and sends to an SNS topic that pages, emails, or triggers automation. The alerting lesson's rule decides which alarms to make: symptoms the user feels, not causes.

The set that earns its keep for a Spring Boot service behind an ALB and RDS:

  • HTTPCode_Target_5XX_Count / RequestCount above 1% for 5 minutes — errors, as a ratio, so a quiet night does not page for one failure.
  • TargetResponseTime p99 above the SLO for 5 minutes — latency, using the percentile statistic, never the average.
  • HealthyHostCount below the minimum — capacity.
  • HTTPCode_ELB_5XX_Count — the load balancer's own errors: no healthy targets, or targets timing out (504).
  • RDS FreeStorageSpace below 20% and DatabaseConnections above 80% of the instance's maximum — the two that end in an outage with hours of warning.
  • A metric filter on the log group for OutOfMemoryError or OOMKilled events — the JVM lessons' failures, surfaced.

INSUFFICIENT_DATA is a state, not an absence: a metric that stops arriving because the task died is not OK, and the alarm's treat missing data as setting should be breaching for anything that means "the service is up". Composite alarms combine several so that one incident pages once. And every alarm's description is the runbook link, as the on-call lesson insists — an alarm that pages without saying what to do is noise with a phone number.

Cost: where the bill comes from, and the four habits

Compute is billed per hour or per second while it exists, whether or not it is busy. A development environment left running over a weekend is a real line. The items that surprise:

  • the NAT gateway (hourly plus per gigabyte; every ECR pull and S3 call from a private subnet crosses it unless there is a VPC endpoint);
  • data transfer out to the internet and between availability zones (cross-AZ traffic between a service and its database replica is billed);
  • CloudWatch custom metrics and logs ingestion;
  • EBS volumes and snapshots that outlive the instances they belonged to;
  • RDS storage and backups beyond the free retention.

Four habits, in the order they pay:

  1. Tag everything with a team and an environment, so the bill can be read by owner (Cost Explorer groups by tag).
  2. Set a budget alarm at the account level. It is one more CloudWatch alarm.
  3. Right-size from the metrics. An instance at 8% CPU for a month is the wrong size, and a Savings Plan or reserved instance for the steady baseline is 30 to 60% off compute you were going to run anyway.
  4. Turn off what is not serving: schedules for development environments, lifecycle rules for logs and objects, and a monthly look for orphaned volumes, addresses and load balancers.

Under the hood: what an ALB actually does to a connection, and how a CloudWatch metric is really assembled

The system-design course's load-balancing lesson covered the algorithm question generically, for any load balancer: round robin versus least-outstanding-requests, and why the choice changes p99 by an order of magnitude. What it did not cover is AWS's own architecture. That is worth being precise about, because "ALB" and "NLB" are not the same kind of thing with a different label. They operate at different layers of the stack, in ways that decide what each one can and cannot do.

An ALB is not one load balancer; it is a fleet, and it terminates two separate TCP connections.

An ALB node runs in each enabled availability zone, and AWS scales the number of nodes per zone with load, invisibly. This is part of why an ALB has no fixed IP address, only a DNS name that can resolve to several, changing IPs. A firewall that needs a static address in front of an ALB is therefore a real operational problem. It is usually solved by putting the ALB behind a fixed-IP mechanism rather than fighting it.

Architecturally, the client's TCP connection ends at the ALB node. The node terminates TLS and reads and parses the full HTTP request (host, path, headers, method: everything its layer-7 routing rules can match on). Then it opens its own, separate TCP connection to the chosen target and re-sends the request on it.

That second connection is what "connection draining" (deregistration delay) actually manages. When a target is being removed, the ALB stops opening new connections to it but lets requests already in flight on existing connections finish. The client-facing and target-facing connections are decoupled, so the ALB is free to hold the client waiting while the target-side request completes.

This two-connection design is also why an ALB can add headers, retry a failed connection attempt to a different target transparently, and multiplex many client connections onto fewer, reused target connections (HTTP keep-alive to targets). None of that requires anything from the client.

An NLB, by contrast, operates at layer 4 and, in the common case, does not terminate the TCP connection at all. It works by forwarding packets, and it preserves the client's source IP by default. An ALB, being a real proxy, replaces the source IP with its own and relies on X-Forwarded-For to carry the original. That is a frequent source of confusion when a service expects the connecting IP to be the client's.

An NLB assigns one static IP per availability zone (an Elastic IP can be attached). An ALB architecturally cannot offer that, because of the fleet-of-nodes design above. So NLB is the answer whenever a partner needs to allow-list a fixed address, or when a protocol other than HTTP is in play: raw TCP/UDP, or gRPC where the application, not the load balancer, needs to see and terminate the real client connection.

The throughput difference the two are known for follows directly from the work each performs. Parsing and re-establishing HTTP requests (ALB) costs far more per connection than forwarding packets (NLB). That is why NLB is rated for a much larger volume of connections per node, and is the choice when raw throughput, not HTTP-aware routing, is the requirement.

A CloudWatch metric is not a live read of "current state"; it is a pre-aggregated data point over a fixed period.

When the ALB (or any AWS service) "publishes" RequestCount, it is not sending one CloudWatch write per request. The data is collected and aggregated over an interval, the period: one minute by default for AWS's own metrics, configurable down to one second for the ones that support it. Only the aggregate is stored. For most metrics, CloudWatch keeps the sum, count, minimum, maximum and average for the period, not the individual samples.

When a dashboard or an alarm asks for TargetResponseTime, it must specify a statistic: Average, Sum, Maximum, or a percentile like p99. That statistic is computed from the aggregate CloudWatch already stored, not recomputed from raw request-level data after the fact.

That is why the alerting lesson's rule to use percentiles, never averages, matters mechanically and not just stylistically. An average over a one-minute period can hide a handful of very slow requests inside a mostly-fast minute, while a stored percentile statistic reflects the actual shape of that period's distribution.

It also explains a specific, easy-to-miss gap. A period with zero requests publishes no data point at all for TargetResponseTime, because there is nothing to aggregate. That is a different state from "latency was zero". It is exactly the case the INSUFFICIENT_DATA alarm state above exists to distinguish from OK.

Try it yourself

Diagnose a metric that "shows nothing happened"

A service behind an ALB is reported as completely unresponsive by an on-call engineer for a five-minute window. But the TargetResponseTime graph for that window in the CloudWatch console shows no line at all: not a spike, not a flat zero, nothing plotted. HealthyHostCount for the same window also shows no data.

Using what this lesson says about how a CloudWatch metric is assembled, and the target-group failure mode described earlier in the lesson, reason through what actually happened. Explain why "no data" is a different signal from "zero requests", and in this case a more alarming one.

Why missing data points, not a zero line, are the real signal

TargetResponseTime is only published when there is at least one request to aggregate for that period. No requests means no data point, so the graph shows a gap rather than a flat zero. Taken alone, a gap in TargetResponseTime could just mean no traffic arrived.

But HealthyHostCount is a state metric the ALB publishes continuously about the target group itself. It does not depend on request volume. A gap there almost always means the ALB itself stopped reporting. That points at one of two things:

  • A total loss of healthy targets. This matches the "every target unhealthy at once" failure mode described earlier, where the ALB fails open and routes anyway. The health-check pipeline that would normally keep publishing HealthyHostCount can itself be affected if the whole target group state is in flux.
  • More mundanely, the ALB or target group was deleted or replaced mid-window (a botched deploy, an infrastructure change), so there is nothing left to report on for part of the period.

The concrete next step is not to stare at the empty graph. Check HTTPCode_ELB_5XX_Count for the same window (the ALB's own error count, which is published independently of whether targets are healthy), and check the target group's current state directly. An empty graph is a prompt to ask "was anything even being measured", not "was performance good".

Misconceptions

  • "NLB is just a faster ALB." They are not the same mechanism at different speeds. An ALB terminates the client's TCP connection and opens a second one to the target, parsing full HTTP requests to route by host, path and header. An NLB forwards packets at layer 4 without that termination step in the common case. That is the actual source of both its higher throughput and its ability to offer a static IP per zone, which the ALB's multi-node architecture cannot do.
  • "A flat line at zero and a gap in the graph mean the same thing." CloudWatch only stores a data point for a period when there was something to aggregate. A period with no requests publishes no point, which renders as a gap, not a zero. A gap in a metric that AWS publishes continuously regardless of traffic (like HealthyHostCount) is a much stronger signal that something is actually broken. A gap in a request-driven metric like TargetResponseTime is not, because a genuinely quiet period produces one too.

Sources

  • AWS documentation, "How Elastic Load Balancing works" and "What is a Network Load Balancer?" — the ALB's per-zone node fleet and two-connection proxy model versus the NLB's packet-forwarding, static-IP design.
  • AWS documentation, "Application Load Balancer components" — target groups, health checks, and the X-Forwarded-For / X-Forwarded-Proto headers.
  • Amazon CloudWatch User Guide, "Amazon CloudWatch concepts" — metrics, periods, statistics and percentiles, and how data points are aggregated.
  • Amazon CloudWatch User Guide, "Alarm states and how Amazon CloudWatch alarms treat missing data."
Progress is saved on this device and to your account when signed in.