SkillSprout
Chapter 11 · Lesson 2
Advanced
7 min read

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

SymptomWhere to lookLikely cause
ALB 502Target logs, keep-alive settingsApp crashes, closes connection early (keep-alive timeout < ALB idle timeout 60s), bad response header
ALB 503HealthyHostCount = 0All targets unhealthy / deregistered / SG blocks health checks
ALB 504TargetResponseTimeBackend slower than idle timeout; DB slow
API Gateway 4294XXError, CountThrottling; adjust usage plan / account limits / caching
API Gateway 502Lambda logsLambda returned wrong format (proxy integration needs statusCode, body)
API Gateway 504IntegrationLatencyIntegration exceeded timeout
Lambda Task timed outDuration near timeoutSlow downstream, cold VPC dependency, too small memory
Lambda AccessDeniedCloudWatch logsExecution role missing permission / resource policy
Lambda cannot reach internetVPC configNo NAT gateway / endpoint for the function's subnets
Lambda out of memoryMax Memory Used in REPORT lineIncrease memory

Lambda diagnostics

bash
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 typeRetry behaviourFailure handling
Synchronous (API Gateway, ALB, SDK)No automatic retry; caller handles errorsClient retry/backoff
Asynchronous (S3, SNS, EventBridge)2 retries over up to 6 hOn-failure destination or DLQ
Event source mapping (SQS)Message returns after visibility timeoutDLQ on queue, maxReceiveCount
Event source mapping (Kinesis/DynamoDB streams)Retries until data expires; blocks shardBisect on error, max retry, on-failure destination
bash
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

bash
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

text
fields @timestamp, @requestId, @message
| filter @message like /ERROR|Task timed out/
| sort @timestamp desc
| limit 50

ECS / container notes

SymptomCause
Task stops immediatelyExit code in stopped reason; container health check; missing secrets/IAM execution role
Cannot pull imageNAT/endpoints for ECR, wrong execution role
Service flapping behind ALBHealth 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 maxReceiveCount and a DLQ; alarm on DLQ depth.### Common application-tier error map
ErrorFrequent causeFirst check
ALB 502Target closed connection or malformed responseTarget logs, keep-alive timeout above ALB idle timeout
ALB 503No healthy targetsTarget group health, security group from ALB
ALB 504Target did not respond in timeIdle timeout, app latency
API Gateway 429ThrottlingUsage plan, account limits
API Gateway 502 / 504Bad Lambda response / 29 s integration limitProxy response format, timeouts
Lambda throttlesReserved or account concurrency reachedConcurrency settings, SQS batch tuning
Lambda timeout in VPCNo route to internet/endpointsNAT or VPC endpoints
SQS messages stuckVisibility timeout shorter than processingRaise timeout, DLQ with maxReceiveCount
bash
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

Tracing a request through the application chain
Architecture
AWS Cloud
Client
API Gateway429 / 502 / 504
Lambdaerrors, throttles
DynamoDB / RDS
Metrics + Logs
X-Ray traces
  1. 1The client sends a request and the edge service returns an HTTP status.
  2. 2API Gateway metrics separate client, integration and gateway errors.
  3. 3Lambda metrics and logs show errors, throttles, duration and memory use.
  4. 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