Troubleshooting, Performance and Cost Optimisation
Overview
Building applications is only half the job; keeping them fast, reliable and affordable is the other half. The DVA-C02 Troubleshooting and Optimization domain tests whether you can read symptoms (timeouts, throttles, 5xx errors, rising bills), find the root cause using monitoring tools, and apply the right fix.
Think of a doctor. Symptoms (fever, pain) are the metrics and error codes; tests are logs and traces; treatment is configuration, code or architecture changes. A good developer does not guess; they follow a diagnostic path.
This lesson collects the common failure patterns across Lambda, API Gateway, DynamoDB, SQS, containers and deployments, plus the main performance and cost levers.
Key Concepts
- Lambda timeouts or slowness: raise memory (CPU), reuse connections, avoid cold starts (provisioned concurrency/SnapStart), tune the timeout, check downstream latency in X-Ray.
- Lambda throttling (429/TooManyRequests): check account/reserved concurrency; use SQS buffering and backoff; request a limit increase.
- API Gateway errors: 4xx are client or auth (403/401/429); 502 = bad Lambda response, 504 = integration timeout (29 s).
- DynamoDB throttling: hot partitions, insufficient capacity, GSI back-pressure; fix with better keys, on-demand mode, auto scaling, DAX, backoff.
- Caching layers reduce latency and cost: CloudFront, API Gateway cache, DAX, ElastiCache, browser/HTTP caching headers and S3 Transfer Acceleration for uploads.
- Right-size with Compute Optimizer, Lambda Power Tuning, and Graviton; use Savings Plans, Spot (fault-tolerant) and on-demand modes for variable load.
- Cost visibility: Cost Explorer, Budgets, cost allocation tags and Cost Anomaly Detection; delete idle resources (NAT gateways, unattached volumes).
- Deployment failures: read CloudFormation stack events, CodeBuild logs, CodeDeploy lifecycle event logs and ECS stopped reasons.
Detailed Notes
Symptom to cause map
| Symptom | Likely causes | First checks |
|---|---|---|
Lambda Task timed out | Slow downstream, too small timeout, DB connection waits | X-Ray, Duration vs timeout, memory |
Lambda Runtime.OutOfMemory / exit 137 | Memory too low or leak | REPORT line max memory used |
| API 502 | Malformed proxy response or function error | Lambda logs for that request ID |
| API 504 | Integration exceeded 29 s | IntegrationLatency metric |
| API 403 | Authoriser deny, WAF, resource policy, missing API key | Execution logs, authoriser logs |
DynamoDB ProvisionedThroughputExceeded | Hot key, low capacity | Throttle metrics per index/partition |
| SQS messages repeatedly reappear | Visibility timeout too short, handler errors | Receive counts, DLQ |
| ECS tasks restart | Failing health check, OOM, bad config | stoppedReason, container logs |
S3 AccessDenied | Bucket policy, KMS key policy, block public access | CloudTrail, get-caller-identity |
CloudFormation ROLLBACK | Resource creation error, missing capability | Stack events (first failed resource) |
A diagnostic routine
- Define the symptom with a metric: latency percentile, error rate.
- Scope with dashboards: which service, Region, version, time of change?
- Trace a slow or failing request with X-Ray and correlate logs by request ID.
- Check changes in CloudTrail, CodeDeploy and CloudFormation history.
- Fix and verify (canary the fix), then add alarms to catch recurrence.
Logs Insights for a failing function
fields @timestamp, @requestId, @message
| filter @message like /Task timed out|ERROR|Exception/
| sort @timestamp desc
| limit 50
Lambda optimisation
| Lever | Effect |
|---|---|
| More memory | More CPU and network; often faster and sometimes cheaper |
| arm64 (Graviton) | About 20% lower price per ms, often better performance |
| Provisioned concurrency / SnapStart | Removes or reduces cold starts |
| Reuse clients, keep-alive | Lower latency; set AWS_NODEJS_CONNECTION_REUSE_ENABLED for older SDK v2 |
| Smaller package, tree shaking | Faster init |
| Batch size and concurrency tuning | Better throughput for event sources |
# Use a pool outside the handler and bounded timeouts so slow calls fail fast
import boto3
from botocore.config import Config
ddb = boto3.client("dynamodb", config=Config(connect_timeout=2, read_timeout=3,
retries={"max_attempts": 3, "mode": "standard"}))
Caching layers
| Layer | Caches | Good for |
|---|---|---|
| CloudFront | HTTP responses at edge | Static and cacheable API content |
| API Gateway cache | Method responses | Repeated GETs |
| DAX | DynamoDB reads | Microsecond item reads |
| ElastiCache | Anything | Sessions, computed results, DB offload |
| Lambda /tmp or memory | Per environment | Config, models, small reference data |
Use Cache-Control headers, versioned object names and invalidations deliberately; cache TTLs trade freshness for speed.
Cost levers
| Area | Action |
|---|---|
| Lambda | Right-size memory, arm64, reduce duration, avoid polling |
| DynamoDB | On-demand for spiky, provisioned + auto scaling for steady, TTL cleanup, projections |
| S3 | Lifecycle rules, Intelligent-Tiering, abort multipart uploads |
| Compute | Savings Plans, Spot, Compute Optimizer |
| Logs | Retention, sampling, lower verbosity |
| Networking | VPC endpoints instead of NAT for AWS services; avoid cross-AZ chatter |
| Governance | Tags, budgets, anomaly detection |
Debugging deployments
- CloudFormation:
aws cloudformation describe-stack-events --stack-name Xand read the earliestCREATE_FAILED. - CodeDeploy EC2: logs under
/opt/codedeploy-agent/deployment-root/and the deployment's lifecycle event details. - CodeBuild: phase details and CloudWatch Logs; check IAM and VPC egress.
- Elastic Beanstalk:
eb logs, enhanced health andeb-engine.log.
Throttling summary
When a service throttles, the standard response is retry with exponential backoff and jitter, reduce request rate, batch, cache, and raise capacity or quotas through Service Quotas if the load is legitimate.
Real World Example
A media API suffered 504s every evening. X-Ray showed Lambda waiting on an ElastiCache-less database query that took 25-30 seconds under load. The team added indexes, introduced ElastiCache for hot queries, raised Lambda memory (which also gave more CPU for JSON serialisation), and reduced the API Gateway integration timeout expectations with an asynchronous pattern for the slowest report endpoint using SQS and a status endpoint. They switched functions to arm64 and used Compute Optimizer for the container tier, reducing the monthly bill by 28%.
Architecture Diagram
Detect, locate, change-check, fix and verify; then add guardrails.
- 1An alarm on latency or errors signals a problem.
- 2Logs Insights and dashboards narrow the scope.
- 3X-Ray identifies the slow or failing component.
- 4CloudTrail and deployment history reveal recent changes, then a fix is deployed gradually.
Best Practices
- ✓Use percentile latency (p95/p99) and error-rate alarms.
- ✓Trace first, tune second; measure before and after.
- ✓Cache at the highest layer that satisfies freshness needs.
- ✓Right-size regularly with Power Tuning and Compute Optimizer.
- ✓Tag resources and set budgets and anomaly alerts.
Common Interview Questions
Exam Tips
DVA-C02 focus
- 502 = bad integration response; 504 = integration timeout; 429 = throttled.
- Timeouts and slow functions: first raise memory and reuse connections.
- Throttling fix pattern: exponential backoff + capacity/quota/caching.
- Cost questions: choose the managed, right-sized, cached option; VPC endpoints can replace NAT for AWS traffic.
Finished this lesson?
0 of 46 lessons done · 0% of the course

