4: Troubleshooting and Optimization

    Logs and metrics to distinguish between an application issue and a deployment issue

    The first triage question on any incident is whether the failure exists in the code that was already in production or in the change that just went out. The same symptom, for example a sudden rise in 500 responses on POST /checkout, can be a backend bug that always existed and was simply uncovered by a new traffic mix, or it can be a regression introduced by the latest deploy. Picking the wrong root cause path costs the team an hour of log diving before the right hypothesis is even on the board. Logs and metrics together answer the question if they are read in the right order, against the right time window, and with the right baseline.

    The signal that separates the two cases is the deployment timeline. Every AWS Lambda update, every AWS Elastic Beanstalk swap, every Amazon ECS task definition rotation, and every AWS CloudFormation stack update emits an event that can be plotted on a CloudWatch dashboard. When the metric break aligns within seconds of the deployment event, the change is the prime suspect; when the metric break is hours after the deployment with no traffic change, the application itself is in play. CloudWatch dashboards accept vertical annotations through the annotations field of a metric widget, so a release marker can sit on top of the latency or error-rate chart without leaving the same screen.

    The metric break itself has to be measured against a baseline window, not against an absolute number. A function that has an average error rate of 0.05 percent and suddenly sits at 0.6 percent is broken even though both numbers sound small. CloudWatch metric math expressions like ANOMALY_DETECTION_BAND(m1, 2) give a confidence band that follows the diurnal traffic shape, and CloudWatch Logs metric filters can convert log patterns into time series so a custom application metric like OrderValidationFailed can be plotted next to the AWS-emitted Errors metric. When the two move together, the failure originated inside the application; when only the AWS-emitted metric moves and the custom metric is silent, the code never executed and the failure is at the platform edge (timeout, throttling, network).

    Application issues and deployment issues differ in their signature on logs as well. A deployment issue tends to show a clean cliff: the very first invocation of the new version fails, traffic that lands on the new alias version raises errors at a stable rate, and rolling the alias back to the previous version restores the error rate immediately. An application issue tends to show a gradient: errors rise as a particular data pattern accumulates, certain user IDs or item IDs are over-represented in the failure logs, and rollback does not restore the metric because the data state has shifted. The roll-forward / roll-back behavior is itself a diagnostic, so deployments through AWS CodeDeploy with Canary10Percent5Minutes give a controlled signal: if the 10 percent slice surges to a high error rate, the deployment is the cause.

    The AWS-emitted metrics that matter for this triage step are workload specific. For AWS Lambda the canonical set is Invocations, Errors, Duration, Throttles, ConcurrentExecutions, and the alias-level variants. For Amazon API Gateway it is 5XXError, 4XXError, IntegrationLatency, Latency, Count, and CacheHitCount / CacheMissCount. For Amazon ECS it is CPUUtilization, MemoryUtilization, plus the Application Load Balancer-level HTTPCode_Target_5XX_Count and TargetResponseTime. Reading those in pairs is the trick: if the ALB shows 5xx but the ECS task CPUUtilization is flat, the application returned the 5xx itself; if the ECS task is at 100 percent CPU, the container is saturated. If Lambda Throttles is non-zero alongside the error rate spike, an upstream caller is sending more parallel work than the account or function-level reserved concurrency allows, which is an architecture issue rather than a code defect.

    # CloudWatch metric math: alarm fires when the function error rate
    # exceeds the long-running anomaly band by 2 standard deviations.
    import boto3
    
    cw = boto3.client("cloudwatch")
    cw.put_metric_alarm(
     AlarmName="orderfn-error-rate-anomaly",
     AlarmDescription="Application versus deployment triage signal",
     ActionsEnabled=True,
     EvaluationPeriods=2,
     DatapointsToAlarm=2,
     Threshold=1.0,
     ComparisonOperator="GreaterThanUpperThreshold",
     TreatMissingData="notBreaching",
     ThresholdMetricId="ad1",
     Metrics=[
     {
     "Id": "m1",
     "MetricStat": {
     "Metric": {
     "Namespace": "AWS/Lambda",
     "MetricName": "Errors",
     "Dimensions": [
     {"Name": "FunctionName", "Value": "orderfn"},
     {"Name": "Resource", "Value": "orderfn:live"},
     ],
     },
     "Period": 60,
     "Stat": "Sum",
     },
     "ReturnData": True,
     },
     {
     "Id": "ad1",
     "Expression": "ANOMALY_DETECTION_BAND(m1, 2)",
     "ReturnData": True,
     },
     ],
    )
    

    The other half of the triage workflow is the log search. CloudWatch Logs Insights is the right tool, because it can correlate log fields to a deployment marker. A query like the one below joins the per-request log line with the function version that served it, so the operator can verify whether the failing requests are all on a single version or distributed evenly.

    fields @timestamp, @message, version, requestId, errorCode
    | filter ispresent(errorCode)
    | stats count() as errors by version, bin(1m) as window
    | sort window desc
    

    If the errors count is concentrated on a single version value, the deployment is the cause and a rollback is the correct first move. If the errors count is evenly distributed across versions, the code is consistent and the change is in the data, the upstream caller, or a downstream dependency.

    Caching as a remediation lever (Amazon API Gateway, Amazon CloudFront, Amazon DynamoDB Accelerator, Amazon ElastiCache)

    Latency-driven incidents and load-driven incidents are not always code defects. They are often signals that a missing cache is allowing every request to reach a backend that cannot keep up. The four cache surfaces tested at this level of certification sit at four different layers of the request path, and choosing the wrong one is one of the most common distractor patterns on the exam.

    Amazon API Gateway stage cache sits at the API boundary. It keys cache entries on the request, including configured headers and query parameters, and stores the integration response for a configured time-to-live up to 3600 seconds. It is the right answer when an API method receives many identical requests and the integration is expensive to call. Cache invalidation can be triggered per request with the Cache-Control: max-age=0 header when the caller carries the InvalidateCache permission. The cost is a per-hour charge that depends on the chosen cache size, from 0.5 GB up through 237 GB.

    Amazon CloudFront sits at the edge. It caches HTTP responses at points of presence around the world and is the right answer when the audience is geographically distributed and the response is cacheable at the URL or origin-request level. The cache key is controlled by a cache policy that selects which headers, query strings, and cookies participate; for dynamic APIs an origin request policy passes through the values the backend needs without making them part of the cache key. CloudFront cache behaviors integrate with AWS WAF, AWS Lambda@Edge, and CloudFront Functions, so URL rewrites and authentication can run before the cache lookup.

    Amazon DynamoDB Accelerator (DAX) sits in front of DynamoDB. It is a fully managed write-through cache for the DynamoDB API itself: the application uses the DAX client, which exposes the same GetItem, Query, Scan, and write operations and falls back to the underlying table on a miss. DAX is the right answer when read latency on DynamoDB needs to drop from single-digit milliseconds to microseconds, when the workload is read-heavy with hot keys, and when the application code already speaks the DynamoDB API. DAX clusters live in a VPC and clients connect through the cluster discovery endpoint.

    Amazon ElastiCache, in either the Redis or the Memcached engine, is a general-purpose in-memory cache. It is the right answer when the cache holds data that is not natively DynamoDB, when the application needs data structures like sorted sets and streams, or when the workload requires Pub/Sub. The application is responsible for the cache-aside pattern: read from the cache, fall back to the database on miss, populate the cache, and respect a time-to-live. ElastiCache Serverless removes the node-management work for variable traffic.

    💡 Exam Trap: A stem that says "drop DynamoDB read latency without changing application code" points to DAX, because the DAX client is API-compatible with the DynamoDB SDK. A stem that says "cache the response of a Lambda integration of an API method" points to API Gateway stage cache. A stem that says "deliver low-latency static and dynamic content to users in multiple geographies" points to CloudFront. Map the cache layer to the layer of the request path the question mentions, not to the word "cache" alone.

    💡 Exam Trap: Stage cache on Amazon API Gateway is configured per stage, not per method, but per-method overrides are allowed. A stem that says "cache only the GET /products method but not GET /orders" requires enabling the stage cache and then setting cachingEnabled=false on the /orders method's methodSettings block.

    ⚠️ Anti-Pattern: Putting Amazon ElastiCache in front of Amazon DynamoDB to cache primary-key lookups when DynamoDB Accelerator exists. ElastiCache forces the application to write a cache-aside pattern, manage serialization, and invalidate keys on write. DAX gives the same effect through an API-compatible client with write-through semantics out of the box.

    🎯 Scenario: A team sees Latency rise on Amazon API Gateway from 80 ms to 600 ms an hour after a Lambda deploy. The Lambda Duration metric is flat at 70 ms, and the integration latency of the API method tracks the user-facing latency. Because the Lambda code is fast, the application code did not regress. The deploy turned off the stage cache by accident through a SAM template change, and every method call is now landing on the integration. Restoring the MethodSettings.CacheEnabled flag in the SAM template and redeploying restores the previous behavior.

    📊 Limit: Amazon API Gateway stage cache TTL ranges from 0 to 3600 seconds and the cache sizes available are 0.5, 1.6, 6.1, 13.5, 28.4, 58.2, 118 and 237 GB.

    Decision Anchor: Choose Amazon API Gateway stage cache when the cached response lives at the API boundary and the cache key is controlled by request parameters; choose Amazon CloudFront when the audience is geographically distributed and the response is cacheable at the edge; choose Amazon DynamoDB Accelerator when the workload is DynamoDB and the application uses the DynamoDB API; choose Amazon ElastiCache when the cache holds arbitrary keys or needs Redis data structures.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the AWS - Developer Associate learning hub.