Troubleshooting Load Balancers, Lambda and APIs
Overview
Modern applications chain load balancers, containers, Lambda functions, queues and APIs. When something fails the symptom is often a vague 5xx or timeout at the edge; the cause lies several hops away. A SysOps administrator follows the request through the chain using metrics, logs and traces.
Picture a relay race where the baton is dropped somewhere. You check each handover in order: crowd to track (CloudFront/ALB), runner one (API Gateway), runner two (Lambda), runner three (database). CloudWatch metrics tell you where; logs tell you why; AWS X-Ray shows the whole route with timings.
Knowing the standard error codes and the associated limits (Lambda concurrency, API Gateway throttles, SQS visibility timeout) lets you resolve many incidents in minutes.
Key Concepts
- ALB errors: 502 (invalid response from target), 503 (no healthy targets / capacity), 504 (target timeout); ELB-generated vs target-generated 5xx metrics tell you which tier is at fault.
- Lambda metrics: Invocations, Errors, Throttles, Duration, ConcurrentExecutions, IteratorAge (streams), AsyncEventsDropped / DeadLetterErrors.
- Throttles occur when account concurrency (default 1,000 per Region) or reserved concurrency is exhausted; use reserved/provisioned concurrency and request quota increases.
- Async invocations retry twice by default; configure on-failure destination / DLQ and maximum event age.
- Timeouts (max 15 min) and memory (up to 10 GB) are tuned together as CPU scales with memory; use Lambda Insights / Power Tuning.
- API Gateway returns 429 when throttled (default 10,000 rps account, 5,000 burst), 502 for malformed Lambda responses, 504 at 29-second integration timeout (can be raised for Regional REST APIs).
- X-Ray traces requests across services; CloudWatch ServiceLens / Application Signals and CloudWatch Synthetics (canaries) provide end-to-end visibility.
- SQS-triggered Lambda: set visibility timeout >= 6x function timeout; failing batches return to the queue; configure a DLQ and partial batch responses.
Detailed Notes
Mapping symptoms to causes
| Symptom | Where to look | Likely cause |
|---|---|---|
| ALB 502 | Target logs, keep-alive settings | App crashes, closes connection early (keep-alive timeout < ALB idle timeout 60s), bad response header |
| ALB 503 | HealthyHostCount = 0 | All targets unhealthy / deregistered / SG blocks health checks |
| ALB 504 | TargetResponseTime | Backend slower than idle timeout; DB slow |
| API Gateway 429 | 4XXError, Count | Throttling; adjust usage plan / account limits / caching |
| API Gateway 502 | Lambda logs | Lambda returned wrong format (proxy integration needs statusCode, body) |
| API Gateway 504 | IntegrationLatency | Integration exceeded timeout |
Lambda Task timed out | Duration near timeout | Slow downstream, cold VPC dependency, too small memory |
Lambda AccessDenied | CloudWatch logs | Execution role missing permission / resource policy |
| Lambda cannot reach internet | VPC config | No NAT gateway / endpoint for the function's subnets |
| Lambda out of memory | Max Memory Used in REPORT line | Increase memory |
Lambda diagnostics
aws lambda get-function-configuration --function-name orders --query "[Timeout,MemorySize,Role,VpcConfig]"
aws logs tail /aws/lambda/orders --since 30m --follow
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name Throttles \
--dimensions Name=FunctionName,Value=orders --statistics Sum --period 60 \
--start-time 2025-03-01T10:00:00Z --end-time 2025-03-01T11:00:00Z
aws lambda put-function-concurrency --function-name orders --reserved-concurrent-executions 200
aws lambda put-provisioned-concurrency-config --function-name orders --qualifier prod --provisioned-concurrent-executions 20
Reserved concurrency guarantees and caps a function's share of the pool; provisioned concurrency keeps environments initialised to avoid cold starts (extra cost).
Retries and failure handling
| Invocation type | Retry behaviour | Failure handling |
|---|---|---|
| Synchronous (API Gateway, ALB, SDK) | No automatic retry; caller handles errors | Client retry/backoff |
| Asynchronous (S3, SNS, EventBridge) | 2 retries over up to 6 h | On-failure destination or DLQ |
| Event source mapping (SQS) | Message returns after visibility timeout | DLQ on queue, maxReceiveCount |
| Event source mapping (Kinesis/DynamoDB streams) | Retries until data expires; blocks shard | Bisect on error, max retry, on-failure destination |
aws lambda put-function-event-invoke-config --function-name orders \
--maximum-retry-attempts 1 --maximum-event-age-in-seconds 3600 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:111122223333:orders-dlq"}}'
Distributed tracing and synthetic monitoring
aws lambda update-function-configuration --function-name orders --tracing-config Mode=Active
aws xray get-service-graph --start-time 2025-03-01T10:00:00Z --end-time 2025-03-01T10:15:00Z
X-Ray service maps highlight which segment has errors or latency. CloudWatch Synthetics canaries run scripted checks every minute from outside, alarming before users notice.
Logs Insights for Lambda
fields @timestamp, @requestId, @message
| filter @message like /ERROR|Task timed out/
| sort @timestamp desc
| limit 50
ECS / container notes
| Symptom | Cause |
|---|---|
| Task stops immediately | Exit code in stopped reason; container health check; missing secrets/IAM execution role |
| Cannot pull image | NAT/endpoints for ECR, wrong execution role |
| Service flapping behind ALB | Health check path/grace period too short |
SQS + Lambda gotchas
- Visibility timeout shorter than the function timeout causes duplicate processing.
- Use batch item failures (partial batch response) to avoid reprocessing successful messages.
- Set
maxReceiveCountand a DLQ; alarm on DLQ depth.### Common application-tier error map
| Error | Frequent cause | First check |
|---|---|---|
| ALB 502 | Target closed connection or malformed response | Target logs, keep-alive timeout above ALB idle timeout |
| ALB 503 | No healthy targets | Target group health, security group from ALB |
| ALB 504 | Target did not respond in time | Idle timeout, app latency |
| API Gateway 429 | Throttling | Usage plan, account limits |
| API Gateway 502 / 504 | Bad Lambda response / 29 s integration limit | Proxy response format, timeouts |
| Lambda throttles | Reserved or account concurrency reached | Concurrency settings, SQS batch tuning |
| Lambda timeout in VPC | No route to internet/endpoints | NAT or VPC endpoints |
| SQS messages stuck | Visibility timeout shorter than processing | Raise timeout, DLQ with maxReceiveCount |
aws elbv2 describe-target-health --target-group-arn <arn>
aws lambda get-function-concurrency --function-name orders
aws logs filter-log-events --log-group-name /aws/lambda/orders --filter-pattern "?ERROR ?Task timed out"
aws sqs get-queue-attributes --queue-url <url> --attribute-names All
Work from the symptom inward: metrics (what changed and when), logs (why), traces with X-Ray (where), then configuration history in Config and CloudTrail (who changed it). Correlate with the deployment timeline and roll back first, investigate second.
Real World Example
Scenario – intermittent 502s from an API. Customers see random 502 responses. API Gateway metrics show 5XXError spikes; Lambda Errors are zero, but CloudWatch Logs show responses like {"message": "ok"} without statusCode. A recent code change returned an invalid proxy-integration response in one branch of the code.
The engineer fixes the response format, adds a canary that exercises both branches, enables X-Ray active tracing and sets an alarm on API 5XX rate. For a separate throttling incident they set reserved concurrency to protect a critical function from a noisy batch job sharing the account pool.
Architecture Diagram
- 1The client sends a request and the edge service returns an HTTP status.
- 2API Gateway metrics separate client, integration and gateway errors.
- 3Lambda metrics and logs show errors, throttles, duration and memory use.
- 4X-Ray traces pinpoint the slow or failing downstream call.
Best Practices
- ✓Enable X-Ray / Application Signals and structured logging with request IDs.
- ✓Configure DLQs or on-failure destinations for all asynchronous paths and alarm on them.
- ✓Use reserved concurrency to isolate critical functions and provisioned concurrency for latency-sensitive ones.
- ✓Align timeouts across layers (client > API > Lambda > downstream) and use retries with backoff.
- ✓Deploy Synthetics canaries for critical user journeys.
Common Interview Questions
Exam Tips
SOA-C03 focus
- ALB: 502 bad response, 503 no healthy targets, 504 timeout.
- Lambda throttling -> reserved/provisioned concurrency or quota increase; failed async events -> DLQ/destination.
- Trace requests across services -> AWS X-Ray; synthetic user checks -> CloudWatch Synthetics.
- VPC Lambda needs NAT or endpoints to reach outside the VPC.
Finished this lesson?
0 of 46 lessons done · 0% of the course

