Thuta Learning
AWS Advanced
ExercisesDevOpsAdvanced

Exercises: Six Architecture Review and Troubleshooting Scenarios

AWS AdvancedLesson 3260 min

What you'll walk away with

  • Analyse an incident from symptom to prevention with a five-step method
  • Pick the first evidence source (metrics, logs, CloudTrail, Cost Explorer) for each kind of symptom
  • Prove a root cause with AWS CLI commands and Logs Insights queries
  • Turn every fix into a guardrail or alarm so it cannot recur silently

Explain it simply

Think like a doctor

A good doctor does not hand out pills the moment you say 'headache'. They ask when it started and where it hurts, run a blood test, and only then diagnose and treat. Finally they tell you how to avoid it next time (the vaccine).

Cloud incidents work the same way: describe the symptom precisely, gather evidence, find the root cause, fix it, and add a guardrail so it cannot happen again. This lesson combines the services from the whole course to practise six realistic scenarios.

Problem → Why → Solution

Treating the symptom, keeping the disease

Under incident pressure, teams apply the first fix that comes to mind. Lambda throttling? Request a quota increase. DynamoDB throttling? Add capacity. AccessDenied? Put '*' in the policy. The alarm goes quiet, the ticket is closed, and the real disease stays.

Next month, on a busier day, the problem comes back bigger, or the '*' becomes a new security hole. And because no evidence was gathered systematically, nobody remembers what was changed.

  • Raising a limit often just postpones the problem
  • Widening permissions trades one incident for another
  • Without evidence, a postmortem is just guesses

Why this happens

During an incident the goal is to restore service (containment), and that is right. The mistake is stopping there. With a fixed method, containment is always followed by root cause and prevention.

The five-step review method

Write the symptom in measurable terms: not 'it is slow' but 'checkout API p99 latency went from 300 ms to 4 s at 09:40 UTC, mobile users only'. Once what, since when and who are clear, the search space for evidence shrinks.

Gather evidence in layers. Metrics show what and when, logs show why, and CloudTrail shows who changed what. Most incidents line up with a deploy or a config change, so always look at the CloudTrail events around the moment the symptom began.

The root cause is not the trigger. A traffic spike is a trigger; 'we chose the date as the partition key' is a root cause. Keep asking 'why?' until you reach a design decision or a missing guardrail.

Split the fix in two: containment first (stop the bleeding), then repair (cure the disease). Finally, prevention must be an alarm, an SCP, a test or a baseline control that will catch or block this incident automatically next time. 'We will be more careful' is not prevention.

text
REVIEW LOOP
-----------
+-----------+   +------------+   +------------+   +---------+
| SYMPTOM   |-->| EVIDENCE   |-->| ROOT CAUSE |-->|   FIX   |
| what      |   | metrics    |   | ask 'why?' |   | contain |
| since when|   | logs       |   | until you  |   | then    |
| who       |   | CloudTrail |   | hit design |   | repair  |
+-----------+   +------------+   +------------+   +----+----+
      ^                                                 |
      |          +------------------------------+       |
      +----------| PREVENTION: alarm, SCP, test |<------+
                 | baseline control, runbook    |
                 +------------------------------+
Kind of symptomFirst place to look
Bill went upCost Explorer, grouped by usage type
Errors or throttlingCloudWatch metrics (Throttles, 5xx, ThrottleEvents)
AccessDeniedThe full error message, CloudTrail, then the policies
Wrong or duplicated dataLogs Insights, counting per ID
Exposure (public access)IAM Access Analyzer and S3 policy status

The method is not heavy process. A five-minute glitch needs five lines of notes; a major outage needs a full record. What matters is never skipping a step, above all never stopping at 'it works again' after containment and leaving root cause and prevention for later. Every scenario below follows these steps.

For every incident
  1. Symptom: what, since when, who
  2. Evidence: metrics, logs, trail
  3. Root cause: ask why to design
  4. Fix: contain, then repair
  5. Prevent: alarm, SCP or test

