Nov 23, 20265 min read

Fix ALB 502 Bad Gateway Errors

How to tell whether an Application Load Balancer or your target produced a 502, and the usual causes: keep-alive timeouts shorter than the load balancer's idle timeout, malformed responses, resets during deploys and Lambda response limits.

Illustration for Fix ALB 502 Bad Gateway Errors

An ALB returns 502 when it received something from the target that it could not turn into a response. That covers a connection reset, a response with bad headers and a target that closed a connection at the wrong moment, so the status alone does not say which one you have.

Start by finding out who generated the 502, then match the pattern to the usual causes below.

Which 502 is it?

SignalMeaningWhere to look
HTTPCode_ELB_502_CountThe load balancer generated the 502CloudWatch ALB metrics
HTTPCode_Target_502_CountThe target itself returned a 502Your app or an upstream behind it
elb_status_code 502, target_status_code -No usable response from the targetALB access logs
Errors only during deploysTargets removed while serving requestsDeregistration delay and shutdown handling
Errors on idle-then-reused connectionsKeep-alive mismatchServer keep-alive setting

Turn on access logs if they are off, since the status fields and the target IP identify the failing target, and the error_reason field is filled for many load balancer errors.

What does AWS list as the causes?

The ALB troubleshooting page lists the 502 causes: a TCP RST from the target, a target that closed the connection with RST or FIN while a request was outstanding, a malformed response or invalid headers, response headers over 32 K, a deregistered target whose delay elapsed mid-request, an SSL handshake failure to the target, and several Lambda cases. The Lambda cases are a response body over 1 MB, a function that timed out, and a function that errored or was throttled.

Why do 502s appear randomly under steady traffic?

The most common cause is a keep-alive mismatch. The ALB keeps connections to targets open and reuses them, and its idle timeout defaults to 60 seconds. If the server closes idle connections sooner, the ALB can send a request on a connection the server is closing in the same instant, and the request fails with a 502.

Node's HTTP server closes idle connections after 5 seconds by default, which is far below 60. Set the keep-alive timeout above the ALB idle timeout, and the headers timeout slightly above that:

const server = app.listen(8080); server.keepAliveTimeout = 65_000; // above the ALB idle timeout of 60 s server.headersTimeout = 66_000; // must be greater than keepAliveTimeout

Other servers have the same setting under other names. Go's http.Server uses IdleTimeout, Gunicorn uses --keep-alive and its default of 2 seconds is too low, and nginx behind the ALB needs keepalive_timeout above 60 seconds.

Why do 502s appear during deploys?

When a target is deregistered, the ALB stops sending new requests and waits for the deregistration delay, 300 seconds by default, before closing connections. If the container exits on SIGTERM immediately, requests still in flight are cut and the ALB reports a 502. Handle SIGTERM by stopping the listener, finishing active requests and then exiting, and keep the container's stop timeout longer than your slowest request.

resource "aws_lb_target_group" "api" { name = "api" port = 8080 protocol = "HTTP" target_type = "ip" vpc_id = var.vpc_id deregistration_delay = 60 # long enough for your slowest request health_check { path = "/healthz" interval = 15 } }

A shorter delay makes deploys faster, but it must stay above the time your slowest request needs.

What about Lambda targets?

A Lambda target can only return a body up to 1 MB, and a function that errors, times out or is throttled produces a 502. Return large payloads as a link to object storage, check the function's own timeout against what the ALB expects, and look at the function's logs and Throttles metric before looking at the ALB.

How does Encore handle the load balancer?

Encore

Encore brings infrastructure from code: per the AWS infrastructure docs, it provisions the Application Load Balancer, the compute subnets and a Fargate or EKS deployment for your app in your own AWS account, so the load balancer, target registration and task definition come from the same application as the services behind them, in each deploy. Deploy-time 502s come from requests cut off during shutdown, and a service struct can hold a Shutdown hook that waits for in-flight work.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create orders-api --example=hello-world$ cd orders-api
// orders/service.go package orders import ( "context" "sync" ) //encore:service type Service struct { wg sync.WaitGroup } func initService() (*Service, error) { return &Service{}, nil } // Shutdown runs when the service is asked to stop. It waits for background // work to finish until the force context is cancelled. func (s *Service) Shutdown(force context.Context) { done := make(chan struct{}) go func() { s.wg.Wait(); close(done) }() select { case <-done: case <-force.Done(): } } // Receipt starts follow-up work that should finish before the process exits. // //encore:api public method=POST path=/orders/:id/receipt func (s *Service) Receipt(ctx context.Context, id string) error { s.wg.Add(1) go func() { defer s.wg.Done() // send the receipt email, write the audit row and so on }() return nil }

encore run starts the service locally and the testing docs cover exercising it, and a coding agent that adds a worker to the service changes the same file and runs it right away, so the shutdown behavior is tested next to the code that needs it.

Best fit: Teams that keep chasing load balancer and shutdown settings across several services and want them generated from the application.

Frequently asked questions

What causes a 502 Bad Gateway on an Application Load Balancer?

The load balancer got a response it could not use. The usual causes are a target that closed the connection while a request was in flight, a malformed or oversized response header, a TCP reset, a deregistered target that was still handling requests, or a Lambda target that errored, timed out or returned more than 1 MB.

How do you tell if the ALB or the target returned the 502?

Compare the metrics HTTPCode_ELB_502_Count and HTTPCode_Target_502_Count, or the elb_status_code and target_status_code fields in the access logs. If elb_status_code is 502 and target_status_code is a dash, the load balancer generated the error without a usable target response.

Why do I get intermittent 502 errors behind an ALB?

Intermittent 502s often come from a target whose keep-alive timeout is shorter than the ALB idle timeout, which defaults to 60 seconds. The target closes an idle connection just as the load balancer reuses it. Set the target's keep-alive timeout higher than the idle timeout.

Does Encore remove the need to configure the load balancer?

Yes. Encore provisions the ALB, target registration and the compute for an app in your AWS account from the application code, so those settings are generated together with the service rather than written as separate Terraform. A service struct's Shutdown hook lets in-flight requests finish during a deploy.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders