SkillSprout
Chapter 11 · Lesson 3
Advanced
6 min read

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

SymptomLikely causesFirst checks
Lambda Task timed outSlow downstream, too small timeout, DB connection waitsX-Ray, Duration vs timeout, memory
Lambda Runtime.OutOfMemory / exit 137Memory too low or leakREPORT line max memory used
API 502Malformed proxy response or function errorLambda logs for that request ID
API 504Integration exceeded 29 sIntegrationLatency metric
API 403Authoriser deny, WAF, resource policy, missing API keyExecution logs, authoriser logs
DynamoDB ProvisionedThroughputExceededHot key, low capacityThrottle metrics per index/partition
SQS messages repeatedly reappearVisibility timeout too short, handler errorsReceive counts, DLQ
ECS tasks restartFailing health check, OOM, bad configstoppedReason, container logs
S3 AccessDeniedBucket policy, KMS key policy, block public accessCloudTrail, get-caller-identity
CloudFormation ROLLBACKResource creation error, missing capabilityStack events (first failed resource)

A diagnostic routine

  1. Define the symptom with a metric: latency percentile, error rate.
  2. Scope with dashboards: which service, Region, version, time of change?
  3. Trace a slow or failing request with X-Ray and correlate logs by request ID.
  4. Check changes in CloudTrail, CodeDeploy and CloudFormation history.
  5. Fix and verify (canary the fix), then add alarms to catch recurrence.

Logs Insights for a failing function

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

Lambda optimisation

LeverEffect
More memoryMore CPU and network; often faster and sometimes cheaper
arm64 (Graviton)About 20% lower price per ms, often better performance
Provisioned concurrency / SnapStartRemoves or reduces cold starts
Reuse clients, keep-aliveLower latency; set AWS_NODEJS_CONNECTION_REUSE_ENABLED for older SDK v2
Smaller package, tree shakingFaster init
Batch size and concurrency tuningBetter throughput for event sources
python
# 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

LayerCachesGood for
CloudFrontHTTP responses at edgeStatic and cacheable API content
API Gateway cacheMethod responsesRepeated GETs
DAXDynamoDB readsMicrosecond item reads
ElastiCacheAnythingSessions, computed results, DB offload
Lambda /tmp or memoryPer environmentConfig, models, small reference data

Use Cache-Control headers, versioned object names and invalidations deliberately; cache TTLs trade freshness for speed.

Cost levers

AreaAction
LambdaRight-size memory, arm64, reduce duration, avoid polling
DynamoDBOn-demand for spiky, provisioned + auto scaling for steady, TTL cleanup, projections
S3Lifecycle rules, Intelligent-Tiering, abort multipart uploads
ComputeSavings Plans, Spot, Compute Optimizer
LogsRetention, sampling, lower verbosity
NetworkingVPC endpoints instead of NAT for AWS services; avoid cross-AZ chatter
GovernanceTags, budgets, anomaly detection

Debugging deployments

  • CloudFormation: aws cloudformation describe-stack-events --stack-name X and read the earliest CREATE_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 and eb-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

Troubleshooting loop
Architecture
Operate
Alarmsymptom
Logs Insights
X-Ray trace
CloudTrail / deploy history
Deploy

Detect, locate, change-check, fix and verify; then add guardrails.

  1. 1An alarm on latency or errors signals a problem.
  2. 2Logs Insights and dashboards narrow the scope.
  3. 3X-Ray identifies the slow or failing component.
  4. 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