A postmortem without a prevention item is not finished.

A guardrail check script for review day

Before the scenarios, let us write a small script that finds, in advance, the misconfigurations behind most incidents in this lesson. It checks bucket-level Block Public Access, queues without a DLQ, visibility timeouts shorter than the consumer timeout allows, and tables without PITR. It only reads, so it is safe to run in production accounts.

guardrail_check.py
"""Review-day guardrail check: the misconfigurations behind this lesson's incidents."""
from __future__ import annotations

import json

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client("s3")
sqs = boto3.client("sqs")
ddb = boto3.client("dynamodb")
CONSUMER_TIMEOUT = 30  # seconds: the Lambda timeout of the queue consumers
findings: list[str] = []


def report(level: str, resource: str, message: str) -> None:
    print(f"[{level:<4}] {resource}: {message}")
    if level != "ok":
        findings.append(resource)


def check_buckets() -> None:
    for bucket in sorted(b["Name"] for b in s3.list_buckets()["Buckets"]):
        try:
            cfg = s3.get_public_access_block(Bucket=bucket)
            flags = cfg["PublicAccessBlockConfiguration"]
            if all(flags.values()):
                report("ok", f"s3:{bucket}", "Block Public Access fully on")
            else:
                off = sorted(k for k, v in flags.items() if not v)
                report("FAIL", f"s3:{bucket}", "BPA partly off: " + ", ".join(off))
        except ClientError as err:
            if err.response["Error"]["Code"] != "NoSuchPublicAccessBlockConfiguration":
                raise
            report("FAIL", f"s3:{bucket}", "no bucket-level Block Public Access")


def check_queues() -> None:
    urls = sorted(sqs.list_queues().get("QueueUrls", []))
    for url in urls:
        name = url.rsplit("/", 1)[-1]
        if name.endswith("-dlq"):
            continue
        attrs = sqs.get_queue_attributes(
            QueueUrl=url, AttributeNames=["All"]
        )["Attributes"]
        if "RedrivePolicy" not in attrs:
            report("FAIL", f"sqs:{name}", "no DLQ - a poison message retries forever")
            continue
        redrive = json.loads(attrs["RedrivePolicy"])
        visibility = int(attrs["VisibilityTimeout"])
        report("ok", f"sqs:{name}", f"DLQ after {redrive['maxReceiveCount']} receives")
        if visibility < 6 * CONSUMER_TIMEOUT:
            report("WARN", f"sqs:{name}",
                   f"visibility {visibility}s < 6 x {CONSUMER_TIMEOUT}s consumer timeout")


def check_tables() -> None:
    for table in sorted(ddb.list_tables()["TableNames"]):
        backups = ddb.describe_continuous_backups(TableName=table)
        pitr = backups["ContinuousBackupsDescription"]["PointInTimeRecoveryDescription"]
        if pitr["PointInTimeRecoveryStatus"] == "ENABLED":
            report("ok", f"dynamodb:{table}", "point-in-time recovery on")
        else:
            report("WARN", f"dynamodb:{table}", "point-in-time recovery off")


if __name__ == "__main__":
    check_buckets()
    check_queues()
    check_tables()
    print(f"{len(findings)} finding(s): {', '.join(findings)}")

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. report()print(f"[{level:<4}] {resource}: {message}")

    Every result prints as level (ok/WARN/FAIL), resource and message in one format, so it is easy to grep and to parse in CI. Anything not ok is collected in the findings list.

  2. check_bucketsexcept ClientError ... NoSuchPublicAccessBlockConfiguration

    With no Block Public Access configuration at all, the API raises an error. That becomes a 'no BPA' finding, while any other error is re-raised so that a missing permission is never mistaken for 'all good'. Flags that are off are listed by name.

  3. check_queuesif visibility < 6 * CONSUMER_TIMEOUT:

    Without a RedrivePolicy, a poison message retries forever. A visibility timeout under six times the consumer Lambda timeout risks double processing, so it is a WARN: exactly the root cause of scenario 5.

  4. check_tablesdescribe_continuous_backups(TableName=table)

    A table without PITR cannot be restored to a point in time after a bad delete or a buggy write. It has a cost, so it is a WARN rather than a FAIL, and the team decides.

