Troubleshooting
Real AWS error messages, symptoms and how to diagnose them with the aws CLI
IAM and Access Errors
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied for a user who has S3 read access. What is wrong?
Beginner
An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied for a user who has S3 read access. What is wrong?Likely causes โ The policy grants object actions but not s3:ListAllMyBuckets; or the user is on a different profile than expected.
Diagnose โ
aws sts get-caller-identity
aws iam list-attached-user-policies --user-name alice
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111111111111:user/alice --action-names s3:ListAllMyBucketsFix โ
- Confirm you are using the intended profile with
AWS_PROFILE - Add
s3:ListAllMyBucketson*if bucket listing is genuinely required - Otherwise instruct the user to
aws s3 ls s3://bucketdirectly
Prevent โ Document the minimal policy template for S3 users; bucket-scoped listing needs s3:ListBucket on the bucket ARN.
Q2 ExpiredToken: The security token included in the request is expired in a long CI job. How do you fix it?
Beginner
ExpiredToken: The security token included in the request is expired in a long CI job. How do you fix it?Likely causes โ Assumed-role sessions last 1 hour by default and the job exceeded it, or cached credentials are stale.
Diagnose โ
aws sts get-caller-identity
env | grep AWS_
aws iam get-role --role-name ci-deploy --query Role.MaxSessionDurationFix โ
- Raise role
MaxSessionDurationand request--duration-secondsaccordingly - Re-authenticate mid-job or split the job
- Unset stale
AWS_SESSION_TOKENvariables left over from a prior step
Prevent โ Use OIDC with fresh credentials per job and keep jobs short.
Q3 User: arn:aws:sts::111111111111:assumed-role/dev/bob is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::222222222222:role/deploy. Why?
Intermediate
User: arn:aws:sts::111111111111:assumed-role/dev/bob is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::222222222222:role/deploy. Why?Likely causes โ Caller lacks an sts:AssumeRole allow, or the target trust policy excludes the caller, or an SCP denies it.
Diagnose โ
aws iam get-role --role-name deploy --query Role.AssumeRolePolicyDocument
aws iam list-role-policies --role-name dev
aws organizations list-policies-for-target --target-id 111111111111 --filter SERVICE_CONTROL_POLICYFix โ
- Add allow on the target ARN to the caller's policy
- Fix the trust policy principal
- Remove blocking SCP conditions
Prevent โ Keep a trust-policy template in IaC and test with a CI assume-role smoke test.
Q4 An error occurred (AccessDenied) ... because no identity-based policy allows the s3:GetObject action yet a bucket policy allows the user. Cross-account?
Intermediate
An error occurred (AccessDenied) ... because no identity-based policy allows the s3:GetObject action yet a bucket policy allows the user. Cross-account?Likely causes โ For cross-account, both the caller's account identity policy and the bucket policy must allow.
Diagnose โ
aws s3api get-bucket-policy --bucket shared
aws iam list-attached-role-policies --role-name reader
aws iam simulate-principal-policy --policy-source-arn <arn> --action-names s3:GetObject --resource-arns arn:aws:s3:::shared/*Fix โ
- Add
s3:GetObjectto the caller role's identity policy - Keep the bucket policy as is
Prevent โ Treat cross-account access as two changes in your runbook.
Q5 IAM policy validation: MalformedPolicyDocument: Policy document should not specify a principal. What happened?
Intermediate
MalformedPolicyDocument: Policy document should not specify a principal. What happened?Likely causes โ A resource-based policy element was placed in an identity policy.
Diagnose โ
aws accessanalyzer validate-policy --policy-document file://p.json --policy-type IDENTITY_POLICYFix โ
- Remove
Principalfrom the identity policy - Use a trust policy for roles instead
- Re-run validation
Prevent โ Validate policies in CI by policy type.
Q6 The security token included in the request is invalid when using aws CLI.
Beginner
The security token included in the request is invalid when using aws CLI.Likely causes โ Wrong region or partition, a mangled session token, or credentials of a deleted key.
Diagnose โ
aws configure list
env | grep -i aws
aws sts get-caller-identity --debug 2>&1 | head -50Fix โ
- Unset environment credentials and rerun
aws configureoraws sso login - Check for trailing whitespace in the token
- Re-create the access key if deleted
Prevent โ Prefer SSO and avoid copy-pasting tokens.
Q7 SSO login works in the browser but aws sso login hangs or gives Error loading SSO Token: Token for ... does not exist.
Intermediate
aws sso login hangs or gives Error loading SSO Token: Token for ... does not exist.Likely causes โ Missing or stale cache in ~/.aws/sso/cache, wrong sso_session, or a headless terminal.
Diagnose โ
cat ~/.aws/config
ls ~/.aws/sso/cache
aws sso login --profile dev --use-device-code --debugFix โ
- Remove stale cache files and log in again
- Use
--use-device-codeon remote machines - Verify
sso_regionandsso_start_url
Prevent โ Use aws configure sso-session templates for the team.
Q8 An SCP is suspected of denying actions but console errors are vague. How do you confirm?
Advanced
Likely causes โ Explicit deny from SCP shows in the error text of recent API versions and in CloudTrail.
Diagnose โ
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=RunInstances --max-results 5
aws organizations describe-effective-policy --policy-type SERVICE_CONTROL_POLICY --target-id 111111111111
aws organizations list-policies-for-target --target-id ou-xxxx --filter SERVICE_CONTROL_POLICYFix โ
- Adjust the SCP, test in a sandbox OU first
- Use an exception for the required principal via condition keys
Prevent โ Keep SCPs in IaC with a test suite of allowed and denied calls.
Q9 iam:PassRole error: User is not authorized to perform: iam:PassRole on resource: arn:aws:iam::...:role/task-role.
Intermediate
iam:PassRole error: User is not authorized to perform: iam:PassRole on resource: arn:aws:iam::...:role/task-role.Likely causes โ The deployer can launch a service but lacks permission to hand the role to it.
Diagnose โ
aws iam get-role --role-name task-role
aws iam simulate-principal-policy --policy-source-arn <deployer-arn> --action-names iam:PassRole --resource-arns <role-arn>Fix โ
- Add
iam:PassRoleon that specific role ARN with conditioniam:PassedToService - Do not use wildcard resources
Prevent โ Scope PassRole narrowly; it is a privilege escalation path.
Q10 A newly created IAM user cannot see anything in the console. Why?
Beginner
Likely causes โ New users have no permissions.
Diagnose โ
aws iam list-attached-user-policies --user-name new
aws iam list-groups-for-user --user-name newFix โ
- Attach a group with required policies
- Wait a few seconds for propagation
Prevent โ Manage by groups or SSO, not by individual attachments.
Q11 Policy changes do not seem to apply for several minutes. Is something broken?
Intermediate
Likely causes โ IAM is eventually consistent, and existing sessions keep old permissions until refreshed.
Diagnose โ
aws iam get-policy-version --policy-arn <arn> --version-id v2
aws sts get-caller-identity
aws iam get-role --role-name rFix โ
- Retry with backoff
- Re-assume the role to get a fresh session
- Avoid create-then-use in the same script without waiting
Prevent โ Build retries into IaC and deployment pipelines.
Q12 AccessDenied with message explicit deny in a resource-based policy for a KMS decrypt in a cross-account pipeline.
Advanced
AccessDenied with message explicit deny in a resource-based policy for a KMS decrypt in a cross-account pipeline.Likely causes โ The key policy lacks the caller or has a deny condition on kms:ViaService or encryption context.
Diagnose โ
aws kms get-key-policy --key-id <key> --policy-name default
aws kms list-grants --key-id <key>
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=DecryptFix โ
- Add the role ARN to the key policy or a grant
- Add the identity policy allow for
kms:Decrypt - Check encryption context
Prevent โ Review key policies when granting cross-account S3 or EBS access.
Q13 The error You are not authorized to perform this operation. Encoded authorization failure message: .... How do you read it?
Intermediate
You are not authorized to perform this operation. Encoded authorization failure message: .... How do you read it?Likely causes โ EC2 encodes failure details that must be decoded.
Diagnose โ
aws sts decode-authorization-message --encoded-message <msg> --query DecodedMessage --output text | jq .Fix โ
- Read
explicitDeny,matchedStatements, and context keys - Fix the policy statement that matched
Prevent โ Grant sts:DecodeAuthorizationMessage to engineers.
Q14 An IAM role created by CloudFormation cannot be assumed by a Lambda: The role defined for the function cannot be assumed by Lambda.
Intermediate
The role defined for the function cannot be assumed by Lambda.Likely causes โ Trust policy missing lambda.amazonaws.com, or the role was just created.
Diagnose โ
aws iam get-role --role-name fn-role --query Role.AssumeRolePolicyDocumentFix โ
- Add
lambda.amazonaws.comto trust policy - Add
DependsOnor wait; retry creation
Prevent โ Use SAM or CDK helpers that wire trust automatically.
Q15 Your IAM role limit error: LimitExceeded: Cannot exceed quota for PoliciesPerRole: 10.
Beginner
LimitExceeded: Cannot exceed quota for PoliciesPerRole: 10.Likely causes โ Managed policy attachments per role are capped at 10 by default (up to 20 by quota).
Diagnose โ
aws iam list-attached-role-policies --role-name big
aws service-quotas get-service-quota --service-code iam --quota-code L-0DA4ABF3Fix โ
- Consolidate policies into fewer customer managed ones
- Request a quota increase
- Split the role by function
Prevent โ Design roles per workload, not mega-roles.
Q16 Policy size exceeds quota: Maximum policy size of 6144 characters when attaching an inline policy.
Intermediate
Policy size exceeds quota: Maximum policy size of 6144 characters when attaching an inline policy.Likely causes โ Role inline policies total limit is 10,240 chars; managed policies cap at 6,144.
Diagnose โ
wc -c policy.json
aws iam list-role-policies --role-name rFix โ
- Use wildcards by prefix with care
- Split into several managed policies
- Use tag-based ABAC to shrink statements
Prevent โ Prefer ABAC and resource tags over listing ARNs.
Q17 Access Analyzer reports an external access finding for an S3 bucket you thought was private.
Intermediate
Likely causes โ Bucket policy or ACL grants a principal outside the zone of trust, possibly via Principal: *.
Diagnose โ
aws accessanalyzer list-findings --analyzer-arn <arn>
aws s3api get-bucket-policy-status --bucket b
aws s3api get-bucket-acl --bucket bFix โ
- Remove the offending statement
- Re-enable Block Public Access
- Archive the finding if intentional
Prevent โ Alert on new findings through EventBridge.
Q18 Cross-account role session shows AccessDenied only for sts:TagSession calls from an SSO flow.
Advanced
AccessDenied only for sts:TagSession calls from an SSO flow.Likely causes โ Trust policy lacks sts:TagSession which is needed when sessions carry tags.
Diagnose โ
aws iam get-role --role-name target
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleFix โ
- Add
sts:TagSessionto the trust policy action list - Retry
Prevent โ Include sts:TagSession whenever you use session tags or ABAC.
Q19 The config profile (prod) could not be found.
Beginner
The config profile (prod) could not be found.Likely causes โ Profile name not defined in ~/.aws/config.
Diagnose โ
aws configure list-profiles
cat ~/.aws/configFix โ
- Add the profile or fix the name
- Check
AWS_PROFILEenv value
Prevent โ Standardize profile names across the team.
Q20 GitHub Actions OIDC fails: Not authorized to perform sts:AssumeRoleWithWebIdentity.
Intermediate
Not authorized to perform sts:AssumeRoleWithWebIdentity.Likely causes โ Trust policy sub or aud conditions mismatch the workflow's token.
Diagnose โ
aws iam get-role --role-name gh-deploy --query Role.AssumeRolePolicyDocument
# in workflow print the token claims with a debug step (never in production logs)Fix โ
- Align
subwithrepo:org/repo:ref:refs/heads/mainor environment form - Ensure
audequalssts.amazonaws.com - Add
id-token: writepermission
Prevent โ Test trust policy with a staging branch pattern.
Q21 Instance role credentials stopped working inside a container on an EC2 host: Unable to locate credentials.
Intermediate
Unable to locate credentials.Likely causes โ IMDSv2 hop limit of 1 blocks containers from reaching metadata.
Diagnose โ
curl -s -X PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60'
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].MetadataOptions'Fix โ
- Set hop limit to 2:
aws ec2 modify-instance-metadata-options --instance-id i-0abc --http-put-response-hop-limit 2 --http-tokens required - Or use task or pod roles
Prevent โ Bake hop limit into launch templates.
Q22 Organization CloudTrail stopped delivering logs. How do you recover?
Advanced
Likely causes โ The bucket policy changed, KMS key permissions broke, or the trail was disabled.
Diagnose โ
aws cloudtrail get-trail-status --name org-trail
aws s3api get-bucket-policy --bucket log-archive
aws kms describe-key --key-id <key>Fix โ
- Restore bucket policy allowing
cloudtrail.amazonaws.com - Fix KMS key policy
aws cloudtrail start-logging --name org-trail
Prevent โ Alarm on LatestDeliveryError and protect via SCP.
Q23 Console says You don't have permission to view this for CloudWatch Logs but CLI works.
Intermediate
You don't have permission to view this for CloudWatch Logs but CLI works.Likely causes โ Console needs extra read permissions such as logs:DescribeLogGroups.
Diagnose โ
aws iam simulate-principal-policy --policy-source-arn <arn> --action-names logs:DescribeLogGroups logs:GetLogEventsFix โ
- Add console-required describe actions
- Use the AWS managed
CloudWatchLogsReadOnlyAccess
Prevent โ Test console flows for each new role.
Q24 InvalidClientTokenId when calling an API in a new opt-in region.
Intermediate
InvalidClientTokenId when calling an API in a new opt-in region.Likely causes โ The region is disabled for the account or credentials are for the wrong partition.
Diagnose โ
aws account get-region-opt-status --region-name ap-south-2
aws sts get-caller-identity --region ap-south-2Fix โ
- Enable the region:
aws account enable-region --region-name ap-south-2 - Wait for enablement
Prevent โ Document region opt-ins in the landing zone.
Q25 Root user lost MFA device. How to recover?
Beginner
Likely causes โ Use the account recovery flow.
Diagnose โ
Sign in as root and choose the troubleshooting link
Verify email and phone
Contact AWS Support if requiredFix โ
- Re-register MFA after verification
- Review recent activity
Prevent โ Register multiple MFA devices for root.
VPC and Connectivity
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 ssh: connect to host 3.250.1.1 port 22: Connection timed out. Walk the checks.
Beginner
ssh: connect to host 3.250.1.1 port 22: Connection timed out. Walk the checks.Likely causes โ Timeout means packets are dropped: SG, NACL, route, public IP, or an on-instance firewall.
Diagnose โ
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].[PublicIpAddress,SecurityGroups,SubnetId]'
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-0abc
aws ec2 describe-network-acls --filters Name=association.subnet-id,Values=subnet-0abc
aws ec2 describe-network-insights-analysesFix โ
- Add SG rule for your IP
- Ensure route
0.0.0.0/0to the IGW - Fix NACL rules
- Prefer SSM Session Manager
Prevent โ Remove public SSH and use SSM.
Q27 ssh: connect to host ... port 22: Connection refused. How is it different from a timeout?
Beginner
ssh: connect to host ... port 22: Connection refused. How is it different from a timeout?Likely causes โ Refused means the packet arrived but nothing is listening, or the OS firewall rejected.
Diagnose โ
aws ec2 get-console-output --instance-id i-0abc --latest --output text | tail -50
aws ssm start-session --target i-0abc
sudo ss -ltnp | grep 22
sudo systemctl status sshdFix โ
- Start
sshd - Fix
sshd_config - Check
ufworiptables
Prevent โ Bake sshd settings into the AMI.
Q28 Permission denied (publickey) on a new EC2 instance.
Intermediate
Permission denied (publickey) on a new EC2 instance.Likely causes โ Wrong key pair, wrong username, or wrong permissions on the key file.
Diagnose โ
ssh -vvv -i key.pem ec2-user@host
chmod 400 key.pem
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].KeyName'Fix โ
- Use correct user:
ec2-user,ubuntu,admin - Use the right key
- Use EC2 Instance Connect or SSM to inject a new key
Prevent โ Document usernames per AMI.
Q29 Private instances cannot reach the internet; curl: (28) Connection timed out after 10000 milliseconds.
Intermediate
curl: (28) Connection timed out after 10000 milliseconds.Likely causes โ NAT gateway missing, route absent, or NAT in a subnet without an IGW route.
Diagnose โ
aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=vpc-0abc
aws ec2 describe-route-tables --route-table-ids rtb-0abc
aws ec2 describe-subnets --subnet-ids <nat-subnet>
curl -v https://example.comFix โ
- Create the NAT in a public subnet
- Fix routes
- Check NACL and SG egress
Prevent โ Test egress in IaC pipelines.
Q30 NAT gateway shows ErrorPortAllocation in CloudWatch and connections drop.
Intermediate
ErrorPortAllocation in CloudWatch and connections drop.Likely causes โ Too many concurrent connections to the same destination from one NAT IP.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/NATGateway --metric-name ErrorPortAllocation --dimensions Name=NatGatewayId,Value=nat-0abc --start-time 2026-11-08T00:00:00Z --end-time 2026-11-09T00:00:00Z --period 300 --statistics Sum
aws ec2 describe-nat-gatewaysFix โ
- Add secondary EIPs or more NAT gateways
- Spread across AZs
- Reuse connections and reduce churn
Prevent โ Alarm on port allocation errors.
Q31 VPC peering is active but ping fails.
Intermediate
active but ping fails.Likely causes โ Missing routes, SG rule, or NACL.
Diagnose โ
aws ec2 describe-vpc-peering-connections
aws ec2 describe-route-tables --filters Name=route.vpc-peering-connection-id,Values=pcx-0abc
aws ec2 describe-security-groups --group-ids sg-0abcFix โ
- Add routes both ways
- Allow ICMP or app port in SG
- Fix NACL
Prevent โ Use Reachability Analyzer in CI.
Q32 VPC Reachability Analyzer says BLACKHOLE. What does it mean?
Advanced
BLACKHOLE. What does it mean?Likely causes โ A route points to a deleted or inactive target.
Diagnose โ
aws ec2 create-network-insights-path --source i-0abc --destination i-0def --protocol tcp --destination-port 443
aws ec2 start-network-insights-analysis --network-insights-path-id nip-0abc
aws ec2 describe-route-tablesFix โ
- Remove or fix the blackhole route (deleted NAT, TGW or peering)
- Re-run the analysis
Prevent โ Alert on blackhole routes via Config.
Q33 Transit Gateway attached VPCs cannot talk to each other.
Intermediate
Likely causes โ Missing association or propagation in TGW route tables, or VPC routes.
Diagnose โ
aws ec2 get-transit-gateway-route-table-associations --transit-gateway-route-table-id tgw-rtb-0abc
aws ec2 search-transit-gateway-routes --transit-gateway-route-table-id tgw-rtb-0abc --filters Name=state,Values=active
aws ec2 describe-route-tablesFix โ
- Associate attachments with the right route table
- Enable propagation
- Add VPC routes to the TGW
Prevent โ Model TGW routing with diagrams.
Q34 Site-to-Site VPN tunnel is DOWN on one side.
Intermediate
DOWN on one side.Likely causes โ IKE mismatch, wrong pre-shared key, or on-prem device idle with no DPD.
Diagnose โ
aws ec2 describe-vpn-connections --vpn-connection-ids vpn-0abc --query 'VpnConnections[].VgwTelemetry'
# check device logs for IKE phase 1 and 2Fix โ
- Align IKE version and proposals
- Reapply the configuration download
- Enable DPD and keepalives
Prevent โ Monitor TunnelState.
Q35 Elastic IP association fails: Resource ... is already associated with a different resource.
Beginner
Resource ... is already associated with a different resource.Likely causes โ EIP attached elsewhere.
Diagnose โ
aws ec2 describe-addresses --allocation-ids eipalloc-0abcFix โ
- Disassociate then associate, or use
--allow-reassociation
Prevent โ Track EIPs in IaC.
Q36 Unable to resolve host inside a VPC though internet is available.
Intermediate
Unable to resolve host inside a VPC though internet is available.Likely causes โ DNS support disabled, or custom DHCP option set points to unreachable DNS.
Diagnose โ
aws ec2 describe-vpc-attribute --vpc-id vpc-0abc --attribute enableDnsSupport
aws ec2 describe-dhcp-options
cat /etc/resolv.conf
dig @169.254.169.253 example.comFix โ
- Enable DNS support and hostnames
- Fix DHCP options
Prevent โ Keep default DHCP options unless needed.
Q37 Private hosted zone names do not resolve from a peered VPC.
Intermediate
Likely causes โ Zone not associated with that VPC.
Diagnose โ
aws route53 get-hosted-zone --id Z123
dig db.internal.example.comFix โ
- Associate the VPC (cross-account needs authorization)
- Enable DNS resolution on peering
Prevent โ Use Resolver rules shared via RAM.
Q38 Interface endpoint created but SDK calls still go to the internet.
Intermediate
Likely causes โ Private DNS disabled or no DNS support.
Diagnose โ
aws ec2 describe-vpc-endpoints --vpc-endpoint-ids vpce-0abc
dig sqs.eu-west-1.amazonaws.comFix โ
- Enable PrivateDns on the endpoint
- Fix VPC DNS attributes
Prevent โ Verify DNS answers in post-deploy test.
Q39 S3 gateway endpoint blocks access: AccessDenied through VPC endpoint.
Intermediate
AccessDenied through VPC endpoint.Likely causes โ Endpoint policy or bucket policy restricts.
Diagnose โ
aws ec2 describe-vpc-endpoints --filters Name=service-name,Values=com.amazonaws.eu-west-1.s3
aws s3api get-bucket-policy --bucket bFix โ
- Allow the bucket in endpoint policy
- Add needed AWS managed buckets such as package repos
Prevent โ Test endpoint policies with real workloads.
Q40 Security group references do not work across peered VPCs in different regions.
Intermediate
Likely causes โ Cross-region peering cannot reference SGs.
Diagnose โ
aws ec2 describe-security-groups --group-ids sg-0abcFix โ
- Use CIDR rules for cross-region peers
Prevent โ Document limits.
Q41 Security group rule limit: RulesPerSecurityGroupLimitExceeded.
Beginner
RulesPerSecurityGroupLimitExceeded.Likely causes โ Too many rules in one SG.
Diagnose โ
aws ec2 describe-security-groups --group-ids sg-0abc --query 'SecurityGroups[].IpPermissions | length(@)'Fix โ
- Use prefix lists
- Split groups
- Request quota
Prevent โ Use managed prefix lists.
Q42 Return traffic is blocked even though SG allows; NACL is suspected.
Intermediate
Likely causes โ NACL is stateless; ephemeral ports not allowed.
Diagnose โ
aws ec2 describe-network-acls --network-acl-ids acl-0abc
# check flow logs for REJECT on high portsFix โ
- Allow ephemeral
1024-65535outbound and inbound as needed
Prevent โ Keep NACLs default unless required.
Q43 Instances in a new subnet cannot get an IP: InsufficientFreeAddressesInSubnet.
Intermediate
InsufficientFreeAddressesInSubnet.Likely causes โ Subnet exhausted.
Diagnose โ
aws ec2 describe-subnets --subnet-ids subnet-0abc --query 'Subnets[].AvailableIpAddressCount'Fix โ
- Launch in another subnet
- Add subnets
- Add secondary CIDR
Prevent โ Monitor available IPs.
Q44 Asymmetric routing breaks a stateful firewall behind GWLB.
Advanced
Likely causes โ Flow returns via a different AZ.
Diagnose โ
aws ec2 describe-transit-gateway-vpc-attachments --query 'TransitGatewayVpcAttachments[].Options'
# check flow logs per AZFix โ
- Enable appliance mode on the TGW attachment
- Keep route per AZ consistent
Prevent โ Test failover per AZ.
Q45 Network Load Balancer targets show unhealthy but the app works when tested directly.
Intermediate
Network Load Balancer targets show unhealthy but the app works when tested directly.Likely causes โ SG on targets blocks NLB source, or health check port mismatch.
Diagnose โ
aws elbv2 describe-target-health --target-group-arn <arn>
aws elbv2 describe-target-groups --target-group-arns <arn>Fix โ
- Allow health check source ranges
- Fix port and protocol
Prevent โ Use client IP preservation rules carefully.
Q46 Direct Connect virtual interface BGP session stays Down.
Intermediate
Down.Likely causes โ VLAN, ASN or MD5 mismatch.
Diagnose โ
aws directconnect describe-virtual-interfaces
# check router BGP summaryFix โ
- Align VLAN ID, ASN, auth key and IPs
- Contact the colo provider if layer 2 is down
Prevent โ Keep a config checklist.
Q47 RequestLimitExceeded from the EC2 API during mass operations.
Intermediate
RequestLimitExceeded from the EC2 API during mass operations.Likely causes โ API throttling.
Diagnose โ
aws ec2 describe-instances --max-items 50Fix โ
- Add exponential backoff and jitter
- Use pagination
- Reduce polling
Prevent โ Use the SDK retry modes (adaptive).
Q48 Cannot delete a VPC: The vpc has dependencies and cannot be deleted.
Beginner
The vpc has dependencies and cannot be deleted.Likely causes โ ENIs, endpoints, NAT or gateways still exist.
Diagnose โ
aws ec2 describe-network-interfaces --filters Name=vpc-id,Values=vpc-0abc
aws ec2 describe-vpc-endpoints --filters Name=vpc-id,Values=vpc-0abc
aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=vpc-0abcFix โ
- Delete dependencies in order: instances, endpoints, NAT, IGW, subnets, SGs, route tables, VPC
Prevent โ Manage VPCs with IaC for clean teardown.
Q49 SSH and small HTTP requests work across a VPN / Transit Gateway, but large file transfers and TLS handshakes hang.
Advanced
Likely causes โ An MTU mismatch. Instances use jumbo frames (9001 MTU) inside the VPC, but Site-to-Site VPN supports at most 1446 bytes and Transit Gateway 8500. Small packets fit; big ones need fragmentation. Path MTU Discovery fails because ICMP "fragmentation needed" (type 3 code 4) is blocked by a security group, NACL or on-prem firewall.
Diagnose โ
ip link show eth0 | grep mtu # 9001 on most Nitro instances
ping -M do -s 1418 10.20.0.15 # 1418 + 28 = 1446, should pass
ping -M do -s 1472 10.20.0.15 # fails => MTU is the problem
tracepath 10.20.0.15 # shows the pmtu hop by hop
aws ec2 describe-security-groups --group-ids sg-0abc --query 'SecurityGroups[].IpPermissions[?IpProtocol==`icmp`]'Fix โ
- Allow inbound ICMP type 3 code 4 (Destination Unreachable / Fragmentation Needed) in the SGs and NACLs on both sides
- Enable TCP MSS clamping on the customer gateway (for example MSS 1379 for IPsec)
- As a short-term workaround, lower the instance MTU:
sudo ip link set dev eth0 mtu 1400
Prevent โ Treat ICMP unreachable as required traffic in baseline SGs, and document per-path MTU (VPN 1446, TGW 8500, internet 1500).
Q50 InvalidSubnet.Conflict: The CIDR '10.0.1.0/24' conflicts with another subnet when creating a subnet.
Beginner
InvalidSubnet.Conflict: The CIDR '10.0.1.0/24' conflicts with another subnet when creating a subnet.Likely causes โ The CIDR overlaps an existing subnet in the same VPC. A related error, InvalidSubnet.Range: The CIDR '10.1.0.0/24' is invalid, means the block is outside the VPC CIDR(s) or smaller than /28.
Diagnose โ
aws ec2 describe-vpcs --vpc-ids vpc-0abc --query 'Vpcs[].CidrBlockAssociationSet[].CidrBlock'
aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-0abc \
--query 'Subnets[].[SubnetId,CidrBlock,AvailabilityZone]' --output tableFix โ
- Pick a free, non-overlapping range inside the VPC CIDR
- If the VPC is full, add a secondary CIDR:
aws ec2 associate-vpc-cidr-block --vpc-id vpc-0abc --cidr-block 10.1.0.0/16 - Then create the subnet inside the new range
Prevent โ Plan subnets with IPAM or a documented CIDR map. Calculate subnets in Terraform with cidrsubnet() rather than typing them by hand.
EC2, Auto Scaling and Load Balancing
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 InsufficientInstanceCapacity: We currently do not have sufficient m5.large capacity in the Availability Zone you requested (us-east-1a).
Beginner
InsufficientInstanceCapacity: We currently do not have sufficient m5.large capacity in the Availability Zone you requested (us-east-1a).Likely causes โ AWS has no spare capacity for that instance type in that AZ right now. Your account is fine; this is not a quota problem.
Diagnose โ
aws ec2 describe-instance-type-offerings --location-type availability-zone \
--filters Name=instance-type,Values=m5.large --region us-east-1
aws autoscaling describe-scaling-activities --auto-scaling-group-name web-asg --max-items 5Fix โ
- Retry in a few minutes or launch in another AZ
- Try a similar type (
m6i.large,m5a.large,m7i.large) - For an ASG, use a mixed instances policy with several types and subnets in every AZ
Prevent โ Never pin critical workloads to one type in one AZ. For events where you know you will need capacity, buy an On-Demand Capacity Reservation.
Q52 An instance shows 1/2 checks passed and you cannot reach it.
Beginner
1/2 checks passed and you cannot reach it.Likely causes โ If the system status check fails, the problem is AWS hardware or the host (power, network, physical host). If the instance status check fails, the problem is inside the OS: a kernel panic, a broken network config, a full disk or bad /etc/fstab.
Diagnose โ
aws ec2 describe-instance-status --instance-ids i-0abc \
--query 'InstanceStatuses[].[SystemStatus.Status,InstanceStatus.Status]'
aws ec2 get-console-output --instance-id i-0abc --latest --output text | tail -50
aws ec2 get-console-screenshot --instance-id i-0abc --query ImageData --output text | base64 -d > shot.jpgFix โ
- System check failed: stop and start the instance (not reboot), which moves it to new hardware
- Instance check failed: read the console output, then fix through the EC2 Serial Console or by attaching the root volume to a rescue instance
Prevent โ Add a CloudWatch alarm on StatusCheckFailed_System with the recover action, and run stateless instances behind an ASG.
Q53 VcpuLimitExceeded: You have requested more vCPU capacity than your current vCPU limit of 32 allows for the instance bucket that the specified instance type belongs to.
Beginner
VcpuLimitExceeded: You have requested more vCPU capacity than your current vCPU limit of 32 allows for the instance bucket that the specified instance type belongs to.Likely causes โ You have hit the account's vCPU-based On-Demand quota for that instance family group in this Region (for example, "Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances").
Diagnose โ
aws service-quotas get-service-quota --service-code ec2 --quota-code L-1216C47A
aws ec2 describe-instances --filters Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].InstanceType' --output text | tr '\t' '\n' | sort | uniq -cFix โ
- Terminate unused instances
- Request an increase:
aws service-quotas request-service-quota-increase --service-code ec2 --quota-code L-1216C47A --desired-value 128
Prevent โ Watch quota usage with CloudWatch AWS/Usage metrics and Trusted Advisor. Raise quotas before launches and DR tests, not during them.
Q54 A new instance goes pending โ terminated within seconds with state reason Client.InternalError: Client error on launch.
Intermediate
pending โ terminated within seconds with state reason Client.InternalError: Client error on launch.Likely causes โ Usually the EBS volumes are encrypted with a customer managed KMS key that the launching principal (or the ASG service-linked role) cannot use. It can also mean a snapshot is missing or the volume limit was exceeded.
Diagnose โ
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].StateReason'
aws ec2 describe-images --image-ids ami-0abc --query 'Images[].BlockDeviceMappings[].Ebs'
aws kms get-key-policy --key-id <key-id> --policy-name defaultFix โ
- Allow the launching principal and
AWSServiceRoleForAutoScalingto use the key:kms:CreateGrant,kms:Decrypt,kms:GenerateDataKeyWithoutPlaintext,kms:ReEncrypt*andkms:DescribeKey - For cross-account AMIs, update the key policy in the owning account and create a grant for the service-linked role
Prevent โ Keep a tested key-policy template for EBS keys that names the ASG service-linked role.
Q55 Session Manager: An error occurred (TargetNotConnected) when calling the StartSession operation: i-0abc is not connected.
Intermediate
An error occurred (TargetNotConnected) when calling the StartSession operation: i-0abc is not connected.Likely causes โ The SSM Agent is not registered. Common reasons: the instance profile does not have AmazonSSMManagedInstanceCore, the private subnet has no NAT or ssm, ssmmessages and ec2messages endpoints, the agent is stopped, or IMDS is disabled.
Diagnose โ
aws ssm describe-instance-information --filters Key=InstanceIds,Values=i-0abc
aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0abc
aws ec2 describe-vpc-endpoints --filters Name=vpc-id,Values=vpc-0abc --query 'VpcEndpoints[].ServiceName'
# on the box via serial console:
sudo systemctl status amazon-ssm-agent; sudo tail /var/log/amazon/ssm/amazon-ssm-agent.logFix โ
- Attach a role that has
AmazonSSMManagedInstanceCore - Add the three interface endpoints, with private DNS on and an SG that allows 443 from the instances
- Restart the agent, or turn on Default Host Management Configuration
Prevent โ Bake the agent into AMIs and turn on Default Host Management Configuration across the organization.
Q56 User data did not run: packages are missing and the app never started.
Intermediate
Likely causes โ The script has no shebang, or it was saved with CRLF line endings. It may have failed part-way. Or it already ran once: by default, user data runs only on the first boot, so editing it on a stopped instance does nothing.
Diagnose โ
aws ec2 describe-instance-attribute --instance-id i-0abc --attribute userData \
--query UserData.Value --output text | base64 -d | head
sudo cat /var/log/cloud-init-output.log
sudo grep -i error /var/log/cloud-init.log
cloud-init status --longFix โ
- Start the script with
#!/bin/bashand addset -euxo pipefailso failures show up - Convert the file to LF line endings
- To re-run it for testing, run
sudo cloud-init clean && sudo reboot
Prevent โ Keep user data small: bootstrap a config tool or pull a versioned script. Better still, bake an AMI with Packer.
Q57 curl http://169.254.169.254/latest/meta-data/ returns 401 - Unauthorized on a new instance.
Intermediate
curl http://169.254.169.254/latest/meta-data/ returns 401 - Unauthorized on a new instance.Likely causes โ The instance requires IMDSv2 (HttpTokens=required), and the request has no session token. Older SDKs and tools that only speak IMDSv1 break the same way.
Diagnose โ
aws ec2 describe-instances --instance-ids i-0abc \
--query 'Reservations[].Instances[].MetadataOptions'
TOKEN=$(curl -sX PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-idFix โ
- Update scripts to use the token flow, and upgrade SDKs and agents
- For containers on the host, set
HttpPutResponseHopLimitto 2:aws ec2 modify-instance-metadata-options --instance-id i-0abc --http-put-response-hop-limit 2
Prevent โ Make IMDSv2 the default at account level (aws ec2 modify-instance-metadata-defaults), and track the MetadataNoToken metric before you enforce it.
Q58 InvalidAMIID.NotFound: The image id '[ami-0abc123]' does not exist.
Beginner
InvalidAMIID.NotFound: The image id '[ami-0abc123]' does not exist.Likely causes โ AMI IDs are Regional, so the ID belongs to another Region. Other causes: the AMI was deregistered, or it is private and not shared with your account.
Diagnose โ
aws configure get region
aws ec2 describe-images --image-ids ami-0abc123 --region eu-west-1
aws ec2 describe-image-attribute --image-id ami-0abc123 --attribute launchPermissionFix โ
- Use the AMI ID for the right Region, or copy the AMI there:
aws ec2 copy-image --source-region eu-west-1 --source-image-id ami-0abc123 --region us-east-1 --name app-v12 - Look up public AMIs through SSM parameters instead of hard-coding IDs:
aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Prevent โ Resolve AMIs dynamically (SSM parameter or a data source filtered by tag) and copy golden AMIs to every Region you use.
Q59 An ASG keeps launching and terminating instances in a loop; activity history says an instance was taken out of service in response to an ELB system health check failure.
Intermediate
an instance was taken out of service in response to an ELB system health check failure.Likely causes โ The ASG uses ELB health checks, but the health check grace period is shorter than the app's boot time. It can also be a wrong health check path, or a target SG that does not allow traffic from the ALB.
Diagnose โ
aws autoscaling describe-scaling-activities --auto-scaling-group-name web-asg --max-items 10
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names web-asg \
--query 'AutoScalingGroups[].[HealthCheckType,HealthCheckGracePeriod]'
aws elbv2 describe-target-health --target-group-arn <tg-arn>Fix โ
- Raise the grace period above the real boot time:
aws autoscaling update-auto-scaling-group --auto-scaling-group-name web-asg --health-check-grace-period 300 - Fix the health check path and port, and the SG rule from the ALB SG
- To debug a live instance, suspend
ReplaceUnhealthyfor a while:aws autoscaling suspend-processes --auto-scaling-group-name web-asg --scaling-processes ReplaceUnhealthy
Prevent โ Use a cheap /healthz endpoint, plus a lifecycle hook or warm pool for slow boots.
Q60 ASG activity fails: Value (app-profile) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name.
Beginner
Value (app-profile) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name.Likely causes โ The instance profile does not exist, or it was just created and has not propagated yet. Another common cause: the role was created in the console with a different profile name, or created through the CLI without a profile.
Diagnose โ
aws iam get-instance-profile --instance-profile-name app-profile
aws iam list-instance-profiles-for-role --role-name app-roleFix โ
- Create the profile and add the role to it:
aws iam create-instance-profile --instance-profile-name app-profilethenaws iam add-role-to-instance-profile --instance-profile-name app-profile --role-name app-role - Wait a few seconds after creating it, then retry the launch
Prevent โ In IaC, create aws_iam_instance_profile explicitly and reference it, so the dependency order is correct.
Q61 An ASG instance refresh fails with Instance refresh failed: ... could not maintain the minimum healthy percentage.
Advanced
Instance refresh failed: ... could not maintain the minimum healthy percentage.Likely causes โ New instances from the updated launch template never become healthy, so the refresh cannot replace more instances without dropping below MinHealthyPercentage. Typical reasons: a bad AMI, broken user data or a failing health check. A checkpoint or alarm-based rollback may also have stopped it.
Diagnose โ
aws autoscaling describe-instance-refreshes --auto-scaling-group-name web-asg --max-records 1
aws autoscaling describe-scaling-activities --auto-scaling-group-name web-asg --max-items 10
aws elbv2 describe-target-health --target-group-arn <tg-arn> \
--query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State,TargetHealth.Reason]'Fix โ
- Roll back:
aws autoscaling rollback-instance-refresh --auto-scaling-group-name web-asg, or cancel it and fix the template - Debug one new instance (console output, cloud-init log), then start the refresh again with
--preferences '{"MinHealthyPercentage":90,"InstanceWarmup":300,"AutoRollback":true}'
Prevent โ Turn on AutoRollback with CloudWatch alarms, use checkpoints for canary-style refreshes, and test AMIs in staging first.
Q62 ALB returns 502 Bad Gateway. Where do you look?
Intermediate
502 Bad Gateway. Where do you look?Likely causes โ The target closed the connection, sent a malformed response, or reset during a request. Common reasons: the app crashed, or its keep-alive timeout is shorter than the ALB idle timeout (60s), so the target drops idle connections the ALB still reuses. A Lambda target that returns an invalid response also causes 502.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/ApplicationELB --metric-name HTTPCode_ELB_502_Count \
--dimensions Name=LoadBalancer,Value=app/web/abc123 --statistics Sum --period 60 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws elbv2 describe-load-balancer-attributes --load-balancer-arn <alb-arn>
# access logs: elb_status_code=502 with target_status_code="-" means no response from targetFix โ
- Set the app keep-alive timeout above the ALB idle timeout (for example, Node.js
server.keepAliveTimeout = 65000, Nginxkeepalive_timeout 75s) - Fix the app crashes and response headers
Prevent โ Turn on ALB access logs to S3 and alarm on the ratio of HTTPCode_ELB_5XX_Count to request count.
Q63 ALB returns 504 Gateway Timeout on a report endpoint.
Intermediate
504 Gateway Timeout on a report endpoint.Likely causes โ The target did not respond before the ALB idle timeout (60s by default). Either the request is too slow, or the target is unreachable (blocked by an SG or NACL), so the connection attempt times out.
Diagnose โ
aws elbv2 describe-load-balancer-attributes --load-balancer-arn <alb-arn> \
--query "Attributes[?Key=='idle_timeout.timeout_seconds']"
# access logs: high target_processing_time, or request_processing_time -1
aws cloudwatch get-metric-statistics --namespace AWS/ApplicationELB --metric-name TargetResponseTime \
--dimensions Name=LoadBalancer,Value=app/web/abc123 --extended-statistics p99 --period 60 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)Fix โ
- As a short-term fix, raise the idle timeout:
aws elbv2 modify-load-balancer-attributes --load-balancer-arn <arn> --attributes Key=idle_timeout.timeout_seconds,Value=180 - As the real fix, make long jobs asynchronous: return 202, process through a queue, and let the client poll or receive a webhook
Prevent โ Track TargetResponseTime p99 per route, and keep synchronous requests well under the timeout.
Q64 ALB returns 503 Service Temporarily Unavailable immediately.
Beginner
503 Service Temporarily Unavailable immediately.Likely causes โ The target group behind the matched listener rule has no registered targets, or all of its targets are in AZs the ALB is not enabled in. If every target is unhealthy, the ALB "fails open" and still routes traffic, so 503 usually means no targets.
Diagnose โ
aws elbv2 describe-rules --listener-arn <listener-arn> \
--query 'Rules[].[Priority,Actions[0].TargetGroupArn]'
aws elbv2 describe-target-health --target-group-arn <tg-arn>
aws elbv2 describe-load-balancers --load-balancer-arns <alb-arn> --query 'LoadBalancers[].AvailabilityZones'Fix โ
- Register targets, or attach the ASG or ECS service to the right target group
- Enable the ALB in the AZs where the targets run
Prevent โ Alarm on HealthyHostCount < 1 per target group, and check that targets are attached in your IaC.
Q65 Target health shows Target.ResponseCodeMismatch: Health checks failed with these codes: [404].
Intermediate
Target.ResponseCodeMismatch: Health checks failed with these codes: [404].Likely causes โ The health check path does not exist on the app, or it redirects (301/302) to HTTPS or a login page. By default, the matcher only accepts 200.
Diagnose โ
aws elbv2 describe-target-groups --target-group-arns <tg-arn> \
--query 'TargetGroups[].[HealthCheckPath,HealthCheckPort,Matcher.HttpCode]'
# from an instance in the same subnet:
curl -i http://10.0.1.25:8080/healthFix โ
- Point the health check at a real endpoint:
aws elbv2 modify-target-group --target-group-arn <tg-arn> --health-check-path /healthz - Or widen the matcher if the endpoint legitimately returns another code:
--matcher HttpCode=200-299
Prevent โ Every service exposes an unauthenticated /healthz that does not redirect, and IaC defines it next to the target group.
Q66 Target health shows Target.Timeout: Request timed out for every target.
Intermediate
Target.Timeout: Request timed out for every target.Likely causes โ The ALB cannot reach the targets. The usual reasons: the target SG does not allow the health check port from the ALB SG, a NACL blocks it, the app listens only on 127.0.0.1, or the health check uses the wrong port.
Diagnose โ
aws elbv2 describe-target-health --target-group-arn <tg-arn>
aws ec2 describe-security-groups --group-ids <target-sg> --query 'SecurityGroups[].IpPermissions'
# on the target:
sudo ss -lntp | grep 8080 # 127.0.0.1:8080 means not reachable from the ALBFix โ
- Allow the app port from the ALB SG:
aws ec2 authorize-security-group-ingress --group-id <target-sg> --protocol tcp --port 8080 --source-group <alb-sg> - Bind the app to
0.0.0.0 - Check that the NACL allows the ephemeral return ports
Prevent โ Use SG-to-SG references in IaC rather than CIDRs, and run Reachability Analyzer from the ALB ENI to the target.
Q67 ALB access logs show many 460 responses and some 463. What do they mean?
Advanced
460 responses and some 463. What do they mean?Likely causes โ These are ALB-specific codes. 460 means the client closed the connection before the idle timeout ran out, usually because the client timeout is shorter than the backend latency. 463 means the X-Forwarded-For header has more than 30 IP addresses, usually from a proxy loop or a misbehaving client.
Diagnose โ
aws s3 cp s3://alb-logs/AWSLogs/111111111111/elasticloadbalancing/us-east-1/2026/11/09/ . --recursive
zcat *.log.gz | awk '$9==460 {print $13,$14}' | sort | uniq -c | sort -rn | head # method + URL
zcat *.log.gz | awk '$9==460 {print $7}' | sort -n | tail # target_processing_timeFix โ
- For 460, find the slow endpoints and fix their latency, or align the client and SDK timeouts with the server
- For 463, find the proxy chain that keeps appending to XFF, and break the loop (for example, CloudFront โ ALB โ nginx โ the same ALB)
Prevent โ Load ALB logs into Athena with a saved table, and alarm on the p99 latency of the top routes.
Q68 Creating an HTTPS listener fails with CertificateNotFound: Certificate 'arn:aws:acm:...' not found.
Intermediate
CertificateNotFound: Certificate 'arn:aws:acm:...' not found.Likely causes โ The ACM certificate is in a different Region from the ALB, it is still PENDING_VALIDATION, or the ARN belongs to another account.
Diagnose โ
aws acm list-certificates --region us-east-1 \
--query 'CertificateSummaryList[].[DomainName,Status,CertificateArn]'
aws acm describe-certificate --certificate-arn <arn> \
--query 'Certificate.DomainValidationOptions[].[DomainName,ValidationStatus,ResourceRecord]'Fix โ
- Request or import the certificate in the ALB's Region
- Finish DNS validation by creating the CNAME that ACM shows (Route 53 can do it in one click)
- Use the ISSUED ARN in the listener
Prevent โ Manage certificates in IaC with aws_acm_certificate_validation, so the listener waits until the certificate is issued.
Q69 Behind an NLB, one target gets most of the traffic while the others sit idle.
Advanced
Likely causes โ An NLB balances per connection (flow hash), not per request. A few long-lived connections, such as gRPC, HTTP/2, WebSockets or pooled DB clients, stick to whichever target they first hit. Cross-zone load balancing is off by default on an NLB, so an AZ with fewer targets gets proportionally more load per target.
Diagnose โ
aws elbv2 describe-load-balancer-attributes --load-balancer-arn <nlb-arn> \
--query "Attributes[?Key=='load_balancing.cross_zone.enabled']"
aws elbv2 describe-target-health --target-group-arn <tg-arn>
# per-target ActiveFlowCount / NewFlowCount in CloudWatch (AWS/NetworkELB)Fix โ
- Turn on cross-zone:
aws elbv2 modify-load-balancer-attributes --load-balancer-arn <nlb-arn> --attributes Key=load_balancing.cross_zone.enabled,Value=true - For HTTP/2 or gRPC, use an ALB, which balances per request. Or make clients recycle connections regularly (max connection age)
- Spread targets evenly across AZs
Prevent โ Pick the LB for the protocol: an ALB for request-level balancing, an NLB for raw TCP, static IPs and very high throughput.
Q70 Spot instances disappear and the state reason is Server.SpotInstanceTermination.
Intermediate
Server.SpotInstanceTermination.Likely causes โ AWS reclaimed the Spot capacity. You get a 2-minute interruption notice, and possibly an earlier rebalance recommendation.
Diagnose โ
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].StateReason'
aws ec2 describe-spot-instance-requests --filters Name=instance-id,Values=i-0abc \
--query 'SpotInstanceRequests[].Status'
# on the instance, the notice endpoint:
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/spot/instance-actionFix โ
- Diversify across many instance types and all AZs, and use the
price-capacity-optimizedallocation strategy - Handle the interruption notice: drain from the LB and checkpoint work. On EKS, use Karpenter or the Node Termination Handler
- Turn on Capacity Rebalancing on the ASG
Prevent โ Run only stateless, interruptible workloads on Spot, and keep an On-Demand base capacity for the minimum.
Q71 After a kernel update and reboot, the instance never comes back: status check fails and SSH times out.
Advanced
Likely causes โ The new kernel or initramfs does not boot (missing NVMe or ENA modules), GRUB points at a bad entry, or /etc/fstab references a device that no longer exists.
Diagnose โ
aws ec2 get-console-output --instance-id i-0abc --latest --output text | tail -80
# interactive: EC2 Serial Console (needs account-level enablement and a password user)
aws ec2 enable-serial-console-access
aws ec2-instance-connect send-serial-console-ssh-public-key --instance-id i-0abc --serial-port 0 --ssh-public-key file://key.pubFix โ
- Use the Serial Console to pick the previous kernel in GRUB, then fix it
- Or use a rescue instance: stop the instance, detach the root volume, attach it to a rescue instance in the same AZ, mount it, fix
gruborfstab(nofail, UUIDs), then reattach as/dev/xvdaand start - AWSSupport-ExecuteEC2Rescue automation can do this for you
Prevent โ Patch through AMI rebuilds and rolling replacement instead of in place, and take snapshots before kernel changes.
Q72 Changing an old instance to c5.large fails: Enhanced networking with the Elastic Network Adapter (ENA) is required for the 'c5.large' instance type. Ensure that your instance 'i-0abc' is enabled for ENA.
Advanced
c5.large fails: Enhanced networking with the Elastic Network Adapter (ENA) is required for the 'c5.large' instance type. Ensure that your instance 'i-0abc' is enabled for ENA.Likely causes โ The instance came from an old AMI built for Xen (for example m4 or t2). Nitro types need the ENA driver for networking and NVMe drivers for EBS, and the instance attribute enaSupport must be true.
Diagnose โ
aws ec2 describe-instances --instance-ids i-0abc --query 'Reservations[].Instances[].EnaSupport'
# on the instance:
modinfo ena; lsmod | grep -E 'ena|nvme'Fix โ
- Install or confirm the ENA and NVMe drivers inside the OS, and add them to the initramfs
- Stop the instance and run
aws ec2 modify-instance-attribute --instance-id i-0abc --ena-support - Change the type, and change
/etc/fstabto use UUIDs, because device names become/dev/nvme*
Prevent โ Use current AMIs (AL2023, Ubuntu 22.04/24.04) and move off previous-generation types in planned windows.
Q73 A t3.medium web server becomes slow every afternoon, but CPU never goes above ~20%.
Beginner
t3.medium web server becomes slow every afternoon, but CPU never goes above ~20%.Likely causes โ The instance is a burstable type in standard credit mode. Once CPUCreditBalance reaches 0, it is throttled to its baseline (20% for t3.medium). CloudWatch then shows CPU flat at the baseline.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUCreditBalance \
--dimensions Name=InstanceId,Value=i-0abc --statistics Minimum --period 300 \
--start-time $(date -u -d '-1 day' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws ec2 describe-instance-credit-specifications --instance-ids i-0abcFix โ
- Switch to unlimited mode:
aws ec2 modify-instance-credit-specification --instance-credit-specification 'InstanceId=i-0abc,CpuCredits=unlimited'(you pay for surplus credits) - Or move to a fixed-performance type (m7i, c7g) if the load is sustained
Prevent โ Alarm on CPUCreditBalance and use T instances only for workloads that really are bursty.
Q74 During scale-in, the ASG terminates instances in the middle of long batch jobs.
Advanced
Likely causes โ Scale-in picks instances using the termination policy and knows nothing about the work on them. Without lifecycle hooks or protection, jobs are killed.
Diagnose โ
aws autoscaling describe-scaling-activities --auto-scaling-group-name workers --max-items 10
aws autoscaling describe-lifecycle-hooks --auto-scaling-group-name workers
aws autoscaling describe-auto-scaling-instances --query 'AutoScalingInstances[].[InstanceId,ProtectedFromScaleIn]'Fix โ
- The worker sets scale-in protection while it is busy:
aws autoscaling set-instance-protection --instance-ids i-0abc --auto-scaling-group-name workers --protected-from-scale-in(and clears it when done) - Add a
autoscaling:EC2_INSTANCE_TERMINATINGlifecycle hook. The instance finishes or checkpoints its job, then callscomplete-lifecycle-action - Scale on queue depth per instance instead of CPU
Prevent โ Design jobs to be idempotent and checkpointed, and size the hook HeartbeatTimeout to the longest job.
Q75 You updated the launch template with a new AMI, but new ASG instances still boot the old AMI.
Beginner
Likely causes โ The ASG references a specific template version, or $Default, and you created a new version without making it the default. New versions are not used until the ASG points at them.
Diagnose โ
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names web-asg \
--query 'AutoScalingGroups[].[LaunchTemplate,MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification]'
aws ec2 describe-launch-template-versions --launch-template-id lt-0abc \
--query 'LaunchTemplateVersions[].[VersionNumber,DefaultVersion,LaunchTemplateData.ImageId]'Fix โ
- Point the ASG at
$Latest, or set the new version as default:aws ec2 modify-launch-template --launch-template-id lt-0abc --default-version 7 - Start an instance refresh to replace the instances that are already running
Prevent โ Have the pipeline create the version, update the ASG and start an instance refresh in one step.
S3, EBS and EFS
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 BucketAlreadyExists: The requested bucket name is not available. The bucket namespace is shared by all users of the system.
Beginner
BucketAlreadyExists: The requested bucket name is not available. The bucket namespace is shared by all users of the system.Likely causes โ S3 bucket names are global across all AWS accounts, and another account already owns this name. If you own it, you get BucketAlreadyOwnedByYou instead. That error is common when IaC re-runs a create in a different Region.
Diagnose โ
aws s3api head-bucket --bucket my-app-logs # 403 = exists in someone else's account, 404 = free
aws s3api list-buckets --query "Buckets[?Name=='my-app-logs']"Fix โ
- Pick a unique name, for example with the account ID and Region:
my-app-logs-111111111111-us-east-1 - For
BucketAlreadyOwnedByYou, import the bucket into state instead of creating it
Prevent โ Use a naming convention with the account and Region in it, or the S3 account-regional namespace option where it is available. Never rely on a deleted name being free again.
Q77 PermanentRedirect: The bucket you are attempting to access must be addressed using the specified endpoint.
Beginner
PermanentRedirect: The bucket you are attempting to access must be addressed using the specified endpoint.Likely causes โ The client is calling the wrong Regional endpoint for this bucket, usually because the profile Region is different from the bucket's Region, or an old SDK hard-codes s3.amazonaws.com.
Diagnose โ
aws s3api get-bucket-location --bucket my-bucket # null LocationConstraint = us-east-1
aws configure get region
aws s3 ls s3://my-bucket --debug 2>&1 | grep -i 'x-amz-bucket-region'Fix โ
- Pass the right Region:
aws s3 ls s3://my-bucket --region eu-central-1 - Configure the SDK client with the bucket's Region
Prevent โ Keep Region per environment in config, and include the Region in bucket names to make mismatches obvious.
Q78 A partner account uploads objects into your bucket, but your own admins get 403 Forbidden reading them.
Intermediate
403 Forbidden reading them.Likely causes โ Object Ownership is ObjectWriter (the legacy setting), so the uploading account owns the objects and the bucket policy cannot grant access to them. This happens when the uploader did not set bucket-owner-full-control.
Diagnose โ
aws s3api get-bucket-ownership-controls --bucket shared-ingest
aws s3api get-object-acl --bucket shared-ingest --key incoming/file.csvFix โ
- Turn on Bucket owner enforced (ACLs disabled):
aws s3api put-bucket-ownership-controls --bucket shared-ingest --ownership-controls 'Rules=[{ObjectOwnership=BucketOwnerEnforced}]' - That takes ownership of all objects, including existing ones. Re-check the bucket policy grants
Prevent โ Use BucketOwnerEnforced everywhere (the default for new buckets since 2023), and control access only through policies.
Q79 aws s3 cp gets An error occurred (AccessDenied) when calling the GetObject operation but the IAM policy allows s3:GetObject and the bucket policy is fine.
Intermediate
aws s3 cp gets An error occurred (AccessDenied) when calling the GetObject operation but the IAM policy allows s3:GetObject and the bucket policy is fine.Likely causes โ The object is encrypted with SSE-KMS using a customer managed key, and the caller has no kms:Decrypt on that key (through the key policy or IAM). For uploads, the missing permission is kms:GenerateDataKey.
Diagnose โ
aws s3api head-object --bucket data --key reports/q3.parquet \
--query '[ServerSideEncryption,SSEKMSKeyId]'
aws kms get-key-policy --key-id <key-arn> --policy-name default --output text
# CloudTrail: look for kms Decrypt with errorCode AccessDeniedFix โ
- Grant
kms:Decrypton the key ARN to the role in IAM, and make sure the key policy allows IAM policies (the root principal statement) or names the role - For cross-account access, both the key policy and the caller's IAM policy must allow it
Prevent โ Every S3 access policy template includes the matching KMS statement, and S3 Bucket Keys are on to reduce KMS calls.
Q80 An S3 static website endpoint returns 403 Forbidden with Code: AccessDenied.
Intermediate
403 Forbidden with Code: AccessDenied.Likely causes โ Block Public Access is on at the account or bucket level, or no bucket policy grants s3:GetObject to *. Also check that the index document exists exactly as named (keys are case-sensitive) and that objects are not KMS-encrypted (website endpoints cannot serve SSE-KMS objects).
Diagnose โ
aws s3control get-public-access-block --account-id 111111111111
aws s3api get-public-access-block --bucket my-site
aws s3api get-bucket-policy --bucket my-site
aws s3api get-bucket-website --bucket my-site
aws s3 ls s3://my-site/index.htmlFix โ
- In production, keep the bucket private and put CloudFront with OAC in front of it
- If a public website endpoint is truly intended, turn off BPA for that bucket only and add a read-only public policy for
arn:aws:s3:::my-site/*
Prevent โ Keep account-level BPA on, and serve all public content through CloudFront.
Q81 High-throughput writes get 503 SlowDown: Please reduce your request rate.
Intermediate
503 SlowDown: Please reduce your request rate.Likely causes โ You are above the per-prefix request rate (about 3,500 PUT/COPY/POST/DELETE and 5,500 GET/HEAD per second per partitioned prefix), and S3 has not repartitioned yet. All writes going to one hot prefix such as logs/2026-11-09/ make it worse.
Diagnose โ
aws s3api put-bucket-metrics-configuration --bucket data --id all --metrics-configuration Id=all
# then CloudWatch AWS/S3 metrics: AllRequests, 5xxErrors per FilterId
aws s3api list-objects-v2 --bucket data --prefix logs/2026-11-09/ --max-items 5Fix โ
- Retry with exponential backoff. SDK retries do this, and
adaptivemode helps - Spread keys across more prefixes (for example, a hash or shard prefix)
- Batch small objects into larger ones
Prevent โ Design key layouts for parallelism, and ramp traffic up gradually so S3 can scale partitions.
Q82 BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket. even after aws s3 rm --recursive.
Beginner
BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket. even after aws s3 rm --recursive.Likely causes โ Versioning is on. aws s3 rm only adds delete markers, and all older versions and delete markers remain.
Diagnose โ
aws s3api get-bucket-versioning --bucket old-bucket
aws s3api list-object-versions --bucket old-bucket --max-items 5Fix โ
- For small buckets, delete versions in batches:
aws s3api list-object-versions --bucket old-bucket \
--query '{Objects: [Versions[].{Key:Key,VersionId:VersionId}, DeleteMarkers[].{Key:Key,VersionId:VersionId}][]}' \
--max-items 1000 --output json > del.json
aws s3api delete-objects --bucket old-bucket --delete file://del.json- For big buckets, add a lifecycle rule that expires current and noncurrent versions and delete markers, wait a day, then delete the bucket
Prevent โ In IaC, use force_destroy only for ephemeral buckets, and give every versioned bucket a noncurrent-version lifecycle rule.
Q83 A browser upload to S3 fails: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Intermediate
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Likely causes โ The bucket has no CORS configuration, or it does not list the origin, method (PUT/POST) or headers the browser sends in the preflight. Presigned PUTs with custom headers such as Content-Type need AllowedHeaders.
Diagnose โ
aws s3api get-bucket-cors --bucket uploads
curl -i -X OPTIONS "https://uploads.s3.amazonaws.com/test.txt" \
-H 'Origin: https://app.example.com' -H 'Access-Control-Request-Method: PUT'Fix โ
aws s3api put-bucket-cors --bucket uploads --cors-configuration '{
"CORSRules":[{"AllowedOrigins":["https://app.example.com"],"AllowedMethods":["PUT","GET"],
"AllowedHeaders":["*"],"ExposeHeaders":["ETag"],"MaxAgeSeconds":3000}]}'If CloudFront is in front, forward the Origin header in the origin request policy.
Prevent โ Keep the CORS config in IaC with explicit origins per environment. Never use * together with credentials.
Q84 Presigned URLs return SignatureDoesNotMatch for some users and Request has expired for others.
Intermediate
SignatureDoesNotMatch for some users and Request has expired for others.Likely causes โ SignatureDoesNotMatch means the request is different from what was signed: another HTTP method, a missing Content-Type, the wrong Region endpoint, or the URL was re-encoded. Request has expired means the expiry passed, or the URL was signed with temporary role credentials that expired earlier (a URL is valid only as long as the signing credentials).
Diagnose โ
aws s3 presign s3://bucket/file.zip --expires-in 3600 --region us-east-1
# inspect X-Amz-Expires, X-Amz-Date, X-Amz-Credential in the URL
aws sts get-caller-identity # signed with a role session? check its expiryFix โ
- Sign with the exact method and headers the client will send, using a Regional endpoint
- For long-lived links, sign with credentials that last at least as long. SigV4 allows a maximum of 7 days
- Fix client clock skew
Prevent โ Generate URLs on demand with a short expiry, and serve large public downloads through CloudFront signed URLs.
Q85 S3 Cross-Region Replication is configured, but new objects show ReplicationStatus: FAILED.
Advanced
ReplicationStatus: FAILED.Likely causes โ The replication role does not have s3:ReplicateObject on the destination, or the destination bucket policy does not allow the role (cross-account). Objects are SSE-KMS but the rule has no SseKmsEncryptedObjects or KMS permissions in the destination Region. Versioning is off on one side. Or Object Lock is in use without the right configuration.
Diagnose โ
aws s3api get-bucket-replication --bucket src
aws s3api head-object --bucket src --key path/obj --query ReplicationStatus
aws s3api get-bucket-versioning --bucket dst
# enable replication metrics + S3 event notifications for s3:Replication:OperationFailedReplicationFix โ
- Fix the role permissions (source read, destination replicate, KMS decrypt on the source key and encrypt on the destination key)
- Fix the destination bucket policy for cross-account
- Re-replicate the failed and existing objects with S3 Batch Replication
Prevent โ Turn on Replication Time Control metrics and alarm on OperationsFailedReplication.
Q86 A lifecycle rule "expire after 30 days" has been on for months, yet storage is still growing.
Intermediate
Likely causes โ The bucket is versioned. Expiring current objects only adds delete markers, so noncurrent versions build up. Other causes: the rule's prefix or tag filter does not match the keys, or the objects are below the minimum size for transitions.
Diagnose โ
aws s3api get-bucket-lifecycle-configuration --bucket logs
aws s3api get-bucket-versioning --bucket logs
aws s3api list-object-versions --bucket logs --prefix app/ --max-items 10 \
--query 'Versions[?IsLatest==`false`].[Key,LastModified]'Fix โ Add NoncurrentVersionExpiration (for example, after 7 days) and ExpiredObjectDeleteMarker: true. Correct the filter prefix.
Prevent โ Use S3 Storage Lens to watch noncurrent bytes per bucket, and use one standard lifecycle template for versioned buckets.
Q87 The bill shows far more S3 storage than aws s3 ls --summarize reports.
Advanced
aws s3 ls --summarize reports.Likely causes โ Incomplete multipart uploads (the parts are stored and billed, but ls does not show them), noncurrent versions, or storage-class overhead (minimum object size and duration charges for IA and Glacier).
Diagnose โ
aws s3api list-multipart-uploads --bucket data --query 'Uploads[].[Key,Initiated]' --output table
aws cloudwatch get-metric-statistics --namespace AWS/S3 --metric-name BucketSizeBytes \
--dimensions Name=BucketName,Value=data Name=StorageType,Value=StandardStorage \
--statistics Average --period 86400 --start-time $(date -u -d '-3 day' +%FT%TZ) --end-time $(date -u +%FT%TZ)Fix โ
- Abort stale uploads:
aws s3api abort-multipart-upload --bucket data --key <key> --upload-id <id> - Add a lifecycle rule with
AbortIncompleteMultipartUploadDaysAfterInitiation: 7
Prevent โ Put that lifecycle rule on every bucket by default, and use Storage Lens for "incomplete MPU bytes".
Q88 s3api put-object fails: EntityTooLarge: Your proposed upload exceeds the maximum allowed size.
Beginner
s3api put-object fails: EntityTooLarge: Your proposed upload exceeds the maximum allowed size.Likely causes โ One PUT can be at most 5 GB. aws s3api put-object does a single PUT, while aws s3 cp switches to multipart automatically. Objects larger than that can only be uploaded with multipart upload.
Diagnose โ
ls -lh backup.tar
aws configure get default.s3.multipart_thresholdFix โ
- Use
aws s3 cp backup.tar s3://bucket/(multipart, parallel parts) - Tune it for speed:
aws configure set default.s3.multipart_chunksize 64MBandmax_concurrent_requests 20
Prevent โ Use the high-level transfer managers (CLI s3 cp, SDK TransferManager) for anything larger than about 100 MB.
Q89 Someone added a bucket policy with "Effect":"Deny" unless aws:SourceVpce matches. Now even admins get AccessDenied, including on PutBucketPolicy.
Advanced
"Effect":"Deny" unless aws:SourceVpce matches. Now even admins get AccessDenied, including on PutBucketPolicy.Likely causes โ An explicit deny in the bucket policy beats every allow, including admin IAM policies. Calls from outside the VPC endpoint (console, laptop CLI) are denied, and that includes changing the policy.
Diagnose โ
aws s3api get-bucket-policy --bucket locked --output text # likely denied too
# CloudTrail: GetBucketPolicy / PutBucketPolicy errorCode AccessDeniedFix โ
- Call from a principal that matches the condition, for example an instance in the VPC that uses that endpoint, and run
aws s3api delete-bucket-policy --bucket locked - If nothing can match, sign in as the account root user, which can always delete a bucket policy that locks it out (with Organizations, the management account can use centralized root access for member accounts)
Prevent โ Always exempt a break-glass role in deny conditions (aws:PrincipalArn with StringNotLike), and test policies with Access Analyzer policy validation before applying them.
Q90 You attached a new EBS volume, but df -h does not show it and /dev/sdf does not exist.
Beginner
df -h does not show it and /dev/sdf does not exist.Likely causes โ Attaching a volume does not format or mount it. On Nitro instances, the device shows up as /dev/nvme1n1, not /dev/sdf.
Diagnose โ
aws ec2 describe-volumes --volume-ids vol-0abc --query 'Volumes[].Attachments'
lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT,SERIAL # SERIAL shows vol0abc...
sudo file -s /dev/nvme1n1 # "data" = no filesystemFix โ
sudo mkfs -t xfs /dev/nvme1n1
sudo mkdir -p /data && sudo mount /dev/nvme1n1 /data
echo "UUID=$(sudo blkid -s UUID -o value /dev/nvme1n1) /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstabPrevent โ Use UUIDs and nofail in fstab, and do the formatting in user data or configuration management.
Q91 You grew an EBS volume from 20 to 50 GiB, but the server still says No space left on device.
Beginner
No space left on device.Likely causes โ You resized the volume, but not the partition and filesystem inside it.
Diagnose โ
aws ec2 describe-volumes-modifications --volume-ids vol-0abc --query 'VolumesModifications[].ModificationState'
lsblk # disk 50G, partition still 20G
df -hT /Fix โ
sudo growpart /dev/nvme0n1 1
sudo xfs_growfs -d / # XFS (Amazon Linux)
# or
sudo resize2fs /dev/nvme0n1p1 # ext4 (Ubuntu)If df shows the disk is not full, check inodes: df -i.
Prevent โ Alarm on disk usage from the CloudWatch agent (disk_used_percent), and send logs off-box so they do not fill the disk.
Q92 modify-volume fails: You've reached the maximum modification rate per volume limit. Wait at least 6 hours between modifications per EBS volume.
Intermediate
modify-volume fails: You've reached the maximum modification rate per volume limit. Wait at least 6 hours between modifications per EBS volume.Likely causes โ EBS allows one modification per volume every 6 hours, and the previous change must have reached completed or optimizing.
Diagnose โ
aws ec2 describe-volumes-modifications --volume-ids vol-0abc \
--query 'VolumesModifications[].[ModificationState,StartTime,EndTime,TargetSize,TargetIops]'Fix โ
- If you need space now, attach a second volume and extend with LVM, or move data out
- Otherwise wait, and change size, IOPS and throughput in one call:
aws ec2 modify-volume --volume-id vol-0abc --size 200 --iops 6000 --throughput 500
Prevent โ Right-size with headroom, and batch all attribute changes into one modification.
Q93 InvalidVolume.ZoneMismatch: The volume 'vol-0abc' is not in the same availability zone as instance 'i-0def'.
Beginner
InvalidVolume.ZoneMismatch: The volume 'vol-0abc' is not in the same availability zone as instance 'i-0def'.Likely causes โ An EBS volume exists in one AZ and can only attach to instances in that AZ.
Diagnose โ
aws ec2 describe-volumes --volume-ids vol-0abc --query 'Volumes[].AvailabilityZone'
aws ec2 describe-instances --instance-ids i-0def --query 'Reservations[].Instances[].Placement.AvailabilityZone'Fix โ
aws ec2 create-snapshot --volume-id vol-0abc --description move-az
aws ec2 create-volume --snapshot-id snap-0123 --availability-zone us-east-1b --volume-type gp3Then attach the new volume.
Prevent โ Keep shared or portable data on EFS or S3, and pin stateful instances (and their ASG subnets) to the AZ of their volumes.
Q94 A database on gp2 is fast in the morning, then latency jumps and VolumeQueueLength climbs.
Advanced
VolumeQueueLength climbs.Likely causes โ gp2 gets baseline IOPS at 3 per GiB (minimum 100) and bursts to 3,000 IOPS from a credit bucket. Once BurstBalance reaches 0, the volume falls back to baseline. Another possibility is the instance's EBS bandwidth limit (EBSIOBalance% / EBSByteBalance% on smaller instances).
Diagnose โ
for m in BurstBalance VolumeQueueLength VolumeReadOps VolumeWriteOps; do
aws cloudwatch get-metric-statistics --namespace AWS/EBS --metric-name $m \
--dimensions Name=VolumeId,Value=vol-0abc --statistics Average --period 300 \
--start-time $(date -u -d '-6 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ) --output text | tail -3; doneFix โ
- Migrate online to gp3, which gives 3,000 IOPS and 125 MiB/s baseline independent of size:
aws ec2 modify-volume --volume-id vol-0abc --volume-type gp3 --iops 6000 --throughput 250 - If the instance is the bottleneck, move to an instance type with more EBS bandwidth
Prevent โ Use gp3 as the default volume type and alarm on queue length and latency (VolumeAverageReadLatency).
Q95 A volume restored from a snapshot is very slow for the first hour of a DR test.
Advanced
Likely causes โ Snapshot restores are lazy-loaded: each block is fetched from S3 the first time it is read, so first reads have high latency.
Diagnose โ
aws ec2 describe-fast-snapshot-restores --filters Name=snapshot-id,Values=snap-0abc
# on the instance: high await on first reads
iostat -x 5Fix โ
- Pre-warm by reading every block:
sudo fio --filename=/dev/nvme1n1 --rw=read --bs=1M --iodepth=32 --ioengine=libaio --direct=1 --name=init - For critical paths, turn on Fast Snapshot Restore (paid per AZ-hour):
aws ec2 enable-fast-snapshot-restores --availability-zones us-east-1a --source-snapshot-ids snap-0abc - Or use a provisioned initialization rate where supported
Prevent โ Count hydration time in your RTO, and test DR with real reads, not just "the instance is running".
Q96 Sharing an EBS snapshot with the DR account fails because it is encrypted with the default aws/ebs key.
Intermediate
aws/ebs key.Likely causes โ You cannot share snapshots encrypted with the AWS managed key, because its key policy cannot be changed to grant other accounts.
Diagnose โ
aws ec2 describe-snapshots --snapshot-ids snap-0abc --query 'Snapshots[].[Encrypted,KmsKeyId]'
aws kms describe-key --key-id <key-id> --query 'KeyMetadata.KeyManager' # AWS = managed keyFix โ
- Copy the snapshot and re-encrypt it with a customer managed key:
aws ec2 copy-snapshot --source-region us-east-1 --source-snapshot-id snap-0abc --encrypted --kms-key-id <cmk-arn> - Allow the DR account in the CMK key policy, then share:
aws ec2 modify-snapshot-attribute --snapshot-id snap-0new --attribute createVolumePermission --operation-type add --user-ids 222222222222 - In the DR account, copy it again with its own key
Prevent โ Set EBS default encryption to a CMK (aws ec2 modify-ebs-default-kms-key-id), or use AWS Backup cross-account copy.
Q97 mount -t efs hangs, then fails with mount.nfs4: Connection timed out.
Beginner
mount -t efs hangs, then fails with mount.nfs4: Connection timed out.Likely causes โ The mount target's SG does not allow NFS (TCP 2049) from the client, there is no mount target in the client's AZ, or DNS resolution of the file system name is off in the VPC.
Diagnose โ
aws efs describe-mount-targets --file-system-id fs-0abc --query 'MountTargets[].[AvailabilityZoneName,IpAddress,LifeCycleState]'
aws efs describe-mount-target-security-groups --mount-target-id fsmt-0abc
nc -zv fs-0abc.efs.us-east-1.amazonaws.com 2049Fix โ
- Allow TCP 2049 from the client SG on the mount target SG
- Create a mount target in every AZ where clients run
- Turn on
enableDnsSupportandenableDnsHostnameson the VPC
Prevent โ Create mount targets for every AZ in IaC, and use amazon-efs-utils with _netdev,tls in fstab.
Q98 mount.nfs4: access denied by server while mounting fs-0abc.efs....
Intermediate
mount.nfs4: access denied by server while mounting fs-0abc.efs....Likely causes โ An EFS file system policy requires IAM authorization or TLS, and the mount did not use -o tls,iam. Or the client role has no elasticfilesystem:ClientMount/ClientWrite. Or an access point's root directory or POSIX user does not match what is expected.
Diagnose โ
aws efs describe-file-system-policy --file-system-id fs-0abc
aws efs describe-access-points --file-system-id fs-0abcFix โ
- Mount with efs-utils:
sudo mount -t efs -o tls,iam,accesspoint=fsap-0abc fs-0abc:/ /mnt/efs - Grant the instance or task role
elasticfilesystem:ClientMountandClientWrite(plusClientRootAccessif needed)
Prevent โ Standardize on access points per app, with IAM auth and TLS required by policy.
Q99 An app on EFS slows to a crawl under load; PercentIOLimit sits at 100% or throughput flat-lines.
Advanced
PercentIOLimit sits at 100% or throughput flat-lines.Likely causes โ In Bursting mode, throughput depends on stored size, and BurstCreditBalance has run out. PercentIOLimit at 100% means the file system has hit the I/O operation limit for General Purpose performance mode. Lots of small-file metadata operations also have high per-operation latency on NFS.
Diagnose โ
aws efs describe-file-systems --file-system-id fs-0abc --query 'FileSystems[].[ThroughputMode,PerformanceMode,SizeInBytes.Value]'
# CloudWatch AWS/EFS: BurstCreditBalance, PermittedThroughput, MeteredIOBytes, PercentIOLimitFix โ
- Switch to Elastic throughput:
aws efs update-file-system --file-system-id fs-0abc --throughput-mode elastic - Spread I/O across more clients and threads, and avoid hot
lsloops over huge directories - Cache read-heavy content locally
Prevent โ Use Elastic throughput by default for spiky workloads, and keep databases off EFS.
Q100 put-bucket-notification-configuration fails: Unable to validate the following destination configurations.
Intermediate
put-bucket-notification-configuration fails: Unable to validate the following destination configurations.Likely causes โ S3 checks that it may publish to the destination. The Lambda has no resource policy allowing s3.amazonaws.com, or the SNS topic or SQS queue policy does not allow S3, or the destination's KMS key does not let S3 use it.
Diagnose โ
aws lambda get-policy --function-name thumbnailer
aws sqs get-queue-attributes --queue-url <url> --attribute-names Policy KmsMasterKeyIdFix โ
aws lambda add-permission --function-name thumbnailer --statement-id s3invoke \
--action lambda:InvokeFunction --principal s3.amazonaws.com \
--source-arn arn:aws:s3:::uploads --source-account 111111111111For SQS or SNS, add a policy statement for s3.amazonaws.com with an aws:SourceArn condition. With SSE, the key policy must allow S3 kms:GenerateDataKey and kms:Decrypt.
Prevent โ Create the permission and the notification together in IaC (with depends_on), or route events through EventBridge.
RDS, Aurora and DynamoDB
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q101 The app cannot connect to RDS: psql: error: connection to server at "mydb.abc.us-east-1.rds.amazonaws.com" (10.0.3.12), port 5432 failed: Connection timed out.
Beginner
psql: error: connection to server at "mydb.abc.us-east-1.rds.amazonaws.com" (10.0.3.12), port 5432 failed: Connection timed out.Likely causes โ A timeout means the packets are dropped. The DB SG does not allow 5432 from the app SG, a NACL blocks it, or the client is outside the VPC (for example, a laptop) while the DB is not publicly accessible (which is how it should be).
Diagnose โ
aws rds describe-db-instances --db-instance-identifier mydb \
--query 'DBInstances[].[Endpoint.Address,Endpoint.Port,PubliclyAccessible,VpcSecurityGroups,DBSubnetGroup.Subnets[].SubnetIdentifier]'
nc -zv mydb.abc.us-east-1.rds.amazonaws.com 5432
aws ec2 describe-security-groups --group-ids <db-sg> --query 'SecurityGroups[].IpPermissions'Fix โ
- Allow 5432 on the DB SG from the app SG
- From a laptop, use SSM port forwarding through a bastion:
aws ssm start-session --target i-0abc --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters host=mydb...,portNumber=5432,localPortNumber=5432
Prevent โ Keep databases in private subnets and grant access by SG reference only.
Q102 FATAL: password authentication failed for user "postgres" and nobody knows the master password.
Beginner
FATAL: password authentication failed for user "postgres" and nobody knows the master password.Likely causes โ The password is wrong or was rotated (Secrets Manager managed password), or the username is wrong. The master username is set at creation and is not always postgres.
Diagnose โ
aws rds describe-db-instances --db-instance-identifier mydb \
--query 'DBInstances[].[MasterUsername,MasterUserSecret.SecretArn]'
aws secretsmanager get-secret-value --secret-id <secret-arn> --query SecretString --output textFix โ
- If RDS manages the secret, read the current value from Secrets Manager
- Otherwise reset the password:
aws rds modify-db-instance --db-instance-identifier mydb --master-user-password '<new>' --apply-immediately - Update the apps, and restart connection pools
Prevent โ Use --manage-master-user-password so RDS stores and rotates the password in Secrets Manager, and give apps their own least-privilege DB users.
Q103 FATAL: no pg_hba.conf entry for host "10.0.1.25", user "app", database "orders", no encryption.
Intermediate
FATAL: no pg_hba.conf entry for host "10.0.1.25", user "app", database "orders", no encryption.Likely causes โ The parameter group sets rds.force_ssl=1 (the default for RDS PostgreSQL 15+), and the client connects without TLS. You cannot edit pg_hba.conf on RDS; it is controlled through parameters.
Diagnose โ
aws rds describe-db-parameters --db-parameter-group-name pg16-app \
--query "Parameters[?ParameterName=='rds.force_ssl']"Fix โ
- Connect with TLS:
psql "host=... dbname=orders user=app sslmode=verify-full sslrootcert=global-bundle.pem" - Download the CA bundle:
curl -O https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem - Set
sslmode=requireorverify-fullin the app's JDBC or driver URL
Prevent โ Require TLS everywhere, and ship the RDS CA bundle in your base images.
Q104 App logs show FATAL: remaining connection slots are reserved for non-replication superuser connections (or MySQL ERROR 1040 (HY000): Too many connections).
Intermediate
FATAL: remaining connection slots are reserved for non-replication superuser connections (or MySQL ERROR 1040 (HY000): Too many connections).Likely causes โ You have hit max_connections. Usually too many app replicas each open a large pool, or Lambda functions open a new connection per invocation, or connections leak.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name DatabaseConnections \
--dimensions Name=DBInstanceIdentifier,Value=mydb --statistics Maximum --period 60 \
--start-time $(date -u -d '-2 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
psql -c "select usename, application_name, state, count(*) from pg_stat_activity group by 1,2,3 order by 4 desc;"Fix โ
- Shrink the pool per pod: total = replicas ร pool size, which must stay under max_connections
- Put RDS Proxy (or PgBouncer) in front for Lambda and bursty clients
- Kill idle connections and set
idle_in_transaction_session_timeout
Prevent โ Budget connections per service, alarm at 80% of max, and use RDS Proxy for serverless callers.
Q105 RDS status shows storage-full and writes fail.
Intermediate
storage-full and writes fail.Likely causes โ FreeStorageSpace reached zero. Common reasons: growing tables, unvacuumed bloat, a large temp sort, binlogs or WAL kept by a stalled replication slot, or verbose logs.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name FreeStorageSpace \
--dimensions Name=DBInstanceIdentifier,Value=mydb --statistics Minimum --period 300 \
--start-time $(date -u -d '-1 day' +%FT%TZ) --end-time $(date -u +%FT%TZ)
psql -c "select slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) from pg_replication_slots;"Fix โ
- Add storage now:
aws rds modify-db-instance --db-instance-identifier mydb --allocated-storage 500 --apply-immediately - Drop stale replication slots, and vacuum or clean up data
- Turn on storage autoscaling:
--max-allocated-storage 1000
Prevent โ Alarm on FreeStorageSpace below 20%, turn on autoscaling, and alarm on OldestReplicationSlotLag / TransactionLogsDiskUsage.
Q106 A read replica's ReplicaLag keeps growing and reports show stale data.
Intermediate
ReplicaLag keeps growing and reports show stale data.Likely causes โ The replica is smaller than the primary, or IOPS-bound. Heavy write bursts or long-running queries on the replica cause conflicts (PostgreSQL max_standby_streaming_delay). MySQL replication may apply single-threaded.
Diagnose โ
aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name ReplicaLag \
--dimensions Name=DBInstanceIdentifier,Value=mydb-replica --statistics Maximum --period 60 \
--start-time $(date -u -d '-3 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws rds describe-db-instances --db-instance-identifier mydb-replica --query 'DBInstances[].[DBInstanceClass,StorageType,Iops]'Fix โ
- Size the replica the same as the primary, with the same storage performance
- For MySQL, turn on parallel apply (
replica_parallel_workers) - Move heavy analytics to a dedicated replica or to Aurora, where replicas share storage and lag is usually well under a second
Prevent โ Alarm on lag, and route reads that must not be stale to the primary.
Q107 After a Multi-AZ failover, some app servers keep failing with connection errors for 10+ minutes while others recover in a minute.
Advanced
Likely causes โ A failover flips the endpoint's DNS CNAME to the standby. Clients that cache DNS for a long time (JVM networkaddress.cache.ttl set to forever, or a misconfigured local resolver) or keep stale pooled connections keep hitting the old IP.
Diagnose โ
aws rds describe-events --source-identifier mydb --source-type db-instance --duration 120
dig +short mydb.abc.us-east-1.rds.amazonaws.com
# on the bad host
getent hosts mydb.abc.us-east-1.rds.amazonaws.comFix โ
- Set the JVM DNS TTL to a low value (
networkaddress.cache.ttl=5) - Turn on pool connection validation and max lifetime (for example, HikariCP
maxLifetime) - Restart the affected app instances to recover now
Prevent โ Use RDS Proxy (it keeps client connections during failover) or the AWS Advanced JDBC Wrapper, and test failover regularly with aws rds reboot-db-instance --force-failover.
Q108 Restoring a snapshot fails: InvalidParameterCombination: Cannot find version 11.22 for postgres.
Beginner
InvalidParameterCombination: Cannot find version 11.22 for postgres.Likely causes โ The engine version has reached end of standard support or is not offered in this Region any more, so you cannot create new instances on it without Extended Support or an upgrade.
Diagnose โ
aws rds describe-db-engine-versions --engine postgres --query 'DBEngineVersions[].EngineVersion' --output text
aws rds describe-db-snapshots --db-snapshot-identifier snap-1 --query 'DBSnapshots[].EngineVersion'Fix โ
- Restore with a supported version, specifying
--engine-versionif the restore path allows it - Or upgrade the snapshot first:
aws rds modify-db-snapshot --db-snapshot-identifier snap-1 --engine-version 12.22(RDS PostgreSQL supports upgrading DB snapshots), then upgrade the restored instance further
Prevent โ Track engine end-of-life dates, upgrade on a schedule, and run restore tests regularly.
Q109 You changed work_mem in the parameter group, but SHOW work_mem; still shows the old value.
Intermediate
work_mem in the parameter group, but SHOW work_mem; still shows the old value.Likely causes โ The instance uses a different parameter group, the parameter is static (it needs a reboot, status pending-reboot), or the session or role overrides it.
Diagnose โ
aws rds describe-db-instances --db-instance-identifier mydb \
--query 'DBInstances[].DBParameterGroups'
aws rds describe-db-parameters --db-parameter-group-name pg16-app \
--query "Parameters[?ParameterName=='work_mem'].[ParameterValue,ApplyType,IsModifiable]"
psql -c "select name, setting, source from pg_settings where name='work_mem';"Fix โ
- Attach the right custom group. The default group cannot be modified
- For static parameters, reboot during a window
- Remove role-level overrides (
ALTER ROLE app RESET work_mem)
Prevent โ Use one custom parameter group per engine and environment, managed in IaC, and check pending-reboot after every change.
Q110 RDS IAM authentication fails: FATAL: PAM authentication failed for user "app_iam".
Advanced
FATAL: PAM authentication failed for user "app_iam".Likely causes โ The token was generated for a different host, port, user or Region, or it is older than 15 minutes. The DB user is missing the rds_iam role (PostgreSQL) or AWSAuthenticationPlugin (MySQL). The IAM policy has no rds-db:connect on the right dbuser ARN (it uses the DbiResourceId, not the instance name). Or TLS is not used.
Diagnose โ
aws rds describe-db-instances --db-instance-identifier mydb --query 'DBInstances[].[DbiResourceId,IAMDatabaseAuthenticationEnabled]'
TOKEN=$(aws rds generate-db-auth-token --hostname mydb.abc.us-east-1.rds.amazonaws.com --port 5432 --username app_iam --region us-east-1)
psql "host=mydb.abc.us-east-1.rds.amazonaws.com user=app_iam dbname=orders sslmode=require password=$TOKEN"Fix โ
- Run
GRANT rds_iam TO app_iam; - Policy resource:
arn:aws:rds-db:us-east-1:111111111111:dbuser:db-ABCDEFGH123/app_iam - Generate the token right before you connect, and always use TLS
Prevent โ Wrap token generation in the connection factory, and keep the IAM auth rate limits in mind (use RDS Proxy at high connection rates).
Q111 InvalidParameterCombination: Cannot delete protected DB Instance, please disable deletion protection and try again.
Beginner
InvalidParameterCombination: Cannot delete protected DB Instance, please disable deletion protection and try again.Likely causes โ Deletion protection is on, which is the intended safeguard.
Diagnose โ
aws rds describe-db-instances --db-instance-identifier old-db --query 'DBInstances[].DeletionProtection'Fix โ
aws rds modify-db-instance --db-instance-identifier old-db --no-deletion-protection --apply-immediately
aws rds delete-db-instance --db-instance-identifier old-db --final-db-snapshot-identifier old-db-finalPrevent โ Keep deletion protection on in production. Require a final snapshot, and do the disable step through a change ticket, not by hand.
Q112 Writes fail on Aurora MySQL with ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement.
Intermediate
ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement.Likely causes โ The app is connected to a reader: through the reader endpoint, an instance endpoint that became a reader after failover, or a pooled connection that lived through a failover.
Diagnose โ
aws rds describe-db-clusters --db-cluster-identifier orders \
--query 'DBClusters[].[Endpoint,ReaderEndpoint,DBClusterMembers[].[DBInstanceIdentifier,IsClusterWriter]]'
mysql -h <host> -e "select @@aurora_server_id, @@innodb_read_only;"Fix โ
- Point write traffic at the cluster (writer) endpoint, never at an instance endpoint
- Recycle pools after failover. The AWS Advanced JDBC Wrapper handles this
- Retry the write after a reconnect
Prevent โ Use separate writer and reader data sources in the app, and run failover drills (aws rds failover-db-cluster).
Q113 RDS CPUUtilization is pinned at 100% and the API is timing out.
Advanced
CPUUtilization is pinned at 100% and the API is timing out.Likely causes โ One or a few bad queries: a missing index after a deploy, a plan regression from stale statistics, a runaway report, or lock contention that shows up as CPU spin.
Diagnose โ
aws pi get-resource-metrics --service-type RDS --identifier db-ABCDEFGH123 \
--metric-queries '[{"Metric":"db.load.avg","GroupBy":{"Group":"db.sql_tokenized","Limit":5}}]' \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ) --period-in-seconds 300
psql -c "select pid, now()-query_start dur, state, left(query,80) from pg_stat_activity where state<>'idle' order by dur desc limit 10;"Fix โ
- Kill the runaway query:
select pg_cancel_backend(<pid>); - Add the missing index (
CREATE INDEX CONCURRENTLY), and runANALYZEon the affected tables - Scale up only as a stopgap
Prevent โ Keep Performance Insights and pg_stat_statements on, review query plans in CI for hot paths, and alarm on DB load above the vCPU count.
Q114 An RDS major version upgrade fails, and the event says Database instance is in a state that cannot be upgraded: PreUpgrade checks failed.
Advanced
Database instance is in a state that cannot be upgraded: PreUpgrade checks failed.Likely causes โ Pre-checks found blockers: unsupported extensions or extension versions (PostGIS, pg_repack), reg* data types, open prepared transactions, logical replication slots, or for MySQL, objects incompatible with 8.0/8.4 (reserved words, old temporal types).
Diagnose โ
aws rds describe-events --source-identifier mydb --source-type db-instance --duration 60
aws rds describe-db-log-files --db-instance-identifier mydb --filename-contains upgrade
aws rds download-db-log-file-portion --db-instance-identifier mydb --log-file-name <precheck-log> --output text
aws rds describe-db-engine-versions --engine postgres --engine-version 15.8 --query 'DBEngineVersions[].ValidUpgradeTarget[].EngineVersion'Fix โ
- Upgrade the extensions (
ALTER EXTENSION postgis UPDATE;), drop replication slots, and commit or roll back prepared transactions - Retry with a matching custom parameter group for the target version
- For minimal downtime, use RDS Blue/Green Deployments
Prevent โ Rehearse upgrades on a restored snapshot, and use Blue/Green for major versions.
Q115 Creating a DB fails: InsufficientDBInstanceCapacity: Cannot create a db.r6g.4xlarge instance in us-east-1d.
Beginner
InsufficientDBInstanceCapacity: Cannot create a db.r6g.4xlarge instance in us-east-1d.Likely causes โ The instance class has no capacity in that AZ right now, or the class is not offered there at all.
Diagnose โ
aws rds describe-orderable-db-instance-options --engine postgres --db-instance-class db.r6g.4xlarge \
--query 'OrderableDBInstanceOptions[].AvailabilityZones[].Name' --output textFix โ
- Retry in another AZ, or make sure the subnet group has subnets in AZs that offer the class
- Pick a sibling class (
db.r7g,db.r6i)
Prevent โ Use DB subnet groups that cover at least three AZs, and avoid pinning --availability-zone unless you need to.
Q116 ProvisionedThroughputExceededException: The level of configured provisioned throughput for the table was exceeded.
Intermediate
ProvisionedThroughputExceededException: The level of configured provisioned throughput for the table was exceeded.Likely causes โ The table is in provisioned mode and traffic is above its RCU/WCU. Auto scaling reacts only after a few minutes, so sudden spikes throttle first. Burst capacity covers only short spikes.
Diagnose โ
aws dynamodb describe-table --table-name orders --query 'Table.[BillingModeSummary,ProvisionedThroughput]'
aws cloudwatch get-metric-statistics --namespace AWS/DynamoDB --metric-name WriteThrottleEvents \
--dimensions Name=TableName,Value=orders --statistics Sum --period 60 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws application-autoscaling describe-scalable-targets --service-namespace dynamodbFix โ
- For spiky or unknown traffic, switch to on-demand:
aws dynamodb update-table --table-name orders --billing-mode PAY_PER_REQUEST - Or raise the capacity and the auto scaling minimum before known peaks
- Make sure the SDK retries with backoff
Prevent โ Use on-demand by default, provisioned with auto scaling for steady, predictable load, and alarm on throttle events.
Q117 One DynamoDB table throttles even though consumed capacity is far below provisioned (or it is on-demand).
Advanced
Likely causes โ A hot partition. One partition key, such as status=PENDING, today's date or one big tenant, takes most of the traffic. Each partition is limited to about 3,000 RCU and 1,000 WCU per second, no matter how much the table has.
Diagnose โ
aws dynamodb describe-contributor-insights --table-name orders
aws dynamodb update-contributor-insights --table-name orders --contributor-insights-action ENABLE
# then view top partition keys in CloudWatch Contributor InsightsFix โ
- Redesign the key for higher cardinality, for example write-sharding the hot key:
PENDING#<0-9> - Cache hot reads with DAX or ElastiCache
- Spread time-series writes across shard suffixes
Prevent โ Model access patterns before you build the table, and keep Contributor Insights on for important tables.
Q118 ValidationException: One or more parameter values were invalid: Missing the key orderId in the item.
Beginner
ValidationException: One or more parameter values were invalid: Missing the key orderId in the item.Likely causes โ The PutItem request does not include the partition key (or sort key) attribute, or uses a different name or case (orderID vs orderId), or a different type (S vs N).
Diagnose โ
aws dynamodb describe-table --table-name orders --query 'Table.[KeySchema,AttributeDefinitions]'Fix โ Send every key attribute with the exact name and type:
aws dynamodb put-item --table-name orders \
--item '{"orderId":{"S":"o-1001"},"createdAt":{"N":"1731139200"},"total":{"N":"42.5"}}'Prevent โ Use a typed data layer (for example, the DynamoDB Document Client or ElectroDB) with a schema, and add contract tests.
Q119 Updates fail with ConditionalCheckFailedException: The conditional request failed. Is it a bug?
Intermediate
ConditionalCheckFailedException: The conditional request failed. Is it a bug?Likely causes โ Usually it is working as designed: the ConditionExpression (for example, an optimistic lock on version, or attribute_not_exists(pk)) was false because another writer changed the item first, or the item already exists.
Diagnose โ
aws dynamodb get-item --table-name orders --key '{"orderId":{"S":"o-1001"}}' --consistent-read
aws dynamodb update-item --table-name orders --key '{"orderId":{"S":"o-1001"}}' \
--update-expression 'SET #s=:s, version=version+:one' --condition-expression 'version=:v' \
--expression-attribute-names '{"#s":"status"}' \
--expression-attribute-values '{":s":{"S":"PAID"},":v":{"N":"3"},":one":{"N":"1"}}' \
--return-values-on-condition-check-failure ALL_OLDFix โ
- Treat it as a conflict: re-read, merge, and retry with the new version
- Use
ReturnValuesOnConditionCheckFailure=ALL_OLDto see the current item without a second read
Prevent โ Handle the exception explicitly in code, and count it as a business metric, not an error.
Q120 ValidationException: Item size has exceeded the maximum allowed size.
Beginner
ValidationException: Item size has exceeded the maximum allowed size.Likely causes โ A DynamoDB item, including attribute names, is limited to 400 KB. A common cause is lists that keep growing (events, comments) or embedded blobs.
Diagnose โ
aws dynamodb get-item --table-name sessions --key '{"id":{"S":"u-1"}}' --output json | wc -cFix โ
- Store large payloads in S3 and keep the S3 key in the item
- Split unbounded lists into separate items under the same partition key (for example,
pk=USER#1, sk=EVENT#<ts>) - Compress large attributes (gzip into a Binary attribute)
Prevent โ Never model unbounded collections inside one item, and keep attribute names short in hot tables.
Q121 TransactionCanceledException: Transaction cancelled, please refer cancellation reasons for specific reasons [None, ConditionalCheckFailed].
Advanced
TransactionCanceledException: Transaction cancelled, please refer cancellation reasons for specific reasons [None, ConditionalCheckFailed].Likely causes โ One item in TransactWriteItems failed, so the whole transaction rolled back. The reasons list matches the request order, so the second action's condition failed here. TransactionConflict in the list means a concurrent transaction touched the same item.
Diagnose โ
aws dynamodb transact-write-items --transact-items file://tx.json 2>&1 | tail
# inspect CancellationReasons[].Code / Item in the SDK exceptionFix โ
- Map each reason back to its action, and handle
ConditionalCheckFailedas a business conflict - Retry
TransactionConflictwith backoff - Use a
ClientRequestTokenfor idempotent retries
Prevent โ Keep transactions small (up to 100 items), avoid hot items inside transactions, and log cancellation reasons in a structured form.
Q122 A user updates a profile and immediately reloads, but the GSI query still returns the old value.
Intermediate
Likely causes โ Global secondary indexes are updated asynchronously and only support eventually consistent reads. ConsistentRead=true is rejected on a GSI.
Diagnose โ
aws dynamodb query --table-name users --index-name email-index \
--key-condition-expression 'email=:e' --expression-attribute-values '{":e":{"S":"[email protected]"}}'
aws dynamodb get-item --table-name users --key '{"userId":{"S":"u-1"}}' --consistent-readFix โ
- For read-after-write views, read from the base table by primary key with
--consistent-read - Or use an LSI (it supports strong consistency but must be created with the table)
- Or return the updated item to the client from the write response
Prevent โ Decide consistency needs per access pattern during design, and watch OnlineIndexPercentageProgress and GSI throttles.
Q123 A DynamoDB Query with a filter returns only 12 items, but you know there are hundreds.
Beginner
Query with a filter returns only 12 items, but you know there are hundreds.Likely causes โ Each Query or Scan page reads at most 1 MB before the FilterExpression is applied. The response has a LastEvaluatedKey, and the code does not paginate.
Diagnose โ
aws dynamodb query --table-name orders --key-condition-expression 'customerId=:c' \
--filter-expression '#s=:s' --expression-attribute-names '{"#s":"status"}' \
--expression-attribute-values '{":c":{"S":"c-9"},":s":{"S":"OPEN"}}' --no-paginate \
--query '[Count,ScannedCount,LastEvaluatedKey]'Fix โ
- Loop until
LastEvaluatedKeyis empty (the CLI paginates by default; SDKs have paginators) - If the filter discards most items, add a GSI keyed on that attribute so you query instead of filter
Prevent โ Always use paginators, and compare ScannedCount with Count in reviews; a big gap means the key design is wrong.
Q124 Writes to the base table throttle, but the table itself has plenty of capacity.
Advanced
Likely causes โ A GSI is under-provisioned or hot. GSI writes happen asynchronously, but when a GSI cannot keep up, DynamoDB throttles writes on the base table (back-pressure). This often follows adding a GSI with a low-cardinality key.
Diagnose โ
aws dynamodb describe-table --table-name orders \
--query 'Table.GlobalSecondaryIndexes[].[IndexName,ProvisionedThroughput,IndexStatus]'
# CloudWatch WriteThrottleEvents with dimensions TableName + GlobalSecondaryIndexNameFix โ
- Raise the GSI's WCU, or switch the table to on-demand
- Redesign the GSI partition key so it has high cardinality
- Project only the attributes you need, to lower write size
Prevent โ Give each GSI the same auto scaling as the base table, and alarm on GSI throttles separately.
Q125 TTL is enabled, but expired items are still in the table days later.
Intermediate
Likely causes โ The TTL attribute is not a Number in epoch seconds (a string or milliseconds is ignored), the attribute name does not match, or deletion is simply lagging. TTL deletes in the background, usually within a few days.
Diagnose โ
aws dynamodb describe-time-to-live --table-name sessions
aws dynamodb get-item --table-name sessions --key '{"id":{"S":"s-1"}}' --query 'Item.expiresAt'
date +%sFix โ
- Write
expiresAtas a Number with$(date -d '+1 day' +%s), not milliseconds - Filter out expired items in reads (
expiresAt > :now) until they are deleted
Prevent โ Use a unit test for TTL values, and use the TimeToLiveDeletedItemCount metric to confirm deletes are happening.
ECS, EKS, ECR and Lambda
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q126 docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/api:1.4 fails with no basic auth credentials (or denied: Your authorization token has expired. Reauthenticate and try again.).
Beginner
docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/api:1.4 fails with no basic auth credentials (or denied: Your authorization token has expired. Reauthenticate and try again.).Likely causes โ Docker never logged in to that registry and Region, or the ECR token (valid for 12 hours) expired. Another cause: the repository does not exist (name unknown: The repository with name 'api' does not exist in the registry).
Diagnose โ
aws sts get-caller-identity
aws ecr describe-repositories --repository-names api --region us-east-1
cat ~/.docker/config.json | grep -A2 dkr.ecrFix โ
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS --password-stdin 111111111111.dkr.ecr.us-east-1.amazonaws.com
aws ecr create-repository --repository-name api --image-scanning-configuration scanOnPush=truePrevent โ In CI, log in at the start of every job (for example, aws-actions/amazon-ecr-login), or use amazon-ecr-credential-helper.
Q127 Fargate tasks stop with CannotPullContainerError: pull image manifest has been retried 5 time(s): failed to resolve ref ... dial tcp 52.x.x.x:443: i/o timeout.
Intermediate
CannotPullContainerError: pull image manifest has been retried 5 time(s): failed to resolve ref ... dial tcp 52.x.x.x:443: i/o timeout.Likely causes โ The task runs in a private subnet with no route to ECR: no NAT gateway, and no VPC endpoints for ecr.api, ecr.dkr and S3 (gateway endpoint, because image layers come from S3). Or it is in a public subnet without assignPublicIp=ENABLED.
Diagnose โ
aws ecs describe-tasks --cluster prod --tasks <task-arn> --query 'tasks[].[stoppedReason,containers[].reason]'
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-0abc --query 'RouteTables[].Routes'
aws ec2 describe-vpc-endpoints --filters Name=vpc-id,Values=vpc-0abc --query 'VpcEndpoints[].ServiceName'Fix โ
- Add a NAT route, or add the endpoints:
com.amazonaws.us-east-1.ecr.api,ecr.dkr,logs(interface) ands3(gateway) - The endpoint SG must allow 443 from the task SG
Prevent โ Ship a standard "private VPC endpoints" module, and test task launches in every new subnet.
Q128 ResourceInitializationError: unable to pull secrets or registry auth: ... AccessDeniedException: User: arn:aws:sts::111111111111:assumed-role/ecsTaskExecutionRole/... is not authorized to perform: secretsmanager:GetSecretValue.
Intermediate
ResourceInitializationError: unable to pull secrets or registry auth: ... AccessDeniedException: User: arn:aws:sts::111111111111:assumed-role/ecsTaskExecutionRole/... is not authorized to perform: secretsmanager:GetSecretValue.Likely causes โ The task definition refers to a secret in secrets, but the execution role (not the task role) cannot read it, or cannot decrypt the KMS key behind it. Network reachability to Secrets Manager or SSM can also cause this error.
Diagnose โ
aws ecs describe-task-definition --task-definition api:42 \
--query 'taskDefinition.[executionRoleArn,containerDefinitions[].secrets]'
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111111111111:role/ecsTaskExecutionRole \
--action-names secretsmanager:GetSecretValue --resource-arns <secret-arn>Fix โ Add secretsmanager:GetSecretValue (or ssm:GetParameters) on the specific secret ARNs, plus kms:Decrypt on the CMK, to the execution role. If the tasks are in private subnets, add the secretsmanager endpoint.
Prevent โ Keep one execution role per service, scoped to its own secret paths, and remember: the execution role is for the agent, the task role is for your code.
Q129 A task stops with Essential container in task exited, exit code 137, and reason OutOfMemoryError: Container killed due to memory usage.
Beginner
Essential container in task exited, exit code 137, and reason OutOfMemoryError: Container killed due to memory usage.Likely causes โ The container went over its hard memory limit, so the kernel OOM killer sent SIGKILL (137 = 128 + 9). A JVM heap that is not sized to the container limit, or a memory leak, are the usual reasons.
Diagnose โ
aws ecs describe-tasks --cluster prod --tasks <task-arn> \
--query 'tasks[].containers[].[name,exitCode,reason]'
# Container Insights: MemoryUtilized vs MemoryReserved per task
aws logs tail /ecs/api --since 30mFix โ
- Raise the task or container memory
- Size runtimes to the container:
-XX:MaxRAMPercentage=75for Java,--max-old-space-sizefor Node.js - Fix the leak (take a heap dump before you hit the limit)
Prevent โ Turn on Container Insights, alarm on memory utilization above 85%, and load-test with production-like data.
Q130 The ECS service event says service api was unable to place a task because no container instance met all of its requirements. The closest matching container-instance ... has insufficient memory available.
Intermediate
service api was unable to place a task because no container instance met all of its requirements. The closest matching container-instance ... has insufficient memory available.Likely causes โ On the EC2 launch type, no container instance has enough free CPU, memory or ports (static host ports with bridge mode clash), or placement constraints such as distinctInstance rule them out. Capacity provider scaling may be off.
Diagnose โ
aws ecs describe-services --cluster prod --services api --query 'services[].events[:5]'
aws ecs list-container-instances --cluster prod
aws ecs describe-container-instances --cluster prod --container-instances <arn> \
--query 'containerInstances[].remainingResources[?name==`MEMORY` || name==`CPU`]'Fix โ
- Use a capacity provider with managed scaling, so the ASG grows when tasks are pending
- Use
awsvpcor dynamic host ports (hostPort 0) instead of fixed ports - Right-size task reservations, or move to Fargate
Prevent โ Use capacity providers with targetCapacity around 90%, and alarm on pending tasks.
Q131 An ECS deployment rolls back automatically, and the event says deployment failed: tasks failed to start from the circuit breaker.
Advanced
deployment failed: tasks failed to start from the circuit breaker.Likely causes โ The new tasks crash at startup (bad config or secret, failed migration), fail the container health check, or fail ALB health checks before healthCheckGracePeriodSeconds. The deployment circuit breaker detected repeated failures and rolled back.
Diagnose โ
aws ecs describe-services --cluster prod --services api \
--query 'services[].[deployments,events[:10]]'
aws ecs list-tasks --cluster prod --service-name api --desired-status STOPPED
aws ecs describe-tasks --cluster prod --tasks <stopped-task> --query 'tasks[].[stoppedReason,containers[].[exitCode,reason]]'
aws logs tail /ecs/api --since 20m --filter-pattern ERRORFix โ
- Fix the root cause from the stopped-task reasons and logs
- If the app is slow to start, raise
healthCheckGracePeriodSecondsand the container health checkstartPeriod - Redeploy
Prevent โ Keep the circuit breaker with rollback on, add CloudWatch alarm-based rollback, and smoke-test images in staging with the same task definition.
Q132 aws ecs execute-command fails: The execute command failed because execute command was not enabled when the task was run or the execute command agent isn't running.
Intermediate
aws ecs execute-command fails: The execute command failed because execute command was not enabled when the task was run or the execute command agent isn't running.Likely causes โ The task was started without enableExecuteCommand. Other causes: the task role has no ssmmessages:* permissions, the private subnet cannot reach ssmmessages, or the Session Manager plugin is not installed locally.
Diagnose โ
aws ecs describe-tasks --cluster prod --tasks <task-arn> \
--query 'tasks[].[enableExecuteCommand,containers[].managedAgents]'
# AWS's open-source checker:
bash <(curl -s https://raw.githubusercontent.com/aws-containers/amazon-ecs-exec-checker/main/check-ecs-exec.sh) prod <task-id>Fix โ
aws ecs update-service --cluster prod --service api --enable-execute-command --force-new-deployment(existing tasks must be replaced)- Give the task role
ssmmessages:CreateControlChannel,CreateDataChannel,OpenControlChannelandOpenDataChannel - Add the
ssmmessagesendpoint for private subnets
Prevent โ Enable exec in non-production by default, log sessions to CloudWatch or S3, and restrict it with IAM conditions in production.
Q133 kubectl get pods returns error: You must be logged in to the server (Unauthorized) on a new EKS cluster.
Beginner
kubectl get pods returns error: You must be logged in to the server (Unauthorized) on a new EKS cluster.Likely causes โ Your IAM principal is not mapped into the cluster. Only the cluster creator gets admin automatically (and only if bootstrap admin was on). Other causes: the kubeconfig uses a different profile or role than the one that has an access entry.
Diagnose โ
aws sts get-caller-identity
aws eks update-kubeconfig --name prod --region us-east-1
aws eks list-access-entries --cluster-name prod
aws eks describe-cluster --name prod --query 'cluster.accessConfig'Fix โ
aws eks create-access-entry --cluster-name prod --principal-arn arn:aws:iam::111111111111:role/platform-admin
aws eks associate-access-policy --cluster-name prod --principal-arn arn:aws:iam::111111111111:role/platform-admin \
--policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy --access-scope type=clusterPrevent โ Use authentication mode API with access entries managed in IaC, not the aws-auth ConfigMap.
Q134 New EKS worker nodes never join; kubectl get nodes does not list them, while the EC2 instances are running.
Intermediate
kubectl get nodes does not list them, while the EC2 instances are running.Likely causes โ The node IAM role has no access entry (type EC2_LINUX) or aws-auth mapping. Other causes: the node SG cannot reach the API endpoint (private endpoint, missing 443 rule), the nodes cannot reach ECR or STS (no NAT or endpoints), or the bootstrap or nodeadm config has the wrong cluster name or CA.
Diagnose โ
aws eks list-access-entries --cluster-name prod
aws eks describe-nodegroup --cluster-name prod --nodegroup-name ng-1 --query 'nodegroup.health'
# on the node via SSM:
sudo journalctl -u kubelet --no-pager | tail -50
sudo journalctl -u nodeadm-run --no-pager | tail -20 # AL2023Fix โ
- Run
aws eks create-access-entry --cluster-name prod --principal-arn <node-role-arn> --type EC2_LINUX - Allow 443 from the node SG to the cluster SG, and add NAT or endpoints (
ecr.api,ecr.dkr,s3,sts,ec2)
Prevent โ Use managed node groups or Karpenter, which create the access entries, and check node health issues in describe-nodegroup.
Q135 Pods stay Pending with 0/6 nodes are available: 6 Too many pods, but the nodes have plenty of CPU and memory.
Advanced
Pending with 0/6 nodes are available: 6 Too many pods, but the nodes have plenty of CPU and memory.Likely causes โ With the VPC CNI, every pod gets a VPC IP, and max pods per node is limited by ENIs ร IPs per ENI (for example, 29 on m5.large). Small instance types fill up quickly. The subnet may also be running out of IPs (failed to assign an IP address to container in aws-node logs).
Diagnose โ
kubectl get nodes -o custom-columns=NAME:.metadata.name,MAXPODS:.status.allocatable.pods
kubectl -n kube-system logs ds/aws-node -c aws-node | grep -i -E 'insufficient|failed to assign'
aws ec2 describe-subnets --subnet-ids subnet-0abc --query 'Subnets[].AvailableIpAddressCount'Fix โ
- Turn on prefix delegation:
kubectl set env ds/aws-node -n kube-system ENABLE_PREFIX_DELEGATION=true, and raise max pods (managed node groups and Karpenter calculate it) - Use larger instances
- If the subnet is out of IPs, add a secondary CIDR (for example 100.64.0.0/16) with custom networking
Prevent โ Plan pod IP capacity at design time (/19 or larger node subnets), and alarm on free IPs per subnet.
Q136 A pod's S3 calls fail with AccessDenied ... User: arn:aws:sts::111111111111:assumed-role/eks-node-role/i-0abc is not authorized. Why is it using the node role?
Advanced
AccessDenied ... User: arn:aws:sts::111111111111:assumed-role/eks-node-role/i-0abc is not authorized. Why is it using the node role?Likely causes โ The pod has no working IRSA or Pod Identity setup, so the SDK falls back to the node's instance profile through IMDS. Common reasons: the service account has no eks.amazonaws.com/role-arn annotation (IRSA), or no Pod Identity association exists, or the Pod Identity Agent add-on is missing, or the pod was created before the association and was never restarted. An old SDK that does not support the credential source does the same.
Diagnose โ
kubectl get sa app -n prod -o yaml | grep -A2 annotations
aws eks list-pod-identity-associations --cluster-name prod --namespace prod
kubectl exec -n prod deploy/app -- env | grep -E 'AWS_ROLE_ARN|AWS_WEB_IDENTITY|AWS_CONTAINER_CREDENTIALS_FULL_URI'
kubectl get ds -n kube-system eks-pod-identity-agentFix โ
- Pod Identity: install the add-on, then run
aws eks create-pod-identity-association --cluster-name prod --namespace prod --service-account app --role-arn <role>. The role trust policy allowspods.eks.amazonaws.comwithsts:AssumeRoleandsts:TagSession - Restart the pods so the credentials get injected
Prevent โ Block pod access to IMDS (set the hop limit to 1 on nodes) so a missing setup fails loudly instead of quietly using node permissions.
Q137 An Ingress never gets an ALB, and the AWS Load Balancer Controller logs Failed build model due to couldn't auto-discover subnets: unable to resolve at least one subnet.
Intermediate
Failed build model due to couldn't auto-discover subnets: unable to resolve at least one subnet.Likely causes โ The subnets do not have the discovery tags: kubernetes.io/role/elb=1 for public subnets (internet-facing) or kubernetes.io/role/internal-elb=1 for private ones. Another cause: fewer than two AZs qualify.
Diagnose โ
kubectl -n kube-system logs deploy/aws-load-balancer-controller | tail -30
kubectl describe ingress web -n prod
aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-0abc \
--query 'Subnets[].[SubnetId,AvailabilityZone,Tags[?starts_with(Key,`kubernetes.io/role`)]]'Fix โ
aws ec2 create-tags --resources subnet-0pub1 subnet-0pub2 --tags Key=kubernetes.io/role/elb,Value=1Or list the subnets explicitly with the annotation alb.ingress.kubernetes.io/subnets. Also check that the controller's IAM role has the current policy, because new features need new permissions.
Prevent โ Tag subnets in the VPC module, and pin the controller and its IAM policy version together.
Q138 An EKS cluster upgrade to the next minor version is blocked, or workloads break right after it.
Advanced
Likely causes โ Manifests or Helm charts still use removed APIs. Add-ons (VPC CNI, CoreDNS, kube-proxy, EBS CSI) are at versions that do not support the new Kubernetes version. Or nodes are more than the allowed skew behind the control plane.
Diagnose โ
aws eks list-insights --cluster-name prod --filter kubernetesVersions=1.33
aws eks describe-insight --cluster-name prod --id <insight-id>
aws eks describe-addon-versions --addon-name vpc-cni --kubernetes-version 1.33 \
--query 'addons[].addonVersions[].addonVersion' --output text | head
kubectl get --raw /metrics | grep apiserver_requested_deprecated_apisFix โ
- Migrate manifests (
kubectl-convert,pluto detect-helm) - Upgrade the add-ons to compatible versions before the control plane, then upgrade the control plane, then the nodes
- Update PDBs so node drains can finish
Prevent โ Upgrade one minor version at a time, every quarter, rehearsed on a staging cluster. Track EKS upgrade insights in CI.
Q139 A PVC stays Pending with waiting for a volume to be created, either by external provisioner "ebs.csi.aws.com" or manually created by system administrator.
Intermediate
Pending with waiting for a volume to be created, either by external provisioner "ebs.csi.aws.com" or manually created by system administrator.Likely causes โ The EBS CSI driver add-on is not installed, or its controller has no IAM permissions (no IRSA or Pod Identity role with AmazonEBSCSIDriverPolicy). Or the StorageClass uses WaitForFirstConsumer and no pod has been scheduled yet, which is normal.
Diagnose โ
kubectl describe pvc data-db-0 -n prod
aws eks describe-addon --cluster-name prod --addon-name aws-ebs-csi-driver --query 'addon.[status,serviceAccountRoleArn]'
kubectl -n kube-system logs deploy/ebs-csi-controller -c csi-provisioner | tail -20
kubectl get scFix โ
aws eks create-addon --cluster-name prod --addon-name aws-ebs-csi-driver \
--service-account-role-arn arn:aws:iam::111111111111:role/ebs-csi-roleIf the volumes are KMS-encrypted, add KMS permissions for that key to the role.
Prevent โ Install CSI drivers as managed add-ons with their roles in IaC, and set a default gp3 StorageClass.
Q140 A deployment fails with ErrImagePull ... manifest unknown (or ECS CannotPullContainerError: ... not found) for an image that used to work.
Beginner
ErrImagePull ... manifest unknown (or ECS CannotPullContainerError: ... not found) for an image that used to work.Likely causes โ The tag does not exist in that repository or Region. A typo, a pipeline that never pushed, or an ECR lifecycle policy that expired old tags.
Diagnose โ
aws ecr describe-images --repository-name api --image-ids imageTag=1.4.2
aws ecr get-lifecycle-policy --repository-name api
aws ecr describe-images --repository-name api --query 'sort_by(imageDetails,&imagePushedAt)[-5:].imageTags'Fix โ
- Push the missing tag again, or deploy an existing digest
- Change the lifecycle policy so it keeps images that are still deployed (for example, keep the last 50, and expire only untagged images after 14 days)
Prevent โ Deploy by immutable digest, turn on tag immutability, and make lifecycle rules generous enough for rollbacks.
Q141 A container starts and immediately exits with exec /usr/local/bin/app: exec format error on the new Graviton nodes.
Intermediate
exec /usr/local/bin/app: exec format error on the new Graviton nodes.Likely causes โ The image was built only for linux/amd64 and is running on an arm64 (Graviton) node, or the other way round.
Diagnose โ
docker buildx imagetools inspect 111111111111.dkr.ecr.us-east-1.amazonaws.com/api:1.4
kubectl get nodes -L kubernetes.io/archFix โ
docker buildx build --platform linux/amd64,linux/arm64 \
-t 111111111111.dkr.ecr.us-east-1.amazonaws.com/api:1.4 --push .For a quick fix, pin the workload with nodeSelector: kubernetes.io/arch: amd64, or set ECS runtimePlatform.cpuArchitecture.
Prevent โ Build multi-arch images in CI, and run arm64 smoke tests before you add Graviton capacity.
Q142 Lambda logs end with Task timed out after 3.00 seconds.
Beginner
Task timed out after 3.00 seconds.Likely causes โ The default timeout is 3 seconds. The function is slow, or it hangs on a network call: a VPC function with no route to the internet or endpoint, a DB connection without a timeout, or a downstream that is slow.
Diagnose โ
aws lambda get-function-configuration --function-name orders-api --query '[Timeout,MemorySize,VpcConfig]'
aws logs tail /aws/lambda/orders-api --since 15m
# enable X-Ray active tracing to see which segment takes the timeFix โ
- Set client timeouts on every network call below the function timeout
- Raise the timeout to a realistic value:
aws lambda update-function-configuration --function-name orders-api --timeout 15 - Raising memory also gives more CPU, which speeds up CPU-bound code
Prevent โ Alarm on the Duration p99 against the timeout, and turn on X-Ray tracing.
Q143 A Lambda function was moved into a VPC, and now every AWS SDK call hangs until timeout.
Intermediate
Likely causes โ Lambda ENIs in a VPC never get public IPs, even in public subnets. Without a NAT gateway or VPC endpoints, the function cannot reach AWS APIs or the internet.
Diagnose โ
aws lambda get-function-configuration --function-name worker --query 'VpcConfig'
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-0priv --query 'RouteTables[].Routes'Fix โ
- Put the function in private subnets with a route to a NAT gateway
- Or add interface or gateway endpoints for the services it calls (S3, DynamoDB gateway endpoints are free)
- Allow outbound 443 in the function's SG
Prevent โ Only attach Lambda to a VPC when it needs private resources, and always pair that with endpoints or NAT.
Q144 Runtime.ImportModuleError: Unable to import module 'app': No module named 'requests'.
Beginner
Runtime.ImportModuleError: Unable to import module 'app': No module named 'requests'.Likely causes โ Third-party dependencies were not packaged with the function code (the zip contains only app.py). Other causes: they were built for the wrong platform (native wheels built on macOS), or the handler path is wrong.
Diagnose โ
aws lambda get-function-configuration --function-name api --query '[Handler,Runtime,Layers]'
unzip -l function.zip | headFix โ
pip install -r requirements.txt -t package/ --platform manylinux2014_x86_64 --only-binary=:all:
cp app.py package/ && (cd package && zip -r ../function.zip .)
aws lambda update-function-code --function-name api --zip-file fileb://function.zipOr move shared dependencies into a layer, or ship the function as a container image.
Prevent โ Build packages in CI with SAM or a container matching the Lambda runtime, never from a laptop.
Q145 Callers get TooManyRequestsException: Rate Exceeded from Lambda and the Throttles metric spikes.
Intermediate
TooManyRequestsException: Rate Exceeded from Lambda and the Throttles metric spikes.Likely causes โ You hit concurrency limits: the account limit in the Region (1,000 by default), the function's reserved concurrency, or another function used up the shared pool.
Diagnose โ
aws lambda get-account-settings --query 'AccountLimit.[ConcurrentExecutions,UnreservedConcurrentExecutions]'
aws lambda get-function-concurrency --function-name orders-api
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name ConcurrentExecutions \
--statistics Maximum --period 60 --start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)Fix โ
- Request an account concurrency increase through Service Quotas
- Give critical functions reserved concurrency, and cap noisy ones
- Put SQS in front of bursty async producers
Prevent โ Alarm on ConcurrentExecutions near the limit, and on Throttles above 0 for synchronous APIs.
Q146 A Java Lambda behind API Gateway has p99 latency of 6โ8 seconds on the first request after idle periods.
Advanced
Likely causes โ Cold starts: JVM startup, heavy framework init (Spring) and large packages. VPC attachment adds little now (Hyperplane ENIs), so init code is usually the cause.
Diagnose โ
aws logs filter-log-events --log-group-name /aws/lambda/orders-api \
--filter-pattern '"Init Duration"' --max-items 5 --query 'events[].message'Fix โ
- Turn on SnapStart (Java, Python, .NET):
aws lambda update-function-configuration --function-name orders-api --snap-start ApplyOn=PublishedVersions, then publish a version and point the alias at it - Or use provisioned concurrency on an alias for predictable traffic
- Trim dependencies, initialize lazily, and raise memory (more CPU during init)
Prevent โ Track Init Duration as an SLO input, and choose lighter runtimes or frameworks for latency-critical paths.
Q147 Deploying fails: InvalidParameterValueException: Unzipped size must be smaller than 262144000 bytes.
Beginner
InvalidParameterValueException: Unzipped size must be smaller than 262144000 bytes.Likely causes โ The function code plus all layers is larger than 250 MB unzipped. Large ML libraries (numpy, pandas, torch) or bundled test files and caches usually cause it.
Diagnose โ
unzip -l function.zip | tail -1
aws lambda get-function --function-name ml-infer --query 'Configuration.Layers[].CodeSize'
du -sh package/* | sort -h | tailFix โ
- Package the function as a container image (up to 10 GB)
- Or remove tests,
__pycache__and docs from the package, and use AWS-provided layers (for example AWS SDK for pandas)
Prevent โ Use container images for heavy dependencies, and fail CI builds when package size grows past a set budget.
Q148 An SQS-triggered Lambda processes the same messages again and again, and some end up in the DLQ even though the code succeeded.
Intermediate
Likely causes โ The queue's visibility timeout is shorter than the function timeout, so messages become visible again while they are still being processed. Or one failing record makes the whole batch retry, because partial batch responses are not enabled.
Diagnose โ
aws sqs get-queue-attributes --queue-url <url> --attribute-names VisibilityTimeout RedrivePolicy
aws lambda get-function-configuration --function-name consumer --query Timeout
aws lambda list-event-source-mappings --function-name consumer --query 'EventSourceMappings[].[BatchSize,FunctionResponseTypes]'Fix โ
- Set the visibility timeout to at least 6ร the function timeout (AWS guidance)
- Turn on
ReportBatchItemFailuresand return only the failed message IDs:aws lambda update-event-source-mapping --uuid <id> --function-response-types ReportBatchItemFailures - Make handlers idempotent
Prevent โ Use a standard SQS-Lambda module with these defaults, and alarm on DLQ depth above 0.
Q149 A Lambda dies with Runtime exited with error: signal: killed and Runtime.ExitError, and no stack trace.
Intermediate
Runtime exited with error: signal: killed and Runtime.ExitError, and no stack trace.Likely causes โ The function ran out of memory. The REPORT line shows Max Memory Used equal to Memory Size. Large files loaded into memory, or a leak across warm invocations from global caches, are common reasons.
Diagnose โ
aws logs filter-log-events --log-group-name /aws/lambda/etl \
--filter-pattern 'REPORT' --max-items 5 --query 'events[].message'Fix โ
- Raise
MemorySize. Use Lambda Power Tuning to find the cheapest setting that works - Stream large objects instead of loading them whole, and use
/tmp(configurable up to 10 GB) for scratch space - Clear global caches between invocations
Prevent โ Alarm when Max Memory Used goes above 80% of the configured memory (through Lambda Insights).
Q150 An S3-triggered Lambda bill exploded, and you get a notification that Lambda stopped a recursive invocation loop.
Advanced
Lambda stopped a recursive invocation loop.Likely causes โ The function writes its output back into the same bucket and prefix that triggers it, so every write triggers the function again. Lambda recursive loop detection (for SQS, SNS, S3 and Lambda) stops it after about 16 iterations, but only for supported patterns.
Diagnose โ
aws s3api get-bucket-notification-configuration --bucket images
aws lambda get-function-recursion-config --function-name thumbnailer
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name RecursiveInvocationsDropped \
--dimensions Name=FunctionName,Value=thumbnailer --statistics Sum --period 300 \
--start-time $(date -u -d '-1 day' +%FT%TZ) --end-time $(date -u +%FT%TZ)Fix โ
- Set reserved concurrency to 0 right away to stop it:
aws lambda put-function-concurrency --function-name thumbnailer --reserved-concurrent-executions 0 - Write output to a different bucket, or scope the trigger to the
uploads/prefix and write tothumbs/
Prevent โ Keep recursion detection set to Terminate, use prefix or suffix filters on triggers, and set billing alarms on Lambda spend.
Route 53, CloudFront, API Gateway and Messaging
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q151 You created a public hosted zone and records for example.com, but dig example.com returns NXDOMAIN or old records.
Beginner
example.com, but dig example.com returns NXDOMAIN or old records.Likely causes โ The registrar still points to the old name servers, not to the four NS records of the new hosted zone. Another cause: two hosted zones exist for the same name and you edited the one that is not delegated.
Diagnose โ
aws route53 list-hosted-zones-by-name --dns-name example.com
aws route53 get-hosted-zone --id Z0123ABC --query 'DelegationSet.NameServers'
dig NS example.com +short
dig @a.gtld-servers.net NS example.com +norecurse # what the parent zone delegates toFix โ
- Update the NS at the registrar to match the zone's delegation set. For Route 53 Domains, run
aws route53domains update-domain-nameservers - Delete the duplicate zone
Prevent โ Use one hosted zone per domain in IaC, with an output that checks delegation, and lower NS TTLs before migrations.
Q152 InvalidChangeBatch: RRSet of type CNAME with DNS name example.com. is not permitted at apex in zone example.com.
Beginner
InvalidChangeBatch: RRSet of type CNAME with DNS name example.com. is not permitted at apex in zone example.com.Likely causes โ DNS does not allow a CNAME at the zone apex, because it would clash with the SOA and NS records there.
Diagnose โ
aws route53 list-resource-record-sets --hosted-zone-id Z0123ABC --query "ResourceRecordSets[?Name=='example.com.']"Fix โ Use a Route 53 alias A/AAAA record to the ALB, CloudFront or S3 target:
aws route53 change-resource-record-sets --hosted-zone-id Z0123ABC --change-batch '{
"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"example.com","Type":"A",
"AliasTarget":{"HostedZoneId":"Z35SXDOTRQ7X7K","DNSName":"dualstack.web-123.us-east-1.elb.amazonaws.com","EvaluateTargetHealth":true}}}]}'The alias HostedZoneId is the load balancer's canonical zone ID, not your zone's ID.
Prevent โ Use alias records for AWS targets everywhere. They are free to query and follow IP changes automatically.
Q153 The primary Region is down, but Route 53 failover records still send traffic to it.
Intermediate
Likely causes โ The primary record has no health check associated, or EvaluateTargetHealth is false on the alias. The health check tests something that is still up (for example, the ALB answers / even though the app is broken). Or clients cache DNS beyond the TTL.
Diagnose โ
aws route53 list-resource-record-sets --hosted-zone-id Z0123ABC \
--query "ResourceRecordSets[?Failover!=null].[Name,Failover,HealthCheckId,AliasTarget.EvaluateTargetHealth]"
aws route53 get-health-check-status --health-check-id <id>Fix โ
- Attach a health check that tests a deep
/healthzendpoint (checking the app and its dependencies) to the PRIMARY record - Set
EvaluateTargetHealth: trueon alias records - Use a 60s TTL
Prevent โ Run regular game days that fail the primary, and consider Route 53 ARC routing controls for manual, deterministic failover.
Q154 A Route 53 health check reports Failure: Connection timed out for an endpoint that works fine from your laptop.
Intermediate
Failure: Connection timed out for an endpoint that works fine from your laptop.Likely causes โ The SG, NACL or WAF does not allow the Route 53 health checker IP ranges. Other causes: the check uses HTTP while only HTTPS is open, or the host header or SNI is wrong.
Diagnose โ
aws route53 get-health-check --health-check-id <id> --query 'HealthCheck.HealthCheckConfig'
aws route53 get-health-check-last-failure-reason --health-check-id <id>
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[]|select(.service=="ROUTE53_HEALTHCHECKS").ip_prefix' | headFix โ
- Allow the
ROUTE53_HEALTHCHECKSranges (or the managed prefix listcom.amazonaws.route53-healthcheckswhere available) on the port - Set
FullyQualifiedDomainNameandEnableSNIfor HTTPS checks
Prevent โ For private resources, use CloudWatch alarm-based (calculated) health checks, because Route 53 checkers cannot reach private IPs.
Q155 You changed an A record an hour ago, but some users still reach the old server, and a newly created name returned NXDOMAIN for a while.
Advanced
NXDOMAIN for a while.Likely causes โ Resolvers cache the old answer for the record's TTL (it was 86400). For the new name, the earlier NXDOMAIN was negatively cached for the SOA minimum TTL (default 900s in Route 53, but it can be set higher). Some clients and JVMs cache longer still.
Diagnose โ
dig app.example.com +noall +answer # remaining TTL from your resolver
dig @ns-123.awsdns-45.com app.example.com # authoritative answer
aws route53 list-resource-record-sets --hosted-zone-id Z0123ABC --query "ResourceRecordSets[?Type=='SOA']"Fix โ
- Wait it out, or keep the old server forwarding or redirecting until the TTL passes
- Flush local caches (
resolvectl flush-caches)
Prevent โ Lower TTLs to 60s at least one old-TTL period before a migration, avoid querying names before you create them, and keep the SOA negative TTL reasonable.
Q156 CloudFront returns 403 AccessDenied (S3 XML) for every object after you switched the S3 origin to Origin Access Control.
Intermediate
403 AccessDenied (S3 XML) for every object after you switched the S3 origin to Origin Access Control.Likely causes โ The bucket policy does not allow the cloudfront.amazonaws.com service principal with AWS:SourceArn set to this distribution. Other causes: objects are SSE-KMS and the key policy does not allow CloudFront, the request has no default root object, or the key is missing (S3 returns 403 instead of 404 without s3:ListBucket).
Diagnose โ
aws cloudfront get-distribution-config --id E123ABC --query 'DistributionConfig.[DefaultRootObject,Origins.Items[].[DomainName,OriginAccessControlId]]'
aws s3api get-bucket-policy --bucket site-assets --output text
aws s3api head-object --bucket site-assets --key index.htmlFix โ
{"Effect":"Allow","Principal":{"Service":"cloudfront.amazonaws.com"},
"Action":"s3:GetObject","Resource":"arn:aws:s3:::site-assets/*",
"Condition":{"StringEquals":{"AWS:SourceArn":"arn:aws:cloudfront::111111111111:distribution/E123ABC"}}}Add a kms:Decrypt statement for CloudFront to the key policy if the objects use SSE-KMS, and set DefaultRootObject to index.html.
Prevent โ Create the OAC, the bucket policy and the distribution together in one IaC module.
Q157 CloudFront shows 502 ERROR. The request could not be satisfied. CloudFront wasn't able to connect to the origin.
Intermediate
502 ERROR. The request could not be satisfied. CloudFront wasn't able to connect to the origin.Likely causes โ The CloudFront โ origin TLS handshake fails: the origin certificate does not match the origin domain name, it is self-signed or expired, or the chain is incomplete. Or the origin protocol policy is wrong (HTTPS-only to an origin that only speaks HTTP), or the SG blocks CloudFront.
Diagnose โ
aws cloudfront get-distribution-config --id E123ABC \
--query 'DistributionConfig.Origins.Items[].[DomainName,CustomOriginConfig]'
openssl s_client -connect origin.example.com:443 -servername origin.example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -datesFix โ
- Use an origin domain covered by a valid public certificate (for example, an ACM certificate on the ALB for
origin.example.com), and forward the matching Host or SNI - Match the origin protocol policy and ports to what the origin serves
- Allow the
com.amazonaws.global.cloudfront.origin-facingprefix list on the ALB SG
Prevent โ Monitor origin certificate expiry, and use CloudFront VPC origins or origin-facing prefix lists for ALB origins.
Q158 After deploying a new frontend build, users still see the old JavaScript for hours.
Beginner
Likely causes โ CloudFront (and browsers) cache the objects for the TTL set by the cache policy or by Cache-Control headers. Files with the same name, such as app.js and index.html, are not refetched.
Diagnose โ
curl -sI https://www.example.com/app.js | grep -iE 'x-cache|age|cache-control|etag'
aws cloudfront list-invalidations --distribution-id E123ABC --max-items 3Fix โ
aws cloudfront create-invalidation --distribution-id E123ABC --paths "/index.html" "/app.js"Prevent โ Use content-hashed asset names (app.3f9c2.js) with long TTLs and immutable. Give index.html Cache-Control: no-cache (or a short TTL), and invalidate only index.html on deploy.
Q159 When editing a CloudFront distribution, your ACM certificate does not appear in the dropdown.
Beginner
Likely causes โ CloudFront only uses ACM certificates from us-east-1 (N. Virginia). Other causes: the certificate is not yet ISSUED, or it does not cover the alternate domain name you added.
Diagnose โ
aws acm list-certificates --region us-east-1 --query 'CertificateSummaryList[].[DomainName,Status]'
aws acm describe-certificate --region us-east-1 --certificate-arn <arn> --query 'Certificate.SubjectAlternativeNames'Fix โ Request the certificate in us-east-1 with every CNAME (or a wildcard), validate it by DNS, then attach it.
Prevent โ In Terraform, use a provider alias for us-east-1 just for CloudFront certificates.
Q160 CloudFront cache hit ratio is under 20% and origin load is high, even for static content.
Advanced
Likely causes โ The cache key includes high-cardinality values: all query strings (tracking parameters like utm_*), all cookies, or headers like User-Agent or Authorization. Legacy "forward all" settings split the cache. Short TTLs or Cache-Control: no-store from the origin also prevent caching.
Diagnose โ
aws cloudfront get-distribution-config --id E123ABC \
--query 'DistributionConfig.DefaultCacheBehavior.[CachePolicyId,OriginRequestPolicyId,ForwardedValues]'
aws cloudfront get-cache-policy --id <policy-id>
# CloudFront standard logs / real-time logs: x-edge-result-type Miss vs Hit, by URIFix โ
- Use a cache policy with a minimal key (for example,
CachingOptimizedfor static paths) - Forward the values the origin needs through an origin request policy, which does not affect the cache key
- Normalize or strip query strings, and set proper
Cache-Controlat the origin
Prevent โ Use separate behaviors for /static/* and /api/*, and alarm on CacheHitRate (with additional metrics turned on).
Q161 A React SPA on S3 + CloudFront: / works, but refreshing /dashboard/settings returns 403 AccessDenied.
Intermediate
/ works, but refreshing /dashboard/settings returns 403 AccessDenied.Likely causes โ There is no S3 object at dashboard/settings. With OAC and no ListBucket, S3 returns 403 for missing keys, and the client-side router never loads.
Diagnose โ
curl -sI https://app.example.com/dashboard/settings | head -3
aws cloudfront get-distribution-config --id E123ABC --query 'DistributionConfig.CustomErrorResponses'Fix โ
- Add custom error responses that map 403 and 404 to
/index.htmlwith response code 200 - Or (cleaner) use a CloudFront Function on viewer-request that rewrites paths with no file extension to
/index.html, so real API 404s are not masked
Prevent โ Make it part of your SPA hosting module, and keep APIs on a separate behavior or origin.
Q162 Adding an alternate domain name fails: CNAMEAlreadyExists: One or more of the CNAMEs you provided are already associated with a different resource.
Intermediate
CNAMEAlreadyExists: One or more of the CNAMEs you provided are already associated with a different resource.Likely causes โ Another distribution, possibly in another account (an old environment or a vendor), already has that alternate domain name.
Diagnose โ
aws cloudfront list-conflicting-aliases --distribution-id E123ABC --alias www.example.com
aws cloudfront list-distributions --query "DistributionList.Items[?contains(Aliases.Items,'www.example.com')].Id"Fix โ
- Same account: remove the alias from the old distribution, then add it to the new one
- Different account: prove ownership with a TXT record (
_www.example.compointing to the new distribution's domain) and runaws cloudfront associate-alias --target-distribution-id E123ABC --alias www.example.com
Prevent โ Track aliases in IaC, and remove them when you decommission distributions.
Q163 Calling your API returns {"message":"Missing Authentication Token"}.
Beginner
{"message":"Missing Authentication Token"}.Likely causes โ Despite the name, this almost always means the route does not exist: a wrong path or method, a missing stage in the URL (/prod/orders), or the API was not deployed after the change (REST APIs need a deployment).
Diagnose โ
aws apigateway get-resources --rest-api-id abc123 --query 'items[].[path,resourceMethods]'
aws apigateway get-stages --rest-api-id abc123 --query 'item[].[stageName,deploymentId,lastUpdatedDate]'
curl -i https://abc123.execute-api.us-east-1.amazonaws.com/prod/ordersFix โ
- Call the correct stage, path and method
- Redeploy:
aws apigateway create-deployment --rest-api-id abc123 --stage-name prod
Prevent โ Deploy APIs through IaC, which creates deployments automatically, and add a smoke test per route after each deploy.
Q164 API Gateway returns 502 with {"message": "Internal server error"}, and the execution log shows Execution failed due to configuration error: Malformed Lambda proxy response.
Intermediate
502 with {"message": "Internal server error"}, and the execution log shows Execution failed due to configuration error: Malformed Lambda proxy response.Likely causes โ With Lambda proxy integration, the function must return {"statusCode": int, "headers": {...}, "body": "<string>"}. A dict or object as body, a missing statusCode, or an unhandled exception all produce this error.
Diagnose โ
aws apigateway update-stage --rest-api-id abc123 --stage-name prod \
--patch-operations op=replace,path=/*/*/logging/loglevel,value=INFO
aws logs tail API-Gateway-Execution-Logs_abc123/prod --since 10m
aws lambda invoke --function-name orders-api --payload fileb://event.json out.json && cat out.jsonFix โ Return the exact proxy shape and serialize the body:
return {"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": json.dumps(result)}Catch exceptions and return a 500 response yourself.
Prevent โ Use a framework (Powertools for AWS Lambda event handler) that builds responses, and add contract tests with a sample API Gateway event.
Q165 API Gateway returns 504 with {"message": "Endpoint request timed out"} on long requests.
Intermediate
504 with {"message": "Endpoint request timed out"} on long requests.Likely causes โ The integration took longer than the integration timeout. The default is 29 seconds; for Regional and private REST APIs it can be raised with a quota increase, which may lower throttle limits.
Diagnose โ
aws apigateway get-integration --rest-api-id abc123 --resource-id res1 --http-method POST --query timeoutInMillis
aws cloudwatch get-metric-statistics --namespace AWS/ApiGateway --metric-name IntegrationLatency \
--dimensions Name=ApiName,Value=orders --extended-statistics p99 --period 60 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)Fix โ
- Make the long work asynchronous: the API puts a job on SQS or Step Functions and returns
202with a job ID, and the client polls or gets a callback - Optimize the backend call
Prevent โ Design APIs so every synchronous call finishes in a few seconds.
Q166 The browser shows a CORS error only when the API returns 401 or 4XX, while successful calls work.
Advanced
Likely causes โ The Lambda adds Access-Control-Allow-Origin to its own responses, but errors produced by API Gateway itself (authorizer denies, throttling, missing routes) are gateway responses without CORS headers. The browser then hides the real 401 behind a CORS error.
Diagnose โ
curl -i -X GET https://abc123.execute-api.us-east-1.amazonaws.com/prod/me -H 'Origin: https://app.example.com'
aws apigateway get-gateway-responses --rest-api-id abc123 --query 'items[].[responseType,responseParameters]'Fix โ
aws apigateway put-gateway-response --rest-api-id abc123 --response-type DEFAULT_4XX \
--response-parameters '{"gatewayresponse.header.Access-Control-Allow-Origin":"'"'"'https://app.example.com'"'"'"}'
aws apigateway create-deployment --rest-api-id abc123 --stage-name prodDo the same for DEFAULT_5XX. On HTTP APIs, use the built-in CORS configuration, which covers this.
Prevent โ Define CORS once at the API level in IaC, and test error paths from a browser origin.
Q167 A REST API returns {"message":"Forbidden"} (403) to a client that sends the right path.
Intermediate
{"message":"Forbidden"} (403) to a client that sends the right path.Likely causes โ The method requires an API key and the x-api-key header is missing, or the key is not in a usage plan tied to this stage. For a private API, the call does not come through the allowed VPC endpoint, or the resource policy denies it. A WAF rule may also block it.
Diagnose โ
aws apigateway get-method --rest-api-id abc123 --resource-id res1 --http-method GET --query apiKeyRequired
aws apigateway get-usage-plans --query 'items[].[name,apiStages]'
aws apigateway get-rest-api --rest-api-id abc123 --query '[endpointConfiguration,policy]'Fix โ
- Send
x-api-key, and link the key to a usage plan with this stage:aws apigateway create-usage-plan-key --usage-plan-id up1 --key-id k1 --key-type API_KEY - For private APIs, call through the execute-api VPC endpoint and allow
aws:SourceVpcein the resource policy
Prevent โ Do not use API keys as authentication (use IAM, Cognito or JWT authorizers), and turn on access logging with $context.error.responseType.
Q168 Clients get 429 Too Many Requests with {"message":"Too Many Requests"} from API Gateway at modest traffic.
Beginner
429 Too Many Requests with {"message":"Too Many Requests"} from API Gateway at modest traffic.Likely causes โ Throttling at one of the levels: the usage plan or API key limit, a stage or method throttle set low, or the account-level Regional limit (10,000 rps steady with a 5,000 burst by default) shared by all APIs.
Diagnose โ
aws apigateway get-stage --rest-api-id abc123 --stage-name prod --query methodSettings
aws apigateway get-usage-plan --usage-plan-id up1 --query '[throttle,quota]'
aws apigateway get-account --query throttleSettingsFix โ
- Raise the stage, method or usage plan throttles to match the expected load
- Request an account limit increase if needed
- Make clients retry with backoff and jitter
Prevent โ Load-test with real limits, alarm on the 4XXError rate, and document per-client quotas.
Q169 Messages keep landing in the SQS dead-letter queue even though consumers look healthy.
Intermediate
Likely causes โ Each message was received maxReceiveCount times without being deleted. Reasons: consumers crash or time out on certain payloads ("poison messages"), the visibility timeout is too short, or the code never calls DeleteMessage.
Diagnose โ
aws sqs get-queue-attributes --queue-url <main-url> --attribute-names RedrivePolicy VisibilityTimeout
aws sqs receive-message --queue-url <dlq-url> --max-number-of-messages 5 \
--attribute-names ApproximateReceiveCount --message-attribute-names AllFix โ
- Inspect the DLQ payloads, and fix the parser or the code path
- Make sure consumers delete messages only after success
- Once fixed, redrive:
aws sqs start-message-move-task --source-arn <dlq-arn> --destination-arn <main-arn>
Prevent โ Alarm on ApproximateNumberOfMessagesVisible above 0 on every DLQ, and log the message ID on failures.
Q170 You subscribed an email address to an SNS topic, but nothing arrives when you publish.
Beginner
Likely causes โ The subscription is still PendingConfirmation; the recipient never clicked the confirmation link (check spam). Another cause: a filter policy on the subscription does not match the message attributes.
Diagnose โ
aws sns list-subscriptions-by-topic --topic-arn arn:aws:sns:us-east-1:111111111111:alerts \
--query 'Subscriptions[].[Protocol,Endpoint,SubscriptionArn]'
aws sns get-subscription-attributes --subscription-arn <arn> --query 'Attributes.FilterPolicy'Fix โ
- Confirm the subscription, or delete it and subscribe again to resend the email
- Fix or remove the filter policy
- Publish a test message:
aws sns publish --topic-arn <arn> --message test
Prevent โ Prefer chat integrations (Amazon Q Developer in chat applications, formerly AWS Chatbot) or an SQS/Lambda fan-out over personal emails for operations alerts.
Q171 SNS in account A publishes successfully, but the SQS queue in account B never receives anything.
Intermediate
Likely causes โ The SQS queue policy does not allow sqs:SendMessage from sns.amazonaws.com with aws:SourceArn set to the topic. The queue uses SSE with the AWS managed key aws/sqs, which SNS cannot use. Or the cross-account subscription was never confirmed.
Diagnose โ
aws sqs get-queue-attributes --queue-url <url> --attribute-names Policy KmsMasterKeyId
aws sns list-subscriptions-by-topic --topic-arn <topic-arn>
# SNS delivery status logging / NumberOfNotificationsFailed metric on the topicFix โ
- Add a queue policy statement that allows
sns.amazonaws.comwith"ArnEquals":{"aws:SourceArn":"<topic-arn>"} - Switch the queue to a CMK whose key policy allows
sns.amazonaws.comto usekms:GenerateDataKey*andkms:Decrypt, or to SSE-SQS - Confirm the subscription from account B
Prevent โ Use a reusable cross-account fan-out module, and alarm on NumberOfNotificationsFailed.
Q172 An SQS FIFO queue has thousands of messages, but consumers receive nothing for minutes at a time.
Advanced
Likely causes โ FIFO guarantees order per message group. While a message from a group is in flight (received but not deleted), no other message in that group is delivered. If most messages share one MessageGroupId, a single slow or failing message blocks everything behind it until the visibility timeout ends.
Diagnose โ
aws sqs get-queue-attributes --queue-url <fifo-url> \
--attribute-names ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible VisibilityTimeout RedrivePolicy
# check producer code: what is MessageGroupId set to?Fix โ
- Use a finer-grained group ID (per customer or order), so groups process in parallel
- Add a DLQ so poison messages leave the group
- Make sure consumers delete or extend visibility promptly
Prevent โ Choose the group key for the ordering you really need. Use high-throughput FIFO mode only with many groups.
Q173 An EventBridge rule should trigger a Lambda on EC2 state changes, but the Lambda never runs.
Advanced
Likely causes โ The event pattern does not match: a typo, wrong case, or values not wrapped in arrays. The rule is on the wrong event bus or Region. The Lambda resource policy does not allow events.amazonaws.com, which shows up as FailedInvocations. Or the rule is disabled.
Diagnose โ
aws events describe-rule --name ec2-state --query '[State,EventBusName,EventPattern]'
aws events test-event-pattern --event-pattern file://pattern.json --event file://sample-event.json
aws cloudwatch get-metric-statistics --namespace AWS/Events --metric-name FailedInvocations \
--dimensions Name=RuleName,Value=ec2-state --statistics Sum --period 300 \
--start-time $(date -u -d '-1 day' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws lambda get-policy --function-name on-ec2-changeFix โ
- Correct the pattern, for example
{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"],"detail":{"state":["stopped"]}} - Add the permission:
aws lambda add-permission --function-name on-ec2-change --statement-id evb --action lambda:InvokeFunction --principal events.amazonaws.com --source-arn <rule-arn> - Add a DLQ on the target
Prevent โ Unit-test patterns with test-event-pattern in CI, and alarm on FailedInvocations.
Q174 Kinesis consumers fall behind: GetRecords.IteratorAgeMilliseconds keeps rising, and producers see ProvisionedThroughputExceededException.
Advanced
GetRecords.IteratorAgeMilliseconds keeps rising, and producers see ProvisionedThroughputExceededException.Likely causes โ Shards are saturated (1 MB/s or 1,000 records/s in, 2 MB/s out per shard), often because of a hot partition key. Too many consumers share the 5 reads/s per shard limit. Or the consumer is slow (a Lambda batch that keeps failing and retrying blocks the shard).
Diagnose โ
aws kinesis describe-stream-summary --stream-name clicks --query 'StreamDescriptionSummary.[StreamModeDetails,OpenShardCount]'
aws cloudwatch get-metric-statistics --namespace AWS/Kinesis --metric-name WriteProvisionedThroughputExceeded \
--dimensions Name=StreamName,Value=clicks --statistics Sum --period 60 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
aws lambda list-event-source-mappings --function-name clicks-consumer --query 'EventSourceMappings[].[BatchSize,ParallelizationFactor,BisectBatchOnFunctionError]'Fix โ
- Switch to on-demand mode, or reshard:
aws kinesis update-shard-count --stream-name clicks --target-shard-count 8 --scaling-type UNIFORM_SCALING - Use a high-cardinality partition key
- Use enhanced fan-out for multiple consumers
- On the Lambda mapping, set
ParallelizationFactor,BisectBatchOnFunctionError,MaximumRetryAttemptsand an on-failure destination
Prevent โ Alarm on iterator age, and turn on shard-level metrics to spot hot shards.
Q175 The SDK fails with AWS.SimpleQueueService.NonExistentQueue: The specified queue does not exist. but the queue is in the console.
Beginner
AWS.SimpleQueueService.NonExistentQueue: The specified queue does not exist. but the queue is in the console.Likely causes โ The client is in a different Region or account from the queue, the queue URL or name has a typo (FIFO queues need the .fifo suffix), or the queue was deleted and re-created within 60 seconds.
Diagnose โ
aws sts get-caller-identity
aws sqs get-queue-url --queue-name orders.fifo --region eu-west-1
aws sqs list-queues --queue-name-prefix orders --region eu-west-1Fix โ Use the full queue URL from get-queue-url with the matching Region, and add --queue-owner-aws-account-id for cross-account queues.
Prevent โ Inject queue URLs from IaC outputs through environment variables or SSM, never hand-typed names.
CloudFormation, CloudWatch, KMS, Secrets and Cost
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q176 Updating a stack fails: Stack:arn:aws:cloudformation:...:stack/app/... is in ROLLBACK_COMPLETE state and can not be updated.
Beginner
Stack:arn:aws:cloudformation:...:stack/app/... is in ROLLBACK_COMPLETE state and can not be updated.Likely causes โ The first create of the stack failed and rolled back. A stack in ROLLBACK_COMPLETE cannot be updated; it can only be deleted.
Diagnose โ
aws cloudformation describe-stack-events --stack-name app \
--query "StackEvents[?ResourceStatus=='CREATE_FAILED'].[LogicalResourceId,ResourceStatusReason]" --output tableFix โ
- Read the first
CREATE_FAILEDreason and fix the template - Run
aws cloudformation delete-stack --stack-name app && aws cloudformation wait stack-delete-complete --stack-name app - Create the stack again
Prevent โ Use --disable-rollback (or --on-failure DO_NOTHING) in dev to debug failed creates, and run cfn-lint in CI.
Q177 A stack is stuck in UPDATE_ROLLBACK_FAILED.
Advanced
UPDATE_ROLLBACK_FAILED.Likely causes โ During rollback, CloudFormation could not return a resource to its old state. Typical reasons: the resource was changed or deleted outside CloudFormation, a dependency is gone, or permissions were removed.
Diagnose โ
aws cloudformation describe-stack-events --stack-name app \
--query "StackEvents[?contains(ResourceStatus,'FAILED')].[Timestamp,LogicalResourceId,ResourceStatusReason]" --max-items 10Fix โ
- Fix the underlying issue if you can (re-create the deleted dependency, restore permissions)
- Run
aws cloudformation continue-update-rollback --stack-name app - If a resource cannot be recovered, skip it:
aws cloudformation continue-update-rollback --stack-name app --resources-to-skip MyBrokenResource. Then reconcile that resource manually, because CloudFormation now treats it as matching the old template
Prevent โ Never change stack resources by hand. Use stack policies and drift detection, and deploy through change sets.
Q178 A pipeline fails with An error occurred (ValidationError) when calling the UpdateStack operation: No updates are to be performed.
Beginner
An error occurred (ValidationError) when calling the UpdateStack operation: No updates are to be performed.Likely causes โ The template and parameters are identical to what is deployed. CloudFormation treats this as an error for update-stack.
Diagnose โ
aws cloudformation get-template --stack-name app --query TemplateBody > deployed.yaml
diff deployed.yaml template.yamlFix โ Use aws cloudformation deploy --no-fail-on-empty-changeset, which handles this case. Or catch that specific message and treat it as success.
Prevent โ Deploy with aws cloudformation deploy or change sets in pipelines, not raw update-stack.
Q179 InsufficientCapabilitiesException: Requires capabilities : [CAPABILITY_NAMED_IAM].
Beginner
InsufficientCapabilitiesException: Requires capabilities : [CAPABILITY_NAMED_IAM].Likely causes โ The template creates IAM resources with custom names (RoleName, PolicyName). CloudFormation makes you acknowledge that explicitly. Templates that use Transform macros (SAM) also need CAPABILITY_AUTO_EXPAND.
Diagnose โ
grep -nE 'AWS::IAM::|RoleName|Transform' template.yamlFix โ
aws cloudformation deploy --template-file template.yaml --stack-name app \
--capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPANDPrevent โ Avoid hard-coded IAM names (let CloudFormation generate them) so you only need CAPABILITY_IAM, and let only reviewed pipelines pass capabilities.
Q180 Stack deletion ends in DELETE_FAILED with The bucket you tried to delete is not empty on an S3 bucket resource.
Intermediate
DELETE_FAILED with The bucket you tried to delete is not empty on an S3 bucket resource.Likely causes โ CloudFormation does not empty buckets. A non-empty or versioned bucket blocks deletion. The same thing happens with ECR repositories that contain images and security groups still attached to ENIs.
Diagnose โ
aws cloudformation describe-stack-events --stack-name app \
--query "StackEvents[?ResourceStatus=='DELETE_FAILED'].[LogicalResourceId,PhysicalResourceId,ResourceStatusReason]"Fix โ
- Empty the bucket, including all versions (see Q82), then delete the stack again
- Or keep the bucket:
aws cloudformation delete-stack --stack-name app --retain-resources LogsBucket(only allowed when the stack is inDELETE_FAILED)
Prevent โ Set DeletionPolicy: Retain on data buckets, and use auto-delete custom resources (CDK autoDeleteObjects) only for ephemeral stacks.
Q181 Drift detection shows MODIFIED on a security group and an RDS instance that someone changed in the console. How do you reconcile?
Advanced
MODIFIED on a security group and an RDS instance that someone changed in the console. How do you reconcile?Likely causes โ Changes made outside CloudFormation (console hotfix during an incident). The next stack update may silently undo them, or fail.
Diagnose โ
ID=$(aws cloudformation detect-stack-drift --stack-name app --query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id $ID
aws cloudformation describe-stack-resource-drifts --stack-name app --stack-resource-drift-status-filters MODIFIED DELETED \
--query 'StackResourceDrifts[].[LogicalResourceId,PropertyDifferences]'Fix โ
- Decide which version is correct
- If the console change should stay, put it into the template and deploy a change set (it should show no replacement)
- If not, deploy the template to overwrite it
- For resources deleted out of band, remove them from the template, or re-create and import them (
create-change-set --change-set-type IMPORT)
Prevent โ Run scheduled drift detection (AWS Config rule cloudformation-stack-drift-detection-check), make production console access read-only, and have a break-glass process that requires a follow-up PR.
Q182 Deleting or updating a stack fails: Export network-VpcId cannot be deleted as it is in use by app-stack.
Intermediate
Export network-VpcId cannot be deleted as it is in use by app-stack.Likely causes โ Another stack imports the output through Fn::ImportValue. CloudFormation will not let you change or remove an export while it is imported.
Diagnose โ
aws cloudformation list-imports --export-name network-VpcId
aws cloudformation list-exports --query "Exports[?Name=='network-VpcId']"Fix โ
- In the importing stacks, replace
ImportValuewith a hard-coded value or an SSM parameter and deploy them - Then change or remove the export in the producer stack
Prevent โ For loose coupling, share values between stacks through SSM Parameter Store ({{resolve:ssm:/network/vpc-id}}) rather than exports.
Q183 A stack has been in CREATE_IN_PROGRESS for an hour on a Custom::DbSeeder resource.
Advanced
CREATE_IN_PROGRESS for an hour on a Custom::DbSeeder resource.Likely causes โ The custom resource Lambda never sent a response to the pre-signed ResponseURL. It crashed, timed out, could not reach S3 (in a VPC without NAT or an endpoint), or forgot to answer on Delete. CloudFormation waits up to the service timeout, which is one hour by default.
Diagnose โ
aws cloudformation describe-stack-resource --stack-name app --logical-resource-id DbSeeder
aws logs tail /aws/lambda/app-DbSeeder --since 2hFix โ
- To unblock now, send a response yourself with
curl -X PUT -H 'Content-Type:' --data-binary '{"Status":"FAILURE","Reason":"manual","PhysicalResourceId":"seed","StackId":"...","RequestId":"...","LogicalResourceId":"DbSeeder"}' "<ResponseURL from logs>" - Fix the handler so it always responds in
try/finally, including on Delete
Prevent โ Use the cfn-response module or CDK Provider framework, and set ServiceTimeout on the custom resource to something short (for example, 300 seconds).
Q184 A CloudWatch alarm on a custom metric stays in INSUFFICIENT_DATA forever.
Beginner
INSUFFICIENT_DATA forever.Likely causes โ The alarm's namespace, metric name or dimensions do not match exactly what is published (an alarm must specify all dimensions). Other causes: the period is shorter than the publish interval, or the metric stopped being sent.
Diagnose โ
aws cloudwatch describe-alarms --alarm-names api-errors \
--query 'MetricAlarms[].[Namespace,MetricName,Dimensions,Period,StateReason]'
aws cloudwatch list-metrics --namespace MyApp --metric-name ErrorsFix โ
- Copy the exact dimension set from
list-metricsinto the alarm - Make the period match the publishing rate
- For sparse metrics, set
--treat-missing-data notBreaching
Prevent โ Create alarms in the same IaC module that defines the metric names, and test alarms with set-alarm-state.
Q185 The CloudWatch agent is running, but no mem_used_percent or disk metrics appear in the CWAgent namespace.
Intermediate
mem_used_percent or disk metrics appear in the CWAgent namespace.Likely causes โ The agent was started with the default or no config, so the metrics section is missing. Other causes: the instance role has no CloudWatchAgentServerPolicy, or the agent cannot reach the CloudWatch endpoint (private subnet with no monitoring endpoint).
Diagnose โ
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status
sudo tail -50 /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
aws cloudwatch list-metrics --namespace CWAgent --dimensions Name=InstanceId,Value=i-0abcFix โ
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config -m ec2 -s -c ssm:AmazonCloudWatch-linuxAttach CloudWatchAgentServerPolicy, and add the monitoring and logs endpoints for private subnets.
Prevent โ Store the agent config in SSM Parameter Store, and push it with State Manager to every instance.
Q186 An app writes logs, but its CloudWatch log group stays empty.
Intermediate
Likely causes โ The role cannot write logs (logs:CreateLogStream, logs:PutLogEvents, or logs:CreateLogGroup if the group does not exist). The log group is KMS-encrypted and the key policy does not allow the logs.<region>.amazonaws.com principal. Or you are looking in the wrong Region or group name.
Diagnose โ
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/orders --query 'logGroups[].[logGroupName,kmsKeyId]'
aws logs describe-log-streams --log-group-name /aws/lambda/orders --order-by LastEventTime --descending --max-items 3
aws iam list-attached-role-policies --role-name orders-lambda-roleFix โ
- For Lambda, attach
AWSLambdaBasicExecutionRole. For ECS, give the execution rolelogs:*on the group - Create the group in IaC with retention set
- Fix the KMS key policy for CloudWatch Logs
Prevent โ Pre-create every log group with retention and permissions, rather than relying on auto-create, which also means infinite retention.
Q187 A CPU alarm flaps between OK and ALARM every few minutes and pages the on-call engineer all night.
Intermediate
OK and ALARM every few minutes and pages the on-call engineer all night.Likely causes โ The alarm uses 1 datapoint of 1 over a short period on a noisy metric. Or missing data is treated as breaching while the metric is published irregularly.
Diagnose โ
aws cloudwatch describe-alarm-history --alarm-name web-cpu --history-item-type StateUpdate --max-items 20 \
--query 'AlarmHistoryItems[].[Timestamp,HistorySummary]'
aws cloudwatch describe-alarms --alarm-names web-cpu \
--query 'MetricAlarms[].[Period,EvaluationPeriods,DatapointsToAlarm,TreatMissingData,Threshold]'Fix โ
aws cloudwatch put-metric-alarm --alarm-name web-cpu --namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=AutoScalingGroupName,Value=web-asg --statistic Average --period 60 \
--evaluation-periods 5 --datapoints-to-alarm 4 --threshold 85 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching --alarm-actions <sns-arn>Use composite alarms (for example, high CPU and high latency) for paging.
Prevent โ Page on symptoms (SLO burn, errors, latency) and send resource alarms to tickets.
Q188 Decrypt calls fail with KMSInvalidStateException: arn:aws:kms:...:key/... is pending deletion.
Intermediate
KMSInvalidStateException: arn:aws:kms:...:key/... is pending deletion.Likely causes โ Someone scheduled the key for deletion (7โ30 day waiting period). While pending, the key cannot be used, and everything encrypted with it stops working.
Diagnose โ
aws kms describe-key --key-id <key-id> --query 'KeyMetadata.[KeyState,DeletionDate]'
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ScheduleKeyDeletion --max-results 5Fix โ
aws kms cancel-key-deletion --key-id <key-id>
aws kms enable-key --key-id <key-id> # cancel leaves it DisabledPrevent โ Deny kms:ScheduleKeyDeletion through SCP except for a break-glass role, alarm on that CloudTrail event through EventBridge, and use the 30-day window.
Q189 A cross-account decrypt fails: AccessDeniedException: The ciphertext refers to a customer master key that does not exist, does not exist in this region, or you are not allowed to access it.
Advanced
AccessDeniedException: The ciphertext refers to a customer master key that does not exist, does not exist in this region, or you are not allowed to access it.Likely causes โ One of three: (1) the key is in another Region, because KMS keys are Regional unless multi-Region, (2) the key policy in the owning account does not allow the caller's account or role, or (3) the caller's IAM policy has no kms:Decrypt on the key ARN. Cross-account access needs both the key policy and IAM. The error deliberately does not say which one failed.
Diagnose โ
aws kms describe-key --key-id arn:aws:kms:us-east-1:222222222222:key/abcd... --query 'KeyMetadata.[Arn,KeyState,MultiRegion]'
aws kms get-key-policy --key-id <arn> --policy-name default --output text # run in owning account
aws iam simulate-principal-policy --policy-source-arn <caller-role-arn> --action-names kms:Decrypt --resource-arns <key-arn>Fix โ
- Add a key policy statement allowing
arn:aws:iam::111111111111:role/consumerto usekms:Decryptandkms:DescribeKey - Add a matching IAM allow on the consumer role, referencing the key ARN (not an alias)
- Call KMS in the key's Region, or use a multi-Region replica
Prevent โ Template cross-account key grants, and use encryption context conditions to scope them.
Q190 Under load, S3 and SSM calls start failing with ThrottlingException: You have exceeded the rate at which you may call KMS. Reduce the frequency of your calls.
Advanced
ThrottlingException: You have exceeded the rate at which you may call KMS. Reduce the frequency of your calls.Likely causes โ Every SSE-KMS object read or write, every SecureString parameter read and every envelope encryption call hits KMS, and they share a per-account, per-Region request quota for cryptographic operations (thousands of requests per second, depending on the Region).
Diagnose โ
aws service-quotas list-service-quotas --service-code kms \
--query "Quotas[?contains(QuotaName,'Cryptographic operations')].[QuotaName,Value]"
# CloudWatch AWS/Usage: Service=KMS, Type=API, Resource=Decrypt/GenerateDataKey
aws s3api get-bucket-encryption --bucket data --query 'ServerSideEncryptionConfiguration.Rules[].BucketKeyEnabled'Fix โ
- Turn on S3 Bucket Keys, which cut KMS calls from S3 by up to 99%:
aws s3api put-bucket-encryption --bucket data --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms","KMSMasterKeyID":"<key>"},"BucketKeyEnabled":true}]}' - Cache decrypted secrets and parameters in the app (Secrets Manager caching client, Parameters and Secrets Lambda extension)
- Use data key caching (AWS Encryption SDK)
- Request a quota increase
Prevent โ Alarm on KMS usage at 70% of the quota, and design for caching from the start.
Q191 ResourceNotFoundException: Secrets Manager can't find the specified secret. but the secret is in the console.
Beginner
ResourceNotFoundException: Secrets Manager can't find the specified secret. but the secret is in the console.Likely causes โ The call goes to the wrong Region or account. Or the code uses a partial ARN: Secrets Manager adds a random 6-character suffix to ARNs, so arn:...:secret:prod/db without the suffix fails, while the name prod/db works. The secret may also be scheduled for deletion.
Diagnose โ
aws secretsmanager describe-secret --secret-id prod/db --region us-east-1 --query '[ARN,DeletedDate]'
aws secretsmanager list-secrets --filters Key=name,Values=prod/ --region us-east-1 --query 'SecretList[].Name'Fix โ
- Reference the secret by name, or by full ARN including the suffix
- Set the Region explicitly
- If the secret is pending deletion:
aws secretsmanager restore-secret --secret-id prod/db
Prevent โ Pass secret ARNs from IaC outputs, and in IAM policies use secret:prod/db-?????? to match the suffix.
Q192 Secrets Manager rotation fails, and the secret shows AWSPENDING stuck on a version.
Advanced
AWSPENDING stuck on a version.Likely causes โ The rotation Lambda failed in one of its four steps (createSecret, setSecret, testSecret, finishSecret). Common reasons: it cannot reach the DB (VPC or SG), it cannot reach the Secrets Manager endpoint from a private subnet, the DB user has no rights to change its password, or a previous failed rotation left AWSPENDING behind, which blocks the next try.
Diagnose โ
aws secretsmanager describe-secret --secret-id prod/db --query '[RotationEnabled,LastRotatedDate,VersionIdsToStages]'
aws logs tail /aws/lambda/SecretsManagerRDSPostgreSQLRotationSingleUser --since 2hFix โ
- Fix the network path: the Lambda must reach both the DB and the
secretsmanagerendpoint - Remove the stale stage:
aws secretsmanager update-secret-version-stage --secret-id prod/db --version-stage AWSPENDING --remove-from-version-id <id> - Retry:
aws secretsmanager rotate-secret --secret-id prod/db
Prevent โ Prefer RDS managed master passwords, use the alternating-users strategy for apps, and alarm on rotation failures through EventBridge (RotationFailed).
Q193 aws ssm get-parameter --name /prod/db/password returns an encrypted blob instead of the password.
Beginner
aws ssm get-parameter --name /prod/db/password returns an encrypted blob instead of the password.Likely causes โ The parameter is a SecureString, and the call did not ask for decryption. If you add the flag and get AccessDeniedException, the caller has no kms:Decrypt on the key.
Diagnose โ
aws ssm describe-parameters --parameter-filters Key=Name,Values=/prod/db/password --query 'Parameters[].[Type,KeyId]'Fix โ
aws ssm get-parameter --name /prod/db/password --with-decryption --query Parameter.Value --output text
aws ssm get-parameters-by-path --path /prod/db --recursive --with-decryptionGrant ssm:GetParameter* on arn:aws:ssm:...:parameter/prod/db/* and kms:Decrypt on the key.
Prevent โ Scope parameter access by path per service, and use ParameterNotFound checks in startup code so missing config fails fast.
Q194 Re-creating a secret fails: InvalidRequestException: You can't create this secret because a secret with this name is already scheduled for deletion.
Beginner
InvalidRequestException: You can't create this secret because a secret with this name is already scheduled for deletion.Likely causes โ A secret with that name was deleted with a recovery window (7โ30 days) and is still recoverable. This often happens in IaC teardown and re-create cycles.
Diagnose โ
aws secretsmanager describe-secret --secret-id dev/api-key --query '[Name,DeletedDate]'Fix โ
- To reuse it, restore it:
aws secretsmanager restore-secret --secret-id dev/api-key - For dev only, force deletion now:
aws secretsmanager delete-secret --secret-id dev/api-key --force-delete-without-recovery
Prevent โ For ephemeral environments, set recovery_window_in_days = 0 in Terraform, and keep a 30-day window in production.
Q195 A production security group rule disappeared overnight. How do you find out who removed it?
Beginner
Likely causes โ A manual console change, an automation job, or an IaC apply that removed the rule as drift.
Diagnose โ
aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue=sg-0abc \
--start-time $(date -u -d '-2 day' +%FT%TZ) \
--query 'Events[].[EventTime,EventName,Username]' --output table
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=RevokeSecurityGroupIngress --max-results 10
aws configservice get-resource-config-history --resource-type AWS::EC2::SecurityGroup --resource-id sg-0abc --limit 5Fix โ
- Restore the rule through IaC
- Find the principal (
userIdentity.arn,sourceIPAddress, user agent such as Terraform) and close the gap
Prevent โ Keep an organization trail with Athena queries, AWS Config rules for SG baselines, and EventBridge alerts on SG changes in production. Note that lookup-events covers only 90 days of management events.
Q196 The NAT Gateway line is the second-biggest item on the AWS bill.
Intermediate
Likely causes โ NAT charges per GB processed as well as per hour. Big traffic through NAT, such as pulling container images, S3 or DynamoDB transfers, or backups, adds up quickly. Cross-AZ NAT usage adds data transfer charges on top.
Diagnose โ
aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-11-01 --granularity MONTHLY --metrics UnblendedCost \
--filter '{"Dimensions":{"Key":"USAGE_TYPE_GROUP","Values":["EC2: NAT Gateway - Data Processed"]}}'
# CloudWatch AWS/NATGateway BytesOutToDestination per NAT
# VPC Flow Logs on the NAT ENI -> top destinations by bytes (Athena)Fix โ
- Add free gateway endpoints for S3 and DynamoDB
- Add interface endpoints for ECR, Logs and STS where the volume justifies their hourly cost
- Use one NAT per AZ with AZ-local routes
- Cache images (ECR pull-through cache)
Prevent โ Tag and dashboard NAT bytes, and review the top talkers through flow logs every month.
Q197 Data transfer costs jumped after you spread services across three AZs.
Advanced
Likely causes โ Inter-AZ traffic is charged in both directions (about $0.01/GB each way). Chatty microservices, Kafka or Elasticsearch replication, and cross-AZ load balancing to targets (on ALB it is free inside the LB; on NLB with cross-zone on, you pay inter-AZ) add up. Calling through public IPs or Elastic IPs inside the Region costs even more.
Diagnose โ
aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-11-01 --granularity DAILY \
--metrics UnblendedCost --group-by Type=DIMENSION,Key=USAGE_TYPE \
--filter '{"Dimensions":{"Key":"SERVICE","Values":["Amazon Elastic Compute Cloud - Compute","EC2 - Other"]}}' \
--query 'ResultsByTime[-1].Groups[?contains(Keys[0],`DataTransfer-Regional`)]'
# Flow logs with az-id fields to find top cross-AZ pairsFix โ
- Use topology-aware routing (Kubernetes
trafficDistribution: PreferClose, or Istio locality LB) - Use rack- or AZ-aware consumers (Kafka
client.rack) - Use private IPs, not public ones, for in-Region calls
Prevent โ Make data transfer a design review item, and put cross-AZ bytes on a dashboard per service.
Q198 A budget alert fired at 120% of forecast mid-month. How do you find what is spending money?
Intermediate
Likely causes โ A new or forgotten resource (a big instance, a GPU node pool, a NAT), runaway usage (Lambda loop, logs ingestion), or a missing commitment discount.
Diagnose โ
aws ce get-cost-and-usage --time-period Start=2026-11-01,End=2026-11-09 --granularity DAILY \
--metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE \
--query 'ResultsByTime[-1].Groups | sort_by(@,&to_number(Metrics.UnblendedCost.Amount))[-5:]'
aws ce get-cost-and-usage --time-period Start=2026-11-01,End=2026-11-09 --granularity DAILY \
--metrics UnblendedCost --group-by Type=DIMENSION,Key=LINKED_ACCOUNT
aws ce get-anomalies --date-interval StartDate=2026-11-01,EndDate=2026-11-09Fix โ
- Drill down from service to usage type, then account, then tag (
Type=TAG,Key=team) - Stop or right-size the offender
- Fix the runaway trigger
Prevent โ Turn on Cost Anomaly Detection with alerts to a channel, use per-team budgets with actions, and enforce cost allocation tags.
Q199 All dev instances are stopped every night, yet the account still costs money each day.
Beginner
Likely causes โ Stopped instances still have charged EBS volumes. Other charges continue too: snapshots, Elastic IPs and all public IPv4 addresses (charged hourly since February 2024), NAT gateways, load balancers, RDS instances (which also restart automatically after 7 days stopped) and CloudWatch Logs storage.
Diagnose โ
aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].[VolumeId,Size,CreateTime]'
aws ec2 describe-addresses --query 'Addresses[?AssociationId==null].[PublicIp,AllocationId]'
aws ec2 describe-nat-gateways --filter Name=state,Values=available --query 'NatGateways[].NatGatewayId'
aws elbv2 describe-load-balancers --query 'LoadBalancers[].LoadBalancerName'Fix โ
- Delete unattached volumes and unused EIPs
- Expire old snapshots with Data Lifecycle Manager
- Remove idle NATs and ALBs in dev (recreate them with IaC when needed)
Prevent โ Run ephemeral dev environments from IaC that are destroyed nightly, and use Trusted Advisor or Compute Optimizer idle-resource checks.
Q200 You bought a Compute Savings Plan last month, but Cost Explorer shows only 40% coverage and costs barely moved.
Advanced
Likely causes โ The commitment covers less spend than you thought (the commitment is $/hour of discounted usage). Other reasons: most spend is on services the plan does not cover (RDS, OpenSearch, ElastiCache and Redshift are not covered by Compute Savings Plans and need their own Reserved Instances), usage is in member accounts with discount sharing turned off, or you bought an EC2 Instance Savings Plan locked to a family and Region you then moved away from.
Diagnose โ
aws ce get-savings-plans-coverage --time-period Start=2026-10-01,End=2026-11-01 --granularity MONTHLY
aws ce get-savings-plans-utilization --time-period Start=2026-10-01,End=2026-11-01
aws savingsplans describe-savings-plans --query 'savingsPlans[].[savingsPlanType,commitment,region,ec2InstanceFamily,state]'
aws ce get-savings-plans-purchase-recommendation --savings-plans-type COMPUTE_SP --term-in-years ONE_YEAR \
--payment-option NO_UPFRONT --lookback-period-in-days THIRTY_DAYSFix โ
- If utilization is low, move workloads onto the covered family or Region, or switch to Compute SP for new purchases
- If coverage is low, layer extra commitments based on the recommendation, plus RIs for databases
- Turn on RI/SP discount sharing in the payer account
Prevent โ Buy in small tranches every quarter based on a steady-state baseline, prefer Compute SP for flexibility, and alarm on utilization below 95%.