You should see
[ok  ] s3:app-assets: Block Public Access fully on
[FAIL] s3:legacy-reports: no bucket-level Block Public Access
[FAIL] s3:partner-exports: BPA partly off: BlockPublicPolicy, RestrictPublicBuckets
[FAIL] sqs:emails: no DLQ - a poison message retries forever
[ok  ] sqs:orders: DLQ after 5 receives
[WARN] sqs:orders: visibility 30s < 6 x 30s consumer timeout
[ok  ] dynamodb:orders: point-in-time recovery on
[WARN] dynamodb:sessions: point-in-time recovery off
5 finding(s): s3:legacy-reports, s3:partner-exports, sqs:emails, sqs:orders, dynamodb:sessions

Scenario 1: The NAT Gateway bill spike

Symptom: the monthly bill is up 40%, and in Cost Explorer 'EC2 - Other' grew the most. App traffic has not changed. Two weeks ago the data team launched a new batch job in a private subnet that reads terabytes from S3 every day.

Break the cost down by usage type

'EC2 - Other' mixes EBS, data transfer and NAT Gateway, so filter by usage type group. If NAT Gateway - Data Processed is what grew, the problem is volume.

Which NAT gateway, how many bytes

Look at BytesOutToDestination in the AWS/NATGateway namespace per day and line up the jump with the day the batch job started.

Where the bytes go

Aggregate the NAT ENI's flow logs by source and destination in Logs Insights. If the destinations fall in S3's public IP ranges, S3 traffic is going through the NAT.

nat-investigation.sh
# 1. Which usage type grew? (NAT shows up under "EC2 - Other")
aws ce get-cost-and-usage \
  --time-period Start=2026-10-01,End=2026-11-01 \
  --granularity DAILY --metrics UnblendedCost \
  --filter file://nat-filter.json
# nat-filter.json:
# {"Dimensions": {"Key": "USAGE_TYPE_GROUP",
#                 "Values": ["EC2: NAT Gateway - Data Processed"]}}

# 2. Which NAT gateway, and how many bytes?
aws cloudwatch get-metric-statistics --namespace AWS/NATGateway \
  --metric-name BytesOutToDestination \
  --dimensions Name=NatGatewayId,Value=nat-0a1b2c3d4e5f67890 \
  --start-time 2026-10-25T00:00:00Z --end-time 2026-11-01T00:00:00Z \
  --period 86400 --statistics Sum

# 3. Does the VPC already have an S3 gateway endpoint?
aws ec2 describe-vpc-endpoints \
  --filters Name=vpc-id,Values=vpc-0a1b2c3d4e5f67890 \
  --query 'VpcEndpoints[].[ServiceName,VpcEndpointType]'
nat-top-talkers.logsinsights
# CloudWatch Logs Insights, on the VPC Flow Logs log group.
# Flow records of the NAT gateway's network interface: who sends the bytes,
# and where to? (10.20.0.0/16 is the VPC CIDR)
filter interfaceId = "eni-0a1b2c3d4e5f67890"
| filter isIpv4InSubnet(srcAddr, "10.20.0.0/16")
| filter not isIpv4InSubnet(dstAddr, "10.20.0.0/16")
| stats sum(bytes) as totalBytes by srcAddr, dstAddr
| sort totalBytes desc
| limit 10

Root cause, fix, prevention

Root cause: the VPC had no S3 gateway endpoint, so all same-region S3 traffic went through the NAT and paid per GB processed. Fix: add S3 (and DynamoDB) gateway endpoints associated with the private route tables; gateway endpoints are free. With heavy ECR image pulls, consider ECR interface endpoints too. Prevention: put gateway endpoints in the baseline network stack and add a budget alert on the NAT usage type.

Scenario 2: Lambda throttling during a traffic spike

Symptom: in the first ten minutes of a sale, the checkout API returns 429 and 502 errors. Oddly, checkout traffic is not higher than planned. At the same moment the marketing team uploaded 200,000 new product images to S3, triggering the image-resizer function.

Check the account limit

Lambda concurrency is one pool shared by every function in the account and region (the default quota is 1,000 and can be raised). get-account-settings shows the limit and how much is unreserved.

Who was throttled, who was consuming

Compare checkout-api's Throttles with image-resizer's ConcurrentExecutions over the same window. You will see the resizer holding almost the entire pool.

lambda-throttling.sh
# Account-wide concurrency limit and what is left unreserved
aws lambda get-account-settings \
  --query 'AccountLimit.[ConcurrentExecutions,UnreservedConcurrentExecutions]'

# Who was throttled, and who was eating the concurrency?
aws cloudwatch get-metric-statistics --namespace AWS/Lambda \
  --metric-name Throttles --dimensions Name=FunctionName,Value=checkout-api \
  --start-time 2026-11-07T09:00:00Z --end-time 2026-11-07T11:00:00Z \
  --period 60 --statistics Sum
aws cloudwatch get-metric-statistics --namespace AWS/Lambda \
  --metric-name ConcurrentExecutions \
  --dimensions Name=FunctionName,Value=image-resizer \
  --start-time 2026-11-07T09:00:00Z --end-time 2026-11-07T11:00:00Z \
  --period 60 --statistics Maximum

# Fix: guarantee the critical path, cap the noisy batch job
aws lambda put-function-concurrency --function-name checkout-api \
  --reserved-concurrent-executions 200
aws lambda put-function-concurrency --function-name image-resizer \
  --reserved-concurrent-executions 50

Root cause, fix, prevention

Root cause: a critical function and a batch function shared one concurrency pool with no protection. Fix: give checkout-api reserved concurrency (a guarantee that is also a cap) and limit image-resizer with a small reservation. Better still, put the resizer behind SQS instead of direct S3 invocation and cap it with maxConcurrency. Prevention: alarm on account-level ConcurrentExecutions and agree each function's concurrency budget in design review.

Scenario 3: Cross-account AccessDenied

Symptom: since Monday morning, the reporting job in the shared services account (111122223333) can no longer assume its role in the reporting account (444455556666): 'not authorized to perform: sts:AssumeRole'. No code changed. On Friday the platform team deleted and recreated the reporting-job role through CDK.

Layer to checkHow
Caller identityget-caller-identity: is it the role you expect?
Caller's identity policyDoes it allow sts:AssumeRole on the target role ARN?
Target role trust policyDoes the Principal name the caller; do the conditions match?
SCPs (both accounts)Is the region, action or principal denied?
cross-account-debug.sh
# Who am I really? (a surprising number of tickets end here)
aws sts get-caller-identity

# Reproduce the exact call the job makes, and read the full message
aws sts assume-role \
  --role-arn arn:aws:iam::444455556666:role/reporting-reader \
  --role-session-name debug-ticket-4711

# Does the target role trust us? (run in the TARGET account)
aws iam get-role --role-name reporting-reader \
  --query 'Role.AssumeRolePolicyDocument'

# Which SCPs apply to the target account? (run in the management account)
aws organizations list-policies-for-target --target-id 444455556666 \
  --filter SERVICE_CONTROL_POLICY
aws organizations describe-policy --policy-id p-a1b2c3d4 \
  --query 'Policy.Content' --output text

# What did CloudTrail record for the failed calls?
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRole \
  --max-results 20 --query 'Events[].CloudTrailEvent'

Reading the trust policy, the Principal shows not the role ARN but a unique ID starting with 'AROA'. IAM ties a role ARN in a trust policy to that role's unique ID, so when the role was deleted the principal was left as the old ID. The recreated role has a new ID and is no longer trusted. This is a security feature: recreating a role with the same name must not silently regain access.

reporting-reader-trust.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "TrustOnlyTheReportingJobRole",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:role/reporting-job" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": { "aws:PrincipalOrgID": "o-a1b2c3d4e5" }
      }
    }
  ]
}

Fix, prevention (and the SCP case)

Fix: update the trust policy with the role ARN again (the JSON above); the aws:PrincipalOrgID condition adds protection against callers outside the organization. Prevention: keep cross-account roles on RETAIN, catch CDK changes that would replace them (such as a role rename) in the diff, and alarm on failed AssumeRole calls. If the error says something like 'explicit deny in a service control policy', look at SCPs instead of the trust policy: many AccessDenied messages now name the policy type that denied the request.

Scenario 4: DynamoDB hot partition throttling

Symptom: the orders table is on-demand, yet WriteThrottleEvents appear during a flash sale, while table-wide consumed capacity is far below any table limit. The partition key is a status value such as 'STATUS#PENDING', and every new order starts as PENDING.

Table or key?

Low table-wide consumption with throttling means load is concentrated on one partition (one key). Each partition is limited to 3,000 RCU and 1,000 WCU per second, and on-demand mode does not remove that limit.

Name the hot key

Enable CloudWatch Contributor Insights for DynamoDB to rank the most accessed and most throttled keys. STATUS#PENDING will be at the top.

ddb-hot-key.sh
# Throttles on the table vs. consumed capacity: is it the TABLE or a KEY?
aws cloudwatch get-metric-statistics --namespace AWS/DynamoDB \
  --metric-name WriteThrottleEvents --dimensions Name=TableName,Value=orders \
  --start-time 2026-11-07T09:00:00Z --end-time 2026-11-07T10:00:00Z \
  --period 60 --statistics Sum

# Turn on Contributor Insights: it ranks the most-accessed / most-throttled keys
aws dynamodb update-contributor-insights --table-name orders \
  --contributor-insights-action ENABLE
aws dynamodb describe-contributor-insights --table-name orders

Root cause, fix, prevention

Root cause: a data-model decision to use a low-cardinality attribute (status) as the partition key; it is not a capacity problem. Fix: give the base table a high-cardinality key such as ORDER#<id>, and if a GSI by status is needed, shard its writes with a suffix like 'STATUS#PENDING#<0-9>' (reads then query all ten shards). Remember that a throttled GSI also throttles writes to the base table. Prevention: add access patterns and key cardinality to the design review checklist, and alarm on ThrottledRequests > 0.

Scenario 5: SQS messages processed twice

Symptom: some customers receive two confirmation emails and some orders get loyalty points twice. It only happens in the busy evening hours, when the worker takes 40 to 50 seconds per batch.

Prove the duplicates

Count processing per orderId with Logs Insights. The duplicates will show a 'slowest' duration above 30 seconds.

Compare two numbers

Compare the queue's VisibilityTimeout (30) with the function's Timeout (60). The visibility timeout is shorter than the function timeout.

duplicates.logsinsights
# CloudWatch Logs Insights, on /aws/lambda/order-worker
# Orders that were processed more than once in the window
filter @message like /processed order/
| parse @message "processed order * in * ms" as orderId, ms
| stats count(*) as times, max(ms) as slowest by orderId
| filter times > 1
| sort times desc
| limit 20
sqs-visibility.sh
# Compare the two numbers that must agree
aws sqs get-queue-attributes --queue-url "$QUEUE_URL" \
  --attribute-names VisibilityTimeout RedrivePolicy
aws lambda get-function-configuration --function-name order-worker \
  --query 'Timeout'

# Fix: visibility timeout at least 6x the function timeout (60s -> 360s)
aws sqs set-queue-attributes --queue-url "$QUEUE_URL" \
  --attributes VisibilityTimeout=360

Root cause, fix, prevention

Root cause: when a batch takes longer than 30 seconds, its messages become visible again and another invocation takes them; the consumer was not idempotent, so each duplicate had a double effect. Fix: set the visibility timeout to six times the function timeout (360 s), make the consumer idempotent with a conditional write as in the project-event-driven-orders lesson, and enable partial batch responses. Prevention: run this lesson's guardrail script in CI to catch visibility/timeout mismatches before deploy.

Scenario 6: An S3 bucket accidentally made public

Symptom: IAM Access Analyzer reports a public-access finding on the partner-exports bucket. To make downloads easy for a partner, an engineer partly disabled the bucket's Block Public Access and added a bucket policy with Principal '*'. New buckets have had BPA on by default since April 2023, but it can still be switched off by hand.

Contain first

Turn all four BPA flags back on at bucket and account level. BPA neutralises the public effect immediately without deleting the policy, so evidence is preserved.

Measure the impact

Knowing who downloaded what while it was public needs S3 server access logs or CloudTrail S3 data events, enabled before the incident. Without them, assume the data was exposed and follow your notification process.

Give the partner proper access

Instead of a public bucket, use short-lived presigned URLs, a cross-account bucket policy for the partner's account, or CloudFront with OAC.

s3-exposure.sh
# Is the bucket public, and through which door: policy or ACL?
aws s3api get-bucket-policy-status --bucket partner-exports
aws s3api get-public-access-block --bucket partner-exports
aws s3api get-bucket-policy --bucket partner-exports --query Policy --output text

# Contain first: close the door at bucket AND account level
BPA="BlockPublicAcls=true,IgnorePublicAcls=true"
BPA="$BPA,BlockPublicPolicy=true,RestrictPublicBuckets=true"
aws s3api put-public-access-block --bucket partner-exports \
  --public-access-block-configuration "$BPA"
aws s3control put-public-access-block --account-id 111122223333 \
  --public-access-block-configuration "$BPA"

# Then measure the damage: who downloaded what (needs server access logs
# or CloudTrail S3 data events enabled BEFORE the incident)
aws accessanalyzer list-findings --analyzer-arn "$ANALYZER_ARN" \
  --filter '{"resourceType": {"eq": ["AWS::S3::Bucket"]}}'

For prevention, add an SCP so nobody can switch off account-level BPA again, with a single break-glass role as the exception. The guardrail script also catches bucket-level BPA being off, every day.

scp-protect-account-bpa.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "NobodyTurnsOffAccountLevelBPA",
      "Effect": "Deny",
      "Action": "s3:PutAccountPublicAccessBlock",
      "Resource": "*",
      "Condition": {
        "ArnNotLike": {
          "aws:PrincipalArn": "arn:aws:iam::*:role/platform-break-glass"
        }
      }
    }
  ]
}

In production

How production teams run reviews

Good teams write a blameless postmortem after every incident: not 'who made the mistake?' but 'what about our system made this mistake easy?'. They rebuild the timeline minute by minute from CloudTrail, deploy logs and alarm history, and every action item has an owner and a due date.

The scenarios become runbooks, so an on-call engineer can copy and paste these commands and queries at midnight. On game days, teams deliberately create these failures in a staging account, with AWS Fault Injection Service or by hand, to test the runbooks and alarms.

New architectures are reviewed against the pillars of the AWS Well-Architected Framework before launch, with one extra question: 'which of these six incidents could happen in this design?'. Answering it before launch costs an hour; answering it during an outage costs far more.

Common mistakes

Common troubleshooting mistakes

Destroying the evidence

Terminating the broken instance immediately, shortening log retention, or deleting a public bucket policy without saving it destroys the evidence you need for the root cause. Contain by isolating (change the security group, turn on BPA) and take snapshots and copies first.

Changing many things at once

Raise the timeout, add memory, change concurrency and roll back the code all at once, and the problem may disappear, but nobody knows which change fixed it. For containment, make the single least risky change first and check its effect on the metrics.

Looking only at the identity policy

With AccessDenied, people assume 'we have permission' because the identity policy allows it. In reality resource policies, trust policies, permission boundaries, session policies and SCPs all take part in the decision, and one explicit deny beats every allow.

Best practices

Best practices

  • Write the symptom precisely: time, metric and who is affected
  • Always check CloudTrail changes around the moment the symptom started
  • Separate containment from repair and preserve evidence
  • Every postmortem needs at least one automated prevention item

💰 Cost & Cleanup

The guardrail script only reads, so it creates nothing. The investigation tools do cost money: each Cost Explorer API request is charged, DynamoDB Contributor Insights bills per event analysed, VPC Flow Logs bill for CloudWatch Logs ingestion and storage, and CloudTrail S3 data events and Logs Insights queries bill by volume. Switch off any diagnostics you enabled for practice.

Clean up when you are done

cleanup.sh
# The audit script only reads. If you enabled diagnostics while practising,
# switch them off again: Contributor Insights is billed per event analysed.
aws dynamodb update-contributor-insights --table-name orders \
  --contributor-insights-action DISABLE
aws lambda delete-function-concurrency --function-name image-resizer

Mini challenge

Add a DLQ depth check to the guardrail script

One lesson from the scenarios is 'a DLQ nobody watches'. Write a function that checks every queue ending in '-dlq' for waiting messages.

  • Only check queues whose name ends in '-dlq'
  • Print FAIL when ApproximateNumberOfMessages > 0, otherwise ok, in the same format as the other checks
  • Return the names of queues that need attention

Expected: In an account with emails-dlq (empty) and orders-dlq (one message) you see '[ok ] sqs:emails-dlq: 0 message(s) waiting', '[FAIL] sqs:orders-dlq: 1 message(s) waiting' and "needs attention: ['orders-dlq']".

Show hint

Request only AttributeNames=['ApproximateNumberOfMessages'] from get_queue_attributes. The value is a string, so convert it with int().

Show solution
check_dlqs.py
import boto3

sqs = boto3.client("sqs")


def check_dead_letter_queues() -> list[str]:
    """A DLQ that is not empty is an incident nobody has looked at yet."""
    waiting = []
    for url in sorted(sqs.list_queues(QueueNamePrefix="").get("QueueUrls", [])):
        name = url.rsplit("/", 1)[-1]
        if not name.endswith("-dlq"):
            continue
        attrs = sqs.get_queue_attributes(
            QueueUrl=url, AttributeNames=["ApproximateNumberOfMessages"]
        )["Attributes"]
        depth = int(attrs["ApproximateNumberOfMessages"])
        level = "FAIL" if depth else "ok"
        print(f"[{level:<4}] sqs:{name}: {depth} message(s) waiting")
        if depth:
            waiting.append(name)
    return waiting


if __name__ == "__main__":
    print("needs attention:", check_dead_letter_queues())

Quick quiz 1 / 3

An on-demand DynamoDB table shows WriteThrottleEvents while table-wide consumed capacity is low. What is the most likely root cause?

Quick quiz 2 / 3

After a role was deleted and recreated with the same name, cross-account AssumeRole fails and the target role's trust policy shows an 'AROA...' ID. What should you do?

Quick quiz 3 / 3

During an incident you calm Lambda throttling by raising the account concurrency quota. Per the review method, what is still left to do?

What to remember

  • Go through symptom, evidence, root cause, fix and prevention in order for every incident
  • The root cause is not the trigger: keep asking why until you reach a design decision or missing guardrail
  • Preserve evidence while containing, and change one thing at a time
  • A fix only sticks once it becomes an alarm, an SCP, a baseline control or a CI check

AWS Well-Architected Framework — AWS Documentation

Troubleshoot IAM access denied errors — AWS Documentation

Analyzing log data with CloudWatch Logs Insights — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercises: Six Architecture Review and Troubleshooting Scenarios | Thuta Learning