Top 100 Cloud Engineer Interview Questions and Answers
The questions most likely to come up in your Cloud Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed:
Q&A-1Walk through what a private subnet instance needs to reach the internet, and why a NAT gateway rather than an internet gateway is the answer.
The 2-minute answer
I'll assume an AWS VPC with IPv4, since that's where the subnet-versus-gateway distinction matters most. The instance has only a private address, say 10.0.2.15, and no public IP. For it to reach the internet, three things have to line up: a route out of its subnet, a translation step that gives it a routable source address, and a path from that translation point to the internet gateway.
The instance's subnet route table needs 0.0.0.0/0 → nat-0ab…, pointing at a NAT gateway that sits in a public subnet. That NAT gateway holds an Elastic IP. The public subnet's route table has 0.0.0.0/0 → igw-…. The security group must allow egress, and if the subnet has a network ACL, it must allow the return traffic on ephemeral ports 1024-65535, because NACLs are stateless.
Why NAT and not the internet gateway: an internet gateway only translates between a private address and a public IPv4 address that is assigned to the instance itself. A private-only instance has no such address, so pointing its default route at the IGW gets it nothing. The traffic leaves with source 10.0.2.15, which cannot be routed back. A NAT gateway does the translation for it, and it is one-way: connections must be initiated from inside. Nothing on the internet can open a connection to the instance through it, which is exactly the property you want for a private workload.
Trace of one outbound HTTPS call
| Step | Source | Destination | What happens |
|---|---|---|---|
| 1 | 10.0.2.15:51734 | 93.184.216.34:443 | instance sends SYN, matches 0.0.0.0/0 in its subnet table |
| 2 | 10.0.2.15:51734 | 93.184.216.34:443 | NAT gateway in public subnet records the flow |
| 3 | 54.x.x.x:40112 | 93.184.216.34:443 | NAT rewrites the source to its Elastic IP and a mapped port |
| 4 | 93.184.216.34:443 | 54.x.x.x:40112 | reply arrives at the NAT, which maps it back to 10.0.2.15:51734 |
(The 54.x.x.x address is a placeholder, not a real allocation.)
Where it breaks
The NAT gateway is zonal. If you run one gateway in eu-west-1a and route private subnets in 1b and 1c through it, an AZ outage takes all egress down, and cross-AZ data transfer adds cost on every byte. The usual fix is one NAT gateway per AZ with each AZ's private route table pointing at its local gateway.
Port exhaustion is the second failure. Each NAT gateway Elastic IP supports up to 55,000 simultaneous connections to a single destination IP and port. If many instances hammer one API endpoint, you hit that ceiling before you run out of bandwidth. You detect it with the ErrorPortAllocation CloudWatch metric, which counts connection attempts dropped for lack of a port. The fix is more Elastic IPs on the gateway, or connection reuse on the client side.
The third is the one people miss: a route in a private table pointing at a NAT gateway in a different AZ still works, but it fails the moment that AZ is unhealthy, and it is invisible in normal operation.
Trade-offs
A NAT gateway has an hourly charge per gateway plus a per-GB charge on data processed, so a chatty workload pulling large volumes from S3 or a public registry can cost more than the instances it serves. Gateway VPC endpoints for S3 and DynamoDB avoid both the NAT charge and the internet path. Interface endpoints cover other AWS services. Check current pricing on the AWS page before you quote numbers.
When not to use a NAT gateway: if the instance genuinely needs inbound connections from the internet, it belongs in a public subnet with its own public address, behind a load balancer. A NAT instance (a self-managed EC2 box doing the same job) is cheaper at very low volume, but you own its patching, scaling and failover.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Which one blocks return traffic when only inbound rules are configured: AWS security groups or network ACLs, and why?
The 60-second answer
Security groups are stateful. Network ACLs are stateless. A security group that allows inbound TCP 443 also lets the reply leave, because it tracks the connection and admits the return packets automatically. A network ACL evaluates every packet on its own, so the inbound rule for 443 does nothing to the response. The return traffic has to match an outbound rule, and it is the network ACL that blocks it when that rule is missing.
Why the two behave differently
A security group records the connection when the first packet is allowed. Packets belonging to that flow are then permitted without consulting the rules again, in either direction. Security groups have allow rules only, and nothing is denied unless no rule matches.
A network ACL has no connection table. Each packet, inbound or outbound, is checked against the subnet's rule list. Rules are numbered and evaluated from lowest number upward, the first match wins, and an explicit deny is possible. The implicit final rule is deny.
Trace
A client at 203.0.113.9 opens TCP to a web server on 10.0.1.20:443. The source port is ephemeral, say 51514.
| Step | Packet | Security group | Network ACL |
|---|---|---|---|
| 1 | client to 10.0.1.20:443, SYN | inbound 443 from 0.0.0.0/0, allowed, flow recorded | inbound rule 100 allows TCP 443, allowed |
| 2 | 10.0.1.20:443 to client:51514, SYN-ACK | matches the tracked flow, allowed | outbound rule needed for destination ports 1024-65535; without it, dropped |
With the outbound ACL rule in place, step 2 passes. Without it, the handshake never completes, and the server logs show the SYN arriving while the client retransmits and times out.
Failure modes and detection
- Custom network ACL with only inbound rules: the default outbound deny drops replies. Symptom: connections that appear to open then hang, with SYN retransmits on the client. VPC Flow Logs show accepted inbound and rejected outbound records for the same flow.
- Ephemeral range too narrow: the client OS picks source ports outside the range in the outbound rule. Linux defaults to 32768-60999, while IANA's suggested range is 49152-65535. A rule for 1024-65535 covers both. Check the client's port range before narrowing it.
- Default network ACL assumed to be restrictive: the default NACL allows all traffic in both directions, so the problem only appears after someone attaches a custom one.
When the distinction matters in practice
Use security groups for most per-instance access control, because they follow the instance and need no return rules. Use network ACLs for coarse subnet-level denies, such as blocking a known bad CIDR, where stateless evaluation and explicit deny are the point. Any custom network ACL needs an outbound rule for the ephemeral range, and it is easy to forget because the security group in front of the same instance works without one.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design a three-tier VPC across three availability zones with public, private and data subnets. The app tier runs EKS with the AWS VPC CNI and must scale to 6,000 pods per zone. What CIDR plan do you choose, and how do you justify the sizing?
The 90-second answer
I start with the pod count, because the VPC CNI gives every pod a real VPC IP from the node's subnet. That makes the app tier the sizing constraint, not the node count. I budget a /18 per zone for app subnets, /20 for public, /22 for data, and keep the rest of the 10.0.0.0/16 free.
Sizing arithmetic. AWS reserves 5 addresses in every subnet, so usable = 2^(32-prefix) - 5.
| Tier | Per AZ | Usable per subnet | Need |
|---|---|---|---|
| Public (ALB, NAT) | /20 | 4,091 | a few hundred |
| App (EKS nodes, pods) | /18 | 16,379 | 6,000 pods + node ENIs + warm pool |
| Data (RDS, cache) | /22 | 1,019 | a few hundred |
Why /18 and not /19: 6,000 pods plus a warm IP pool of roughly 10 addresses on each of about 150 nodes is about 7,500. A /19 has 8,187 usable, which leaves no room for a zone to lose a node group or a burst to land. The per-node warm pool is tunable (WARM_IP_TARGET, MINIMUM_IP_TARGET), so I size the pool, not the hope.
Layout (all in 10.0.0.0/16):
- Public:
10.0.0.0/20,10.0.16.0/20,10.0.32.0/20 - Data:
10.0.48.0/22,10.0.52.0/22,10.0.56.0/22(10.0.60.0/22spare) - App:
10.0.64.0/18,10.0.128.0/18,10.0.192.0/18
Total allocated: 3 x 4,096 + 3 x 1,024 + 3 x 16,384 = 64,512 of 65,536. The data blocks sit in the gap between public and app so each tier stays contiguous. Summarising by tier gives clean route and security-group rules.
Routing. Public route table: 0.0.0.0/0 to the internet gateway. Each app route table: 0.0.0.0/0 to the NAT gateway in the same AZ, so a zone failure does not send traffic through another zone. Data route table: local only, no default route. Add S3 and DynamoDB gateway endpoints to the app route tables. They are free and keep that traffic off the NAT gateway bill.
Failure modes.
- Pod IP exhaustion. Pods stick in
ContainerCreatingwithfailed to assign an IP address. Detect it with theAvailableIpAddressCountsubnet metric alerting at about 20% free. The fix is a secondary CIDR (default quota is 5 IPv4 CIDR blocks per VPC) or prefix delegation (/28blocks per ENI), not a rebuild. - Cross-AZ NAT. One shared NAT gateway makes a single-AZ failure an outage for all zones and bills cross-AZ data transfer. One NAT per zone costs more per hour but keeps the blast radius to one AZ.
- Overlap. The on-prem or peered ranges must not overlap
10.0.0.0/16. Check that before the first subnet is created, because renumbering a populated VPC means rebuilding the app tier.
I would not use /16 per zone or one flat app subnet across zones. Each zone needs its own subnet so that scheduling, IP exhaustion and failure stay per zone.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4An instance at 10.10.1.15 in VPC A cannot reach 10.20.3.40 in peered VPC B. The peering is active and A's subnet route to 10.20.0.0/16 is in place. Where does the traffic fail, and how do you prove it?
An active peering proves the control plane accepted the connection. It does not prove either subnet has a route, or that security groups and network ACLs allow the flow in both directions. With A's route to 10.20.0.0/16 confirmed, the first suspect is the return route in B's subnet route table to 10.10.0.0/16 via the same peering connection. You prove it by finding where the SYN stops, not by guessing from one route table.
The VPC router does an independent longest prefix match for each packet. The forward packet and the reply share no route state, so a correct forward route says nothing about the reply.
Worked trace for a missing return route
| Step | Location | Packet | Decision |
|---|---|---|---|
| 1 | A instance | SYN 10.10.1.15:49152 -> 10.20.3.40:5432 | Sent to the VPC router |
| 2 | A subnet route table | Destination 10.20.3.40 | Matches 10.20.0.0/16 -> pcx-..., forwarded over peering |
| 3 | B subnet route table | Destination 10.20.3.40 | Matches local, delivered inside VPC B |
| 4 | B host | SYN arrives on 5432 | Host sends SYN-ACK to 10.10.1.15 |
| 5 | B subnet route table | Destination 10.10.1.15 | No route to 10.10.0.0/16 via peering, packet dropped |
The client sees retransmitted SYNs and a connect timeout, not a TCP RST. A silent drop also matches a security group deny or a NACL deny, so the symptom alone does not isolate the cause.
Prove which side drops it
Capture on both hosts at the same time, using the service port and a window long enough to catch a retransmit:
# On 10.10.1.15 in VPC A
sudo tcpdump -ni eth0 'host 10.20.3.40 and tcp port 5432'
# On 10.20.3.40 in VPC B
sudo tcpdump -ni eth0 'host 10.10.1.15 and tcp port 5432'| Capture result | Meaning | Next check |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| SYN on A, no SYN on B | Forward path fails in A, in the peering, or on entry to B | A's subnet route table association, B's NACL inbound for 5432, B's security group inbound for 5432 |
| SYN on both, no SYN-ACK on B | Packet arrives but host or its security group drops it | B's security group inbound rule for 10.10.1.15/32 on 5432, host firewall |
| SYN-ACK on B, nothing back on A | Return path fails in B or on entry to A | B's route to 10.10.0.0/16 via peering, A's NACL outbound for ephemeral ports 1024-65535 |
Security groups are stateful, so a reply to an allowed inbound connection needs no outbound rule. NACLs are stateless, so both directions need explicit allows. That difference is why the third row points at A's NACL even though the SYN-ACK was generated correctly.
Then confirm the control plane state for the subnets the instances actually sit in:
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=<A-subnet-id>
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=<B-subnet-id>
aws ec2 describe-vpc-peering-connections --vpc-peering-connection-ids pcx-...You want 10.20.0.0/16 -> pcx-... in A, 10.10.0.0/16 -> pcx-... in B, and peering status active. If B's subnet uses the main route table, the route must be there, not in a custom table attached to a different subnet.
Choosing the diagnostic tool
Reachability Analyzer models the control plane for a source, destination, and port, and shows the hop where the path breaks. It is fast when you lack host access or need to compare both route tables before changing anything. It will not show a host firewall drop or a packet that never left the instance, and it reflects configuration at analysis time rather than traffic at failure time. The tcpdump pair costs host access and a capture window, but it proves what actually traversed each host. Use Analyzer to narrow the side, then capture to confirm before and after the fix. VPC Flow Logs for the B subnet ENI corroborate the capture by showing the SYN accepted with no outbound reply flow.
Peering versus transit gateway
| VPC peering | Transit gateway | |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Topology | Direct, non-transitive, one route per side per CIDR | Hub and spoke, routes propagate through the gateway |
| Use it when | Two VPCs need to talk, as here | Many VPCs share services or need central inspection |
| Avoid it when | You need transitive routing through a third VPC, which peering will not provide | Only two VPCs are involved, where the gateway adds cost and a hop for no routing benefit |
Overlapping CIDRs are rejected when a peering is created, so an active peering between 10.10.0.0/16 and 10.20.0.0/16 already rules out overlap on those ranges. A more specific route cannot separate identical blocks, and AWS will not accept the peering in the first place if they collide.
For the common case the fix is one route in B: 10.10.0.0/16 targeting pcx-... in the route table associated with the subnet containing 10.20.3.40. Re-run the capture after adding it. You should see SYN-ACK on B, SYN-ACK on A, and the handshake complete.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5A private subnet's route table has 0.0.0.0/0 pointing at a NAT gateway and 10.20.0.0/16 pointing at a transit gateway. Which target does a packet to 10.20.7.9 use, and how does the router decide when several routes match?
The 60-second answer
The packet goes to the transit gateway. The router compares the destination against every route in the table and keeps the matches. Among those, it picks the one with the longest prefix, meaning the most network bits fixed. 10.20.0.0/16 fixes 16 bits and 0.0.0.0/0 fixes none, so the /16 wins. Its specificity is decided by prefix length, not by the order of entries or by which route was added first.
I'd state the assumption first: this is AWS VPC route tables, where the rule is longest prefix match on the destination IP. The route table is evaluated per packet, at the subnet's ingress to the VPC router, and nothing else in the table gets a vote.
Trace
| Destination | Matching routes | Winner | Target |
|---|---|---|---|
10.20.7.9 | 0.0.0.0/0, 10.20.0.0/16 | /16 (16 > 0 fixed bits) | transit gateway |
93.184.216.34 | 0.0.0.0/0 | /0 | NAT gateway |
10.30.1.5 | 0.0.0.0/0 | /0 | NAT gateway |
The last row is the trap. A host in 10.30.0.0/16 is inside the VPC's address space but has no specific route, so it falls through to the default and goes out the NAT. If you expected that traffic to stay private, the missing route is the bug, and no amount of reordering entries fixes it.
Adding a route can change behaviour silently. Suppose someone adds 10.20.7.0/24 pointing at a VPC peering connection. The /24 has 24 fixed bits, more than the /16, so every 10.20.7.x packet now moves from the transit gateway to the peering connection. Nothing in the subnet changed. Before you add a more specific route, list every destination it will capture, and check the result in the console's route analysis or your own probe, not by reading the table.
Failure modes to name
- Overlapping CIDRs across transit gateway attachments: two attachments advertising the same prefix leads to asymmetric or black-holed flows. Detect it with route propagation reports and VPC Flow Logs showing traffic sent but no response.
- A blackhole route: the longest match is a route whose target is gone (deleted gateway or attachment). The packet is dropped, not forwarded to the next-shorter route. Detect it as a sudden drop with the route showing
blackholestate. - Assuming longest match applies across tables: each subnet has one route table, and a subnet's traffic never consults another subnet's routes.
When not to rely on specificity
For intent that must hold regardless of what other routes get added later, use separate route tables per tier and keep the default route out of tiers that must not reach the internet. Specificity is a correct tie-breaker, but as a control it depends on everyone who edits the table understanding it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6In Route 53, when a private hosted zone and a public hosted zone both contain a record for the same name, which one answers a query from an instance in an associated VPC?
The 60-second answer
The private hosted zone answers. Route 53 Resolver checks the private hosted zones associated with the VPC before it considers a public zone for the same name. A query from the internet never sees the private zone. That is split-horizon DNS: one name, two answers, chosen by where the query originates.
Check it yourself (hypothetical figures)
from an instance in vpc-0a1 (private zone Z_PRIV associated):
dig +short api.payments.corp.example
10.20.4.17 <- record in Z_PRIV
from a laptop on the internet:
dig +short api.payments.corp.example
203.0.113.80 <- record in the public zoneAlternatives, and when each wins
| Setup | VPC instance sees | Internet client sees | Main cost |
|---|---|---|---|
| Single public zone | Public IP | Public IP | Internal-only services have no private name to use. Traffic from the VPC hairpins out to the public IP, which needs a public route back in and exposes the service address in public DNS. |
| Private plus public zones for the same name | Private IP | Public IP | Two records for one name. Every change has to be made twice, and a missed update leaves the two sides pointing at different systems. |
| Different names inside and outside | Internal name resolves privately | External name resolves publicly | No divergence for a single name, but clients, certificates and configuration now carry two names for what is nominally one service. |
Split horizon is worth that sync cost when the internal address should stay out of public DNS, or when internal clients should reach the service over the VPC network rather than via a public IP. A single public zone is simpler when the service is genuinely public, reachable from the VPC at its public address, and has no internal-only counterpart. Separate names are the cleaner choice when the internal and external services differ enough that sharing a name would mislead operators about which system a record describes.
Failure modes to name in the interview
- The rule only applies when the private zone is associated with that VPC. An unassociated private zone is invisible to the instance, which then gets the public answer.
- The VPC needs DNS resolution enabled (
enableDnsSupport) for the Route 53 Resolver to answer from private zones at all. - If the private zone holds the name but no record of the queried type, the instance gets an empty answer (NODATA), not the public record. Clients see a missing record, so the bug looks like it is somewhere else.
- If the two zones drift, the VPC and the internet can be talking to different backends under the same name. That shows up as a service that works from a laptop and fails in the VPC, or the reverse, and the fix is a record change in one zone only.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Your public API hostname points at a primary load balancer with a 300 s TTL. Failover to a standby region must restore traffic for 99% of clients within 5 minutes of the primary failing. Walk through the timeline and show where the budget goes, and say what you change before the incident.
The 90-second answer
The TTL is a ceiling on how long a resolver may keep serving the old answer after you change the record. It is not the failover time. Worst-case cutover is roughly detection time plus the remaining TTL on the stalest cache, plus any client-side caching that ignores the TTL. With a 300 s TTL, the record alone can consume the whole 5-minute budget, so I lower the TTL before any incident and use a health-checked DNS failover policy so the switch is automatic.
Budget with the current setup (hypothetical figures)
| Stage | Assumption | Time |
|---|---|---|
| Health check detection | 10 s interval, 3 consecutive failures | about 30 s, up to 40 s with probe timeout |
| Record change visible at authoritative servers | managed failover, changes propagate in seconds | about 5 s |
| Stalest resolver cache | resolver fetched record 1 s before change | 300 s |
| Client-side cache | JVM positive cache at 30 s default | up to 30 s |
| Total worst case | about 375 s |
375 s misses 5 minutes. Note that the 99th percentile is what matters here, and resolvers that fetched the record just before the change dominate the tail.
What I change
Lower the TTL to 60 s at least 24 h before the change window, so that any resolver holding the old 300 s value has expired it. Then the stalest cache contributes 60 s and the total is about 40 + 5 + 60 + 30 = 135 s. The cost is query volume: a resolver that serves N clients refreshes roughly once per TTL per name, so 60 s versus 300 s is five times the authoritative queries for that name. At 10,000 resolvers that is about 167 QPS against 33 QPS, which is usually fine but should be checked against your DNS provider's billing and rate limits.
Route 53 alias records to an ALB have no TTL you set. They resolve with a 60 s TTL, which already gives you the lower bound. Check this in the current Route 53 documentation before you rely on it, since it is a vendor-controlled value.
Failure modes
- Some resolvers clamp short TTLs upward. Measure from a sample of networks (dig against the resolvers your users actually use) rather than assuming 60 s is honoured.
- Long-lived connections never re-resolve. Keep-alive connections to the old region keep working until the server closes them, so the failover must also drain or close connections at the old load balancer.
- Health checks that test the wrong thing. A health check on
/that returns 200 from a static cache keeps routing to a dead backend. Check a path that exercises the database. - Flapping. A 10 s interval with threshold 3 can fail over on a 30 s blip; add hysteresis and alert on every failover event.
Test it with a game day: fail the primary, time the first successful request from clients in three regions, and record the 99th percentile against the 5-minute target.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Your team runs an HTTP API behind an NLB and is considering an ALB instead. What does each one see of a request, and how do their health checks differ? Which would you keep for this service?
The 60-second answer
An NLB forwards TCP, UDP or TLS connections without reading them. It chooses a target from the connection's 5-tuple, and the client's TCP session runs straight through to the instance. An ALB terminates the client connection, parses the HTTP request, and opens a separate connection to the target. That lets it route on host, path, headers and method, but it also means the ALB, not the client, owns the connection to the app.
For a plain HTTP API with one target group, the NLB is a reasonable choice. The ALB earns its place only if you need path or host routing, HTTP-level health checks, or edge features such as WAF or authentication. Those trade-offs are what I would state first.
| NLB (L4) | ALB (L7) | |
|---|---|---|
| Sees | TCP/UDP/TLS bytes, source IP, port | Method, host, path, headers |
| Routing | 5-tuple hash across targets | Listener rules on host, path, header, query |
| Client IP to app | Preserved for instance targets | Via X-Forwarded-For |
| TLS | Passthrough or terminate | Terminates |
| Health check | TCP connect, or HTTP/HTTPS status | HTTP path with success matcher, default 200 |
| Failure it misses | Process returns 500s but accepts TCP | Route that never reaches the target |
Health checks. A TCP check passes as long as the port accepts a handshake. A process that returns 500 on every request, or has an exhausted thread pool, still accepts TCP and stays in service. An HTTP check against a path that exercises the app's dependencies, with the success matcher set to the exact expected code, catches that. Detection time is interval × unhealthy threshold. With a 30 s interval and threshold 2, a bad target can keep receiving traffic for about 60 s. A 10 s interval cuts that to about 20 s, at the cost of more probe load on every target.
Worked comparison. Suppose the API has 4 targets and 2,000 requests per second, and each target fails silently at t = 0. With a TCP check on an NLB, all four keep passing and about 500 req/s per target keeps erroring until a human notices. With an HTTP check on the same NLB, the failing target drops after about 60 s and the remaining three carry 667 req/s each. The ALB gives the same HTTP check, so the health check decides the outcome more than the layer does.
When to pick each. Keep the NLB if the service has one HTTP API surface, the app can terminate its own TLS, and you want the client IP at the app without header parsing. Move to the ALB when you need several services on one hostname or path prefix, WAF rules, or OIDC authentication at the edge. Do not switch to an ALB expecting it to fix errors caused by the app's own health logic; the health check configuration matters more.
Check current ELB documentation for default intervals and thresholds before quoting them, since they differ by target group type.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9A pod's readiness probe calls the database and returns 503 during a brief DB failover. Explain what the Service does with that pod in the next 15 seconds, and what you would change so one failed check does not pull it out of rotation.
The 90-second answer
The Service removes a pod from its endpoints as soon as its readiness probe has failed failureThreshold times in a row. With periodSeconds: 5 and failureThreshold: 3, a pod that starts failing at t=0 leaves endpoints around t=15 s, and kube-proxy or the endpoint controller propagates that a moment later. Existing connections are not torn down by the probe itself; they drain as the pod stops receiving new ones.
So a 10 s DB failover, probed inline with a 2 s timeout, empties endpoints for most pods. The fix is not to remove the DB check. It is to decouple the probe from a live query, so the probe reports the last known dependency state and a single failed check cannot flip readiness.
The pattern: a background goroutine or thread runs the SELECT 1 every 5 s with a 2 s timeout and writes the result to memory with a timestamp. /readyz reads that cached value. It returns 200 when the last successful check is under 15 s old, and 503 after that. A failover of 10 s then never reaches the probe's failure window.
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
periodSeconds: 5
timeoutSeconds: 1 # the handler only reads memory
failureThreshold: 3 # 15 s of failure before unreadyThe trade-off to state out loud: a cached status is up to 5 s stale, so a pod can accept a request it will fail on for a few seconds. Inline checks are accurate but turn every slow query into an outage for the Service. For a hard dependency you accept the staleness. For a soft dependency, such as a cache with a database fallback, leave it out of readiness and handle it in the request path.
Liveness stays free of dependency checks. If the DB is down, restarting pods does nothing but add a CrashLoopBackOff on top of the outage.
What I'd verify before the incident: run a 10 s DB failover in staging and graph endpoint count per Service next to the 5xx ratio. With the cached check, endpoints should hold through the failover and errors should appear only for requests that hit the dead connection pool. If endpoints drop inside 10 s, the threshold or the probe interval is wrong.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10What is connection draining on an AWS Application Load Balancer, and what is its default window?
The 90-second answer
Connection draining is the period during which the load balancer stops sending new requests to a target that is being deregistered, while requests already in flight are allowed to finish. AWS calls this setting the deregistration delay. The default is 300 seconds, and the allowed range is 0 to 3600 seconds.
The delay only governs what happens to requests already accepted. It does not make a target stop receiving traffic instantly, and it does not protect a request that the target itself abandons.
A useful follow-up is how that differs from the failures that show up as 502 and 504. A 502 Bad Gateway means the target closed the connection or returned an invalid response before the load balancer got a complete reply. A 504 Gateway Timeout means the target did not answer within the load balancer's idle timeout, which defaults to 60 seconds. Draining prevents the first case during a planned deploy, provided the application honours shutdown signals and keeps serving open requests until they finish.
Set the deregistration delay to at least your longest normal request, and no longer than your deploy pipeline can afford to wait. Confirm the current defaults in the AWS documentation for your load balancer type before you quote them.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Same-account role: identity policy allows s3:GetObject on app-bucket/*, permission boundary allows GetObject only on app-bucket/reports/*, and the bucket policy allows GetObject on app-bucket/logs/* for that role. Do GetObject calls on logs/ and reports/ succeed, and how would you prove it?
The 90-second answer
Both succeed. The rule that decides it: an explicit deny anywhere wins, otherwise a request in the same account is allowed if either the identity side or the resource side allows it, and the permissions boundary only caps the identity side. The boundary does not grant anything and it does not cap resource-based grants for same-account principals.
Assumptions: no SCPs, no session policy, no explicit deny in any policy, and the request has no conditions that fail.
| Request | Identity policy | Permission boundary | Bucket policy | Result |
|---|---|---|---|---|
| GetObject logs/x | allow (app-bucket/*) | no match, identity leg fails | allow (logs/*) | allowed |
| GetObject reports/y | allow | allow | no statement | allowed |
| GetObject uploads/z | allow | no match | no statement | denied (implicit) |
Trace for logs/x: the evaluator collects explicit denies across identity policies, the boundary, the bucket policy and any SCPs. None. Then it checks the identity side: the identity policy allows, but the boundary is an intersection with no allow for logs/x, so the identity leg yields no allow. The resource side has an allow from the bucket policy for the same-account role. Same account, so one allow is enough. Allowed.
The trap is treating the boundary as a global filter. It is not one for same-account resource grants. Cross-account changes this: the caller's account must allow through its identity side (inside the boundary) and the resource account must allow through the resource policy, and the boundary intersects with the identity side, so a boundary miss there is a hard deny.
| Case | Identity side must allow | Resource side must allow |
|---|---|---|
| same account, resource policy only | no | yes |
| same account, identity only | yes (boundary included) | no |
| cross account | yes (boundary included) | yes |
One caveat I would not state without checking: which services honour resource-only grants for a principal whose boundary excludes the action. Confirm against the service's IAM actions and resource-policy documentation for the service in question.
Proof, in order:
aws iam simulate-principal-policywith the role ARN, the action, the resource ARN and the boundary as input, plus the bucket policy as--resource-policy. Check the CLI reference for your version, since parameter names have changed. Read theMatchedStatementsandEvalDecisionfields.- IAM Access Analyzer or the Policy Simulator in the console to confirm the same answer from the evaluator.
- A live call from the role, then CloudTrail: an allowed call shows no
errorCode; a denial showsAccessDenied. Search forResourceType: AWS::S3::Objectevents to match the object key.
Failure modes to check when logs/x fails in production: an explicit deny in an SCP or a bucket-level Block Public Access setting that the resource policy cannot override; a KMS key policy missing kms:Decrypt on the role for SSE-KMS objects, which fails with AccessDenied even though S3 allows the read; and a stale boundary from a different environment attached to the role. Explicit deny and implicit deny look identical to the caller, so the simulator's EvalDecision (explicitDeny versus implicitDeny) is what tells you which layer to fix.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12A worker reads objects under one S3 prefix and writes messages to one SQS queue. Its role grants only s3:GetObject on arn:aws:s3:::orders-ingest/inbound/*, yet it logs 403 AccessDenied for keys that are not there yet, and the same key returns 200 once it exists. Explain why, and make the smallest policy change that fixes it without widening access.
The 60-second answer
S3 does not tell a caller whether a key exists unless that caller can list the bucket. The worker has GetObject on the prefix but no listing permission, so a read of a missing key is reported as 403 AccessDenied rather than 404 NoSuchKey. The 403 is not a permissions gap on the object. It is S3 hiding existence. The fix is one more statement: s3:ListBucket on the bucket ARN, with a condition that restricts it to inbound/*.
Assumptions: the worker runs under an IAM role (instance profile, EKS Pod Identity or IRSA), the bucket is in the same account, and the objects are not KMS encrypted for this read.
The mechanism
s3:GetObject is evaluated against the object ARN. s3:ListBucket is evaluated against the bucket ARN, and it is the only action that can carry the s3:prefix condition key. When a GetObject fails for a missing key, S3 checks whether the caller could have learned the key existed. Without ListBucket, it returns 403, so probing cannot distinguish 'no such key' from 'not allowed'. With ListBucket, the missing key returns 404.
The change
{"Version":"2012-10-17","Statement":[
{"Sid":"ReadInbound","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::orders-ingest/inbound/*"},
{"Sid":"ListInboundOnly","Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::orders-ingest","Condition":{"StringLike":{"s3:prefix":"inbound/*"}}},
{"Sid":"SendReady","Effect":"Allow","Action":"sqs:SendMessage","Resource":"arn:aws:sqs:eu-west-1:111122223333:orders-ready"}
]}Without the condition, ListBucket on the bucket ARN would let the worker enumerate every prefix in the bucket, which is a larger grant than the one you started with.
Trace
| Request | Before | After |
|---|---|---|
GetObject inbound/a.json (exists) | 200 | 200 |
GetObject inbound/b.json (missing) | 403 | 404 NoSuchKey |
GetObject outbound/a.json | 403 | 403 |
ListBucket prefix=inbound/ | 403 | 200 |
| ListBucket with no prefix | 403 | 403, condition not met |
The worker should now treat 404 as a race or a bad event (skip or dead-letter), and 403 as a real permissions fault to alert on. Before the change, both looked the same in logs.
Alternatives
The other common fix is to catch the 403 and retry, which hides the cause and turns a configuration error into a slow failure. Granting s3:ListBucket on the whole bucket works but exposes key names under every prefix. The prefix-conditioned grant costs one statement and keeps listing as narrow as reading.
What to check
Run aws iam simulate-principal-policy for the four rows above, including the no-prefix listing case, which must still be denied. Then confirm in CloudTrail that the worker's ListObjectsV2 calls carry prefix=inbound/. If they do not, the condition is not doing its job.
Failure modes
A missing condition, which widens listing to the bucket. A GetObject retry loop that masks 403s as transient. A KMS-encrypted bucket, where the same 403 can come from a missing kms:Decrypt on the object, so check the error on an object you know exists before blaming the listing grant.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Your monitoring vendor's collector assumes a read-only role in each customer account through a cross-account trust. Explain how the external ID stops one customer's vendor tenant from getting the collector to assume another customer's role, and what it does not protect against.
The 90-second answer
The confused deputy problem here: the vendor's collector holds sts:AssumeRole authority across many customer accounts. A tenant that is not ours can ask the collector to act on our role ARN, and the collector, which is trusted by our account, has no way to know the request was not meant for us. The external ID fixes that by binding each assumption to one tenant. Our role's trust policy only allows the assumption when the caller presents the ID the vendor issued for our tenant. A different tenant can present only its own ID, so the assumption fails.
The trust policy names the collector role, not the vendor account root, and requires the ID:
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111122223333:role/vendor-collector"},"Action":"sts:AssumeRole","Condition":{"StringEquals":{"sts:ExternalId":"ext-7Kq2-acme-9f"}}}]}Trace. Tenant B, another vendor customer, submits our role ARN arn:aws:iam::444455556666:role/vendor-readonly as a monitoring target. The collector looks up the ID it holds for tenant B, ext-B1x0-globex-22, and calls:
AssumeRoleon our role withExternalId=ext-B1x0-globex-22.- STS evaluates the trust policy.
StringEqualscompares the supplied value withext-7Kq2-acme-9f. No match. - STS returns
AccessDenied. The collector records the failure against tenant B and touches nothing in our account.
The ID is not a secret credential and does not authenticate the caller. It binds the assumption to a tenant the vendor already knows about, which only works if the vendor issues a distinct ID per tenant and never reuses one.
Trade-off: external ID versus a plain principal trust. Trusting the collector role without a condition is simpler and works until a second tenant's operator learns our ARN. The external ID adds one condition and one piece of vendor-side state to maintain. Its cost is operational: each onboarding has to generate, store and rotate a per-tenant value, and the customer has to paste it into the trust policy correctly.
What it does not protect against.
| Risk | Covered by external ID? | What covers it |
|---|---|---|
| Another tenant names our role ARN | Yes, if IDs are unique per tenant | Vendor-side mapping from tenant to ID |
| Vendor reuses one ID for all customers | No, the check protects nothing | Reject shared IDs at onboarding |
Collector role has sts:AssumeRole on * | Partly, only for roles carrying the check | Scope the collector to registered role ARNs per tenant |
| Collector is compromised | No | Narrow permissions on our role, SCP or permissions boundary |
Failure modes to check first.
- The vendor uses one ID across customers. The policy looks right and the denial never fires. Ask the vendor to show two tenants' IDs side by side.
- Onboarding accepts a role ARN from a different account than the tenant registered. Validate that the account in the ARN belongs to the tenant before any assumption is attempted.
Detection. CloudTrail records the failed call as AssumeRole with errorCode: AccessDenied and the collector's principal. A burst of denials against one role ARN points at a tenant probing roles it does not own. Alarm on the rate per role ARN, not on the total.
Least privilege. The external ID stops the confused deputy and nothing else. Keep the role read-only, and add a permissions boundary or SCP if the account sits in an organization, so a successful assumption cannot reach beyond monitoring.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14What happens to a long-lived IAM access key if it leaks, compared with temporary credentials from an instance profile?
The 90-second answer
A long-lived access key stays valid until someone deactivates or deletes it, so a leaked key works for as long as nobody notices. Temporary credentials from an instance profile carry an Expiration. Once that time passes, the leaked pair stops working, and the SDK has already replaced it on the instance. The one rule to hold: a static key is valid until revoked, and a role session is valid only until it expires.
That single difference sets the blast radius. The leaked key is open-ended. The leaked session is bounded by its lifetime, which is typically a few hours for an instance role.
Comparing the two
| Property | Instance profile | Long-lived access key |
|---|---|---|
| Who holds it | the instance, via metadata | whoever copied the file |
| Validity after a leak | until Expiration (typically hours) | until deactivated |
| Rotation | automatic, SDK refreshes before Expiration | manual, you rotate it |
| Revocation | detach the role, or deny by aws:TokenIssueTime | deactivate or delete the key |
The instance profile's credentials come from the instance metadata service. With IMDSv2 the SDK requests a session token, then reads the role credentials with it:
TOKEN=$(curl -s -X 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/iam/security-credentials/app-roleWorked example (hypothetical figures)
An app's access key leaks on Monday at 09:00 and nobody spots it until Thursday. The key was valid for all four days. The same app on an instance profile leaks a credential set that expires within a few hours, and the attacker's copy stops working on its own.
What to check before you rely on it
- Require IMDSv2 (
HttpTokens=required). With IMDSv1, a server-side request forgery bug can read the credentials from the metadata endpoint. - Find keys that remain.
aws iam list-access-keys --user-name svc-appandaws iam get-access-key-last-usedshow what is still live and when it was last used.
Where a workload cannot assume a role, such as an on-premises agent, the long-lived key stays. Store it in a secrets manager with rotation enabled, and give each key a single purpose.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Your service pulls a database password from AWS Secrets Manager at container start, and a second copy is baked into the image for the migration job. Security wants the password rotated every 30 days without a restart. Walk me through how you would inject secrets at runtime versus baking them in, and what you change so rotation takes effect without restarting the pods.
The 90-second answer
Baking a secret into an image puts it in every layer, in every registry copy, and in every rollback target. Rotation then means rebuilding and redeploying, and the old value lives on in old images. Runtime injection keeps the value out of the artefact and makes rotation a change to the secret store, not the image. The catch is that a secret read once at start is still stale after rotation, so the design has to decide who re-reads it and when.
I would do three things: fetch at runtime through the workload's identity, not a static key; have the app re-resolve the secret on a schedule or on auth failure; and keep the old credential valid during an overlap window so the switch is not a cliff.
Why baking fails here
docker history shows every ENV and RUN step. A secret written in a build step survives in a layer even if a later RUN rm removes it, because the layer is immutable. Any engineer with pull access to the registry can extract it. Multi-stage builds do not fix this for the migration image, since the final stage still carries the value.
The runtime path
The pod's ServiceAccount is bound to an IAM role through IRSA (or EKS Pod Identity). The app calls secretsmanager:GetSecretValue with VersionStage=AWSCURRENT. No long-lived access key exists on the node or in the manifest.
Trace for one rotation with a 30-day schedule and a 4-hour overlap:
| Time | Event | Secret store state | Pod behaviour |
|---|---|---|---|
| T+0 | rotation lambda creates new version | AWSCURRENT=v2, AWSPREVIOUS=v1 | pods still hold v1 |
| T+0 | DB user app_v2 created with same grants | both valid | nothing yet |
| T+5 min | pods re-read on 5 min refresh | v2 in use | v2 in memory |
| T+4 h | app_v1 dropped | v1 invalid | no pod should hold v1 |
The overlap is what matters. Dropping v1 at T+0 breaks any pod that has not refreshed, and any connection pool that already holds a v1 session will keep working until it recycles, which is a different failure from a new connect failing.
Making the app pick up the change
Three options, in order of my preference:
- The app re-fetches on an interval (5 min here) and rebuilds its connection pool on success, so new connections use v2. The AWS Secrets Manager caching client does this with a TTL.
- The app retries once with a fresh secret on an authentication error (
28P01for Postgres). This catches rotations faster than the interval. - Projected volume with the Secrets Store CSI driver and rotation enabled. The kubelet updates the file, and the app watches it. This needs the app to watch the file rather than read once at boot, which many do not.
I avoid option 4, restarting pods on rotation, because a rolling restart of 200 pods to swap one password is a self-inflicted outage risk and it hides the real bug, which is that the app caches credentials forever.
Failure modes to detect
- Pool holds v1 after v1 is dropped: connections fail only when the pool recycles. Detect with a metric on auth failures by secret version, and alert on any non-zero rate after the drop.
- Migration job still uses the baked copy: the job works until the baked value rotates out. Remove the baked value and make the job fetch at runtime too.
- Refresh storms: 200 pods polling Secrets Manager every second. At the default per-account quota this throttles. Use a 5 minute jittered interval and cache.
- Rotation lambda and app disagree on the secret's JSON key: the new version parses wrong and every pod keeps v1 silently. Validate the new version against a canary connection before promoting it to
AWSCURRENT.
What I change before the incident
Bake nothing. Move the migration job to the same runtime fetch. Add the refresh and retry logic, then run one rotation in staging and read the auth-failure metric by version before enabling it in production. Only then set the 30-day schedule.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Terraform marks a database password as sensitive, but the value still shows up in plaintext in the state file. Why does that happen, and how would you limit who can read that state?
The 90-second answer
sensitive = true only hides a value in plan and apply output. Terraform must keep the real value in state, because on the next run it diffs state against configuration to decide whether to update a resource. So state holds every attribute the provider returned, in plaintext JSON, including the ones you marked sensitive. You cannot hide values inside state. You control who can read the state object, and you keep secrets out of state where the provider allows it.
Assumptions: S3 backend, Terraform 1.10 or later, AWS provider v5 or later.
Trace (hypothetical values):
$ jq -r '.resources[] | select(.type=="aws_db_instance") | .instances[0].attributes.password' terraform.tfstate
h7Qd-example-onlyThe same value appears in every stored version of the state object.
Limiting access, in order of impact
- Keep the secret out of state. Write-only arguments (Terraform 1.11+) are not persisted in state or plan, so check whether your resource exposes one. Where it does not, let Secrets Manager generate or rotate the secret outside Terraform and pass only the ARN. Note that
random_passwordwrites its result to state. - Encrypt with a customer managed KMS key:
encrypt = trueandkms_key_idon the S3 backend. With SSE-KMS, reading state needskms:Decrypton the key as well ass3:GetObjecton the object, so the key policy becomes a second gate. - Restrict the bucket policy to the CI role and one break-glass role. Deny requests where
aws:SecureTransportis false. Engineers get plan output through CI, not raw state reads. - Split state by environment and layer. Someone with read access to dev state should not be able to read prod.
- Versioning keeps old copies that contain the secret. Apply the same restriction to noncurrent versions and expire them on a schedule.
- Saved plan files (
terraform plan -out) contain values too. Encrypt them or delete them at the end of the CI job. - Use
use_lockfile = truefor locking on Terraform 1.10+ rather than adding a DynamoDB table.
Failure mode and detection
A developer gets s3:GetObject on the state prefix to debug a failed apply, and that role can read the production password. Nothing in Terraform output shows the read. Enable CloudTrail data events on the state bucket and alert on GetObject from principals other than CI and break-glass.
Trade-off
Terraform Cloud and HCP Terraform encrypt state at rest, but anyone with workspace read access can still pull state through the API, so the same question about who can read state applies there. Managed storage moves the storage problem; it does not remove the access decision.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17You need PostgreSQL for an order service. Compare patching responsibility for Amazon RDS for PostgreSQL against PostgreSQL on a self-managed EC2 VM. Who patches what, and where is each option exposed?
The 90-second answer
On RDS, AWS patches the host, the operating system and the database engine's minor versions, on a schedule you control. You patch nothing below the engine and you have no shell on the box. On EC2, AWS patches the hypervisor and hardware, and you patch everything above that: guest OS, kernel, PostgreSQL binaries, extensions and the agents you install. The question is not who has the duty to patch. It is who decides when, who verifies it, and who gets paged when it goes wrong.
| Layer | RDS for PostgreSQL | PostgreSQL on EC2 |
|---|---|---|
| Hardware, hypervisor | AWS | AWS |
| Guest OS and kernel | AWS, during maintenance window | You |
| PostgreSQL minor version | AWS auto minor upgrade, or you apply manually | You |
| PostgreSQL major version | You initiate; not automatic | You |
| Extensions, parameter tuning | You (within supported list) | You |
| Detection of missing patches | Pending maintenance actions | Patch compliance tooling you run |
What I would say first. Use RDS unless the workload needs something RDS blocks: a custom kernel setting, an unsupported extension, or a host agent. Then the patching burden is mostly about scheduling and testing, not about doing the work.
RDS mechanics. Set a preferred maintenance window per instance. Pending updates appear through aws rds describe-pending-maintenance-actions, and some are mandatory with advance notice. Minor version upgrades can be automatic if the instance has auto minor version upgrade enabled, so check that setting rather than assuming it. On a Multi-AZ instance, OS patching involves a failover, so the application must reconnect cleanly and retry. Major version upgrades never run unattended; you test them against a copy of production.
EC2 mechanics. You own a patch baseline and a window, and you must reboot the VM to pick up kernel updates. A common setup uses AWS Systems Manager Patch Manager with a maintenance window, and Inspector or Patch Manager compliance reports to show what is still missing. PostgreSQL itself is installed from a repository or AMI, so you pin the minor version and roll it forward deliberately.
Failure modes to name.
- RDS minor upgrade changes a planner behaviour and a query regresses. Detection: a staging instance on the same target version, run with a replay of production queries before the window.
- EC2 kernel patch reboots the only primary at 02:00 because nobody set a window. Detection: uptime and compliance dashboards that flag hosts with pending reboots.
- EC2 VM drifts: half the fleet is on 15.4, half on 15.7, because one host missed a run. Detection: a version inventory query across instances, compared to the target.
- RDS parameter group left on an old default after a major upgrade. Detection: a config drift check against the parameter group you intend to use.
Trade-off. RDS removes a large class of toil and makes patching state visible through an API. It costs you control: no host access, a fixed set of extensions, and a patching clock you cannot pause indefinitely. EC2 gives full control and the same duties, plus the inventory, reboot scheduling and compliance reporting you would otherwise have bought as a managed service.
I would state the answer as: RDS shifts the OS and engine patch work to AWS and leaves timing and verification with you. EC2 keeps all of it with you.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18What is the minimum waiting period you can set when scheduling a customer managed KMS key for deletion?
The 30-second answer
Seven days. ScheduleKeyDeletion accepts a PendingWindowInDays value from 7 to 30, and the default is 30. Within that window the key sits in PendingDeletion, and CancelKeyDeletion returns it to Disabled so you can re-enable it.
The window exists because deletion is permanent. Once it elapses, KMS removes the key material. Any data encrypted under that key can no longer be decrypted, because envelope encryption stores each object's data key encrypted under the KMS key, and that key is gone.
aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7
aws kms cancel-key-deletion --key-id <key-id>If someone asks why you would not always pick 7 days: a longer window gives more time to notice a mistaken deletion and to find services still depending on the key. The trade-off is that a genuinely unwanted key lingers longer. Pick the value your team can actually monitor during the window, and confirm the key's KeyState with describe-key before assuming the deletion was cancelled.
What to say in the room: the minimum is 7 days, the default is 30, and nothing is lost until the window closes.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Two terraform apply runs start against the same S3 backend, configured with use_lockfile = true, within the same second. Walk through what each process does, what the second one sees, and what the lock does not stop.
The 90-second answer
The state lock is mutual exclusion on the state object. It is not mutual exclusion on the infrastructure. Terraform takes the lock before it reads state for plan or apply, and holds it until the run exits. With the S3 backend and use_lockfile = true (Terraform 1.10 or later), the lock is a <key>.tflock object written with a conditional create, so the first writer wins atomically. The second apply does not queue. The default -lock-timeout is 0s, so it fails with Error acquiring the state lock and shows the holder's ID, operation, who and created time.
So concurrency is refused at the state layer. Whether the cloud resources stay consistent is a separate question, and that is what this question tests.
terraform {
backend "s3" {
bucket = "acme-tfstate"
key = "net/prod/terraform.tfstate"
region = "eu-west-1"
use_lockfile = true
encrypt = true
}
}| Time | Run A (apply) | Run B (apply) | Lock object |
|---|---|---|---|
| t0 | reads state, writes .tflock | absent, then created by A | |
| t1 | plans | conditional PUT (If-None-Match: *) returns 412 | held by A |
| t2 | applies route change to VPC | exits: Error acquiring the state lock | held by A |
| t3 | writes new state, deletes .tflock | deleted | |
| t4 | operator re-runs, now succeeds | created by B |
What the lock does not stop
The lock covers one state file. It does not cover:
- Two pipelines using different
keyvalues that both manage the same VPC or route table. Each state is internally consistent and each apply succeeds, and the second one overwrites the first's changes or fails on a duplicate. - A run started with
-lock=false. Plan takes the lock by default, so someone who disables it has opted out of the one guarantee you have. - Console or CLI edits during a run. Terraform refreshes at the start, so a change made after refresh becomes drift that the next plan has to reconcile, and it may revert the change.
- A saved plan applied after another run changed state. Terraform checks lineage and serial and refuses with
Saved plan is stale, which is the lock working as a freshness check, not a conflict resolver.
Crashed holders
If run A is killed (runner evicted, network drop), the lock object stays. Confirm no process is still alive, then run terraform force-unlock <LOCK_ID>. Unlocking while A is still writing state is how state gets corrupted.
Trade-off against DynamoDB
The older dynamodb_table backend uses a conditional PutItem on LockID. It gives the same atomic exclusion. Terraform 1.11 documents it as deprecated in favour of use_lockfile, but it still works. Keep it only if you already run that table and need lock records outside the state bucket.
Proving it and detecting it
To prove the lock in a sandbox, start two applies with -lock-timeout=0 and check that the second exits with the lock error and that no resource changed. In production, enable bucket versioning so any bad state write can be rolled back, alert on force-unlock in CI logs, and check S3 access logs or CloudTrail for 412 responses on the .tflock key to see how often runs collide.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Your next terraform plan wants to remove an ingress rule that someone added to a production security group in the console. Should you codify it or revert it, and what Terraform resource shape decides whether a console-added rule survives the next apply?
The 90-second answer
I decide the owner of the rule first, then pick the Terraform resource shape that enforces that decision. The plan only tells me the drift exists. It does not tell me whether the rule is legitimate.
The mechanism is what matters. In aws_security_group, the inline ingress and egress blocks are authoritative: Terraform treats the full rule set as the desired state, so any rule not in the config is removed on the next apply. aws_vpc_security_group_ingress_rule is non-authoritative per rule: Terraform manages only the rules it created, and a console rule with a different ID is left alone. So the same drifted rule gets removed in one shape and survives in the other. That is the choice I have to make consciously.
If the rule is legitimate, I codify it. I add it to config, run terraform plan, and confirm it shows no change. If it is not legitimate, I apply the removal. Either way I check who added it in CloudTrail (AuthorizeSecurityGroupIngress) before deciding, because a rule added by a pipeline may be the real owner.
Trace
The plan below is hypothetical, with a made-up port.
$ terraform plan
~ resource "aws_security_group" "api" {
~ ingress = [
- { from_port = 8443, to_port = 8443, protocol = "tcp", cidr_blocks = ["10.40.0.0/16"] },
]
}The - line means the inline block would remove the rule. If the group had been managed with aws_vpc_security_group_ingress_rule resources instead, the same console rule would not appear in the plan at all.
| Situation | Resource shape | Result on next apply |
|---|---|---|
| Console rule should be removed | inline ingress blocks | removed, in-place |
| Console rule should stay | inline ingress blocks | must be added to config, or it is removed |
| Console rule should stay, other rules are managed by a pipeline | per-rule resources | survives untouched |
Trade-off
Inline blocks give a complete, reviewable picture of the group, and drift is loud. The cost is that anything outside the config is treated as wrong. Per-rule resources tolerate out-of-band rules, but the group's full rule set is no longer visible in one block, and you can end up with two sources of truth if someone also edits the group inline. I pick one shape per security group and do not mix them.
Failure modes
A lifecycle { ignore_changes = [ingress] } hides the drift, so the config and the live group diverge silently. I treat it as temporary.
Renaming the group or changing its vpc_id is ForceNew, so it destroys and recreates the group and detaches it from its ENIs. Rule reconciliation should never need that, so if a plan shows -/+ on the group, I stop and find the cause.
If I want the rule under Terraform control without changing AWS, I run terraform import for the rule resource. terraform state rm only forgets it, and the next plan then tries to create it again.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Your Terraform root module has grown to 180 resources and plans take eleven minutes. Compare splitting it into child modules within one root against splitting it into separate roots with their own state, and say which you would pick for a team that owns networking and EKS separately.
The 90-second answer
A child module is a unit of reuse. A root module is a unit of state and apply. Splitting into child modules keeps one state file and one plan, so references between parts stay plain and nothing can drift out of sync. Splitting into separate roots gives each part its own state and its own apply, which shortens plans and limits blast radius, but the parts must now share values through a published interface. For two teams that own networking and EKS separately, I would split the roots, because the lock and review problems come from one shared apply, not from file size.
Where the time goes. Plan time scales with the number of resources refreshed in one state. With 180 resources, refresh alone can run for minutes before any diff is computed. Splitting roots cuts that to the resources each root holds. Child modules do not cut it at all: the same 180 resources still refresh in one plan.
| Dimension | One root, child modules | Separate roots |
|---|---|---|
| plan time | unchanged, 180 resources refreshed | scales with each root's resources |
| state lock | one lock, teams queue | one lock per root |
| cross-part references | direct, e.g. module.vpc.private_subnet_ids | published outputs or lookups |
| blast radius of a bad apply | whole stack | one layer |
The interface between roots. The network root publishes its subnet and security group IDs, and the EKS root reads them. Do not use terraform_remote_state for this: it needs read access to the whole network state file, which can hold secrets and state for resources the EKS team should not see. Publish the handful of IDs as SSM parameters or tags, and read them with data sources. The network team owns the contract, and changing a published name is a breaking change.
Versioning. If networking is a shared module, pin it: version = "~> 4.2" for a registry module or ?ref=v4.2.1 for git. A local path module has no version of its own and moves with the commit, so a networking change lands in every root that calls it on its next apply. Commit .terraform.lock.hcl in each root so provider versions are fixed per root.
Moving resources safely. Moving the database or the VPC from one root to another without a migration makes the plan show destroy-and-create. Use terraform state mv in the source root and import in the target, or removed blocks with lifecycle { destroy = false } so state is forgotten rather than deleted. Then confirm the target plan shows no changes before the source apply runs.
Failure mode to catch in CI. Any plan that contains destroy on aws_db_instance, aws_eks_cluster or a subnet is a blocking check. Detect it with a JSON plan (terraform show -json) and fail the job on those action types, rather than relying on a reviewer to notice one line in eleven minutes of output.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22In Terraform, what identifies a resource created with count, so that it can be matched to its state entry?
The 90-second answer
A resource created with count is identified by its index: aws_subnet.this[0], aws_subnet.this[1], and so on. Terraform matches each state entry to a config block by that address, and the index is the position in the count, not the value the instance was built from.
That has one practical consequence worth stating in the interview. If you remove an element from the middle of a list that drives count, the later elements shift down to lower indexes. Terraform then sees a changed attribute at [1] and a missing [2], not a deleted subnet and a surviving one. With for_each over a map keyed by name, the address is aws_subnet.this["private-b"], so removing one key destroys only that address. This is why I use for_each for anything that can be removed or reordered, and reserve count for fixed-size sets that never change order.
Trace with count = length(var.cidrs) and var.cidrs = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"], then remove 10.0.2.0/24:
| State address | Before | After | Plan action |
|---|---|---|---|
[0] | 10.0.1.0/24 | 10.0.1.0/24 | no change |
[1] | 10.0.2.0/24 | 10.0.3.0/24 | update, or replace if cidr_block forces it |
[2] | 10.0.3.0/24 | (none) | destroy |
For an aws_subnet, changing cidr_block forces replacement, so the [1] row can mean destroying and recreating a subnet that holds running instances.
When not to use count: when the set can change, or when you need stable addresses. for_each requires keys known at plan time and rejects duplicate list values in a set, so check that the key set is computable before the apply. A moved block (Terraform 1.1 and later) can rename existing state addresses, but it only covers the renames you declare. Confirm against the Terraform language docs for count and for_each for your version.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23An RDS instance is managed by a Terraform stack that sets prevent_destroy, and its owner is moving it to another stack. Walk through the applies that get it there without deletion, and say what each guard does and does not stop.
The 90-second answer
There are two guards and they fail in different places. prevent_destroy is a plan-time check, and Terraform evaluates it against the configuration of the resource it is about to destroy. deletion_protection is enforced by RDS itself. Deleting the Terraform block deletes the first guard along with it, so the move must never produce a destroy plan. Assumptions: Terraform 1.7 or later (for removed blocks), AWS provider 5.x, one aws_db_instance.orders.
Sequence:
- Confirm
deletion_protection = trueis set in the old stack and applied. Verify withaws rds describe-db-instances --db-instance-identifier orders-prod --query 'DBInstances[0].DeletionProtection'. - In the old stack, remove the resource block and add:
removed {
from = aws_db_instance.orders
lifecycle {
destroy = false
}
}The plan reports the instance as no longer managed, with 0 to destroy. The apply drops it from state and leaves the database alone.
- In the new stack, add an
importblock withid = "orders-prod"andto = aws_db_instance.orders, and setprevent_destroy = truethere. Plan shows one import and no destroy. Apply. - Run plan again. It must be empty. If it proposes an update, the config does not match the live instance, usually on parameter group, engine version or the master password, which the API never returns.
Ordering matters. If the new stack imports while the old stack still manages the instance, two states own it. The next old-stack plan then sees a destroy the old prevent_destroy may or may not cover, depending on whether its block survived.
| Action | Blocked by prevent_destroy? | Blocked by deletion_protection? |
|---|---|---|
Delete the resource block with no removed block | No, the guard is gone with the block | Yes, if API delete is attempted |
terraform state rm | No | Yes |
Change identifier (forces replacement) | Yes, if the block is still present | Yes |
terraform apply -replace | Yes | Yes |
Console or delete-db-instance with protection off | No | No |
The trap is step 2 done carelessly: a bare deletion of the block gives a plan with 1 to destroy and nothing in the code to veto it. The removed block is reviewable in the PR and keeps the destroy count at zero.
Failure modes and detection:
- A PR removes the block with no
removedblock. Detect it by failing CI when a plan JSON contains adeleteaction onaws_db_instance, or with a policy check. - Import drift after step 3. Detect it from the non-empty plan in step 4. Fix it with
ignore_changeson the password only, not on anything that changes the engine. - A later rename of the identifier. Detect it because the plan shows replacement, which
prevent_destroyblocks in the new stack.
skip_final_snapshot defaults to false, so an intentional destroy needs final_snapshot_identifier set, and a manual snapshot taken first is the safer habit. None of this protects against someone with RDS admin rights who turns off deletion protection and deletes the instance outside Terraform. That needs an IAM condition or an SCP.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24Your service runs on 40 EC2 instances and gets patched monthly. Compare rolling out a newly baked AMI by replacing instances with configuring the running hosts in place. What drift does each approach create, and how do you detect it?
The 90-second answer
Bake a new AMI with Packer, publish a new launch template version, and let an Auto Scaling group instance refresh replace instances. Each instance then matches one image ID, and rollback means pointing the group at the previous AMI. Configuring running hosts with Ansible or an SSM association converges each host toward a desired state, but the hosts drift apart over time: each one carries its own history of package upgrades, failed runs and manual fixes. I'd bake, because the question I need answered during an incident is "what exactly is running?" and an image ID answers it.
The immutable approach does not remove drift. It moves it. Anything read at boot (user data, parameters, secrets fetched at start) still varies per instance, and an instance can run for months after its image was superseded if nothing terminates it.
| Immutable AMI and instance refresh | In-place configuration | |
|---|---|---|
| Unit of change | new image ID | per-host convergence run |
| Rollback | previous launch template version | reverse playbook, if one exists |
| Drift source | boot-time inputs, long-lived instances | manual changes, failed or skipped runs, package versions differing by host |
| Detection | ImageId of each instance vs launch template | ansible-playbook --check --diff or SSM association compliance |
| Typical failure | refresh stalls on a failing health check | a host fails halfway and is left in a mixed state |
Worked figures (hypothetical). With 40 instances, MinHealthyPercentage: 90 means at most 4 are replaced at a time. If each replacement needs a 120 s warm-up before it counts as healthy, a full roll is about 10 batches × 120 s ≈ 20 minutes, plus boot and drain time. A stuck refresh shows up as instances that stay on the old image ID past that window.
Detection. For immutable hosts, compare each instance's ImageId with the image in the group's current launch template version, and alert on any instance older than your rotation period. For in-place hosts, run the playbook in check mode on a schedule, or use SSM State Manager association compliance, and treat a non-compliant host as an incident, not a backlog item.
Failure modes to name. A baked AMI that includes a secret or a stale CA bundle spreads that fault to every instance. A refresh that keeps failing health checks can leave the group half on each image, so you need the old version still available to roll back to. In-place runs that succeed on 38 of 40 hosts leave two hosts silently different, which is the drift you least want during a patch window.
My default is immutable for the application tier and in-place only for the thin layer I can't rebake without a change window, with that layer's drift checked on a schedule.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Your Dockerfile copies the whole repo before running npm ci, so every commit reinstalls dependencies. Explain what the layer cache keys on, and what you would change to make a one-line source edit skip the install.
The 90-second answer
A layer is reused only when its instruction matches and every layer above it was also reused. For COPY, the check is on the content of the copied files, so changing any file that COPY picks up invalidates that layer and every layer below it. In the current Dockerfile, COPY . . sits above npm ci, so editing src/handler.ts busts the cache for the install too. The fix is to copy only the manifests and lockfile, run the install, and then copy the source.
FROM node:20-bookworm-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run buildTrace for a one-line edit to src/handler.ts (timings are hypothetical, for arithmetic only):
| Step | Cache check | Result | Time |
|---|---|---|---|
COPY package.json package-lock.json | checksums unchanged | HIT | 0 s |
RUN npm ci | parent and command unchanged | HIT | 0 s |
COPY . . | src/handler.ts checksum changed | MISS | 1 s |
RUN npm run build | parent missed | MISS | 20 s |
Before the change, the same edit reruns a 70 s hypothetical install. At 40 builds a day that is about 47 minutes of avoidable installs. Copy the lockfile with the manifest, because copying package.json alone lets npm ci resolve differently from what the lockfile pins.
What the check does not see. A COPY checksum covers file content, mode and ownership, not mtime. A .dockerignore that omits node_modules and .git matters here: a local node_modules in the context changes the COPY . . input on every build, so the install step is not the only thing that busts. Check the context size in the build log when a cache that should hit keeps missing.
Multi-stage. Once the cache is ordered correctly, split the build when the image also ships tooling. Build in one stage, then copy only dist and production node_modules into a clean runtime stage. Compilers, dev dependencies and the npm cache stay out of the shipped image.
Keeping the cache on CI runners. RUN --mount=type=cache keeps the npm download cache across builds without freezing it into a layer, but it lives on the builder. Ephemeral CI runners start cold, so export layers with --cache-to type=registry,ref=<repo>:buildcache,mode=max and import them with --cache-from on the next run. mode=max includes intermediate stages; the default exports only the final image's layers.
Failure modes
--no-cachein CI hides the ordering bug and makes every build pay the install cost.- A cache that stops printing
CACHEDfor a step means an input to that step changed. Check which file the precedingCOPYpicked up.
Trade-off. Reordering the COPY lines is a one-line change that captures most of the win on a single service. Registry cache and a multi-stage split add push and pull time and another stage to reason about, so add them when CI runners are cold or the build ships tooling.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26A Deployment has 4 replicas, maxSurge 1 and maxUnavailable 0. What is the most pods that can exist at once during a rolling update, and why?
The 60-second answer
At most 5. maxSurge is the number of pods allowed above replicas during the update, so the ceiling is replicas + maxSurge = 4 + 1 = 5. maxUnavailable is the number of pods allowed below replicas, so with 0 the floor is replicas - maxUnavailable = 4 ready pods at every moment. The controller therefore creates one new pod, waits for it to pass readiness, and only then terminates one old pod. Repeat four times and the rollout is done.
The two fields govern different sides of the count, and both are percentages or integers. Defaults are maxSurge: 25% and maxUnavailable: 25%. Percentages resolve differently: maxSurge rounds up and maxUnavailable rounds down. With 4 replicas at 25%, surge is ceil(1.0) = 1 and unavailable is floor(1.0) = 1. With 3 replicas, surge is ceil(0.75) = 1 and unavailable is floor(0.75) = 0. Setting both to 0 is rejected by the API server, because the rollout could never make progress.
Trace of the update, replicas 4, surge 1, unavailable 0
| Step | Old ready | New created | New ready | Total pods |
|---|---|---|---|---|
| start | 4 | 0 | 0 | 4 |
| 1 | 4 | 1 | 0 | 5 |
| 2 | 4 | 1 | 1 | 5 (one old pod terminating: 4 old, 1 new ready) |
| 3 | 3 | 1 | 1 | 4 (one old removed, next new created) |
The step-2 row needs care: the old pod is only scaled down after the new pod reports Ready, which is why ready count never drops below 4.
Why a rollout stalls
The rollout stops when the new pod never becomes Ready. With maxUnavailable: 0, the controller cannot delete an old pod until a replacement is ready, and with maxSurge: 1 it cannot create a second replacement while the first is stuck. Common causes:
- A readiness probe that fails on the new image (wrong port, a dependency it calls at startup).
ImagePullBackOfforErrImagePull, usually a missing tag or a private registry without an imagePullSecret.- Insufficient capacity: on EKS the new pod stays
Pendingbecause the node group has no room for the surge pod, and the managed node group does not scale unless Cluster Autoscaler or Karpenter is present. - A
PodDisruptionBudgetthat blocks eviction of the old pods.
Detection:
kubectl rollout status deploy/api --timeout=5m
kubectl get deploy api -o jsonpath='{.status.conditions[?(@.type=="Progressing")]}'After progressDeadlineSeconds (default 600 s) with no progress, the Progressing condition becomes False with reason ProgressDeadlineExceeded, and rollout status exits non-zero. The Deployment does not roll back on its own. The old pods keep serving, which is why the zero-unavailable setting is safe, but the stuck ReplicaSet stays until someone runs kubectl rollout undo deploy/api.
When I want the rollout to move even at the cost of capacity, I set maxUnavailable: 1 with maxSurge: 0 or 1, accepting a dip to 3 ready pods in exchange for not depending on surplus capacity. For a tight-capacity cluster that is the trade to name out loud.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27Walk through what the Service does with a new pod that fails its readiness probe during a rolling update, and what the Deployment controller does next, using the default surge and unavailable settings.
The 90-second answer
Assume 8 replicas, a Service selecting app=checkout, the default maxSurge: 25% and maxUnavailable: 25%, progressDeadlineSeconds: 600, and no minReadySeconds. The first new pod starts, its readiness probe returns 500, and the pod sits at Running with Ready=False.
The Service does nothing special. The EndpointSlice controller adds a pod IP to the slice only while its Ready condition is true. The unready pod never receives traffic, and the old pods that are still ready keep serving. There is no weighting toward the new pod and no partial exposure.
The rollout is where it gets interesting. Rounding is up for surge and down for unavailable, so 25% of 8 gives a surge of 2 and an unavailable budget of 2. Trace it, with hypothetical timings omitted and only the replica bookkeeping shown:
| Step | Old RS ready | New RS ready/desired | Total pods | Why |
|---|---|---|---|---|
| start | 8 | 0/0 | 8 | steady state |
| 1 | 8 | 0/2 | 10 | surge budget of 2 spent on the new RS |
| 2 | 6 | 0/2 | 8 | old RS may drop to 8 minus 2 = 6 available |
| 3 | 6 | 0/4 | 10 | surge refilled, new pods still unready |
| 4 | 6 | 0/4 | 10 | available is at the floor of 6, so no more old pods are removed |
It then stalls. The controller cannot tell a slow pod from a dead one, so it waits. Six pods now carry the load of eight, which is 33% more requests per pod, and p99 on those six is the number to watch. Nothing is broken yet, but capacity is quietly down by a quarter.
At 600 s with no new pod becoming available, the Deployment's Progressing condition goes False with reason ProgressDeadlineExceeded. Nothing rolls back. kubectl rollout status exits non-zero, and that is the signal a pipeline should act on. The old ReplicaSet stays in place with its revision history (revisionHistoryLimit defaults to 10), so kubectl rollout undo deployment/checkout restores the previous template.
What I check, in order:
kubectl get endpointslices -l kubernetes.io/service-name=checkout: the new pod IP is absent, which confirms the Service is not sending it traffic.kubectl describe pod: events showReadiness probe failed: HTTP probe failed with statuscode: 500, which tells me the probe is failing, not the container crashing.kubectl get deploy checkout -o jsonpath='{.status.conditions}': confirm theProgressingreason.
What I change for a fragile service: set maxUnavailable: 0 and maxSurge: 1 so old capacity never drops below spec during a rollout, at the cost of slower rollouts. Set minReadySeconds so a pod that passes one probe and then flaps does not count as available. Check that the readiness probe reflects this container's ability to serve, and that it does not fail only under load, because that produces a rollout that looks healthy and then stalls once real traffic arrives.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28A pod with a 1 CPU limit has p99 latency spikes while node CPU sits at 40%. Explain why the node looks idle, and what you would change on the limit.
The 90-second answer
The node looks idle because the pod is blocked by its own CPU limit, not by contention on the node. A CPU limit becomes a CFS quota. The kernel lets the container's threads run for 1 CPU worth of time per scheduling period, and once that budget is spent, every thread in the container stops until the next period starts. Other pods on the node still have free CPU, so node-level averages stay low while this pod's requests queue.
The mechanism
With the default cpu.cfs_period_us of 100 ms, a 1 CPU limit grants 100 ms of CPU time per 100 ms period, summed across all threads. Assume the service runs 4 busy threads during a burst:
period starts t=0: 4 threads run in parallel
quota of 100ms CPU is spent at t=25ms (4 threads x 25ms)
throttled from t=25ms to t=100ms (75ms of wall time, all threads stopped)
next period starts at t=100msRequests that arrive in the throttled window wait up to 75 ms before any work happens. That delay sits in the tail, so p99 moves while the average barely does.
How to confirm it
Compare container_cpu_cfs_throttled_periods_total with container_cpu_cfs_periods_total. Throttled periods divided by total periods above a few percent on a latency-sensitive service means the quota is the bottleneck. Node CPU at 40% alongside that ratio is the pattern to look for.
Trade-offs of the two fixes
| Option | Effect on latency | Risk |
|---|---|---|
| Raise the CPU limit to cover bursts | throttling drops as the quota grows | pod can take more of a busy node |
| Remove the CPU limit, keep the request | no quota stalls; pod still gets its share under contention | a runaway thread can use spare node CPU |
The CPU request still sets the pod's weight when the node is busy, so removing the limit does not give it priority over other pods. It only stops the quota from stalling it when the node has room.
What I would change
Set the CPU request to observed steady-state usage so the scheduler reserves enough. For a latency-sensitive service I would remove the CPU limit and rely on the request. Keep a memory limit, since memory overuse ends in an OOM kill with no graceful degradation.
After the change, rerun the load test and watch the throttling ratio and p99 together. The ratio should fall to near zero and p99 should follow it down.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29A Service of type LoadBalancer on EKS, with externalTrafficPolicy set to Local, sends traffic to a node that has no ready pod for it. What happens to that connection, and how does kube-proxy's behaviour differ from the default Cluster policy?
The 60-second answer
With externalTrafficPolicy: Local, kube-proxy on the receiving node only forwards to a ready endpoint on that same node. If there is none, the packet is dropped, not forwarded. The load balancer is expected to stop sending traffic there: the Service exposes a healthCheckNodePort, and kube-proxy answers that health check with failure on any node that has no local ready pod. The default Cluster policy does the opposite. The node picks any ready pod in the cluster, DNATs to it and masquerades the client to the node IP, which costs an extra hop and loses the client source address.
So the trade-off is client IP and a single hop against even load and an LB that must health-check at node granularity.
Trace (hypothetical values). Service checkout with NodePort 31080, healthCheckNodePort 32411, and ready endpoints 10.0.2.17:8080 on node A and 10.0.3.9:8080 on node B. Node C has no local pod.
- Under
Local, a connection that reaches node C on31080finds no local endpoint in the per-service chain, so it gets no DNAT and is dropped. A health probe toC:32411returns a failure, so the LB removes node C from its target group. Connections that land on A or B are DNAT'd to the local pod, and the source IP the pod sees is the client's. - Under
Cluster, the same connection on node C is DNAT'd to10.0.3.9on node B, and SNAT'd to node C's IP. The pod sees10.0.x.yfor node C, the reply returns through C, and the health check on C reports healthy.
Arithmetic on skew. Suppose the LB spreads connections evenly over the nodes that pass health checks. If node A has two pods and node B has one, each node gets half the traffic. Node A's pods then take 1/4 each and node B's pod takes 1/2, so one pod carries twice the load of another. Topology spread constraints remove this skew and make Local safe to use.
Failure modes and how to detect them
- Client IP missing in logs under
Cluster: application logs show node addresses. Check the Service'sexternalTrafficPolicy. - Nodes flagged unhealthy under
Local: the target group shows nodes with no local endpoint failing theirhealthCheckNodePortprobe. This is expected. Confirm that the failing nodes are the ones without a pod. - Dropped connections on a node with no pod: a stale LB target still points at that node after its pod moved. Check the target group health interval against the time it takes kube-proxy to update.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30Which component terminates TLS for a public HTTPS service behind an AWS Application Load Balancer with an ACM certificate on its listener?
The Application Load Balancer terminates TLS. Its HTTPS listener presents the ACM certificate, completes the handshake with the client, decrypts the request, and forwards plain HTTP to the target group unless backend re-encryption is configured. The ingress controller inside the cluster then routes the decrypted request by host and path to a Service. Certificate renewal happens in ACM and takes effect on the listener without restarting pods.
That placement decides which alternatives are credible. Each one moves the private key and the handshake to a different component, and each loses something the ALB gives you. An ALB supports only HTTP and HTTPS listeners, so it cannot pass encrypted traffic through untouched to the ingress controller. That option requires an NLB.
| Option | Where TLS ends | What you gain | What you lose |
|---|---|---|---|
| ALB HTTPS listener, HTTP to targets | ALB | ACM renewal, host and path routing, WAF and redirect rules at the edge, one handshake per client connection | Plain text on the VPC hop between ALB and pods |
| ALB HTTPS listener, HTTPS to targets | ALB, then re-encrypted to target | Edge features plus encrypted traffic inside the VPC | A second handshake per new target connection, target certificate validation to manage, more CPU on both ends |
| NLB TLS listener | NLB | Layer 4 forwarding at high throughput, static IP or Elastic IP per Availability Zone, TLS termination with an ACM certificate | No host or path routing, no WAF, no ALB redirect rules, routing falls to the ingress controller or the application |
| NLB TCP listener, ingress terminates TLS | Ingress controller in the cluster | End-to-end TLS from client to pod, certificate managed in the cluster, for example with cert-manager | NLB cannot inspect host or path, so Layer 7 rules, WAF and HTTPS redirects stop working, and the certificate is no longer the ACM certificate on an ALB listener |
A Terraform listener for the common case looks like this:
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.main.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"
certificate_arn = aws_acm_certificate.api.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.orders.arn
}
}Trace of one request. GET https://api.example.com/orders/42 arrives at the ALB on 443. The listener matches the SNI name api.example.com against the ACM certificate and completes the handshake. The ALB forwards GET /orders/42 over HTTP to port 8080, adding X-Forwarded-For and X-Forwarded-Proto: https. The ingress controller matches host api.example.com and path /orders and proxies to the orders Service.
| Step | Component | What happens |
|---|---|---|
| 1 | Client | Sends ClientHello with SNI api.example.com |
| 2 | ALB listener | Selects the ACM certificate, negotiates TLS 1.2 or 1.3, decrypts the request |
| 3 | ALB target group | Opens or reuses a connection to a target on 8080, adds forwarded headers |
| 4 | Ingress controller | Matches host and path rules, selects the orders Service |
| 5 | Pod | Receives plain HTTP and must trust X-Forwarded-Proto when building absolute URLs |
Choose NLB termination when you need Layer 4 performance or fixed IPs and can route by host inside the cluster. Choose ingress termination when policy requires TLS to end at the workload, and accept that the NLB becomes a TCP pipe. Choose re-encryption when traffic between the ALB and pods must stay encrypted, and budget for the extra handshake. In a labelled hypothetical, re-encryption might add 5 to 15 ms to a new target connection inside one VPC, which connection reuse to the target group largely hides after the first request.
Failure modes follow the placement. An expired or mismatched certificate on the ALB listener fails the handshake before any pod sees traffic, and ClientTLSNegotiationErrorCount on the load balancer rises. With re-encryption, a target that rejects the ALB certificate raises TargetTLSNegotiationErrorCount instead, which points at the target group rather than the listener. With ingress termination behind an NLB TCP listener, the same client symptom appears but the certificate to fix lives in the cluster, and the NLB metrics will show a healthy TCP listener while TLS errors come from the ingress controller logs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31A team applies a default-deny ingress policy to the payments namespace, then adds an allow rule for web pods in namespaces labelled team=frontend. Later they find pods in those namespaces without the app=web label can still reach payments. What selector mistake causes this, and what does the cluster actually enforce?
Core answer (about 90 seconds)
Start with the default. Every pod can reach every other pod, in any namespace, and can send traffic anywhere. Nothing changes until a NetworkPolicy selects the pod. A pod is isolated for a direction only when at least one policy that selects it lists that direction in policyTypes. Policies are additive: the allowed set is the union of every selecting policy. There is no deny rule to order, so a default-deny policy plus an allow policy is the normal pattern, and the allow policy only has to name what is permitted.
The selector mistake is usually a list-item problem in from:
# Version A: one list item, both selectors (AND)
ingress:
- from:
- namespaceSelector: {matchLabels: {team: frontend}}
podSelector: {matchLabels: {app: web}}
# Version B: two list items (OR)
ingress:
- from:
- namespaceSelector: {matchLabels: {team: frontend}}
- podSelector: {matchLabels: {app: web}}| Form | Allows |
|---|---|
| A: one item, both selectors | app=web pods in namespaces labelled team=frontend |
| B: two items | every pod in team=frontend namespaces, plus app=web pods in the policy's own namespace |
The second form looks just as reasonable in review, which is why it survives. The fix is to keep both selectors in one item and to check the rule with a probe, not by reading the YAML.
What the cluster enforces
The API server stores a NetworkPolicy whatever CNI is running. Enforcement is the CNI's job. Flannel does not enforce policies, so kubectl apply succeeds and nothing changes. On EKS, the VPC CNI enforces policies only when network policy support is enabled (ENABLE_NETWORK_POLICY=true on the aws-node DaemonSet, in a version that supports it). Otherwise you need Calico or Cilium. Check the add-on version and the environment variable on the running cluster, not the manifest in git.
Prove it before shipping
Run a probe from each class of source, with a timeout, and record the result:
kubectl -n frontend run probe-unlabelled --rm -it --image=busybox -- nc -zv -w 3 payments.payments.svc 8080
kubectl -n frontend run probe-web --labels=app=web --rm -it --image=busybox -- nc -zv -w 3 payments.payments.svc 8080Expect the unlabelled probe to time out and the labelled probe to connect. Do this against the rule as deployed, and repeat after any change to the namespace labels, because a namespace relabel changes what namespaceSelector matches with no edit to the policy.
Failure modes to name
- Egress-isolated pods lose DNS unless port 53 UDP and TCP to kube-dns is allowed. The symptom is slow lookups and timeouts, not refusals, which looks like an application bug.
hostNetworkpods are not subject to pod-level policies, so a sensitive pod on host networking is outside the rule.- With a load balancer and
externalTrafficPolicy: Cluster, the client source IP is replaced by SNAT. AnipBlockallow then matches nothing, and the fix isLocalor allowing the node range. - Detection: CNI logs, Calico flow logs or Cilium Hubble flows show dropped packets with the policy that dropped them.
My default is a default-deny ingress per namespace, a baseline allow for DNS and the ingress controller, and one policy per application that names its callers with a single from item per caller.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32Your three-broker Kafka cluster runs as a Deployment with hand-made PVCs. Why would a StatefulSet fit better, and what happens to the data when you scale from five replicas down to three?
The 90-second answer
A Deployment gives you interchangeable pods with random names. A broker needs a stable identity: the same name, the same DNS record and the same log directory every time it starts. A StatefulSet gives each replica an ordinal (kafka-0, kafka-1, ...), a predictable DNS name through a headless Service, and a PersistentVolumeClaim that follows the ordinal. When kafka-1 is rescheduled, it comes back as kafka-1 and reattaches data-kafka-1. A Deployment would start a pod with a new name and a volume that may not match it.
Scaling down is where people get hurt. A StatefulSet removes the highest ordinal first, one pod at a time. The PVCs are left behind unless you say otherwise, because the default persistentVolumeClaimRetentionPolicy is Retain for both whenDeleted and whenScaled. That protects the data, but it also means the disks keep billing until someone deletes them.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: kafka
spec:
serviceName: kafka-headless
replicas: 3
podManagementPolicy: OrderedReady
updateStrategy:
type: RollingUpdate
persistentVolumeClaimRetentionPolicy:
whenScaled: Retain
whenDeleted: Retain
selector:
matchLabels:
app: kafka
# template omitted
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: gp3
resources:
requests:
storage: 500GiTrace: scale 5 to 3. Pods kafka-4 and kafka-3 terminate in that order. kafka-2, kafka-1 and kafka-0 keep running. data-kafka-3 and data-kafka-4 remain as Bound PVCs. If you scale back to 5, the new kafka-3 and kafka-4 bind to those same claims and find their old logs. With whenScaled: Delete, the claims are removed during the scale-down and the data is gone, so you only set that when the partitions are fully replicated elsewhere and you have decided to lose that disk.
Ordered rollout. With the default OrderedReady policy, scale-up starts pods in ascending order and waits for each to be Running and Ready before the next. A RollingUpdate replaces pods from the highest ordinal down, again one at a time. partition lets you stage it: setting partition: 2 updates only kafka-2, so you can watch one broker rejoin before touching the others.
| Concern | Deployment with hand-made PVCs | StatefulSet |
|---|---|---|
| Pod identity | random suffix, changes on replace | ordinal, stable |
| Volume binding | you wire it up by hand | one PVC per ordinal from volumeClaimTemplates |
| Scale-down | arbitrary pods removed | highest ordinal first, PVCs kept by default |
| Update order | parallel by surge/unavailable | reverse ordinal, one at a time |
Where it fails. Ready is not the same as caught up. A broker can pass its readiness probe while it is still re-replicating, so the rollout moves on and the cluster is down a replica it thought it had. Detect this by watching under-replicated partitions during the rollout, and gate each step on that metric, not on pod status alone.
With a Deployment sharing one ReadWriteOnce claim, a replacement pod scheduled on another node gets stuck. The event is Multi-Attach error for volume, because the old pod still holds the attachment. That is the symptom that tells you the workload needed per-pod identity in the first place.
Deleting the StatefulSet with cascade set to orphan keeps the pods running and the PVCs in place. Use it for a controlled handover, and remember the pods are then unmanaged until you reapply the object.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33Your ECS service runs 12 tasks behind an ALB. Compare rolling update and blue-green for rolling back a bad release: how fast each one returns traffic to the old version, and what each costs in extra tasks during the deploy?
The 90-second answer
Blue-green rolls back by moving the listener back to the old target group, which takes seconds. A rolling update rolls back by running the deployment again with the old task definition, so the old version comes back one wave at a time. Blue-green costs more during the deploy because the full new set runs next to the old one. A rolling update costs less but is slower to undo.
Assumptions, all hypothetical: each task takes 30 s to start, the ALB health check passes after 2 consecutive 15 s checks (about 30 s), and the service runs 12 tasks.
| Rolling (min 100%, max 200%) | Blue-green (ALB, two target groups) | |
|---|---|---|
| Peak tasks | 24, only while surge is active | 24 for the whole deploy window |
| Rollback action | New deployment with old task definition | Move listener back to blue target group |
| Rollback time, hypothetical | About 2 min: 3 waves of 4 tasks, each wave about 40 s to start and pass health checks | Under 30 s, the time the ALB needs to move traffic |
| Extra task-hours per deploy | About 12 tasks for 10 min, roughly 2 task-hours | About 12 tasks for the whole window, plus the blue termination wait |
The rollback times above are for a rolling update that is already in progress. If the bad release has finished rolling out, the rollback is a full rolling deploy again and the numbers are the same.
Where each one fails. Rolling update runs old and new code side by side for the whole rollout. Any change that the two versions cannot share, such as a renamed column or a changed message format, breaks during the rollout. Blue-green keeps the old set running only until its termination wait ends. After that, rolling back needs a full redeploy.
Detection. Watch ALB 5xx count per target group. For a rolling update, compare the error rate of new tasks against old tasks. For blue-green, alarm on the green target group and flip the listener on alarm. Either way, the rollback time you can promise is the one you have drilled.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34Which metric do you check first to decide whether a canary deployment should be promoted?
The 90-second answer
Check the request error rate on the canary against the baseline, over the same time window. A canary whose 5xx ratio is higher than the baseline's has a regression, and the rollout stops. Latency comes second, and it is usually the p99 from the same window, because a release can keep errors flat while the tail gets slower.
The comparison matters more than the absolute number. The fleet's normal error rate moves with time of day and traffic mix, so a fixed threshold like "under 0.5%" fails in both directions. Comparing canary and baseline during the same 15 minutes removes that shared noise.
Why the error ratio first. It is the signal users feel directly, and it is already on the service's SLO dashboard, so nobody has to invent a new measurement during a rollout. Saturation metrics such as CPU throttling and queue depth are useful, but they predict failure rather than show it, so they belong on the dashboard as guardrails, not as the promotion gate.
| Metric | Role in the gate | Comparison |
|---|---|---|
| 5xx ratio | Primary gate | canary vs baseline, same window |
| p99 latency | Secondary gate | canary vs baseline, same window |
| CPU throttling, queue depth | Guardrail | watch, do not gate |
Failure modes
- Comparing to a fixed threshold instead of the baseline: a normal evening spike fails a good release, or a bad release passes during a quiet hour.
- Mismatched arms: the canary gets cheap requests while the baseline gets expensive ones. Detected by comparing request mix across both arms before reading the error rate.
- Empty canary: the canary receives almost no traffic and reports zero errors. Detected by requiring a minimum request count before a pass counts.
In Argo Rollouts, this is an AnalysisTemplate with a success condition on the error-rate query compared against the baseline.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35You need to rename a column on a live PostgreSQL table behind an autoscaling service that runs 30 pods, and the deploy rolls out over 10 minutes with old and new versions serving at once. Walk through the expand-contract steps, what each step must be safe under, and where the migration itself can break the rollout.
The 90-second answer
Never rename in place. Expand, migrate, contract, with a deploy between each step, because during a rolling deploy version N and N+1 read and write the same table at the same time. A rename is a breaking change for N, so it has to be split so that every intermediate schema works for both versions.
The sequence for customers.fullname becoming customers.display_name:
- Expand. Add
display_nameas nullable, no default. Adding a nullable column without a default is a catalog-only change in PostgreSQL 11 and later, so it does not rewrite the table or hold a long lock. Setlock_timeout(say2s) and retry, otherwise theALTERqueues behind a long transaction and blocks every query behind it. - Dual-write. Ship version N+1 that writes both columns and reads
COALESCE(display_name, fullname). Version N still only knowsfullname, which is fine because it is still populated. - Backfill. Batch the copy in keyed chunks, for example 5,000 rows per transaction ordered by primary key, with a short sleep between batches. A single
UPDATEover 40 million rows writes 40 million dead tuples, bloats the table and holds row locks long enough to stall writers. - Enforce. Only after the backfill is verified (
SELECT count(*) WHERE display_name IS NULLreturns 0 for rows written before the dual-write started), addCHECK (display_name IS NOT NULL) NOT VALID, thenVALIDATE CONSTRAINTseparately.VALIDATEtakes aSHARE UPDATE EXCLUSIVElock and does not block reads or writes, unlike a plainSET NOT NULLwhich scans underACCESS EXCLUSIVE. - Contract. Ship version N+2 that reads and writes only
display_name. Only once no version N pod remains (confirm the rollout is complete and no old ReplicaSet is scaled up), dropfullname.
Where the migration breaks the rollout
The deploy and the migration are not one atomic event. Run the migration before the first pod rolls, and version N must tolerate the new column, which is why step 1 is additive only. Run the contract step too early and in-flight N pods fail with column "fullname" does not exist until they cycle out. Autoscaling makes this worse: a scale-out during the 10-minute window can start N pods after you thought the rollout was finished. Gate step 5 on the ReplicaSet being fully scaled down, not on the deploy job reporting success.
Trace of a single write during the dual-write window: version N pod inserts fullname='Ada' with display_name NULL. The backfill job later sets display_name='Ada' for that row. Version N+1 reads COALESCE, so it sees 'Ada' either way. The backfill must not overwrite a row whose display_name was set after the backfill snapshot, so write it as WHERE display_name IS NULL.
Failure modes and detection
- Long-running transactions holding a lock that the
ALTERwaits on. Detect withpg_stat_activityrows wherewait_event_type = 'Lock'and alock_timeouterror in logs. - Backfill outpacing replication. Watch replica lag while batches run; throttle when it exceeds your budget (for example 5 s).
- Contract applied early. Detect by
undefined columnerror rate on the old version's pods, and keep it at zero before dropping.
Rollback is cheap only before step 5. Before contract, reverting the app to N is safe because fullname still holds every value. After the drop, rollback means restoring data, so the contract deploy is the point of no return and deserves its own change window.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36A release ran an ALTER that makes a column NOT NULL and published new-format messages to SQS before it was rolled back. Why does redeploying the old ECS task definition not undo those effects, and which of the two would you undo first?
The 90-second answer
Redeploying the old task definition reverts the code that runs. It does not revert the database or the messages the new code already produced. Those are separate state changes, and each needs its own answer.
So I'd undo them in a fixed order. Stop the producer first, so no more new-format messages leave. Then roll back the compute. Then handle the schema and the messages that already exist.
Why the schema stays changed. A NOT NULL constraint is enforced by Postgres on every write, whichever code is writing. The old tasks don't know about the rule, but the database still applies it. If the old code writes a row with a NULL in that column, the insert fails. So the rollback can leave the old code failing on writes. Reverting the constraint needs a migration of its own: ALTER TABLE orders ALTER COLUMN fulfilment_v2 DROP NOT NULL;. That is a fast metadata change in Postgres, but it still needs to be planned and run.
Why the messages stay published. Once a consumer has read an SQS message, its side effect may already have happened. Standard queues deliver at least once, so a consumer may also process the same message twice. Old consumers may not understand the new payload version at all. Rolling back the producer stops new bad messages. It does nothing to the ones already sent.
Trace of the failure, with hypothetical figures:
| Step | Effect | Reversible by redeploy? |
|---|---|---|
1. migration sets fulfilment_v2 NOT NULL | constraint enforced for all writers | No |
2. new code publishes OrderPaid v2 | 12,000 messages | No |
| 3. ECS rolls back to the previous task definition | old code runs | Yes |
| 4. old consumer reads v2 payloads | parse errors, DLQ depth climbs | Stops only once producer stops |
What I'd do, in order.
- Stop the producer with a feature flag, or scale it to zero. Do this first, or the rollback keeps adding bad messages.
- Roll back the ECS service to the previous task definition.
- Check the schema. If the old code writes NULLs or needs the old shape, run the down migration now.
- Drain the DLQ by redriving messages only after the consumer is confirmed idempotent, keyed on order id. Otherwise a redrive creates duplicate side effects.
Failure modes to detect. DLQ depth that keeps rising after the rollback means old consumers still reject v2 payloads. Repeated writes for the same order id point to a redrive without idempotency. Write errors from the old tasks show the constraint is still in place, so check the migration state before the code.
The key point for the interview: rollback reverts behaviour, not history. Before the release, name which effects are reversible and which need compensation.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Your pipeline rebuilds the image for each environment with a different build argument for the API URL. Explain why promoting one artifact between environments is safer, and how you would change the build so it is.
The 90-second answer
The rebuild-per-environment setup means the image tested in staging is not the image that reaches production. Each build pulls its own base layers, resolves its own dependency tree, and bakes in its own API URL. Staging can pass on an artifact that prod never runs. The fix is to build once, push one digest, and inject the API URL at deploy time from an environment file.
Why the rebuild breaks the evidence
Two builds of the same commit are not guaranteed to be identical. A rebuild can pick up a newer node:20-slim base, a newer patch release of a transitive npm package, or a different ARG value. Each difference is invisible in the git history.
Trace for a single commit a1b2c3d:
- Staging build:
docker build --build-arg API_URL=https://api.staging.example. Digestsha256:4a1c…. Integration tests pass. - Prod build a few hours later: same commit,
--build-arg API_URL=https://api.example. Base layer has rotated. Digestsha256:7e02…. - Prod deploys
sha256:7e02…. Staging testedsha256:4a1c…. Nothing in the pipeline connects the two.
The git SHA does not identify the image. Only the digest does.
The change
Remove the ARG for environment-specific values. Build once with no environment baked in:
FROM node:20.11-slim@sha256:…
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]The server reads API_URL from its environment at start. The deploy step supplies it:
| Environment | Config source | API_URL |
|---|---|---|
| dev | envs/dev.yaml | https://api.dev.example |
| staging | envs/staging.yaml | https://api.staging.example |
| prod | envs/prod.yaml | https://api.example |
Promotion now changes only the environment file reference. The image line stays app@sha256:4a1c… through every stage.
Verification
Before traffic moves, read the running digest and compare it with the one the pipeline promoted. On EKS, check status.containerStatuses[*].imageID. On ECS, check the task's image digest from DescribeTasks. A mismatch means the wrong artifact is running.
Failure modes
- A value still baked in through a
Dockerfiledefault or a forgottenARGmakes the image environment-specific again. Detect it by building once and running the same digest in two environments with different config; a value that stays fixed across both is a clue. - The server fails to read the env var and falls back to a hardcoded default, so prod silently calls staging. Detect it by making the server refuse to start when a required variable is unset, and logging the resolved value at startup.
- A mutable tag like
:prodis repointed by a second build. Detect it by comparing digests in the deploy record, not tags.
When not to do this: a mobile app or firmware image that must differ per region needs separate variants. Each variant is still built once and promoted by its own digest.
Trade-off: a per-environment rebuild lets you bake in values and skip runtime config plumbing, but you lose the guarantee that the tested artifact is the shipped one. Runtime config costs one extra input at deploy time and buys that guarantee.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38In CI, what is the main security advantage of OIDC federation over a static cloud access key stored as a pipeline secret?
The 60-second answer
The main advantage is that no long-lived credential is stored. A static access key stays valid until someone rotates or revokes it, so anyone who reads the CI secret store, a build log, or a leaked environment can use it. With OIDC federation, the CI provider issues a short-lived token for each job, and the cloud account exchanges that token for role credentials that expire, typically after one hour. A leak then exposes a credential that is already close to expiry and tied to one job.
The trust policy still matters. It should constrain the sub claim (for example repo:acme/payments:ref:refs/heads/main) and check aud, so that other repositories on the same CI provider cannot assume the role.
| Static access key in CI secret | OIDC federation | |
|---|---|---|
| What is stored | Long-lived key pair | Nothing beyond the trust policy |
| Lifetime | Until rotated or revoked | Session, typically 1 h |
| Leak impact | Usable from anywhere until revoked | Short-lived, bound to one job's claims |
Federation does not remove every risk. A wildcard sub condition lets other repositories assume the role, and a missing id-token: write permission makes the token request fail, which tempts teams to add a static key back. Review trust policies for wildcards, and alert on new long-lived keys created for the CI principal.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39Your team runs GitOps for 60 EKS clusters. A teammate proposes replacing the in-cluster pull agent with a CI job that runs kubectl apply, and says secrets can stay in git if they are encrypted. Argue both sides and say what you would build.
Short answer
Keep pull for cluster state. CI should build the artefact and commit the new image digest to git, and nothing else. A pull agent inside each cluster compares live state with a git revision and applies the difference, so no pipeline holds a credential that can write to a cluster API. Push is easier to debug on the day you ship, but every cluster's write credential then lives in CI, and drift is corrected only when someone reruns the pipeline.
| Concern | Pull (agent in cluster) | Push (CI applies) |
|---|---|---|
| Write credential | stays in cluster, scoped to its namespaces | a token per cluster in CI |
| Drift correction | every reconcile, plus on change | next pipeline run only |
| Failure visibility | per-app sync and diff status | job log at deploy time |
| Rollback | revert the commit, agent converges | rerun an old pipeline, which may rebuild or repull |
Drift and self-heal. Auto-sync with self-heal reverts manual console edits. It also fights anything else that writes to the same field. If git sets spec.replicas: 6 and an HPA scales the Deployment to 14, the agent sees a diff and scales back to 6 on its next pass. The HPA then scales up again. Two fixes work: delete replicas from the manifest so the HPA owns it, or tell the controller to ignore that field:
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers:
- /spec/replicasPrune is the other sharp edge. A resource deleted from git is deleted from the cluster, so keep PersistentVolumeClaims and anything stateful out of pruned paths or annotate them to be kept.
Secrets in git. Plaintext never goes in git, and encryption in git is only one of three designs with different failure modes:
- Sealed Secrets: ciphertext is committed; the private key lives in the cluster. Lose the cluster without a key backup and the secrets are unrecoverable. Rotation means re-sealing, and the old ciphertext stays in history.
- SOPS with KMS: values are encrypted in the file. Anyone with
kms:Decrypton the key reads every secret in it, so scope the key per environment. - External Secrets Operator: git holds only an
ExternalSecretthat names a Secrets Manager entry. The operator copies the value into a Kubernetes Secret on itsrefreshInterval(default 1h). Rotation happens in Secrets Manager and propagates within the interval. Env vars sourced from that Secret do not update, so the pod still needs a restart, or the Secret must be mounted as a volume.
I would pick External Secrets Operator for database credentials. Git then never holds the value, and rotation is one change in Secrets Manager.
What if a value was already committed? Deleting the file in a new commit leaves the value in every clone and in history. Treat it as compromised, rotate it, and only then clean history if your policy requires it.
Failure to watch. Track sync status and time since last successful reconcile per application, and alert on OutOfSync for longer than your reconcile interval. A silent controller outage looks identical to a healthy cluster until someone diffs it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40An integration test that writes to a shared SQS queue in CI fails on a commit, then passes when rerun on the same SHA. Explain how you decide whether it is a flake or a regression, and what you do with the test while main stays green.
The 90-second answer
The first question is whether the failure reproduces on the same commit. A rerun of the same SHA settles most of it. If it passes, the test is flaky: something outside the code changed between runs. If it fails again, it is a regression until a bisect says otherwise.
A rerun alone does not tell you the cause of a flake. For a shared SQS queue, the usual suspect is shared state: another pipeline reading or purging the same queue. So I check the queue's activity around the failing timestamp, not just the test log.
| Evidence | Likely cause | Action |
|---|---|---|
| Same SHA fails, then passes on rerun | flaky: timing or shared state | quarantine, open ticket |
Fails on every run since commit a1f9 | regression | revert or fix forward |
| Fails only in one runner pool | environment | fix the environment, not the test |
ThrottlingException from AWS APIs | shared-account limits | isolate resources per run |
Trace from the incident: the test fails on a1f9 with ReceiveMessage timed out after 20s on orders-ingest-ci. The rerun passes. The queue log shows another pipeline calling PurgeQueue on that queue 60 seconds earlier. That is shared state, not a regression.
For main, I move the flaky test to a quarantine lane. It still runs and reports on every push, but it does not block merge, and it carries an owner, a ticket and an expiry date. The fix that removes the flake is one queue per run, named with the run ID, so a purge elsewhere cannot reach it.
Retries get a narrow policy. Retry only on named infrastructure error classes, cap at one retry, and record the retry count per test. A blanket retry setting hides the flake rate from everyone.
Failure modes to watch
- Quarantine becomes a graveyard. Alert when a quarantined test is older than 14 days.
- A bad commit looks flaky on its first run. Alert when retries start passing on one SHA more often than usual.
- A test leaves quarantine too early. Promote it back only after a run of consecutive green runs in the blocking lane.
I would publish flake rate per test over seven days, so the owning team can see whether the fix worked.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41Your stateless API runs on 4 EC2 instances behind an ALB, and p99 climbs when traffic rises. The team wants to replace them with one instance four times the size. Compare scaling up with scaling out for this service, and say which one the database connection count would make you hesitate over.
The 90-second answer
I would scale out, because the service is stateless at the request level and the bottleneck is per-request CPU and concurrency. Scaling up would give one bigger failure domain and the same single pool. The thing to check before adding instances is the database connection count, because each instance opens its own pool and that multiplies.
The comparison
Hypothetical figures: each instance holds a pool of 20 connections to PostgreSQL. Four instances open 80 connections. Doubling to eight opens 160. If the database starts degrading past about 200 connections, scaling out to eight is fine but twelve is not.
| Scale up: one 16 vCPU instance | Scale out: four 4 vCPU instances (now eight) | |
|---|---|---|
| Total vCPU | 16 | 16 to 32 |
| Failure domain | one instance, loss is a full outage | one instance of eight, loss is 1/8 of capacity |
| Deploys | restart is an outage unless you run two | rolling replacement behind the ALB |
| Database connections | one pool, unchanged | 80 to 160 at pool size 20 |
| Ceiling | largest instance type | shared state (database, locks) |
Scale up is the right call when the component is single-writer or licensed per host, or as a short fix while you remove shared state. Its ceiling is the largest instance type and it does nothing for lock contention.
What must be true before adding instances
Any request must be servable by any instance. The usual breakers are in-process sessions and singleton jobs running in every replica. Test it with a trace: tag each response with the instance id, log in through instance A, then read the cart through instance B. If the cart is empty, sessions are local. Move them to a shared store or a signed token.
Failure modes and how to detect them
- Connection exhaustion: pool wait time rises while instance CPU stays low. Compare the count in pg_stat_activity with max_connections. Mitigate with RDS Proxy or smaller per-instance pools.
- Sticky session misses: 401s or cart resets appear after the change. The instance-id trace above finds it.
- Cold instances: new targets take traffic before caches and pools warm. Set ALB slow start on the target group (30 to 900 s).
- Hot-row contention: p99 climbs while every instance is idle. Check lock waits in pg_locks, not CPU.
I would add instances only after confirming the connection count stays under the database limit with headroom.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42An Auto Scaling group uses a target tracking policy on average CPU with a target of 50%. What single metric does that policy compare against its target, and how is the average computed across the group?
The 45-second answer
The policy compares one CloudWatch metric against the 50% target: AverageCPUUtilization in the AWS/AutoScaling namespace, dimensioned by AutoScalingGroupName. That is the group's average CPU utilisation, not the CPU of any individual instance. Target tracking then adds or removes instances to hold that average at 50%.
The average is the CloudWatch Average statistic for that metric over the evaluation period. In practice that means sum every CPU sample reported by every instance in the group during the period, then divide by the total number of samples. With equal reporting from each instance, that is the same as the mean of the per-instance percentages. Three instances reporting 80%, 20% and 50% give (80 + 20 + 50) / 3 = 50%, so the policy does nothing. If all three rise to 90%, the group average is 90% and the policy scales out.
Worked trace (hypothetical figures)
| Instance | CPU sample |
|---|---|
| i-a | 80% |
| i-b | 20% |
| i-c | 50% |
| Group average | 50% |
No scale action fires at the target. Change i-a and i-b to 90% each and keep i-c at 50%: (90 + 90 + 50) / 3 = 76.7%. The policy treats that as above target and adds capacity. The rough capacity arithmetic behind that decision is current capacity multiplied by metric divided by target. Ten instances averaging 90% against a 50% target point to about 10 * 90 / 50 = 18 instances if load per instance stays constant, which is why target tracking can add several instances in one step rather than one at a time.
Details an interviewer will probe
Target tracking has no step-scaling cooldown to tune. It re-evaluates as new metric data arrives and keeps adjusting toward the target. New instances still need time to become useful. The Auto Scaling default warmup period is 300 seconds, and instances in warmup do not immediately bring the average down, so a sudden spike can trigger more than one scale-out before the first new instances report low CPU. That overshoot is a concrete failure mode to name, along with its detection: desired capacity climbing in successive evaluations while the metric stays high.
Averaging also hides a hot instance. One instance at 100% among nine at 40% gives a group average of 46%, below the 50% target, even though that host is saturated and queueing. Heterogeneous instance types make this worse, because a percentage point means different absolute capacity on different sizes.
Choosing a different metric
CPU is a default, not a law. For an Application Load Balancer fronted service, the exact alternative to name is RequestCountPerTarget in the AWS/ApplicationELB namespace, dimensioned by TargetGroup. A target of, say, 1,000 requests per target per minute tracks request load directly, where CPU can stay low while the service waits on a database or downstream I/O. The same averaging logic applies: total requests divided by total targets, averaged over the period. Pick the metric that moves with the constraint you have measured, and be ready to defend the target number with that measurement rather than with the 50% CPU default.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43An autoscaling group serves 3,600 requests per second at peak. Each instance sustains 450 req/s before p99 latency crosses your SLO, and you want 25% headroom for an AZ failure across three zones. How many instances do you run per zone, and what breaks in your arithmetic if the load balancer sends traffic unevenly?
The 90-second answer
First assumption: the 3,600 req/s is the total across all zones, and the 450 req/s figure is the throughput at which p99 stays inside SLO, not the point where the process falls over. Sizing to the knee of the latency curve is what matters.
Without the failure requirement: 3,600 / 450 = 8 instances.
With 25% headroom: 8 × 1.25 = 10 instances.
But the requirement is survive one AZ failure with that headroom still in place. If one of three zones is lost, the remaining two must carry the full 3,600 req/s. Each survivor must then handle 1,800 req/s, which is 1,800 / 450 = 4 instances at the SLO knee, plus 25% headroom gives 5 per zone. Across two surviving zones that is 10 instances, so the spread is 5 per zone and 15 in total.
| Scenario | Zones up | Load per zone | Instances per zone | Total |
|---|---|---|---|---|
| Normal | 3 | 1,200 req/s | 3 (2.67 rounded up) | 9 |
| One AZ lost | 2 | 1,800 req/s | 5 (4 plus headroom) | 10 |
So the answer is 5 per zone, 15 total, sized so the failure case drives the number. Normal operation at 3 per zone sits at 1,200 / 1,350 = 89% of the 3-instance capacity, which is fine.
Where the arithmetic breaks
Uneven distribution is the real failure mode. An ALB with cross-zone load balancing disabled sends each zone its share by node count, not by capacity. If zone A has 5 instances and zones B and C have 3 each, zone A gets 1/3 of traffic at 5 instances, which is 1,200 / 5 = 240 req/s per instance, and zones B and C get 1,200 / 3 = 400 req/s each. That is still under 450, but the failure math changes: when zone A is lost, B and C each receive 1,800 req/s at 3 instances, which is 600 req/s each, 33% over the SLO knee.
Detect this by comparing per-target request counts (RequestCountPerTarget in CloudWatch, per AZ) against the instance count, not by looking at fleet-wide averages. Average CPU hides it, because the hot zone saturates while the fleet average looks healthy.
Trade-offs and when not to do this
If the service is CPU bound and scales cleanly, target tracking on a utilisation of around 60% gives the same answer without a hand-written formula, but it reacts after the fact. Use the formula for capacity reservation and the autoscaler for everything else. Scaling policies also need a warm-up allowance: a new instance that takes 90 s to pass health checks adds no capacity during that window, so the peak needs to be covered by the instances already running.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44A hot product page is served from a Redis cache in front of PostgreSQL, and its key expires under 2,000 requests per second. Explain what happens in the next 100 ms if every request misses, and how you would stop the database from absorbing all of them.
The 90-second answer
If every request misses, all 2,000 requests in that 100 ms go to PostgreSQL, about 200 identical queries for one key. Each one holds a connection while it runs. With a pool of 20 connections, the queries queue behind each other, p99 climbs from a few milliseconds to seconds, and the pool exhausts for every other endpoint sharing it. The fix is single-flight: exactly one request per key goes to the database, and the rest wait briefly for its result.
The mechanism
get(sku):
v = redis.GET cat:sku:{sku}
if v: return v
if redis.SET lock:cat:sku:{sku} 1 NX PX 3000:
row = db.query(sku)
redis.SET cat:sku:{sku} row EX 300
redis.DEL lock:cat:sku:{sku}
return row
sleep(jitter 20-60 ms); retry get(sku) up to 3 times
fall back to db.query(sku) without cachingTrace for the expiry at t=0. The first SET NX succeeds at about t=0.1 ms and that request queries the database. The next roughly 200 requests in the 100 ms window find no value, fail the SET NX, and sleep. The leader writes the key around t=5 ms, and the retries hit the cache. Database queries for that key drop from about 200 to 1.
Why the lock needs an expiry
The PX 3000 is what keeps a crashed leader from blocking the key forever. If the leader dies before DEL, waiters see at most 3 s of misses and then one of them takes the lock. Set the expiry above your worst-case database latency, or a slow query lets a second leader start while the first is still running. That is harmless for correctness here, but it doubles the load on the hot key.
Alternatives and when to use them
- Probabilistic early refresh: a request that finds the TTL within a random margin of expiry refreshes in the background. It removes the miss entirely for keys with predictable reads, but it adds a refresh path that can itself stampede if many keys share a TTL.
- Staggered TTLs: add 10 to 20 percent random jitter to each TTL so keys loaded together do not expire together. This fixes mass expiry, not a single hot key, which is the case here.
- Serving stale on error: keep the expired value for a grace period and return it while one request refreshes. Pick this when a stale price is acceptable for seconds, not when a price change must show immediately.
I would start with the lock because it fixes the single-key case with the least code, then add jitter if expiries cluster.
Failure modes to watch
- Waiters exhaust their retries: a database slower than the retry budget (3 × 20 to 60 ms) sends every waiter to the fallback query, which recreates the stampede. Detect it as a spike in database queries per key, not just total connections.
- Redis failover drops the key set: every key misses at once. Watch the cache hit ratio and database query rate together; a hit ratio falling from 98% to 40% with a connection spike is this failure, and the lock does not help when every key is cold.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45A product catalogue cache on ElastiCache for Redis has a 300 s TTL and sits in front of RDS PostgreSQL. After a cache node restarts, RDS CPU goes from 35% to 100% within a minute. Explain the mechanism and the arithmetic, then say what you change.
The 90-second answer
Separate two failures that look the same on a dashboard. A cold cache is a one-time event with a bounded size. A miss storm is what happens when many clients miss the same key at the same moment and each sends its own query to the database. The restart causes the first. The absence of request coalescing turns it into the second.
The arithmetic, using hypothetical figures: 4,000 reads/s with a steady 97% hit ratio sends 120 reads/s to RDS. After the restart the hit ratio is near 0% until keys repopulate, so about 4,000 reads/s reach the database. If each catalogue query costs 2 ms of CPU, steady state needs 0.24 vCPU and the cold state needs 8 vCPU. A db.r6g.large has 2 vCPUs, so CPU pins and latency queues.
| Phase | Hit ratio | DB reads/s | DB CPU demand (2 ms/query) |
|---|---|---|---|
| steady | 97% | 120 | 0.24 vCPU |
| cold, first seconds | ~0% | ~4,000 | 8 vCPU |
| cold, coalesced | ~0% | one query per hot key in flight | bounded by distinct keys |
The TTL is not the cause. The restart empties every key regardless of TTL. TTL governs how long a key stays hot. Keys written in one batch with identical TTLs expire together, which produces a second wave 300 s later. Add jitter, for example EX = 300 + random(0, 60), so expiry spreads out.
Eviction can cause the same storm without a restart. Check maxmemory-policy in your parameter group. The default for Redis OSS on ElastiCache is volatile-lru, which evicts only keys that have a TTL. If the node is undersized, LRU evicts hot keys and you get misses with no restart at all. Watch the Evictions and CacheMisses metrics in CloudWatch and alarm on sustained evictions above zero.
What I change, in order:
- Request coalescing. On a miss, take
SET lock:{key} 1 NX PX 2000. The holder queries RDS and writes the value. Other callers wait briefly or serve stale. The lock TTL must exceed p99 query time, or a second query starts while the first is still running. If the holder crashes, waiters sit for up to 2 s. - Stale-while-revalidate. Store a soft expiry alongside the value, serve the old value past it, and refresh in the background. Users see slightly old data instead of a database queue.
- Warm before traffic. Restore the node from a Redis backup, or replay the top N keys from access logs, before it joins the read path.
- Cap database concurrency. Put RDS Proxy or the application pool limit in front of RDS so a storm queues in the application rather than opening thousands of connections.
Trade-offs. Coalescing adds latency for the callers that wait and adds a lock that can outlive its holder. Stale serving trades freshness for availability, which is acceptable for a catalogue and not for inventory counts. Warm-up adds restore time to every node replacement.
How you detect it. Alert on a drop in cache hit ratio, a jump in DatabaseConnections, RDS CPUUtilization above 80% for more than two minutes, and p99 latency. Prove the fix in a game day: restart a node under load and count RDS queries per key. With coalescing working, that count should be 1 per key per miss window, not one per request.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46Why can a read from an RDS read replica return a value that was committed on the primary a moment ago?
The 20-second answer
RDS read replicas use asynchronous replication. The primary commits a write and acknowledges the client before the replica has replayed that change. A read sent to the replica in that gap returns the older row. The replica is not broken; it is behind. The gap is exposed as the ReplicaLag CloudWatch metric, in seconds.
Trace, with hypothetical figures:
| Time | Event |
|---|---|
| t=0 ms | UPDATE profiles SET name='Ana' commits on the primary |
| t=5 ms | API returns 200 to the browser |
| t=40 ms | Browser reloads, GET /profile is routed to a replica |
| t=40 ms | Replica has not replayed the commit yet, returns name='Mira' |
| t=900 ms | Replica replays the change; the next read is correct |
The rule to remember: an asynchronous replica guarantees eventual catch-up, not that it is current at the moment you read it. Any read that must see the user's own latest write therefore needs the primary, or a check that the replica has passed that write.
Options, with trade-offs
- Pin the writer's reads to the primary for a short window. After a write, keep that user's reads on the primary for, say, 5 s, tracked in a session cookie or a request header. Simple to build. Cost: primary read load rises with write rate, and the window has to outlast the worst lag you see.
- Track the write position. After commit, capture the position (PostgreSQL
pg_current_wal_lsn(), or the GTID set on MySQL) and store it with the session. Send the next read to a replica only if that replica has replayed past the stored position; otherwise use the primary. Precise, at the cost of more code and a position check per read. - Keep correctness-critical reads on the primary. Authorization checks, balances, and anything that gates a write stay on the primary. Only browse and list traffic goes to replicas.
I would combine the second and third. The position check handles the profile case exactly, and anything that gates money or permissions never leaves the primary.
Safe routing
Standalone RDS read replicas do not come with a reader endpoint that load-balances across them. You keep the replica list yourself, and the application or a proxy chooses among them. Do not point a generic read hostname at the primary and replicas together unless every read on it tolerates staleness, because you lose control of which requests see old data.
A Multi-AZ standby is not a read target. It exists for failover, so do not count it as read capacity.
Failure modes and detection
- Lag grows during a long transaction or a write burst. Alarm on
ReplicaLagand also measure your own replay gap, because the CloudWatch metric is sampled and coarse. - A replica falls far behind and keeps receiving traffic. Remove it from the read pool when lag passes a threshold you choose, for example 2 s, and re-add it after it catches up.
- The write-position check is skipped by a code path that reads directly from the replica pool. Catch it by tagging each read with its target and alerting on replica reads that follow a write from the same session.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47Your order service shards its PostgreSQL data by customer_id across 12 shards, and one customer generates 30% of writes. Walk through how you diagnose the hot shard, what you can change without resharding, and what resharding costs if you have to do it.
The 90-second answer
First I'd confirm it is a hot key and not a hot shard. A shard can be hot because one tenant dominates, or because 12 shards is simply too few for total write volume. The two need different fixes. A single customer sending 30% of writes means that customer's key maps to one shard, and that shard will saturate long before the other eleven. Adding shards does not help that case: the one customer's writes still land on one partition.
What I can change without resharding: isolate the heavy tenant onto a dedicated shard through a lookup table (customer_id to shard), move only that customer, and batch or queue their write-heavy paths at the application layer. What I cannot change without resharding is the mapping function for everyone else.
Diagnosis
Check per-shard write rate and lock wait, not average CPU. Average CPU hides it. Compare the top shard's share of pg_stat_user_tables.n_tup_ins + n_tup_upd against the mean, and group the top shard's statements by customer_id from the application's trace tags.
| Signal | Hot key | Hot shard from low cardinality |
|---|---|---|
| Top shard share of writes | 30% to one shard | spread across many customers |
| Top customer share | 30% of writes | under 2% each |
| Fix | move tenant, split tenant's keys | add shards, change hash |
Worked numbers (hypothetical)
Total write rate 9,000 tx/s. Even distribution gives 750 tx/s per shard. The heavy customer adds 2,700 tx/s, all on shard 7, so shard 7 sees 750 + 2,700 = 3,450 tx/s. Its WAL and fsync budget, not the others, sets your ceiling. Moving that customer to a dedicated instance leaves shard 7 at roughly 750 tx/s and gives the dedicated instance the 2,700.
Resharding cost
With consistent hashing and a virtual-node ring, adding one shard to 12 moves about 1/13 of keys, roughly 7.7%. With plain hash(customer_id) % 12 changed to % 13, almost every key moves. That difference matters more than the shard count. Migration is a dual-write period, a backfill by key range, then a read cutover per key group, with a verification job comparing row counts and checksums per range. Expect the backfill to take hours at this scale and the dual-write window to need idempotent writes so retries do not double-apply.
Cross-shard queries
Any query that does not filter by customer_id becomes a scatter-gather across 12 shards. Its latency is the slowest shard's p99, so a 40 ms p99 per shard can become a 150 ms p99 overall with 12 fan-out. Either denormalise the reporting query into a separate analytics store, or accept the fan-out for low-rate admin paths only.
Failure modes to watch
A lookup table that becomes the new hot spot. Reads of the mapping must be cached with a version, or every write pays a round trip. A dedicated tenant shard that grows past its own ceiling in six months, which is why the move should be paired with a capacity alert at 60% of the shard's measured write limit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48Your RDS for PostgreSQL primary runs in one region across three AZs. Walk through what happens when one AZ fails, then when the whole region fails, and say what recovers automatically in each case.
The 90-second answer
A Multi-AZ RDS instance keeps a synchronous standby in a second AZ. If the primary's AZ fails, RDS promotes the standby and repoints the instance's DNS name to it. The application reconnects to the same endpoint, with no code change. AWS documents this failover as typically 60 to 120 seconds, and in-flight transactions on the old primary are rolled back. Because the standby acknowledged every commit before the failure, the RPO is zero.
A region failure is different. The standby lives in the same region, so it is gone too. Multi-AZ does nothing here. Recovery needs a copy in another region, and that copy is replicated asynchronously, so its RPO is the replication lag at the moment of failure. Promotion is a deliberate act, not an automatic one.
Trace, hypothetical timings.
| Time | Event | Result |
|---|---|---|
| 00:00 | AZ-a fails, primary lost | connections error out |
| 00:05 | RDS detects failure | standby in AZ-b promoted |
| 01:30 | DNS CNAME points to AZ-b | app reconnects, writes resume |
| 00:00 | region us-east-1 fails | no local standby, Multi-AZ idle |
| 00:00 + 2 s | replica in us-west-2 has lag 1.8 s | 1.8 s of commits may be lost |
| after decision | promote us-west-2, repoint DNS | TTL plus client caching sets the RTO |
For the region case, the RTO is the human decision time plus promotion plus DNS TTL plus reconnect. The RPO is the lag you measured, so a 1.8 s lag means up to 1.8 s of committed writes are gone. Aurora Global Database lowers the lag, usually under a second, and offers a managed switchover, but it is still asynchronous.
The trade-off. Multi-AZ is cheap, automatic and zero-RPO, but it only covers loss of a facility. A cross-region replica covers region loss but costs a second instance, cross-region data transfer, and a runbook that someone must run under pressure. I would keep Multi-AZ on for every production instance and add a cross-region replica only where the business has stated an RPO and RTO that a region loss would break.
Failure modes. If the old primary returns in the lost region and still accepts writes, you have split brain, so fence it before promoting the replica. Check the replica is writable and its lag is under your RPO before moving traffic. Detect lag with the replica lag metric and alert on it, not just on failover events.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49The payments ledger runs on RDS for PostgreSQL and costs the business about $1.2M per hour of downtime. Leadership wants RTO 15 minutes and RPO 1 minute. Derive those targets from the impact, then choose between backups and replication to meet them.
The 90-second answer
I start from the business numbers, not the tooling. RTO is how long the service can be down before the cost exceeds what the control costs. RPO is how much recent committed data we can afford to lose, measured in time back from the failure. Here the brief already gives both (15 min and 1 min), so my first job is to check whether they are achievable and which failure each one has to survive. Then I pick the mechanism per failure class, because no single option covers all of them.
Deriving the numbers. $1.2M per hour is $20,000 per minute. The first 15 minutes of downtime therefore cost about $300,000, and each minute beyond that adds $20,000. That is the number that decides how much to spend on the standby: a warm standby that cuts recovery from hours to 15 minutes pays for itself after a single long outage, while a cold restore does not. For RPO, assume the ledger commits 400 transactions per second at peak (hypothetical, to be replaced with measured figures). A 60 s RPO means up to 24,000 committed transactions can be missing after recovery, and each must be reconciled against the payment processor. If reconciliation costs about 2 minutes per 1,000 transactions, that is 48 minutes of manual work, so the RPO is about reconciliation cost as much as data loss.
Matching mechanisms to failure classes.
AZ failure: a Multi-AZ DB instance replicates synchronously to a standby in another AZ. RPO is 0 for committed data, and AWS documents failover as typically 60 to 120 seconds, which fits 15 minutes with room to spare. Limit: it does not protect against region loss or bad writes.
Region failure: a cross-region read replica is asynchronous. Its RPO equals replication lag, which you measure with the ReplicaLag metric. At 400 tx/s, a 30 s lag puts 12,000 transactions at risk, so a 1 minute RPO means alerting on lag above about 45 s, not merely having a replica. Promotion is a manual or scripted step, and RTO is detection plus promotion plus DNS plus app reconnect.
Logical corruption or a bad migration: replication copies the damage within seconds. Point-in-time restore (PITR) from automated backups restores to a chosen second, with the latest restorable time typically within the last 5 minutes. Its RTO scales with database size: a 2 TB restore taking about 90 minutes (hypothetical) blows the 15 minute target outright, so PITR cannot be the regional-failure answer.
The arithmetic for region failure (hypothetical timings): detection 3 min, replica promotion 5 min, DNS change with a 60 s TTL 1 min, application reconnect and cache warm 2 min. Total 11 min, leaving 4 min of margin against the 15 min RTO. Cut the detection step with automated health-based failover, and alert on lag so the 1 min RPO is actually observed.
Failure modes to name. Promotion without a fenced old primary can produce split writes, so the old region must be stopped or write-fenced first. DNS caches can keep clients on the failed endpoint longer than the TTL if they ignore it. Backups that were never restored in a test give an RTO that is a guess; I would run a timed restore each quarter and record the measured figure.
What I would recommend. Multi-AZ for AZ loss, a cross-region replica with lag alarms for region loss, and PITR with a tested restore runbook for corruption. If the regional RTO measured in drills exceeds 15 minutes, the honest move is to tell leadership the cost of the faster option, such as Aurora Global Database, rather than quietly relaxing the target.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50Your nightly backup job reports success. What single fact does that prove about your ability to recover, and what must a restore drill measure that the job does not?
The 60-second answer
The job proves that bytes were written somewhere. It does not prove that those bytes restore into a working service within the recovery time the business allows. A backup can succeed and still be unusable: the restore role cannot decrypt the KMS key, the dump omits a schema the app needs, or the restore takes longer than the RTO. Only a real restore into an isolated target shows that.
What the drill measures:
- Restore completes into an isolated account or VPC, not over the source.
- Elapsed time against RTO, end to end, including secrets and DNS, not just the database coming up.
- Data age against RPO: the timestamp of the newest recovered record compared with the failure time.
- Application-level integrity: a known query or row count checked against an expected value, not "the engine started".
A worked trace (hypothetical figures, RTO 60 min, RPO 15 min):
| Step | Elapsed | Result |
|---|---|---|
| Restore started into isolated account | 0 min | accepted |
| Instance available | 38 min | ok |
| Newest order check | 44 min | newest order 02:57, failure at 03:10, RPO 13 min |
| App smoke test against restored DB | 61 min | fails: payment API key not in backup |
The restore fits the RTO, but the service is not back until the app can authenticate, which is 61 minutes. The drill found a dependency the backup never captured.
How to detect a broken backup path
Record each drill's restore duration, RPO achieved and smoke-test result, and alert when any crosses its target. Re-run the drill after changes to the schema, key policy, engine version or dependent services, because those are the changes that break restores silently.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51Your order API runs in two regions and the primary region is partly degraded, not dead. Compare active-passive and active-active for this service, and say what DNS failover can and cannot guarantee for writes.
The 90-second answer
I'd start with the write path, because that decides the topology. If every write goes to one primary database, run active-passive: the standby takes reads and warms up, and failover is a promotion plus a DNS change. If writes must succeed in both regions during an outage, you need active-active with a rule for which region owns each order. Without that rule you get split brain: two regions accept conflicting updates to the same order, and DNS has no way to stop the one that lost its health check from still answering.
DNS failover moves new connections. It does not fence the old primary. A client with a cached answer, or a resolver that ignores TTL, keeps writing to the degraded region until its connection fails.
Assumptions. Route 53 failover records, a health check on /healthz with a 10 s request interval and a failure threshold of 3, record TTL 60 s, and an async cross-region replication lag of about 2 s at steady state. All figures below are hypothetical and labelled as such.
Where the time goes. Detection is interval times threshold: 10 s × 3 = 30 s, plus the time the health check takes to actually see the outage. Resolver and client caching adds up to the TTL, 60 s. Connections that were already open keep going until they error. A reasonable budget is about 90 s to the first new connection in the standby region for most clients, with a long tail from clients that cache past TTL.
Consistency. In active-passive with async replication, a promotion loses whatever had not replicated. Lost writes are about lag × write rate: 2 s × 300 orders/s = roughly 600 orders. You name that number as the RPO and you decide whether the business accepts it.
In active-active you choose a single writer per customer or order (home region, stored in the data and checked on each write), or you accept conflicts and resolve them. The first avoids conflicts but makes the home region a dependency for that customer. The second needs a merge rule for every field, which most order systems do not have.
Split brain and fencing. Stop the old primary from accepting writes before the standby promotes. Practical options: a lease held in a quorum store that the writer must renew, with writes refused when the lease expires; or a database-level fence such as a generation number on each write that the new primary rejects from the old generation. A health check result alone is not a fence, because the old region may be healthy from its own viewpoint.
| Topology | Writes during regional loss | RPO | Main risk |
|---|---|---|---|
| Active-passive, async | Stop until promotion | seconds of lag | lost acknowledged writes |
| Active-passive, sync cross-region | Stop until promotion | zero | latency on every write |
| Active-active, home region per order | Only orders homed to the failed region stop | zero for owned data | home region is a hard dependency |
| Active-active, multi-writer | Both accept | none defined without merge rules | silent conflicts |
What I change. Lower the health check interval only if the extra checks cost less than the false failovers they cause. Use the lease fence before promoting, and make the write path refuse requests whose generation or lease is stale. Log the region that served each write, so after an incident you can count the orders that had to be reconciled.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52Your load balancer removes an instance after two missed heartbeats, but a healthy instance pausing for 8 seconds in garbage collection keeps getting pulled. How do you tune heartbeat interval and timeout, and what does faster failover cost you?
The 60-second answer
For a check that starts just after a failure, removal takes about timeout + (threshold - 1) x interval: the first failing check runs to its timeout, then the remaining misses each wait one interval. Every setting that shortens detection also shortens how long a stalled but healthy instance can go silent before it is removed. So I tune for the longest pause I expect to tolerate, not the fastest detection the dashboard can show, and I make removal cheap to reverse. Faster failover also concentrates load on the survivors, which is where it usually hurts.
Check the current defaults before quoting them. ALB target group health checks default to a 30 s interval, a 5 s timeout, an unhealthy threshold of 2 and a healthy threshold of 5. Route 53 health checks use a 30 s request interval (10 s fast) and a failure threshold of 3, adjustable from 1 to 10.
| Setting (interval / threshold / timeout) | Approx. time to remove | Stall tolerated before removal | Cost |
|---|---|---|---|
| 30 s / 2 / 5 s (ALB default) | ~35 s | ~35 s | slow failover, few false removals |
| 10 s / 2 / 2 s | ~12 s | ~12 s | moderate false-removal risk |
| 5 s / 2 / 1 s | ~6 s | ~6 s | GC pauses and CPU throttling remove healthy hosts |
Trace of the false positive. Interval 5 s, threshold 2, timeout 1 s. The instance freezes at t=0.5 for 8 s, so it resumes at t=8.5. The check issued at t=1 hangs and times out at t=2 (miss 1). The next check is issued at t=6 and times out at t=7 (miss 2), so the instance is removed at t=7. It resumes at t=8.5, healthy, and is already out of rotation. Its logs show no crash or error, so the removal looks like a random failover. Removal came about 6.5 s after the freeze began, which is the stall the setting tolerates.
The cost of fast failover. Six instances each carry 1,200 req/s, which is 65% of a 1,850 req/s ceiling, for 7,200 req/s in total. Lose one and the other five carry 1,440 req/s each, 78% of capacity. Now suppose an AZ partition makes two of the six look dead at once. The remaining four must take the full 7,200 req/s, so each carries 1,800 req/s, which is 97% of capacity. Fast detection turned a partition into an overload, and p99 crosses the SLO on the survivors. Fast failover is only safe where the surviving capacity covers the peak with the failed share removed.
What I change.
- Split liveness from dependency health. Liveness is a shallow local check that says the process can answer. Anything that calls the database belongs to readiness, so a slow dependency does not evict every instance together.
- Set the threshold so the tolerated stall exceeds the worst observed pause. Measure GC and throttling pauses from metrics before choosing a number.
- Require agreement from several observers, or several consecutive windows, before removing a host from a large pool.
- Keep headroom so losing one zone or one instance still meets the SLO at peak.
How it fails and how you see it. Flapping shows as the same instance entering and leaving the target group several times an hour. A false removal shows as a removal event with no crash, OOM or error in that instance's logs. Track both per week. If removals outnumber real failures, the threshold is too tight, not the instance too unstable.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53A consensus cluster runs five voting members, three in AZ-a and two in AZ-b. Which single AZ failure stops writes, and what would you change so that losing either AZ leaves the cluster writable?
The 90-second answer
Assuming strict majority quorum and whole-AZ failures, losing AZ-a stops writes. Losing AZ-b does not. With five voters, quorum is 3. AZ-a holds three of them, so its loss leaves two, and no leader can gather a majority. AZ-b holds two, so its loss leaves three, which is enough. The cluster survives one failure and not the other, depending on which zone is larger.
The fix is a third failure domain, not more nodes in the same two zones.
| Layout (voters) | Quorum | Lose AZ-a | Lose AZ-b | Lose AZ-c |
|---|---|---|---|---|
| 3 + 2 (two AZs) | 3 | 2 left, stalls | 3 left, writes | n/a |
| 2 + 2 (two AZs, 4 nodes) | 3 | 2 left, stalls | 2 left, stalls | n/a |
| 2 + 2 + 1 (three AZs) | 3 | 3 left, writes | 3 left, writes | 4 left, writes |
The general rule is that a two-AZ split cannot survive either AZ loss. Survival of AZ-a needs AZ-b to hold at least quorum, and survival of AZ-b needs AZ-a to hold at least quorum. Together that requires A + B at least 2 × quorum, but quorum is more than half of N, so A + B = N can never reach it. Adding a node to the two zones does not change this. Making the split even does not help either, because a 2 + 2 split stalls on both sides.
The third AZ can host a witness or a small voter. It does not need full data capacity, only enough to break ties. Put it in a different zone from both data AZs, otherwise you have just moved the problem.
Partitions behave the same way. If the link between AZ-a and AZ-b drops and the zones themselves stay up, the side with three voters keeps writing and the side with two stops. Clients on the minority side get timeouts, not stale reads, if the store is configured for linearizable reads. Check that your client library retries against the other endpoints rather than hanging on the old leader.
Failure modes to watch for.
- Leader election storms after the loss of the majority side, visible as repeated leader changes in the consensus logs and rising commit latency.
- Election timeouts set below the cross-AZ round trip, which cause spurious leader changes during normal load. Measure the inter-AZ RTT first and size timeouts above its p99.
- Quorum loss that goes unnoticed because the service still answers reads from followers. Alert on the count of reachable voters, not only on service health.
What I would ship. Five voters split 2 + 2 + 1 across three AZs, with the single voter in a third zone, and an alert when fewer than four voters are reachable. That alert fires before the next failure can cost you writes.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54Metrics, logs and traces each answer a different production question. Which one answers 'is p99 latency on checkout above 500 ms right now, and since when?' and why is a log line the wrong tool for that?
The 60-second answer
A metric answers the aggregate question: how much, how often, and is it getting worse. For checkout p99 I'd use a histogram metric, http_request_duration_seconds, and alert on a PromQL expression over a 5-minute window:
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket{route="/checkout"}[5m]))
)That gives one number per evaluation interval, stored as a time series, so I can say the value crossed 500 ms at 14:07 and has stayed above it since. It is cheap to keep for months and cheap to alert on.
A log line is a record of one event. Answering 'what is the p99 over the last five minutes' means reading and parsing every line in that window, and the cost grows with traffic. Logs are the right tool for the next question: what happened in this specific request, with its arguments and error text.
| Signal | Question it answers | Shape | Cost driver |
|---|---|---|---|
| Metric | how much, how often, trend | pre-aggregated numeric series | number of distinct label combinations |
| Log | what happened in this event | one record per event | bytes ingested and scanned |
| Trace | where did this one request spend its time | tree of spans across services | spans kept, usually sampled |
Failure modes. The metric breaks when labels carry unbounded values. Putting user_id or raw URL paths into labels creates one series per value, and the time-series database slows or drops data. Use route templates, not raw paths.
Traces break under head sampling. If you keep 1% of requests chosen at the start, the rare slow ones are mostly discarded before you know they were slow. Tail-based sampling, which decides after the trace completes, keeps the slow and errored ones.
The usual pattern is to alert on the metric, then pivot to traces for the slow requests and to logs for the detail of one of them. Linking them through a shared trace ID in log lines is what makes that pivot fast.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55Your Prometheus runs 3 replicas behind a remote_write to a long-term store, and a product team wants a per-tenant error-rate panel for 8,000 tenants with a 15 s scrape. Each replica keeps its own head, and dashboards must show a p99 per tenant. Which labels do you put on the metric, where does the cardinality cost land (per replica, in remote_write, or in the query), and what do you do instead?
The 90-second answer
The cost of a label is paid in three places, and they are not the same place. Each of the 3 replicas scrapes the same targets, so every series exists three times in head memory and in remote_write queues. The remote_write path then ships each unique series, so cardinality multiplies wire volume and the store's ingest and index. The query path pays per series touched. A per-tenant p99 is a histogram per tenant, so tenant cannot sit on the bucket series without multiplying the bucket count too. I would not put tenant on the metric at all. I would keep the histogram bounded, put tenant identity in exemplars and traces, and compute per-tenant error rates from a bounded top-K rule plus logs for the tail.
The arithmetic
Hypothetical figures, labelled as such. A histogram with 12 buckets, 4 routes, 2 methods and 6 status classes:
12 buckets × 4 × 2 × 6 = 576 series per service, plus _sum and _count (2 × 48 = 96), so about 672 series per service with no tenant.
Add tenant across 8,000 tenants:
672 × 8,000 = 5.4 million series per service, times 3 replicas = 16.1 million head series, all shipped by remote_write. At one 15 s scrape that is 1.07 million samples per second per service, against 2,016 per second without the label.
The subtle part is the query. A p99 per tenant needs histogram_quantile over sum by (le, tenant). Prometheus loads every bucket series for every tenant in the window, so a 24 h panel reads about 5.4 million series × 5,760 samples each before any aggregation. The panel times out on the query path long before head memory is the problem.
Failure modes and how you detect them
| Symptom | Cause | Detect with |
|---|---|---|
| Head memory differs by replica | Each replica's churn and series set diverges | prometheus_tsdb_head_series per replica |
| remote_write falls behind | Shards cannot drain the series rate | prometheus_remote_storage_samples_pending and prometheus_remote_storage_highest_timestamp_in_seconds lag |
| Remote store rejects writes | Per-tenant series cap or ingest rate limit | remote_write 429 counts, prometheus_remote_storage_samples_failed_total |
| Query times out only for wide ranges | Query touches every tenant's buckets | prometheus_engine_query_duration_seconds by range |
| Tenant count doubles without warning | Labels created from unbounded input | rate of prometheus_tsdb_head_series_created_total |
What to use instead
- A histogram with only
le,route,methodandstatus_class. Its size is fixed by the bucket count, not the tenant count. - A recording rule per tier, for example
tenant_tier, which is bounded and what finance actually bills against. - Top-K tenants by error volume in a rule, with the rest folded into
other. Keep the rule's top set in a small table so the panel reads 21 series, not 8,000. - Exemplars on the histogram, carrying the trace id. An engineer who asks "why was tenant 4411 slow" follows the exemplar from the bucket to the trace, which holds the tenant.
- Per-tenant error counts from the log index or a columnar store, queried on demand, which costs nothing when nobody opens the panel.
What I would ship
Set sample_limit per scrape job and an explicit per-tenant ceiling in the remote store, so one tenant's misconfigured client fails its own writes. Alert on remote_write lag, not on head size, because lag is what the product team sees first. Give the per-tenant panel a documented query window of 1 h, and say in the panel's title that wider windows use the top-K rule.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56Explain why a multiwindow burn-rate alert pages on a fast error spike without staying open for an hour after the fault is fixed, and what a single one-hour window would get wrong.
A burn-rate alert compares the observed error ratio with the ratio that would spend the error budget at a chosen speed. For a 99.9% SLO over 30 days, the budget is 0.1% of requests, or 0.001 as a ratio. A burn rate of 14.4 sets the threshold at 14.4 x 0.001 = 0.0144, or 1.44% errors. At that rate the budget lasts 720 / 14.4 = 50 hours, so each hour spends 2% of it. That is fast enough to page, because waiting would leave little budget to react with.
A single window cannot give both a clean fire and a clean clear. A 1 h window averages away a brief spike, but after a fix it still contains the bad minutes for close to an hour. A 5 m window clears within minutes of the fix, but a 30-second blip at 100% errors gives it a ratio of 0.5 / 5 = 0.10, well over 0.0144, and pages a human for nothing. Requiring both windows to exceed the threshold keeps the 1 h window as the gate for firing and lets the 5 m window decide when to stop firing. The alert fires only when the long window confirms a sustained burn, and it clears as soon as the short window shows the burn has stopped.
Worked trace. Assume constant traffic, a 99.9% SLO, and 10% errors from 10:00 to 10:30, then 0% after the fix. The threshold is 0.0144. The 1 h ratio during the outage is 0.10 x minutes_elapsed / 60. The 5 m ratio is 0.10 while the outage fills the window and 0 once the window is past the fix.
| Time | 1 h error ratio | 5 m error ratio | Both over 0.0144? |
|---|---|---|---|
| 10:05 | 0.0083 | 0.10 | No |
| 10:10 | 0.0167 | 0.10 | Yes, pages |
| 10:30 | 0.050 | 0.10 | Yes, still firing |
| 10:35 | 0.050 | 0.000 | No, clears |
The 1 h window crosses 0.0144 after 0.0144 / 0.10 x 60 = 8.6 minutes, so the page fires at about 10:09, plus any for: delay. At 10:35 the 1 h ratio is still 0.050 because the window holds all 30 bad minutes, yet the 5 m window is clean, so the combined alert clears at about 10:35, or 10:37 with a 2 m for:. A single 1 h alert would stay open until the bad minutes in its window fell below 8.6 minutes worth, at about 11:21. That is the hour-long tail the short window removes.
- alert: CheckoutFastBurn
expr: |
(sum(rate(http_requests_total{service="checkout",code=~"5.."}[1h]))
/ sum(rate(http_requests_total{service="checkout"}[1h]))) > (14.4 * 0.001)
and
(sum(rate(http_requests_total{service="checkout",code=~"5.."}[5m]))
/ sum(rate(http_requests_total{service="checkout"}[5m]))) > (14.4 * 0.001)
for: 2m
labels:
severity: pageTrade-offs. The AND does not make firing faster than the 1 h window alone. Firing waits for the long window, and the wait depends on the error rate: at 20% errors the 1 h window crosses in 4.3 minutes, at 10% in 8.6 minutes, at 2% in 43 minutes. A slower burn therefore needs its own alert at a lower rate, for example burn 6 over 6 h, which spends 5% of the budget per hour and can go to a ticket instead of a page. Stretching the fast pair to cover slow burns either pages too late or pages on noise.
Failure modes to check. At low overnight traffic a handful of requests can swing the ratio, so add a minimum request count over the window to the expression before paging on it. During a deploy, a brief 5xx spike can trip the 5 m window while the 1 h window is already elevated from earlier errors. If that recurs, gate the rollout on a canary error check rather than silencing the pager, since the alert is correctly reporting a burn.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57Your request-serving API has no SLIs yet. How would you choose them so they reflect what users actually experience, and where would you measure each one?
The 90-second answer
I'd start from the user's journey, not from the server's dashboards. For each important request, the question is: did it succeed, and did it finish fast enough to feel like it worked? That gives two SLIs per journey, availability and latency, each written as a ratio of good events over valid events. I'd add a third only if the service has a correctness promise, such as the order total being right.
The SLI is a proportion, not an average. Take a 99.9% SLO over 30 days. The error budget is 0.1% of the window: 0.001 × 43,200 minutes = 43.2 minutes of full outage. Measured in requests instead, at 10 million valid requests a month the budget is 10,000 bad requests. At a steady 1,000 req/s, 10,000 failed requests equals 10 seconds of total outage, so the budget is spent by a short, sharp failure as easily as by a long, partial one. That is why a request ratio is the right unit: it weights a bad minute at peak more heavily than a quiet one. A mean latency can look healthy while 2% of users wait 3 s, so latency becomes 'proportion of requests under 400 ms' rather than a percentile averaged across instances.
Defining good and valid
| Event | Counted as | Why |
|---|---|---|
| 2xx or 3xx, under threshold | good | user got what they asked for in time |
| 2xx or 3xx, over threshold | valid, not good | succeeded, but too slow |
| 5xx, or timeout at the edge | valid, not good | service failed the user |
| 429 | valid, not good | we refused capacity the user needed |
| other 4xx | excluded | client error, not our failure |
| health checks, synthetic traffic from our own pollers | excluded | they inflate the good count |
Excluding other 4xx is a choice you have to defend. If a bad deploy starts returning 400 for valid payloads, the SLI stays green. Watch the 4xx rate separately, and treat a sudden jump as a budget question too.
Where to measure
The load balancer sees every request that reaches it, with HTTPCode_ELB_5XX_Count and TargetResponseTime. It misses requests that never arrive: DNS failure, TLS handshake errors, a client on a broken network path. Application metrics miss requests that queue before the process accepts them. Synthetic probes from outside the region catch the first class but only sample a few requests a minute. I'd use the load balancer or the service's own histogram for the SLI, a probe for the 'can a user reach us at all' check, and real-user metrics if the product has a client.
A Prometheus form of the latency SLI, assuming a histogram named http_request_duration_seconds with a code label and a 400 ms bucket:
sum(rate(http_request_duration_seconds_bucket{le="0.4",code=~"2..|3..",route!~"/healthz"}[5m]))
/
sum(rate(http_request_duration_seconds_count{code=~"2..|3..|5..|429",route!~"/healthz"}[5m]))The numerator is successful responses at or under 400 ms. The denominator is every valid request, including 5xx and 429, so a failing service cannot raise its own ratio. The availability SLI uses the same denominator with a numerator of code=~"2..|3.." only. Compute both from the same series and the same window, so the ratio cannot drift from the budget it is meant to track. The 5-minute window is illustrative; match it to your alerting.
Failure modes I'd check for
Retries count twice: a client that retries after a timeout produces two events, one of which may be good. Count the attempt the user sees, usually the final response, and say which you chose. A load balancer returning 503 with no healthy targets is a real outage, not a load balancer metric to ignore. And a latency threshold that is never revisited drifts away from what users tolerate, so review the 400 ms number against support tickets and conversion data each quarter.
I would not use CPU, pod count or queue depth as SLIs. They explain why the service is unhealthy after the SLI has already moved.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58For a 99.9% availability SLO measured over 30 days, how many minutes of full downtime does the error budget allow?
The 60-second answer
The error budget is the unreliability the SLO allows: 1 minus the target. For 99.9% that is 0.1% of the window. A 30-day window has 30 × 24 × 60 = 43,200 minutes, so the budget is 0.001 × 43,200 = 43.2 minutes of full unavailability.
Assumptions I state before answering: the SLI is time-based, so each minute is either good or bad, and the window is a rolling or fixed 30 days rather than a calendar month, which changes the minute count.
| SLO | Budget per 30 days |
|---|---|
| 99% | 432 min (7.2 h) |
| 99.9% | 43.2 min |
| 99.95% | 21.6 min |
| 99.99% | 4.32 min |
The useful consequence is burn. A single one-hour full outage uses 60 / 43.2 ≈ 139% of the budget, so the SLO is missed for the window even though the service looks fine the week after. If the SLI is request-based instead, the budget is 0.1% of valid requests, and a 10-minute partial outage at 50% error rate burns roughly 5 minutes of equivalent budget. That is why the SLI definition has to be fixed before the arithmetic means anything.
When not to use the flat minute budget: for a service with very uneven traffic, a time-based SLI rewards quiet outages at 3 a.m. and punishes peak-hour blips. A request-based SLI is the safer default for an API.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59Your 99.9% availability SLO on the checkout API is burning error budget at about 3x for two days, and the static alarm on 5xx rate never fires. Would you page on a static threshold or on multi-window burn rates, and what windows and factors would you set?
The 90-second answer
I'd page on burn rate, not on a raw error-rate threshold. Burn rate is the observed error ratio divided by the error ratio the SLO allows. At 99.9% the allowance is 0.1%, so a burn rate of 1 spends exactly the 30-day budget over 30 days, and 3 spends it in 10 days. A static threshold of 1% never fires at 3x (that is only 0.3%), and a threshold tight enough to catch 3x (0.1%) fires on every small blip at low traffic. Burn rate scales the alert to the budget, so the threshold means the same thing for every service.
Each alert needs two windows that must both breach: a long window that proves the burn is real and a short window that proves it is still happening. Without the short window, the alert keeps firing for an hour after the fault is fixed.
The arithmetic
Budget over 30 days is 0.001 × 43,200 min = 43.2 minutes of full-outage equivalent. A burn rate B over a window W consumes B × W / 720 h of the monthly budget.
| Severity | Long window | Short window | Burn rate | Budget consumed | Action |
|---|---|---|---|---|---|
| Fast | 1 h | 5 min | 14.4 | 2% | page |
| Medium | 6 h | 30 min | 6 | 5% | page |
| Slow | 24 h | 2 h | 3 | 10% | ticket |
A 3x burn for two days is 3 × 48 / 720 = 20% of the budget, so the slow rule catches it inside the day and never pages a human for a bad hour that resolved itself.
The alarm expression
On ALB, I compute the ratio with CloudWatch metric math from HTTPCode_Target_5XX_Count and RequestCount, per target group, and alarm when both windows exceed the threshold:
(errors_1h / requests_1h) > 14.4 * 0.001 AND (errors_5m / requests_5m) > 14.4 * 0.001
The same shape works in any metrics system. In Prometheus I'd use recording rules for each window so the alert query stays cheap.
Trade-offs and when not to use it
Static thresholds still earn their place for hard limits (disk full, certificate expiry, a queue past a physical bound). Burn rates are for error budgets, and they only work if the SLI actually reflects user pain. Measure at the load balancer, and say whether ELB_5XX (generated by the ALB itself) counts against the SLO, because it is a different failure from target 5xx.
Failure modes to name
- Low traffic: at 20 requests per minute, a single failure is 5% in the short window, so the 14.4x rule fires on one bad request. Add a minimum request count or accept ticket-only at low volume.
- Counter resets and missing data: a target deregistered mid-window drops its series. Treat no-data as breaching for SLO alarms, or the alarm goes quiet exactly when the service is broken.
- Mismatched denominators: if health-check requests count in
RequestCountbut not in the SLO, the ratio is diluted and 3x burns look like 1x. - Detection: compare the alert's implied budget spend against the SLO report each month. If the two disagree, the rule is wrong, not the budget.
I'd keep the static 5xx alarm as a sanity check for total outage, and page only on the fast and medium burn rules.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60A sev-1 is open and nobody yet knows the root cause. Who takes which role in the first ten minutes, what does the incident commander stop doing, and how do you keep updates flowing to customers without anyone guessing?
The 90-second answer
The incident commander (IC) runs the incident and does not debug. The first decision is to separate three jobs that otherwise collapse onto whoever noticed the page first: command (IC), technical investigation (one or two responders), and communication (a comms lead who owns every outbound message). A scribe keeps a timeline with timestamps. Until the root cause is known, the IC works from one question: what is the customer impact right now, and what is the fastest action that reduces it, whether or not we understand why it happened. That usually means rollback, traffic shift or disabling a feature flag before diagnosis.
The IC stops doing hands-on work the moment they start taking a shell or reading logs. Once that happens nobody is watching the clock, the comms cadence slips, and decisions get made by whoever is loudest.
Roles and what each one owns
| Role | Owns | Does not own |
|---|---|---|
| Incident commander | Priorities, go/no-go on mitigations, handoffs, declaring resolved | Debugging, writing customer text |
| Technical lead | Hypotheses, the one change in flight at a time | Deciding severity or customer messaging |
| Scribe | Timestamped log of actions, observations, who-said-what | Interpretation |
| Comms lead | Status page, internal channel summary, customer account teams | Technical claims they have not checked with the tech lead |
| Exec liaison (sev-1 only) | Business decisions such as refunds or pausing a launch | Operational changes |
Communication cadence. Set it at declaration and keep it even when nothing has changed. For a sev-1, post an update every 30 minutes at minimum, and say "no change, still investigating, next update at 14:30 UTC" when that is the truth. A missed update reads as silence, and silence reads as a bigger outage.
Mitigate before you diagnose. Trace the first 15 minutes of a plausible incident. 14:02 p99 checkout latency climbs from 300 ms to 4 s. 14:06 IC asks: did a deploy go out in the last hour? Yes, at 13:55. 14:07 IC orders rollback of the deploy, not a root-cause search, because rollback is reversible and takes about 4 minutes on this service. 14:11 error rate falls back to baseline. 14:12 comms posts "mitigated, cause under investigation". The root cause is found at 16:40. The IC never needed it to cut impact by 90%.
Alternatives and when not to use them. A single-threaded IC who also debugs works for a two-person team with a clear fault, and fails as soon as a second system is involved. A committee with no owner is the common failure: five people in the channel, three of them proposing different fixes, none of them executing. Rotate the IC role on long incidents (after about 90 minutes) with an explicit handoff: current state, open hypotheses, what is in flight, next update time.
Failure modes and how you detect them
- Two responders change production at the same time. Detect with a change log: any production mutation is announced in the channel before it runs.
- The status page says "resolved" while error budget is still burning. Detect by comparing the resolve action against the SLI dashboard, not against the responder's memory.
- Customer account teams hear the outage from customers first. Detect with a rule that comms posts within 15 minutes of declaration, even if the message is only "we are aware".
What you change beforehand: a runbook that names the IC, the comms owner and the rollback command for each critical service, and a paging policy that declares the role before the first responder joins.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61Your postmortem names operator error as the root cause of a route-table change that cut a private subnet off from the internet. Explain why that finding fails a blameless review, and how you would turn the contributing factors into action items that get done.
The 90-second answer
"Operator error" ends the analysis at the person who pressed apply. The next engineer with the same access makes the same mistake, so the finding fixes nothing. A blameless review asks why the system let a reasonable action produce that outcome: which checks did not run, what the tooling allowed, and what signal the people on watch actually saw. Each answer is a contributing factor. Action items come from factors, and an item ships only if it has one owner, a date and a done condition someone can check.
Hypothetical example, labelled as such: at 14:02 UTC a Terraform apply removed the 0.0.0.0/0 route from a private route table, so 6 of 40 services lost outbound calls to a payment provider. The first signal was a customer ticket at 14:13, 11 minutes later. The factors were: the change was tagged low-risk, so no second person reviewed the plan; no alarm watched NAT gateway egress against a baseline; and a console edit two weeks earlier had drifted the table, so the diff looked routine.
| Contributing factor | Action item | Done when |
|---|---|---|
| Routing changes skip second review | CI requires a second approver when a plan touches aws_route or aws_route_table | Pipeline blocks a single-approver merge on a test branch |
| No egress signal | Alarm when NAT BytesOutToDestination drops below 50% of its 7-day baseline for 5 min | Alarm fires in a game-day injection within 6 min |
| Console drift hid the diff | Daily terraform plan against prod, drift posted to the owning team's channel | Job has run 14 days with no unowned findings |
Why these ship and others stall: "improve monitoring" has no done condition, and an item with no owner sits in the backlog until someone deletes it. Items that need a new alarm or pipeline gate compete with feature work, so each needs a priority tied to the SLO it protects, agreed before the review closes.
Trade-off: a long list looks thorough and completes at a low rate. I cap a postmortem at three to five items, record the rest as accepted risk, and review open items at 30 days. An item still open then goes to the owner's manager, not to another meeting.
Failure mode: the review lands on a root cause that happens to be the fix the team already wanted. Check that every factor comes from the timeline, not from the proposed fix.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62Which ALB metric tells you whether a 502 was generated by the load balancer itself rather than by your application targets?
The 90-second answer
The metric is HTTPCode_ELB_5XX_Count. It counts 5xx responses the load balancer generated itself, such as 502 when a target closed the connection or sent a malformed response, 503 when no healthy target was available, and 504 when a target did not respond within the idle timeout. The companion metric HTTPCode_Target_5XX_Count counts 5xx responses that the registered targets returned. Comparing the two tells you which layer produced the error before you start reading application logs.
Why the split matters
The two counters point at different fixes. If HTTPCode_Target_5XX_Count climbs, the application is returning the errors, so I look at the new revision's code, config and dependencies. If only HTTPCode_ELB_5XX_Count climbs, the problem sits between the load balancer and the targets: health checks failing, a target group with no healthy hosts, or a timeout that the new version now exceeds.
| Counter | Who generated the 5xx | Typical cause after a deploy |
|---|---|---|
HTTPCode_ELB_5XX_Count | The ALB | No healthy targets (503), target timeout (504), connection reset (502) |
HTTPCode_Target_5XX_Count | The application | Exception, bad dependency, config error in the new revision |
Where to look next
Break the target-generated count down by target group or task definition revision. If the spike appears only on the new revision, the release is the likely cause. Keep the deploy timeline next to the graph so the start of the spike can be compared with the moment the new targets registered.
The mistake I see most is treating every 5xx as an application bug. The ALB's own errors can appear with a healthy application, so the first question is always which counter moved.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63Service-to-service calls on EKS time out for about 1% of requests, only to an external payments API through a NAT gateway, and only at peak. Walk through how you separate MTU, conntrack and SNAT port exhaustion, and which one you fix first.
The 90-second answer
I'd start by checking which of the three is actually failing, because they look the same from the client: a stalled connect or a read that hangs until the timeout. Peak-only points at capacity (conntrack or ports), and an external-only, size-dependent failure points at MTU. I'd confirm with the NAT gateway's ErrorPortAllocation metric and the node's conntrack counters before touching anything.
Port arithmetic. A NAT gateway translates each private source to a public IP and port. For a single destination IP:port, the limit is about 55,000 simultaneous connections per NAT gateway IP. Inside the node, Linux ephemeral ports default to 32768-60999, which is 28,232 ports. A closed connection holds its 4-tuple in TIME_WAIT for 60 s, so one source IP can open at most 28,232 / 60 ≈ 470 new connections per second to one destination IP:port. At 2,000 req/s with keep-alive disabled, you run out in about 15 s. That's the failure: connect() returns EADDRNOTAVAIL, or the NAT gateway drops the SYN.
MTU trace. A 1,500-byte path with a 1,500-byte payload needs DF bit handling. Path MTU discovery depends on the ICMP fragmentation needed message (type 3, code 4). If something drops it, a small TCP handshake succeeds and the first large response segment vanishes. The symptom is a connection that opens, sends a request, then times out on the read. Test it:
| Check | Command | Healthy result |
|---|---|---|
| path MTU | ping -M do -s 1472 payments.example | replies |
| ICMP reaching node | tracepath -n payments.example | pmtu line shows the real value |
| conntrack fill | cat /proc/sys/net/netfilter/nf_conntrack_count vs nf_conntrack_max | count well below max |
| SNAT ports | CloudWatch ErrorPortAllocation | zero |
A full conntrack table logs nf_conntrack: table full, dropping packet in dmesg, and this is the failure that correlates with traffic volume rather than payload size.
Order I'd fix them in. Peak-only and port errors point at SNAT first: add a second NAT gateway per AZ (each gives its own IP pool), and turn on keep-alive or connection pooling so connections stop churning. Conntrack second: raise nf_conntrack_max only after sizing it against memory, which is roughly 300 bytes per entry on modern kernels. MTU last, and the fix is to allow ICMP type 3 code 4 through security groups and NACLs, or set the interface and tunnel MTU deliberately, not to hack the client timeout.
What I'd not do. Raising the client timeout hides the symptom and doubles the load on a service that is already short of ports. Changing the NAT gateway to a bigger instance type does nothing, because NAT gateways are managed and their limits are per IP, not per CPU.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64A NAT gateway shows ErrorPortAllocation climbing, and only connections to one partner API time out while other destinations still work. Explain why only that destination fails, then compare adding Elastic IPs with shrinking the connection pool.
The 90-second answer
First I'd confirm the shape: one destination or many, and whether ErrorPortAllocation is climbing. Assume one partner endpoint over TCP, 203.0.113.10:443.
A NAT gateway rewrites each outbound connection to a source port on one of its Elastic IPs. For a single destination IP, port and protocol, one EIP offers about 55,000 usable ports. Once the gateway holds 55,000 simultaneous connections to that exact destination tuple, the next SYN has no port to map to and is dropped. It is not queued. Other destinations are unaffected because the limit is per destination tuple, which is why only the partner times out.
The arithmetic (hypothetical figures)
Forty instances each keep 1,500 pooled connections open to partner:443. That is 40 × 1,500 = 60,000 against a ceiling of 55,000, so at peak about 5,000 connection attempts fail. Application retries then add new SYNs while the failed sockets sit in the gateway's table, which makes the shortfall worse.
| Signal | Healthy | Exhausted |
|---|---|---|
ErrorPortAllocation (NAT gateway) | 0 | rising, packets dropped |
| Connection failures | none | timeouts to one destination only |
| Active connections to that destination | well under 55,000 | pinned near the ceiling |
IdleTimeoutCount | low | high when clients hold idle sockets past the gateway's 350 s TCP idle timeout |
Two approaches, compared on their main trade-off
Adding Elastic IPs is the fastest relief. A NAT gateway supports up to 8 EIPs, and each one adds about 55,000 ports per destination, so the ceiling moves from 55,000 to roughly 440,000. The trade-off is that it raises the ceiling for a pool that grows with fleet size, so the next scale-out hits the wall at a higher count. It also does nothing about a pool that leaks.
Shrinking the pool attacks the cause. Use keep-alive and a bounded pool per host, and set the client's idle timeout below 350 s so the client closes sockets before the gateway drops them. Retries should back off with jitter, not multiply. The trade-off is a code and config change that takes longer to ship, and a lower pool size can add latency if requests queue for connections.
Two other options take traffic off the shared pool. S3 and DynamoDB gateway endpoints bypass the NAT entirely and carry no hourly charge. For the partner, PrivateLink or a peered path helps only if the partner offers it. Bigger instances or more pods add connections to the same ceiling and make things worse.
How you know it is fixed
ErrorPortAllocation returns to zero and stays there through a peak. Active connections to the partner tuple sit at least 20% below the ceiling at the highest load you have seen.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65A pod in namespace checkout can resolve api.payments.internal, but each lookup takes about 5 seconds, while the same name resolves instantly from the node. Explain why the pod is slower, and how ndots and the search list cause it.
The 90-second answer
The pod and the node use different resolver configurations, and the difference is in how the name is expanded before it leaves the pod. A pod's /etc/resolv.conf contains the cluster DNS Service IP as its only nameserver, a search list built from the namespace (checkout.svc.cluster.local, svc.cluster.local, cluster.local, plus the node's inherited domains), and options ndots:5. The node has no such expansion, so it asks for the name once.
ndots:5 means any name with fewer than five dots is treated as relative to the search list. api.payments.internal has two dots, so the resolver tries each suffix first and the absolute name last. Assume a node search domain of ec2.internal (hypothetical, from a sample VPC):
| Order | Name queried | Result |
|---|---|---|
| 1 | api.payments.internal.checkout.svc.cluster.local | NXDOMAIN |
| 2 | api.payments.internal.svc.cluster.local | NXDOMAIN |
| 3 | api.payments.internal.cluster.local | NXDOMAIN |
| 4 | api.payments.internal.ec2.internal | NXDOMAIN |
| 5 | api.payments.internal | NOERROR, A record |
Each of the four misses is a round trip to CoreDNS before the answer arrives, so the name costs five lookups instead of one. Negative caching makes the misses cheaper on repeat, but it does not remove them from the first query path.
The 5 second figure is a separate effect. glibc defaults to timeout:5 attempts:2, so a lost UDP reply shows up as a 5 second pause, and a retry still succeeds. The search list multiplies the chance of such a loss because it sends more packets per lookup.
Confirm the cause with these three commands:
kubectl exec -n checkout deploy/api -- cat /etc/resolv.conf
kubectl exec -n checkout deploy/api -- sh -c 'time getent hosts api.payments.internal'
kubectl exec -n checkout deploy/api -- dig +search +showsearch api.payments.internalIf the dig +search output shows the four NXDOMAIN attempts before the success, the search list is the cause. Fix it with a trailing dot on the name (api.payments.internal.), which skips the search list for that call. Lowering ndots on the pod helps external-name callers but breaks bare service names that depend on the search path, so change it only for pods that mostly call external names.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66In a TCP handshake, which flag does a peer set to tell the sender that no connection exists on that port, and what happens to the connection attempt?
The 60-second answer
The peer sets the RST flag. A reset answers a SYN for a port with no listener by refusing the connection immediately: the sender's stack tears down the half-open attempt and returns an error to the application, usually ECONNREFUSED on Linux. Nothing is retried, so the failure shows up in milliseconds rather than after a timeout.
That contrasts with a silent drop. A firewall that discards the SYN gives the client no reply, so the client retransmits the SYN on its retry schedule (1 s, 2 s, 4 s on Linux) until the connect timeout expires. Same symptom to the user, very different timing and different fault domain.
| Situation | What the client sees | Typical timing |
|---|---|---|
| No listener, host reachable | RST in reply to SYN | fails in about 1 RTT |
| Firewall silently drops SYN | no reply, SYN retransmits | fails after the connect timeout |
What I would check next
A fast refusal points at the destination host: is anything listening on that port (ss -ltn), and is the service bound to the right address? A slow failure points at the path or a drop rule.
Failure mode
An RST that arrives after a SYN-ACK is a different event. The handshake already completed from the client's view, so the reset tears down an established-looking connection instead of refusing one.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67Intermittent 502s from an ALB to healthy EKS pods, with no application errors logged. Which OSI layer does the symptom point to, and what is the next diagnostic you run?
The 90-second answer
The 502 is the load balancer's own code. ALB returns 502 when the target closes or resets the connection, or sends a response it cannot parse. Healthy targets and silent app logs rule out routing (layer 3), health checks and the application's handler (layer 7 logic). That leaves the transport teardown between ALB and the pod, which is a layer 4 or layer 7 framing problem. I'd check keep-alive timeouts before touching anything else, because the default values almost always explain this pattern.
An ALB keeps idle connections to targets open for its idle timeout, 60 s by default. Many app servers close idle keep-alive connections much sooner: Node's http.Server defaults keepAliveTimeout to 5000 ms, and gunicorn's keepalive defaults to 2 s. The race looks like this (hypothetical timings):
| Time | ALB | Pod |
|---|---|---|
| t=0 | request A on pooled connection | 200, keeps socket open |
| t=5.0 s | idle | server closes idle socket, sends FIN |
| t=5.2 s | sends request B on the same pooled connection | socket is closed, kernel answers RST |
| t=5.2 s | gets reset, returns 502 to client | nothing logged, the request never reached the app |
That is why the app logs nothing: the request dies in the kernel before a handler runs. The failure rate tracks how often a pooled connection sits idle between the app's timeout and the ALB's 60 s, so it rises at off-peak traffic when connections go idle, which is the opposite of what most people expect.
The next diagnostic is cheap and decisive. Confirm the 502 is ELB-generated in the ALB access logs (elb_status_code 502 with target_status_code -) and in HTTPCode_ELB_502_Count versus HTTPCode_Target_5XX_Count. Then compare the two timers: kubectl exec into the pod and read the server's keep-alive setting, and read the ALB idle timeout from the load balancer attributes. If the app's keep-alive is below 60 s, raise it above the ALB idle timeout (AWS recommends the app keep-alive exceed the load balancer's), then watch the 502 rate for an hour. Don't rely on the change alone: capture on the node for a few minutes (ephemeral debug container with tcpdump -i any host <pod-ip> and port <port>) and look for a FIN from the pod followed by a request from the ALB side.
What would change my mind: if the RST comes from the ALB side, or the resets happen within milliseconds of a new connection rather than after idle, the problem is at the TCP handshake or a middlebox (MTU, a security group or NACL dropping return traffic, or a proxy in the pod's sidecar), and I'd move down to layer 3 and 4 tooling instead.
The failure mode to name in the review: a fix that only raises the ALB idle timeout moves the race rather than removing it, because the app keeps closing first. Set the app's keep-alive above the ALB value and verify it from the pod, not from the chart values.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68A VPC instance gets its private address from DHCP, yet some workloads need an address that never changes. How does VPC address assignment work, and where is static addressing still required?
The 60-second answer
A VPC does not run a pool the way a home router does. When an instance launches, its primary network interface gets an address from the subnet CIDR, and the guest learns it over DHCP from the AWS-provided service. That address belongs to the ENI, so it survives stop and start. Terminate the instance and it returns to the subnet. So the address is chosen by the subnet and fixed for the life of the interface, not dynamic in the sense of changing under you.
Static addressing is needed only where something outside the workload has to hold the literal IP: a partner allowlist, a firewall rule on-prem, a database pg_hba.conf entry, a license bound to an address, or a legacy client that will not resolve a name. Everywhere else I use DNS names and accept that the IP moves.
Mechanism
- Each subnet reserves five addresses. For
10.10.1.0/24:.0network,.1VPC router,.2the Amazon-provided DNS resolver (VPC base + 2),.3reserved,.255broadcast. That leaves 251 usable addresses, and the reserved set is the same for every subnet size. - Each VPC has one DHCP option set carrying
domain-name-servers,domain-nameandntp-servers. If you associate a new option set, running instances keep the old options until their lease renews or they reboot. - You can pick an address at launch, but only if it is free in the subnet and not reserved.
aws ec2 create-network-interface --subnet-id subnet-0a1b2c3d \
--private-ip-address 10.10.1.20 --groups sg-0f3e4d5c
aws ec2 run-instances --image-id ami-0abc --instance-type m7i.large \
--network-interfaces NetworkInterfaceId=eni-0d4c5b6a,DeviceIndex=0| Need | Mechanism | Address survives instance replacement? |
|---|---|---|
| Default private address | Subnet DHCP at launch | No |
| Fixed address for one instance | ENI with a fixed private IP, kept across stop/start | Yes, while the ENI is kept |
| Fixed address that moves between instances | Detach and attach the ENI | Yes, follows the ENI |
| Fixed public address | Elastic IP | Yes, until released |
| Service discovery | Private hosted zone record | Name stays, IP changes |
Trade-offs
An ENI is pinned to one subnet, so a fixed address also pins the workload to one AZ. Elastic IPs are a regional quota (check Service Quotas; the default has been five), and a public address costs money even when idle. A fixed private IP on an ENI moves with the ENI only if you detach and reattach it, which is a runbook step, not a failover.
Failure modes and how to detect them
- A terminated instance releases its address, and a new workload gets it. An allowlist still holding that IP now admits the wrong host. Detect with
aws ec2 describe-network-interfaces --filters Name=private-ip-address,Values=10.10.1.20before trusting the entry. - Changing the DHCP option set looks applied but is not, until renewal. Check
domain-name-serverson a running host after a reboot or a forced renewal, not just in the console. - Hard-coding an IP into config breaks when an instance is rebuilt in a different AZ, because the subnet changes. A name plus a short TTL fails far less often.
- Picking
.1,.2or.3by hand fails at launch, so reserve them in your IPAM plan rather than discovering it during cutover.
In an interview I would name the rule first: keep the default DHCP address and use names, and pin an address only where a named external dependency requires it, with the ENI and its subnet recorded beside the dependency.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69Your on-prem reporting database replicates to a VPC over a Site-to-Site VPN, and the team sees latency jitter during the day. Explain why IPsec over the internet causes that jitter, and when you would move the traffic to Direct Connect.
The 60-second answer
The jitter comes from the path, not the tunnel. A Site-to-Site VPN is two IPsec tunnels terminated on AWS-managed endpoints and carried over the public internet. Each packet crosses carrier peering points that are shared with everyone else, so queueing delay changes with time of day. IPsec adds encryption cost but almost no jitter by itself. I would first measure where the variance sits (tunnel, carrier or application) before changing anything. If the variance is in the internet segment, Direct Connect is the fix, because it gives a dedicated port into a Direct Connect location with a fibre route that does not share congestion with the public internet.
How to prove where the jitter lives
Run a probe across the tunnel at a fixed interval and compare it with a probe to a host on the same subnet:
ping -i 0.2 -c 3000 10.20.4.10 | tee vpn-probe.txt
# look at mdev in the summary line, and at tail latency in the outputHypothetical numbers for illustration: if the same-subnet mdev is 0.1 ms and the tunnel mdev is 9 ms with p99 rising from 25 ms at 02:00 to 140 ms at 14:00, the variance is on the internet path and the tunnel is fine.
| Symptom | Likely cause | Check |
|---|---|---|
| Jitter tracks business hours | Congested internet path | Tunnel probe p99 by hour |
| Latency spikes in bursts | BGP reconvergence or tunnel rekey | Tunnel and BGP state logs |
| Throughput drops to one tunnel's rate | ECMP not in use, single flow | Per-tunnel byte counters |
VPN versus Direct Connect on this trade-off
- Latency and jitter: VPN follows the internet path. Direct Connect has a stable fibre route, set by the provider and the location.
- Encryption: VPN is IPsec by default. Direct Connect is not encrypted by default, so add MACsec on supported dedicated connections or an IPsec layer on a transit virtual interface if policy requires it.
- Failover: both use BGP, and the detection time is set by the hold timer. Keep the VPN as the backup for Direct Connect rather than running both as equals.
- Lead time: a VPN is ready within hours. A Direct Connect port takes weeks to months.
Failure modes
- Direct Connect moves the jitter, not the risk: a single location is still a single point of failure. Two connections in separate locations are the real protection.
- VPN backup never tested. Run a scheduled failover drill and watch BGP state during it.
- Jitter blamed on the tunnel when the application is the cause, such as a replica lag spike from long transactions. The same-subnet probe above separates the two.
When I would not move: if the jitter is within the SLO for the replication, or the traffic is low-volume, the VPN is the right and cheaper answer.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70What is the typical inner MTU of an IPsec tunnel over a standard 1500-byte Ethernet path, and why is it smaller than 1500?
Direct answer
On a 1500-byte Ethernet path, a tunnel-mode IPsec tunnel commonly ends up with an inner MTU between about 1400 and 1446 bytes. The exact value depends on the outer IP version, the cipher and integrity algorithm, and whether NAT traversal adds UDP. It is smaller than 1500 because the inner packet is carried as the payload of an ESP packet, and that outer packet must itself fit in 1500 bytes.
Where the bytes go
Take IPv4 outside, IPv4 inside, tunnel mode, AES-GCM as specified in RFC 4106, no NAT traversal. The overhead is fixed except for ESP padding:
| Component | Bytes |
|---|---|
| Outer IPv4 header | 20 |
| ESP header: SPI and sequence number | 8 |
| Explicit IV for AES-GCM | 8 |
| Integrity check value | 16 |
| ESP trailer: pad length and next header | 2 |
| Padding | 0 to 3, to a 4-byte boundary |
That is 54 bytes plus padding. The inner MTU is therefore 1500 minus 54, minus up to 3 bytes of padding, which gives 1446 bytes in the best case.
Change the cipher and the number moves. AES-CBC uses a 16-byte IV and pads the ESP payload to a 16-byte boundary, and its integrity check value length depends on the negotiated integrity algorithm, so its overhead is 20 plus 8 plus 16 plus 2 plus that ICV length plus 0 to 15 bytes of padding. Do not quote a single CBC inner MTU without checking the ICV length your proposal negotiates. Add NAT traversal and UDP adds 8 bytes, taking the AES-GCM figure down to 1438. Use IPv6 for the outer header and it costs 40 bytes instead of 20, taking another 20 bytes off, to 1426 for AES-GCM. GRE inside IPsec costs more again. This is why a single universal number does not exist, and why 1400 is often chosen as a conservative setting that works across cipher suites.
A packet at the limit
Trace the AES-GCM case with an inner MTU of 1446:
inner IPv4 packet 1446 bytes
ESP trailer +2 = 1448, already a multiple of 4, no padding
ESP header, IV, ICV +32
outer IPv4 header +20
total outer packet 1500 bytes, fits exactlyAn inner packet of 1447 bytes needs 1449 bytes of ESP payload before alignment, padded by 3 bytes to 1452, for a 1504-byte outer packet. That packet cannot cross a 1500-byte link unfragmented. The sender either fragments the outer ESP packet, which many firewalls and middleboxes drop or handle poorly, or, if the inner packet has Don't Fragment set, drops it and should return an ICMP Packet Too Big message. If that message is filtered, the connection hangs in a classic path MTU black hole: small packets pass, large ones vanish.
What breaks in practice
BGP will happily bring the tunnel up and install the route while every full-size packet fails. The session itself often survives because BGP keepalives are small, which makes the fault look like an application problem. TCP is hit first because it sends large segments. Clamp the TCP maximum segment size on the tunnel interface to the inner MTU minus the inner IP and TCP headers, 40 bytes for IPv4, so 1406 bytes for the 1446 case above. Setting the tunnel interface MTU to the computed inner value also helps UDP applications that respect interface MTU.
Check the real value on your own equipment rather than trusting a table. Send test pings with fragmentation disabled and increasing sizes, for example ping -M do -s 1418 <address> on Linux, where the payload size plus 28 bytes of IPv4 and ICMP headers equals the 1446-byte packet size being tested. The largest size that passes without fragmentation is your usable inner MTU for that cipher suite. Re-test after changing ciphers, adding NAT traversal, or moving the tunnel onto an IPv6 underlay, since each of those changes the overhead.
Do not rely on outer fragmentation as the fix. Fragmented ESP must be reassembled before decryption, it exposes the tunnel to fragment-based attacks and loss amplification, and a single lost fragment discards the whole packet. A correctly sized inner MTU avoids all of that at the cost of a few percent of payload efficiency.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71Your payments team wants to stop trusting the VPC network as the security boundary. Walk me through what changes in the design of a service that calls another service, and how you would prove the new controls work.
The 90-second answer
Perimeter trust makes the network the authorisation decision: if a caller can reach the port, it is allowed. Zero trust moves that decision to each request and checks the caller's workload identity, the target resource and the action, every time. In a cloud estate the network boundary is weak evidence, because CIDRs are shared across peered VPCs, transit gateways, on-prem links and other accounts. A source IP tells you where a packet came from, not which workload sent it.
What changes in the design:
- Callers authenticate with workload identity (an IAM role via SigV4, or mTLS with a short-lived certificate), not with a source address.
- The target enforces authorisation: a resource policy, or an auth policy on the service, names the allowed principals and actions.
- Network rules stay, but only as defence in depth. Security groups and NACLs no longer carry authorisation.
- Credentials are minutes long, issued by the platform, and never stored in config.
- Logs record the principal on every request, not just the flow.
Trace
batch-worker (role batch-worker, 10.10.1.15) and orders-api (role orders-api, 10.10.1.20) sit in the same subnet. The ledger service exposes POST /entries through VPC Lattice, with this auth policy:
{"Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::111122223333:role/orders-api"}, "Action": "vpc-lattice-svcs:Invoke"}When batch-worker calls POST /entries, the security group still allows 443 from 10.10.0.0/16, so the TCP connection completes and the VPC flow log shows ACCEPT. The service then evaluates the request against its auth policy, the principal is not orders-api, and it returns 403. The access log records the principal, the action and the 403. The network allowed the packet and authorisation denied the request. That split is what you are proving.
| Concern | Perimeter design | Zero-trust design |
|---|---|---|
| Who may call ledger | any host in 10.10.0.0/16 | role orders-api only |
| Lateral movement | reachable from the whole subnet | denied unless policy names the workload |
| Credentials | long-lived keys in config | role credentials, minutes long |
| Evidence | flow logs show IPs | access logs show principal and decision |
Failure modes and detection
- A shared role across services silently restores the perimeter. Detect it by listing principals per policy and alerting on any new principal added to an allow list.
- The certificate issuer or token endpoint goes down, and every deploy fails. Mitigate with cached credentials and a tested break-glass path.
- Policy drift: an allow rule gets widened in a hurry and never narrowed. Run IAM Access Analyzer for unused access and review it monthly.
- Authorisation failures that look like outages. Alert on 403 rate per principal, so a broken caller shows up as a principal, not as noise.
What I would not do
I would not delete subnets or remove security groups because zero trust is the goal. Those controls stop mistakes that policy bugs cause. I would also not force a full mTLS mesh onto a single small internal service where the cost of certificate operations exceeds the risk. For that service, identity-based IAM auth on each call is enough.
For people reaching internal tools, the same logic applies: identity plus device posture through an access proxy such as AWS Verified Access, not a VPN that puts the laptop inside the perimeter.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72A private subnet workload needs to reach S3, and you want to stop it going through the NAT gateway. Gateway endpoint or interface endpoint, and what does each do to the route table?
The 90-second answer
For S3 I would use a gateway endpoint. It is free, it adds a managed prefix-list route to the private route table, and that route is more specific than 0.0.0.0/0, so S3 traffic leaves through the endpoint instead of the NAT gateway. The main trade-off is reachability: a gateway endpoint works only from inside the VPC. Callers over VPN, Direct Connect or peering cannot use it, and for those I would add an interface endpoint with a private IP per AZ.
| Type | Route table change | Reachable from | Cost |
|---|---|---|---|
| Gateway (S3, DynamoDB) | prefix-list route to the endpoint, attached per route table | inside the VPC only | no hourly charge |
| Interface (PrivateLink) | none, the ENI IP is used through private DNS | VPC, peered VPCs, on-prem | hourly per AZ plus per GB |
A worked check: the route table has 0.0.0.0/0 → nat-gw and, after associating the endpoint, a route for the S3 prefix list → vpce-…. A packet to an S3 address matches both, and the longer prefix wins, so it goes to the endpoint. Verify with a flow log: S3 destinations should appear against the endpoint's ENI traffic rather than the NAT gateway.
Failure mode
The gateway endpoint is attached to only one of three route tables. Nothing fails. S3 traffic from the other subnets goes through NAT, and you pay NAT data processing on every gigabyte. Detect it by comparing NAT gateway bytes-out to S3 prefixes against the expected endpoint traffic, and by checking each private route table for the prefix-list route.
What I would tell the interviewer
Choose by who must reach the service, not by cost alone. Gateway endpoints are the default for S3 inside a VPC; interface endpoints are the answer when the network path must extend beyond the VPC.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73A batch worker in a private subnet reads from S3. Compare reaching S3 through a NAT gateway with using an S3 gateway endpoint: what routes each path, and what does the endpoint change about data transfer charges?
The 90-second answer
I'd confirm the bucket is in my account and region, and that the worker has no other reason to reach the internet. Then the answer comes down to routing and cost.
Through a NAT gateway, the worker resolves s3.<region>.amazonaws.com to public IPs. The subnet's 0.0.0.0/0 route sends that traffic to the NAT gateway, which forwards it out the internet gateway. The NAT gateway bills per GB processed, and the worker's subnet depends on NAT being healthy.
An S3 gateway endpoint adds a route to the S3 prefix list in the subnet's route table, with the endpoint as the target. Longest-prefix match prefers that route over 0.0.0.0/0, so S3 traffic bypasses the NAT gateway. The gateway endpoint itself has no hourly or per-GB charge, so the NAT processing charge disappears for S3 traffic. The endpoint does not replace the NAT route for anything else.
| Path | What routes it | Data charge |
|---|---|---|
| Public via NAT | 0.0.0.0/0 to NAT, then IGW | NAT processing per GB |
| S3 gateway endpoint | prefix-list route to vpce-id | none for the endpoint |
Worked example, hypothetical figures: 2 TB a month of S3 reads through NAT at $0.045/GB processed is about $90 in NAT processing, before the NAT hourly charge. The same reads through a gateway endpoint add no per-GB charge.
The endpoint must be associated with the route tables of every subnet whose workers read S3. A subnet missing that association still sends S3 traffic through NAT, so check the route table association for each subnet, not only the VPC.
To confirm the path, run dig s3.<region>.amazonaws.com from the instance: the public-IP answer means the name resolves publicly, and the gateway route is what decides the path. VPC flow logs show whether the traffic leaves via the NAT ENI or not.
Do not use a gateway endpoint as a security control. It does not restrict which buckets the worker can reach, so use IAM and bucket policies for that.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74Your monthly AWS bill jumped 30%. Which Cost Management view do you open to find the top cost drivers, and what must be true before a new team tag appears in it?
The 90-second answer
I open Cost Explorer, set the time range to the last two full months, and group by service with the filter on unblended cost. That names the top drivers in a minute: usually EC2, RDS, NAT gateway data processing, or data transfer. Then I group by usage type inside the top service, because USE1-NatGateway-Bytes and USE1-DataTransfer-Out-Bytes tell you more than the service total does. For allocation I group by a cost allocation tag such as team. The catch is that a user-defined tag does nothing in Cost Explorer until someone activates it in Billing and Cost Management. Activation is not retroactive: spend recorded before activation stays untagged, and the tag can take up to 24 hours to appear after you activate it.
So the first check on a new tag is whether it is activated, and the second is whether the resources carry it. Both are cheap to verify and often are not.
Worked example (hypothetical figures)
The bill is $100k. Group by service:
- EC2: $60k
- RDS: $18k
- NAT gateway: $12k
- S3: $5k
- Everything else: $5k
NAT at $12k looks small until the usage-type view shows $11k of it is NatGateway-Bytes, which is data processed through the gateway. That points at a workload sending bulk traffic to S3 or an external API through NAT when a gateway endpoint or a public path would avoid the processing charge. EC2 at $60k is the big number, but it is the one you can attribute cleanly once tags exist, so it gets a per-team breakdown next.
Designing the tagging scheme
Pick a small set of mandatory keys, lower-case, with a fixed value list: team, service, env, cost-center. Keys are case-sensitive, so Team and team show up as two separate allocations and split your report. Enforce in two layers:
- AWS Organizations tag policies standardise key names and allowed values and report noncompliant resources. They do not stop an untagged resource from being created.
- To block creation, use an SCP with a
aws:RequestTagoraws:TagKeyscondition on the services where it matters, such as EC2RunInstancesand RDSCreateDBInstance. Scope it carefully, because a broad deny breaks CloudFormation and Terraform runs that create resources before tagging them.
Auto Scaling groups are a trap. A tag on the group does not reach the instances unless the tag is set with PropagateAtLaunch true, so the instances appear untagged while the group looks fine.
Failure modes and how you catch them
- Tag drift: a team renames
servicetoappand half the spend moves into an untagged bucket. Track the percentage of monthly cost with noteamvalue and alert when it rises above a threshold you pick, such as 5%. - Shared costs: Savings Plans, support fees, and NAT data processing for several teams have no single owner. Decide on a split rule and write it down, rather than letting each report invent one.
- Late activation: a tag activated in week three gives you a report that is blank for the first two weeks. Activate the keys at account setup, not during the incident.
Say the order out loud in the interview: find the top service, drill into usage type, then check whether the tag that would explain it is active and present.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75Your team runs a 1 TB PostgreSQL order database with a primary and a synchronous standby. Leadership asks whether to keep self-managed PostgreSQL on EC2 or move to Amazon RDS for PostgreSQL. Build a three-year TCO comparison with real figures and operator time, and say where your numbers are most likely to be wrong.
The 90-second answer
I would not compare the instance invoices and call it done. At this size the infrastructure bills land within a few percent of each other, so the decision turns on operator hours, and on whether the workload needs anything RDS will not let you do. I state my assumptions first, then price both sides with the same units.
Assumptions (hypothetical, to be replaced with your pricing page and timesheets): two database nodes plus a witness for failover in each option, 1 TB gp3 per node, 30-day backup retention, us-east-1, on-demand pricing, 730 h per month, fully loaded engineer cost of $120/h.
| Line item | Self-managed EC2 | RDS Multi-AZ |
|---|---|---|
| Compute, 2 nodes at $0.90/h (RDS) or 3 nodes at $0.55/h (EC2) | $1,204/mo (3 EC2 incl. witness) | $1,314/mo |
| Storage, 1 TB per node | $240/mo (3 TB gp3 at $0.08/GB) | $230/mo (2 TB at $0.115/GB) |
| Backups and WAL archive | $69/mo (S3, 3 TB) | included up to storage size |
| Infrastructure total | about $1,513/mo | about $1,544/mo |
| Operator hours per month | about 27 h | about 5 h |
| Operator cost per month | about $3,240 | about $600 |
| Monthly total | about $4,753 | about $2,144 |
Self-managed operator hours: patching three nodes monthly (6 h), Patroni, etcd and pooler upkeep (8 h), restore drills and WAL verification (4 h), alert toil and escalations (6 h), plus 120 h of initial build amortised over 36 months (3.3 h). Managed: parameter group and maintenance window review, major upgrade planning, and monitoring tuning, about 5 h.
Over 36 months the gap is about $2,600 per month, roughly $94k, minus the one-time build cost of about 120 h for self-managed against about 24 h for RDS.
Where the model is weakest:
- Operator time is not linear. Hours spent on patching are roughly fixed, but one failover incident can cost 40 h of senior time, so the average hides the tail.
- Ambient time is not incremental. If the same engineers already run Kubernetes control planes, some of the Patroni and etcd cost is shared. Count only the hours that disappear when you switch.
- Managed has hidden line items: Performance Insights retention, provisioned IOPS, cross-AZ traffic from the application, and log exports. Price them, do not assume they are zero.
- Self-managed wins when you need something RDS blocks: superuser-only extensions, custom compiled modules, or kernel and filesystem tuning. If the workload needs one of those, the comparison ends there.
- At 20 or more clusters the fixed operator cost is shared across them, and self-managed can become cheaper per database. That is a fleet argument, not a single-database one.
What I would check before the meeting: the RDS extension list for the current engine version, the actual engineer hours from the last two patch cycles and the last incident, and the egress path between the application and the database. I would present the result as a range, not one number, and name the hours figure as the figure most worth measuring.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76Your web tier runs a steady 40 instances around the clock, and a nightly batch fleet of 300 instances runs for 6 hours. Which of these should be covered by a Savings Plan, which by spot, and what commitment risk do you take on for each?
The 90-second answer
Split the fleet by how predictable it is. The 40-instance web baseline runs every hour, so it is the only part that justifies a commitment: a Compute Savings Plan or Reserved Instances. The nightly batch fleet is interruptible if the job checkpoints, so it goes on spot with on-demand as fallback. The risk I accept on the commitment is paying for hours I stop using. The risk I accept on spot is losing work, and the design has to bound that loss rather than hope it stays rare.
Assumptions (hypothetical rates, labelled as such): on-demand at $0.20 per instance-hour, a 1-year commitment at 30% off, so $0.14 per instance-hour, and spot at 70% off, so $0.06 when it is available.
Commitment arithmetic
A Savings Plan is a dollar commitment per hour, not a reservation of machines. Committing to the baseline means 40 × $0.14 = $5.60 per hour, paid whether or not the instances run.
| Scenario | Usage at discount | Commitment paid | Unused commitment |
|---|---|---|---|
| Baseline holds at 40 | $5.60/h | $5.60/h | $0 |
| Re-architecture drops to 25 | $3.50/h | $5.60/h | $2.10/h, about $18,400/year |
| Scale-up to 55 for a campaign | $7.70/h | $5.60/h | $0, the rest bills at on-demand |
The commitment is cheap insurance only while the baseline is real. Commit to the floor you have measured for 90 days, not the peak.
Batch on spot
300 instances × 6 h is 1,800 instance-hours a night. Spot interruptions arrive with a 2-minute notice. With checkpoints every 10 minutes, one interruption costs on average about 5 minutes of rework plus the 2-minute notice window the job can use to flush its checkpoint. If 5% of instance-hours are interrupted, that is 90 interruptions and about 450 minutes of rework, roughly 7.5 instance-hours, under half a percent of the night. That is the number to defend, and it only holds if the checkpoint is real and resumable.
Two settings matter. Use the capacity-optimized allocation strategy across several instance families and AZs, so one pool drying up does not stop the fleet. Keep a small on-demand floor for the tail, so the last tasks finish before the morning deadline.
Alternatives and when not to use them
Reserved Instances can be zonal, which reserves capacity, but you pay for it whether used or not. Use an On-Demand Capacity Reservation only when a launch must succeed inside a specific AZ, such as a failover pool. A 3-year commitment deepens the discount but locks you to a family you may outgrow. I would not buy it for a team that is still changing instance types. Do not put the web tier on spot: a 2-minute notice drains it into a fleet-wide capacity shortfall during the same event that reclaims the batch.
Failure modes and detection
- Commitment coverage drops after a re-platform. Detect it in Cost Explorer's Savings Plans utilization report; alert when utilization falls below 90% for three days.
- Spot interruptions cluster in one pool. Detect with the interruption-notice metric per instance type and AZ; alert on a rate above your rework budget.
- A job is not idempotent, so a resumed task writes duplicate rows. Detect with a row-count reconciliation on each run, not with the job's exit code.
The answer is the split, the commit sized to the measured floor, and a rework budget that you can show in numbers.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77A private subnet workload in one AZ sends most of its traffic to S3 through a NAT gateway. Why does a gateway endpoint for S3 cut that cost, and what does it change in the route table?
The 90-second answer
Traffic from a private subnet to S3 normally goes out through the NAT gateway. The NAT gateway bills per GB processed, so every byte to S3 is charged at its processing rate even though S3 is in the same region. A gateway endpoint for S3 removes that charge. It adds a prefix-list route for S3 to the subnet's route table, pointing at the endpoint, so S3-bound packets never reach the NAT. Gateway endpoints for S3 carry no hourly or per-GB charge, so the saving is the NAT processing fee on that traffic.
Two details matter in the interview. The endpoint route is more specific than 0.0.0.0/0 for S3 addresses, so it wins for S3 without touching the default route. And the endpoint policy and bucket policy both still apply: a gateway endpoint does not grant access, it only changes the path.
Trace for one subnet with route table rtb-private:
| Destination | Target before | Target after |
|---|---|---|
| 10.0.0.0/16 | local | local |
| 0.0.0.0/0 | nat-0a1 | nat-0a1 |
| S3 prefix list (pl-xxxx) | (uses 0.0.0.0/0) | vpce-s3 |
A GetObject to s3.us-east-1.amazonaws.com resolves to S3 public addresses, which match the prefix list, so it goes to vpce-s3 and bypasses the NAT. A call to a non-S3 internet host still goes through nat-0a1.
Worked figure, hypothetical: 20 TB a month read from S3 through the NAT at $0.045/GB costs 20,000 × 0.045 = $900. With the endpoint, the same reads cost $0 in endpoint fees. Check the NAT gateway's BytesOutToDestination metric before and after to confirm the drop.
When not to bother: if the traffic to S3 is small, the saving is small, and an endpoint adds one more route table association to manage per subnet. An interface endpoint is the alternative when you need a private IP reachable from on-premises through Direct Connect or a VPN, or when you need to reach S3 from another VPC. It creates elastic network interfaces in chosen subnets, costs per hour and per GB, and is reached through DNS, not a route table entry. For the cost question, the gateway endpoint wins because it is free and it targets exactly this path.
Failure mode: a subnet whose route table lacks the endpoint association keeps paying NAT rates and nothing errors, so the only signal is the bill. Detect it by comparing NAT processed bytes per subnet against S3 request volume, and by checking that every private route table is associated with the endpoint.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78Your team plans to move application logs to S3 Standard-IA after 30 days. Why can that raise the bill when those objects are read again, and what is the minimum charge per object?
The 60-second answer
Standard-IA is cheaper to keep data in, but it charges for every read. Each GB retrieved costs a per-GB retrieval fee on top of the request charge, and every object is billed for a minimum of 30 days of storage and a minimum of 128 KB, even if it is deleted or is smaller. So the class only saves money when data is rarely read. Logs that are still read in their first week are a poor fit for it. I would keep those in S3 Standard until read frequency drops, then transition them.
Assumptions: us-east-1 list prices at time of writing, which change, so check the S3 pricing page before quoting. Figures below are hypothetical.
| Class | Storage (per GB-month) | Retrieval (per GB) | Minimum storage duration | Minimum billable size |
|---|---|---|---|---|
| S3 Standard | $0.023 | none | none | none |
| S3 Standard-IA | $0.0125 | $0.01 | 30 days | 128 KB |
| S3 Glacier Instant Retrieval | $0.004 | $0.03 | 90 days | 128 KB |
| S3 Glacier Flexible Retrieval | $0.0036 | per GB, minutes to hours | 90 days | 40 KB overhead per object |
Worked arithmetic (hypothetical). Suppose 500 GB of logs sits in the bucket. Each month, the team reads the whole set four times.
- Storage saving on Standard-IA: 500 × ($0.023 − $0.0125) = $5.25 per month.
- Retrieval cost on Standard-IA: 500 GB × 4 reads × $0.01 = $20.00 per month.
- Net effect: $14.75 per month more expensive than staying in Standard.
The break-even point is about 0.0105 / 0.01 ≈ 1 full read of the data per month on average. If the set is read more than about once a month, Standard-IA loses money. Reading 1 GB of a single object once is cheap in absolute terms, which is why this only shows up at scale.
Early deletion. Deleting or overwriting an object before its minimum duration still bills you for the remaining days. A 10-day-old object deleted from Standard-IA is billed for 20 more days.
Lifecycle policy. Transition by age and check access patterns first. Use S3 Storage Lens or server access logs to see how often objects are read in each age band. Set the transition to run after the last expected read, not after an arbitrary date. Objects under 128 KB do not transition to Standard-IA under a lifecycle rule, so do not assume every object moves.
When to pick Intelligent-Tiering instead. When access is unpredictable, Intelligent-Tiering moves objects between tiers on access, with no retrieval fee, at a per-object monitoring charge. Objects under 128 KB are never auto-tiered, and objects in the frequent tier are billed as Standard.
Failure mode to watch. A lifecycle rule that moves hot data to Glacier Flexible Retrieval turns a read into a restore request with a wait. Detect it in the first week: check the 4xx and latency on the consuming service, and the S3 retrieval line in Cost Explorer grouped by storage class.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79Your EKS fleet ships 4 TB of application logs a day into CloudWatch Logs, with retention set to never expire. Finance wants 60% off that line without losing audit or incident evidence. What do you keep, sample or move, and what does the bill look like afterwards?
The 90-second answer
I'd start by separating the three things being billed: ingestion, storage, and the retention that makes storage grow forever. The default log group retention is Never expire, so the storage line rises every day and nobody sees it. Ingestion is the larger line today, so I'd cut bytes at the source, sample the bulk that is only useful in aggregate, and move audit data out of CloudWatch entirely. Figures below use us-east-1 Standard class list prices I'm assuming: $0.50/GB ingested and $0.03/GB-month stored. Check them against the pricing page before quoting.
Baseline. 4 TB/day is about 120,000 GB/month. Ingestion alone is 120,000 × $0.50 = $60,000/month. Storage at never-expire grows by about 4,000 GB every day, so after one year it holds about 1.46 million GB, which is roughly $43,800/month in storage by itself.
Step 1: drop at the source. Set the collector to drop DEBUG lines in production and remove health-check and load-balancer probe access lines. In this hypothetical fleet, that removes 45% of bytes, leaving 2.2 TB/day. Dropping is free and loses nothing a responder uses.
Step 2: sample the successful traffic. Of the remaining 2.2 TB, 1.8 TB is 2xx access logs. Keep every 4xx and 5xx line and sample 2xx at 1 in 10. That leaves about 180 GB of 2xx plus about 400 GB of everything else, so 0.58 TB/day. Sample by trace ID, not per line, or a single request's lines split between kept and dropped and the trace becomes useless. Derive request counts and latency histograms as metrics before sampling, so dashboards stay exact while the log text thins out.
Step 3: set retention per group. Application groups go to 30 days. Audit data (CloudTrail, VPC flow logs) goes to S3 with Object Lock and a lifecycle rule to Glacier, not CloudWatch. Storage then holds about 17.4 TB at any time: 17,400 GB × $0.03 ≈ $520/month.
Result. Ingestion 17,400 GB × $0.50 ≈ $8,700/month, plus $520 storage, about $9,200/month against $60,000 before, an 85% cut, and it stays flat instead of climbing.
Failure modes. Sampling hides the rare bug that appears in 1 in 500 requests and only in 2xx paths, so keep unsampled logs for a short tail window and alert on error metrics, not on log counts. Tail-based sampling in an OpenTelemetry collector needs all spans of a trace on one collector, so route with a trace-ID load-balancing exporter, or the decision is made on partial traces. Detect regressions by alarming on IncomingBytes per log group against a weekly baseline, which catches a new chatty library within a day.
When not to sample. Security and billing events, anything a regulator reads as the record, and the first hour after a deploy. Those stay complete.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80A role's last-accessed report shows no use of ec2:TerminateInstances in 90 days. Does that mean the grant can be removed, and why or why not?
The 90-second answer
No. An empty 90-day window is evidence that the role did not call the action in those 90 days. It is not evidence that the role never needs it. The gap that matters is a job that runs less often than the window, such as a quarterly job, a DR runbook or a break-glass path. So before I remove anything I check the window against the longest legitimate cycle the role serves.
The last-accessed data comes from aws iam generate-service-last-accessed-details --arn <role-arn>, followed by get-service-last-accessed-details --job-id. It reports the service and, for many services, the action. Action-level detail is not available for every service, so for a service without it I search CloudTrail for the role's events directly.
The decision rule:
| Observed in window | Longest cycle covered | Decision |
|---|---|---|
| Yes | any | keep, and narrow the resource scope |
| No | 90 days or more | candidate for removal |
| No | less than 90 days | not proven, keep until checked |
The third row is the one people skip. If the longest legitimate cycle is 120 days, the 90-day window cannot show the grant is unused.
To remove a grant safely I change one thing at a time. For a customer managed policy I publish a new version without the grant and set it as default. Managed policies keep up to five versions, so rollback is set-default-policy-version to the previous one. For an inline policy I save the current document to a file first, because inline policies have no version history. I test the change in a non-production account that has the same role name, using the policy simulator against the job's real calls.
Failure modes to watch for:
- A quarterly or DR path outside the window fails with
AccessDeniedthe first time it runs after the change. - Removing
iam:PassRolebreaks a deployment that passes a role, and the error appears in a different service from the one changed. - Treating "not observed" as "never used" for a service that does not track actions in the report.
After the change I alert on CloudTrail AccessDenied events where the principal is this role, and keep the alert on for at least two full job cycles. Access Analyzer's unused-access findings can run continuously; I set the unused-access age to the longest legitimate cycle instead of the default 90, so the findings match the workload.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81Your break-glass role trusts a single named IAM user, and the session must carry a human name in CloudTrail. Explain how sts:SetSourceIdentity puts that name on every event the session makes, and what it does not prove about who was actually at the keyboard.
The 90-second answer
SetSourceIdentity is a session tag the caller sets when it assumes the role. CloudTrail copies it into userIdentity.sessionContext.sourceIdentity on every event the session makes, so an investigator can filter the whole session by a human name. Two conditions make it useful. The role's trust policy must require sts:SetSourceIdentity in the assume-role action, so the name cannot be omitted. The name must come from a source the caller cannot choose freely, which in practice means an identity-centre user the IdP has verified.
What it proves is narrower than it sounds. It proves the session was started with that name. It does not prove that person was typing, because the holder of the break-glass user's credentials can set any value it likes.
{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:user/breakglass-01" },
"Action": ["sts:AssumeRole", "sts:SetSourceIdentity"],
"Condition": {
"Bool": { "aws:MultiFactorAuthPresent": "true" },
"NumericLessThan": { "aws:MultiFactorAuthAge": "900" }
}
}Trace: AssumeRole at 02:14:09 with sourceIdentity=alice. Then ec2:StopInstances at 02:21:40 shows sourceIdentity=alice and sessionIssuer.userName=BreakGlassAdmin. The name travels; the actor is still an inference.
| Claim | Backed by | Not backed by |
|---|---|---|
| Session was started claiming name X | SetSourceIdentity in CloudTrail | Who typed the command |
| Every action carries name X | Session context copied to each event | Actions taken outside CloudTrail data events |
| Name was verified | Nothing in the trail on its own | Caller lying about the name |
So the control is the combination: the sealed credential, the MFA condition on the call, and the time window. A name alone is an assertion, and the MFA age condition is what ties the assertion to a fresh human second factor.
Failure mode to check. If the break-glass user's access key leaks, every event from that key looks like a named human session as long as the attacker sets a plausible name. Detect it by alerting on any break-glass session whose source IP or user agent differs from the sealed-store workstation, and by requiring an incident ticket for every session.
Drill. Once a quarter, assume the role with a test name, make one harmless change, and confirm the name appears on the event in the archive account.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82After a deploy, which ALB metric tells you whether the new targets are passing their health checks?
The 90-second answer
The metric is HealthyHostCount, published in CloudWatch under AWS/ApplicationELB for each target group. Its companion, UnHealthyHostCount, counts the targets failing their health checks. Both are dimensioned by load balancer and target group, so I read them for the group that received the new version, not for the load balancer as a whole.
The reason this comes first after a deploy is that a new target only receives traffic once it passes health checks. Until then it is registered but not serving. If HealthyHostCount has not returned to the desired number, the rollout is still in progress or stuck, and any error or latency graph still describes the old fleet.
The defaults matter when you judge how long that should take. For an ALB target group, the default health check interval is 30 seconds, the timeout is 5 seconds, the healthy threshold is 5 consecutive successes and the unhealthy threshold is 2 consecutive failures. A new target that answers its health check on the first try still needs about 4 intervals, roughly 2 minutes, to count as healthy. If it has not reached that count by then, I look at the health check path and its response code before I look at the application.
| Metric | Meaning | Reading after a deploy |
|---|---|---|
HealthyHostCount | Targets passing health checks | Should climb to the desired count within about 2 minutes |
UnHealthyHostCount | Targets failing health checks | Should fall to zero; a steady non-zero value means a failing probe path |
What this does not prove: a healthy target can still return 5xx responses or slow responses. Health counts tell you the new version is reachable and passing its probe, so the next step is request counts and error origin per target group.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83Peak is 9,000 req/s spread across three AZs with ALB cross-zone load balancing off, and each instance holds its p99 SLO up to 600 req/s. You must keep the SLO when one whole AZ fails at peak. How many instances do you run per zone, and what does the arithmetic have to account for?
The 90-second answer
Assume clients reach the three zones evenly, so each zone gets 3,000 req/s at peak. With cross-zone off, each ALB node sends its traffic only to targets in its own zone, so when one zone fails its share is not spread across the others. The two survivors each take 4,500 req/s. I plan at 75% of the SLO ceiling, not at 100%, which puts the ceiling at 450 req/s per instance. That gives 4,500 / 450 = 10 instances in each zone, 30 in total. Normal peak then runs at 3,000 / 10 = 300 req/s per instance, which is 50% of the 600 limit.
I would not size to 8 per zone (4,500 / 600 = 7.5, rounded up). That passes the arithmetic but leaves no margin, and the SLO breaks at the first skew.
| Scenario | Req/s per zone | Instances per zone | Req/s per instance | Share of 600 limit |
|---|---|---|---|---|
| Normal peak, 3 zones | 3,000 | 10 | 300 | 50% |
| One AZ down, even split | 4,500 | 10 | 450 | 75% |
| One AZ down, 10% skew to a survivor | 4,950 | 10 | 495 | 83% |
| One AZ down, 10% skew, 8 per zone | 4,950 | 8 | 619 | over limit |
What the arithmetic misses
The even split is an assumption, not a fact. Clients with cached DNS keep resolving to the dead zone's ALB IPs until the TTL expires, so during that window the survivors can see more than their steady share. Check the real split per zone from RequestCountPerTarget grouped by AZ, not from the instance count.
Scaling cannot cover the gap. If a new instance takes 4 minutes to pass health checks and warm its caches, any zone loss has to be absorbed by capacity that already exists. Autoscaling is for the slow drift afterwards.
The SLO is per request, so measure it per instance too. A pool that averages 450 req/s can still have one instance over 600 if the load balancer routes by connection count rather than request count. Long-lived keep-alive connections make that skew common.
If instances hold a per-connection resource (database pool, upstream sockets), the same zone-loss math applies to those limits, and they can bind before CPU does. Check them with the same 4,500 req/s figure.
What I would check before signing off
- Confirm the zone split from ALB metrics during the last peak, not from the design.
- Run a game day that drains one AZ at peak and watch p99 per zone for the full DNS TTL.
- Set the scale-in floor so the pool never drops below 30 instances, and alarm when any zone falls below 10.
The design holds one AZ failure at peak with 25% headroom on the surviving zones, paid for by keeping 10 instances where the baseline needs 5 per zone.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84After a security group change on the application port, every instance in an ALB target group goes unhealthy at once. Explain which traffic the health check depends on and how you would confirm which rule broke it.
The health check is not sent by the client. The ALB nodes in each subnet send it, from their own private addresses, to the target's IP and health check port. So the rule that matters is the inbound rule on the target's security group that allows the ALB's source, either the ALB's security group ID or the subnet CIDRs the ALB nodes sit in. A change scoped to the old client CIDR or to a group the ALB no longer uses passes every test you run from a bastion and still fails the check.
The mechanism matters for the next step. Security groups are stateful: the health check's inbound SYN is allowed by the inbound rule, and the reply is allowed automatically. So the only rule that can break health checks is the inbound one. If someone also touched a network ACL on that subnet, that is stateless and needs the ephemeral return range 1024-65535 in both directions, so check it separately.
Two things to rule out first, both quick:
- Read the target group's health check settings.
HealthCheckPortdefaults totraffic-port, and an app port change can leave the check on a path or matcher that no longer matches. ATarget.ResponseCodeMismatchreason means the network path works and the check itself is wrong. - Read the reason code from
describe-target-health.Target.Timeoutmeans packets are dropped, which points at the security group or NACL.Target.FailedHealthCheckswith connection refused means nothing is listening on that port.
To prove the cause, run ss -ltnp on one instance to confirm the process listens on the new port, then curl the health path on 127.0.0.1. If local curl works and the ALB reports Target.Timeout, the block is in the network path. Then compare the rule's source against the ALB's security group ID before and after the change.
The fix is to restore a source that references the ALB's security group, not to widen the rule to 0.0.0.0/0 to make checks pass. Widening exposes the app port to the internet, and the health check problem comes back the moment the rule is reverted. Also check the launch template: if it still references the old security group, new instances will go unhealthy one by one as autoscaling replaces them.
Alert on UnHealthyHostCount per target group rather than on single instances, so you see a group-wide failure as one event.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85A pod behind a ClusterIP Service drops requests during every rolling deploy, even though the app catches SIGTERM. Walk through what happens between the delete and the process exit, and what you change so in-flight requests finish.
The 2-minute answer
The app is not the only party racing the shutdown. When a pod is deleted, the API server sets deletionTimestamp and the grace clock starts (terminationGracePeriodSeconds, default 30 s). Two things then happen independently: the endpoints controller removes the pod from its EndpointSlice, and the kubelet runs the container's preStop hook and then sends SIGTERM. kube-proxy on every node updates its rules from the EndpointSlice on its own schedule, so for a few seconds some nodes still route new connections to a pod that has already received SIGTERM. The fix is to delay the SIGTERM until routing has caught up, then drain whatever is still in flight, and to size the grace period to cover both.
Trace (hypothetical figures, one pod, 30 s grace)
| t (s) | What happens |
|---|---|
| 0 | delete; deletionTimestamp set; grace clock starts |
| 0 | pod removed from EndpointSlice; kube-proxy updates rules on nodes at about 0.5 to 3 s |
| 0 to 10 | preStop runs sleep 10; app still serving, routing catches up |
| 10 | SIGTERM to PID 1; app stops accepting, marks keep-alive connections Connection: close |
| 10 to 20 | in-flight requests finish; longest observed request is 6 s |
| about 20 | process exits 0 |
| 30 | grace expires; SIGKILL if still alive |
Budget: 10 s preStop + 15 s drain + 5 s margin = 30 s. If the drain is 25 s, the budget is blown and the kubelet kills the process mid-request.
Manifest
spec:
terminationGracePeriodSeconds: 30
containers:
- name: api
lifecycle:
preStop:
exec:
command: ["sleep", "10"]The sleep binary must exist in the image; distroless images without it will fail the hook.
Things that break it
- Shell-form
CMD npm startorCMD ./run.shputs a shell at PID 1, which does not forward SIGTERM. The app never sees it and gets SIGKILL at 30 s. Use exec form ortini. - The app handles SIGTERM by exiting immediately. Stopping the listener is not the same as finishing requests.
- Keep-alive connections from an ALB or NAT path stay open after the listener closes. Set an idle timeout or send
Connection: closeduring drain. - A preStop hook longer than the grace period is killed along with the container.
Detection
Watch 5xx and connection-reset counts per pod during deploys, not only fleet-wide. A spike that starts at SIGTERM and stops at the next readiness change points to the drain; a spike at about 0 to 3 s points to routing lag. Kubelet events Killing with reason and the container exit code (137 means SIGKILL) confirm which one happened.
Alternatives
A longer sleep is cheaper to reason about than a custom readiness dance, but it adds a fixed delay to every rollout: 10 s across 40 pods serially is over 6 minutes. Making the app fail readiness on SIGTERM and then drain also works, but readiness only removes the pod once the next probe runs, so pair it with a probe period shorter than the sleep.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86By default, does Docker Compose depends_on wait until the database is accepting connections before it starts the app container?
The 60-second answer
No. Plain depends_on only orders container starts. The default condition, service_started, is met as soon as the database container is running. Postgres inside that container may still be initialising or replaying WAL, so the app can start and get connection refused.
To wait for readiness, add a healthcheck to the database and use the long form of depends_on with condition: service_healthy:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: example
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -h 127.0.0.1"]
interval: 2s
timeout: 2s
retries: 15
app:
image: orders-api:1.4.2
depends_on:
db:
condition: service_healthyCompose holds app in Created until db reports healthy. The conditions you can choose from:
| Condition | App starts when | Use it for |
|---|---|---|
service_started (default) | dependency container is running | ordering only |
service_healthy | dependency healthcheck passes | databases, brokers |
service_completed_successfully | dependency exits 0 | one-off migration jobs |
The healthcheck is a point-in-time test. If the database restarts later, the app still needs its own retries with exponential backoff and a bounded total before it exits non-zero. If retries runs out before the database is ready, db becomes unhealthy and app never starts; docker compose ps shows the state.
On ECS or EKS, neither honours depends_on, so the equivalent is an app-level retry plus a readiness probe on the database connection.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87A kernel update must reach 40 EC2 instances without a service outage, and any node must be rollbackable within 10 minutes. Walk me through in-place patching versus replacing instances, and what each leaves behind if the new kernel misbehaves.
The 90-second answer
I'd replace instances from a newly baked AMI, roll them with an instance refresh, and keep the previous launch template version as the rollback target. In-place patching is cheaper per change, but a rollback then depends on the old kernel still being bootable on that exact host, and that is the thing I can't verify ahead of time. Replacement makes rollback a single, testable operation: point the group back at the old AMI and refresh again.
Two assumptions. The service tolerates one instance at a time leaving the pool (ALB deregistration plus connection draining). And the root volume is EBS, so no state lives on the host that a replacement would lose.
What in-place leaves behind
After dnf update kernel and a reboot, the host carries more than a kernel version:
- The old kernel stays installed only until the package manager's
installonly_limit(default 3 on RHEL-family) prunes it. Rollback needs that entry. - GRUB's default is set by
grub2-set-defaultorgrubby. A rollback is agrub2-set-defaultto the old entry and a reboot, which works only if the old initramfs still matches the old modules. - DKMS modules, hand-tuned sysctl, and hotfixes applied during an incident are drift that a rollback will not reverse.
- Kernel livepatch (kpatch, Canonical Livepatch) avoids the reboot but only for supported CVE fixes. It is not a rollback path for a bad kernel.
What replacement leaves behind
Nothing on the host survives except what sits on EBS or in external stores. Instance store is wiped on stop or terminate, so any host using it needs a data-drain step first. Drift is limited to what the AMI bake captured, and the bake pipeline is the only place it can enter.
| Path | Rollback action | Time to revert (hypothetical, 40 nodes, 2 at a time) | Leftover risk |
|---|---|---|---|
| In-place | GRUB default + reboot per node | 40 / 2 × ~4 min boot and drain ≈ 80 min | old initramfs, DKMS, hand edits |
| Replace | Refresh to previous launch template version | 40 / 2 × ~6 min launch and drain ≈ 120 min | instance-store data, AMI pipeline bugs |
The replacement row is slower in this arithmetic, so the 10-minute requirement is the real constraint. Neither path meets it for the whole fleet. What meets it is a canary: refresh 2 instances, watch error rate for 10 minutes, and roll back only the canary if it fails. The rollback budget then applies to the canary, not 40 nodes.
Drift detection
For in-place hosts, compare uname -r, the GRUB default, and rpm -Va output against the baseline on each node. For replaced hosts, drift is an AMI or launch template mismatch: check that every instance's AMI ID matches the template version, and alert on any instance older than its group's template. Patch Manager compliance reports give you the same signal across the fleet without logging into hosts.
Failure modes I'd name
An instance refresh with MinHealthyPercentage set too low removes capacity exactly when the bad kernel is failing. A new kernel that boots but drops the ENA or NVMe driver path can pass the ELB health check only until the next reboot, so the health check must cover a reboot cycle.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88Your managed node group patches 12 nodes, and the drain on one node hangs on a payments Deployment with 4 replicas and a PodDisruptionBudget of maxUnavailable 1. Explain what the Eviction API checks, why the drain stalls, and what you change so patching finishes without breaking the budget.
The 90-second answer
A drain is a voluntary disruption, so it goes through the Eviction API, and the API checks the PodDisruptionBudget before it removes each pod. If removing the pod would take the healthy count below the budget's floor, the API returns 429 and the pod stays. kubectl drain and the managed node group updater retry, so the node stays cordoned and the patch waits. The budget protects availability during voluntary moves. It does not stop node crashes, and it cannot create capacity.
Here the Deployment has 4 replicas and maxUnavailable: 1, so at most one pod may be missing at a time. An eviction is allowed only while the number of ready pods that would remain is at least 3.
| Step | Ready pods | Disruptions allowed | Result |
|---|---|---|---|
| Evict pod A1 on node-a | 4 | 1 | accepted, pod terminates |
| Controller schedules replacement on node-b | 3 | 0 | replacement not ready yet |
| Evict pod A2 on node-a | 3 | 0 | 429, drain retries |
| Replacement passes readiness | 4 | 1 | retry succeeds, A2 evicted |
The stall happens at the middle row. The drain is only as fast as the replacement becomes Ready. If the replacement cannot schedule (no CPU or memory left, a required anti-affinity rule with no free node, a taint nothing tolerates), ready stays at 3, the budget never reopens, and the drain never finishes.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: payments-api
spec:
maxUnavailable: 1
selector:
matchLabels:
app: payments-apiFailure modes and how to detect them
- Selector mismatch. The PDB matches zero pods and protects nothing, with no error. Check the
ALLOWED DISRUPTIONScolumn ofkubectl get pdbagainst the replica count you expect. - Budget that cannot be met.
maxUnavailable: 0, orminAvailableequal to the replica count, blocks every eviction. The symptom is a node stuck cordoned while the patch job waits. Alert onALLOWED DISRUPTIONSat 0 for longer than the drain window. - Single replica with
minAvailable: 1. The pod is never evictable, so the node can only be patched by a forced path. Either run two replicas or accept an outage and say so in the change record. - Unready pods do not count as healthy. A pod failing readiness during a DB blip lowers the allowance even though its node is fine.
- Managed node group updates. They wait for drains, then force termination after a fixed per-node window. The window varies by version, so confirm it in the EKS docs for your version. Do not treat the forced path as the normal case.
What I change
- Run enough replicas that the budget allows progress: with 4 replicas and
maxUnavailable: 1, the drain moves one pod at a time, which is slow but safe. If the drain is too slow for the window, raise the replica count before loosening the budget. - Add
topologySpreadConstraintsacross nodes and AZs, so the replacement for a pod on node-a lands somewhere other than the node being drained. - Keep headroom during the patch window. Cluster Autoscaler or Karpenter needs room to add a node before the replacement pod can schedule.
- Drain one node at a time and have the patch job fail on a per-node timeout, not wait forever.
The trade-off is patch speed against availability. A strict budget makes the patch window longer. Loosening it to finish on time means a planned dip in capacity, and that decision belongs in the rollout plan, not in a drain flag.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89Your security team asks who changed the bucket policy on orders-archive last Tuesday, and who downloaded objects under reports/ that same day. The trail has only default settings. Which CloudTrail event type answers each question, and what would you change so the second one can be answered?
The 90-second answer
Management events record control-plane calls: operations that create, change, delete or describe AWS resources, such as PutBucketPolicy, CreateRole or RunInstances. Data events record calls on the data plane, where the payload lives: GetObject and PutObject on S3 objects, Invoke on Lambda, item-level DynamoDB calls. Management events are on by default and the first copy per region is free. Data events are off by default and billed per event. So the policy change is already in the record, and the downloads are not. They were never logged.
| Question | Event type | Logged by default? | Retained where |
|---|---|---|---|
| who changed the bucket policy | management (PutBucketPolicy) | yes | Event history for 90 days, longer in a trail |
who read reports/2026-11-24.csv | data (GetObject) | no | trail with an S3 object selector only |
| who deleted a log file | data (DeleteObject) | no | trail with an S3 object selector only |
Event history only holds management events, and only for 90 days. Anything older, and every data event, needs a trail delivering to an S3 bucket. Data events cannot be backfilled: a read that happened before the selector existed is gone.
Scope the selector to the prefix, not the whole bucket:
{"Name":"reports-reads","FieldSelectors":[
{"Field":"eventCategory","Equals":["Data"]},
{"Field":"resources.type","Equals":["AWS::S3::Object"]},
{"Field":"resources.ARN","StartsWith":["arn:aws:s3:::orders-archive/reports/"]},
{"Field":"eventName","Equals":["GetObject"]}]}A record from that selector looks like this:
eventName=GetObject eventCategory=Data
userIdentity.arn=arn:aws:sts::111122223333:assumed-role/reporting-reader/session-1
requestParameters.key=reports/2026-11-24.csv sourceIPAddress=203.0.113.9Cost, using a hypothetical 40 million GetObject calls a month under reports/: 40,000,000 / 100,000 = 400 units at $0.10 per 100,000 events is $40 a month, plus the S3 storage for the log files. Check the current price on the CloudTrail pricing page before quoting it. Logging every bucket's PutObject traffic is a different order of magnitude, which is why the selector stays narrow.
Failure modes to name in the review:
- Presigned URLs: the record shows the principal that signed the URL, not the person who used it. The source IP is the downloader's, so pair the two fields.
- Delivery delay: log files arrive in batches, and events are typically visible within about 15 minutes. Do not build a real-time alert on them without measuring that lag.
- Read-only noise: management events include many
DescribeandListcalls. Filter onreadOnlywhen you only want writes.
S3 server access logs record GetObject at no per-event charge, but they are best-effort and carry no IAM identity, so they answer the download question less well. Use them when cost dominates and gaps are tolerable.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90Which AWS service keeps a record of management API calls for 90 days in the console without you setting up a trail?
The 30-second answer
CloudTrail event history. It records management events (control-plane API calls such as RunInstances, PutBucketPolicy or CreateRole) for the last 90 days, viewable in the console and through LookupEvents, with no trail configured.
The 90 days is the limit that matters for audit. It is shorter than the one-year retention most audit regimes expect, so event history is useful for quick investigation but cannot be your evidence store.
What the 90 days covers and what it does not
| Source | Kept by event history | Needs a trail |
|---|---|---|
| Management events (control plane) | Yes, 90 days | Only for longer retention or delivery to S3 |
| Data events (S3 object reads, Lambda invokes) | No | Yes, opt-in per resource |
| Insights events | No | Yes |
Data events are off by default and are billed per event, so a team that wants object-level read evidence has to create a trail and enable them explicitly.
The fix for longer retention
Create a trail, ideally an organization trail, that delivers to an S3 bucket in a separate log-archive account. Enable log file validation so tampering with delivered files is detectable. Retention is then whatever the bucket's lifecycle and Object Lock say it is, which removes the 90-day ceiling entirely.
Failure modes
- A team assumes the console history is their audit trail, and an incident older than 90 days has no record. Check whether a trail exists in every region before you rely on it.
- Event history covers only the region you are viewing. Global services such as IAM log to us-east-1 in event history, so searching a different region misses them.
- Someone disables the trail during an incident and the gap is invisible. Alert on
StopLoggingandDeleteTrailevents.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91Tell me about a production incident you owned, where you controlled the rollback, the traffic and the update to stakeholders. Walk me through the decision points in order and what you would change now.
The 2-minute answer
I pick an incident where my change caused the outage, because it shows the decisions I controlled rather than ones I watched. Example, with hypothetical figures labelled as such: I changed the ALB target group health check path from /health to /healthz in a Terraform module that also rotated a security group. Within 90 s every target failed its check, and the listener returned 503 for all traffic. Two decisions were mine: how to restore service, and what the first update said.
| Time (hypothetical) | Decision | Why |
|---|---|---|
| T+0 | Stop further applies, freeze the pipeline | Another apply would have reverted the fix or touched the same SG |
| T+3 min | Revert only the health check path with a targeted change, not a full state rollback | A full terraform apply of the previous commit took about 14 min and also reverted the SG rule |
| T+6 min | Confirm recovery by target health, not by the 200 from my own curl | Healthy targets reach healthy after 2 consecutive successes at a 10 s interval, so about 20 s |
| T+8 min | Post the first update: impact, scope, ETA for next update, no cause claimed yet | Customers need a time to expect the next message |
| T+25 min | Open a follow-up to make the SG rule and the health path separate changes | Two unrelated changes in one plan hid the blast radius |
The rollback choice mattered most. A full revert was the textbook answer and would have taken three times longer, and its second effect (removing the SG ingress rule the app still needed on the new port) would have caused a second outage. I chose the smaller change because I could state what it reverted and what it left alone.
What I checked before acting
I did not trust the first signal. The 503s came from the ALB itself (HTTPCode_ELB_503_Count), not from targets, which told me the targets were unhealthy or absent rather than erroring. aws elbv2 describe-target-health showed Target.FailedHealthChecks with reason Target.ResponseCodeMismatch. That single line pointed at the path change, not at capacity.
Where I was slow
I took about four minutes to notice the plan had bundled two changes. The plan output was long and I read the module diff, not the resource list. Now a plan for a load balancer or security group prints a one-line summary of every ingress and health check change, and the reviewer must approve that summary.
What I would change now
- Health check paths and security group rules go in separate applies, with separate reviews.
- Any change that touches a health check gets a canary target in a second target group first, and a 5 min bake before the listener switches.
- The first customer update names what we know and when the next one arrives. It never guesses at a root cause.
What the candidate must be able to defend: why the targeted revert was safe (its blast radius was one attribute), why healthy in the target group was the recovery signal, and what the state file looked like afterwards, including the drift check that confirmed the console matched the code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92An RDS instance sits in private subnets with no internet route, but a vendor asks for 5432 open to 0.0.0.0/0. Explain which network checks decide whether that rule would actually expose the database, and compare a vendor /32 rule with an RDS IAM authentication path on their main trade-off.
The 90-second answer
A security group rule only matters if a packet can reach the instance. For RDS in private subnets with no internet route, a 0.0.0.0/0 rule on 5432 is dangerous as a standing permission, but it does not by itself make the database reachable from the internet. I'd confirm that with two checks, then choose between a vendor /32 on 5432 and IAM database authentication. The trade-off is network scope against credential lifecycle: a /32 depends on a fixed egress address the vendor may not have, and IAM auth depends on the vendor's client supporting token-based login.
The reachability mechanism
A packet from the internet reaches an RDS endpoint only if the subnet's route table sends 0.0.0.0/0 to an internet gateway, the instance has a public IP, and PubliclyAccessible is true. Without all three, the security group is never the first thing a packet meets. The security group is still the control that decides what a permitted source can do once it gets in, so an open rule is a latent exposure that becomes live the moment someone adds a public route or flips the flag.
| Check | Command | Expected for a private DB |
|---|---|---|
| Public flag | aws rds describe-db-instances --db-instance-identifier orders-prod | PubliclyAccessible: false |
| Subnet route | aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-… | no 0.0.0.0/0 to igw-… |
| Path proof | VPC Reachability Analyzer, source internet gateway to the DB ENI on 5432 | status Not reachable |
Two ways to admit the vendor
A /32 rule admits one fixed IPv4 source on 5432. It's narrow and easy to audit, but it fails the moment the vendor's egress changes, and vendors often use shared NAT pools. If I accept it, it carries an owner tag, a description with the ticket, and an expiry date.
IAM database authentication issues a short-lived token instead of a shared password, so a leaked credential ages out within 15 minutes. It doesn't by itself narrow the network path, so I'd still pair it with the /32 or a private connection such as a VPN or PrivateLink. It needs the vendor's client to support IAM tokens for PostgreSQL, which I'd verify before promising it.
I'd pick the /32 for a short, defined engagement, and IAM auth whenever the vendor will hold a long-lived integration.
What I put in the change request
The request names the source, port, expiry and approver, and it states the exposure in one sentence: any source the rule allows may attempt login, and nothing else in the path changes. Without a named approver's decision, I don't create the rule.
What would still break
The rule outlives the engagement. I guard that with an AWS Config rule that flags any 0.0.0.0/0 or ::/0 on 5432, and I put the expiry on the ticket so removal is scheduled, not remembered.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93An alert pages on-call every time a node's disk crosses 85%, and most pages close with no action. Would you lengthen the alert's for: duration or move the alert to a higher threshold, and what does each choice cost in detection?
The 90-second answer
I would not do either before checking why the disk crosses 85%. If the climb is slow and the crossing is brief, the alert is flapping on a transient, and a longer for: removes the page without changing what the alert means. If the disk genuinely sits high for hours, moving the threshold to 90% just delays the same page. The trade-off is in what each change does to detection time, and that is what I'd state before choosing.
| Change | Effect on noise | Effect on detection |
|---|---|---|
Raise for: from 1m to 30m | Removes pages from brief spikes such as log rotation | A real fill that crosses 85% and keeps climbing is paged 29 minutes later |
| Raise threshold to 90% | Removes pages that sit between 85% and 90% | Fills from 90% to 100% have less runway before the disk is full |
Hypothetical figures for 12 nodes: a node writing 2 GB/h on a 100 GB volume reaches 85% at about 6 h of sustained writes from 0%, so a 30 minute for: costs little on that rate. At 20 GB/h the same 15 GB headroom from 85% to 100% lasts 45 minutes, and a 30 minute delay leaves 15 minutes to act. The duration change is safe for slow fills and dangerous for fast ones, so I'd check the fill rate per volume before picking.
Failure mode. A longer window can hide a fill that fails within the window. The check is a symptom alert on write errors or free bytes below a fixed floor. If that alert fires first in past incidents, the disk-usage alert was not the detector and can safely be lengthened.
What I would not do. Silencing the alert with no replacement removes the only early warning for disk fills. Keep one alert on the symptom and retire the cause alert only after that symptom alert has caught the last real fill.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94Tell me about a cost reduction you delivered without a service regression. How did you prove the service was unchanged?
The 90-second answer
I picked one cost line with a clear owner and a signal the service already exposes, then shipped the change behind a weighted canary that compared it against the current fleet during the same hours. Example, with hypothetical figures at on-demand list prices in us-east-1: the ingress fleet ran 40 m5.xlarge instances (4 vCPU each, 160 vCPU total) at about 22% CPU p95 at peak. We moved to 28 m5.large (2 vCPU each, 56 vCPU total) behind the same ALB. Arithmetic at 730 hours a month: 40 × $0.192 × 730 is about $5,606, and 28 × $0.096 × 730 is about $1,961. That is roughly 35% of the original spend, a saving of about $3,645 a month. The vCPU cut is 65%, so the CPU numbers have to move too.
Before anything moved I wrote down the regression checks and their tolerances: p99 TargetResponseTime within +10% of baseline, 5xx rate within 0.05 percentage points, and CPU p95 at peak under 80%.
| Signal | Baseline, peak hour, 7 days | Canary, 6 large (21% weight), 2 days | Full rollout, 7 days after |
|---|---|---|---|
| p99 TargetResponseTime | 180 ms | 186 ms | 182 ms |
| 5xx rate | 0.04% | 0.04% | 0.05% |
| CPU p95 at peak | 22% | 66% | 63% |
| Monthly compute cost | $5,606 | n/a | $1,961 |
The CPU row is checked by arithmetic, not chosen to look good. The same peak work now lands on 56 vCPU instead of 160, so 22% × 160 / 56 is about 63%. The canary weight matches capacity: 6 of 28 instances hold about 21% of the vCPU, so they take about 21% of traffic and see a similar per-vCPU load.
Why the comparison is valid. The canary was a separate target group with weighted forwarding, so both populations served the same traffic mix in the same hours. Comparing against last week's numbers proves little, because traffic shape moves with the calendar. The controlled part is the same-hour, same-mix comparison, not the baseline itself.
The first attempt regressed. The smaller instances hit a connection ceiling set by a sidecar that held sockets open. At the second evening peak p99 rose to 310 ms. The canary's p99 alarm on a 5-minute window fired, and I set weights back to 0 within minutes. The fix was raising the sidecar's connection limit and rerunning the canary before promotion. Rollback was fast only because the old target group stayed warm.
Cost has to be measured on the bill, not inferred from instance count. The list-price figures above ignore reserved instance and savings plan discounts. Coverage hid part of the saving for a month, so the instance math looked right while the invoice did not move. I confirmed the change in Cost Explorer, filtered by the service tag and the rollout date, and compared net amortised cost, not list.
What I would change now. I would replace the fixed tolerances with a burn-rate style check over several windows, so a short spike does not decide the result either way. I would also publish the cost delta as a tagged report with the rollout date, so finance and engineering read the same number.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95Describe an automated change you shipped that took production capacity down. Walk through the decision points in order, what the pipeline and your guardrails allowed, and what you changed afterward so the same class of change cannot do it again.
I would start with the change itself, because the mechanism matters more than the intent. We shared a Terraform module for Application Load Balancer target groups across services. A routine update set health_check.path to /healthz for consistency with a newer service template. The services already in production served /health and returned 404 for /healthz. The plan showed a single in-place update to one attribute. No resource was replaced. That made the diff look cosmetic to the reviewer, including to me.
The Auto Scaling Group used health_check_type = ELB. That setting is the decision point that turned a wrong path into lost capacity. The load balancer marked instances unhealthy, and the ASG treated unhealthy as replaceable. It terminated instances that were serving traffic correctly on the old path and launched replacements that failed the same probe. This was not a bad deploy of application code. The application never changed.
Timeline
Figures below are a hypothetical reconstruction with the thresholds we had configured, included to make the sequence checkable.
| Time | Event | Mechanism |
|---|---|---|
| 14:05:10 | Apply updates the target group health check path | In-place update, no replacement in the plan |
| 14:05:40 | First probes to /healthz return 404 | Application serves /health only |
| 14:06:40 | Instance marked unhealthy | 30 second interval, unhealthy threshold 2 |
| 14:06:45 | ASG terminates the instance and launches a replacement | ELB health check drives replacement |
| 14:09:50 | Replacement boots and fails the same probe | 150 second boot time, probe fails immediately |
| 14:11:00 | 4 of 40 instances healthy | 1,800 req/s capacity against about 3,600 req/s offered |
At 4 of 40, we had 10 percent of desired capacity. Requests did not fail cleanly. They queued at the load balancer, latency rose, and clients retried, which increased offered load. I stopped the pipeline, reverted the path in Terraform, and confirmed the remaining instances recovered before allowing replacements to resume.
Decision points, in order
- Module edit. The author changed a shared default. Nothing in the module required the path to match a route the image implemented.
- Plan review. The reviewer, me included, read one attribute change with no replacement as low risk. Terraform was correct about the infrastructure change. It said nothing about application behaviour.
- Apply. The pipeline had no check between plan and apply that started the candidate image and probed the configured path. It trusted the configuration.
- ASG replacement.
ReplaceUnhealthywas enabled and the health check grace period had already elapsed for running instances. The ASG therefore acted on the first unhealthy verdicts without a human in the loop. - Detection. Our alert was on target group 5xx rate. By the time it fired, most of the fleet had already cycled. We had no alert on
HealthyHostCountfalling as a share of desired capacity.
What I changed afterward
1. A candidate-image gate before apply. CI now extracts the health check path from the saved plan, starts the image being released, and probes that exact path. A mismatch fails the build.
path=$(terraform show -json tfplan | jq -r '.resource_changes[] | select(.type == "aws_lb_target_group") | .change.after.health_check[0].path')
docker run -d --name cand -p 8080:8080 "$IMAGE"
curl -fsS --max-time 5 "http://localhost:8080${path}" >/dev/nullThis gate has its own failure modes. The image may need environment variables or a database to answer the health endpoint, so we run it with the same non-secret configuration as pre-production and use a health endpoint that does not depend on downstream systems. If the endpoint needs authentication, the gate uses the same probe credentials the load balancer uses. A gate that always passes because it probes a different port or path than the load balancer would be worse than no gate, so the path comes from the plan rather than from a checked-in constant.
2. Health check changes classified as availability-impacting. The plan review policy now flags any change to health_check.path, health_check.port, health_check.protocol, interval, or thresholds. Those changes need a second approver and a canary target group first. The canary receives a small share of traffic and must keep HealthyHostCount at 100 percent of its desired count for two evaluation periods before the main target group changes.
3. Rollout protection tied to fleet health. A CloudWatch alarm on HealthyHostCount below 75 percent of desired capacity pauses the ASG pipeline and suspends the ReplaceUnhealthy process. Suspension is deliberate. Automatic replacement is what amplified this incident, so resuming it requires a human to confirm the cause. The trade-off is slower recovery from a genuine bad host, which we accept because a fleet-wide probe failure and a single bad host look identical to the ASG until a human separates them.
4. A drill in pre-production. We change the health check path on a non-production ASG, confirm the alarm fires within two evaluation periods, and confirm that replacement stops. We run this after any change to the alarm or the ASG pipeline itself.
My part in the incident was approving the review without checking the path against the application. The lasting fix is the gate and the classification rule, because they cover the next person who edits the shared module. A reminder to read diffs more carefully would not have stopped the ASG from replacing the fleet once the first probe failed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96Your private subnets in AZ-b and AZ-c send all egress through a NAT gateway in AZ-a. Explain what happens when AZ-a fails, and what you give up by running one gateway per AZ instead.
The short version
A NAT gateway is a zonal resource. The private route table in AZ-b sends 0.0.0.0/0 to the gateway in AZ-a, so every outbound packet from AZ-b crosses into AZ-a before it leaves the VPC. When AZ-a fails, that route target disappears and the packets have nowhere to go. AZ-b and AZ-c lose outbound internet access even though they are healthy.
One gateway per AZ removes that dependency, at the price of two more hourly charges and a rule that each AZ's route table points at its own gateway.
The route, traced
AZ-b private RT: 0.0.0.0/0 -> nat-0a (in AZ-a)
AZ-a fails: nat-0a unavailable
Packet 10.30.4.17 -> 203.0.113.9: forwarded to nat-0a, no response, droppedThe route itself is still valid, so the console shows nothing wrong. The failure appears only in the data path.
The numbers
Using a us-east-1 list price of $0.045 per gateway-hour over 730 hours a month, one gateway costs $32.85 and three cost $98.55. Consolidating saves $65.70 a month. Check the price for your region before quoting it.
The saving is partly offset by cross-AZ transfer. Traffic from AZ-b and AZ-c that reaches the gateway in AZ-a is billed as inter-AZ data, roughly $0.01 per GB in each direction. Hypothetically, 5 TB a month from those zones gives about $50 on the way out and about $50 back, or roughly $100 a month. That is more than the $65.70 saved. At 500 GB the transfer falls to about $10 and the saving looks real. The break-even point depends on your measured bytes, so measure them before deciding.
What I would recommend
Run one gateway per AZ in production, where a regional egress outage is a customer-facing incident. Accept a single gateway in dev and sandbox VPCs, where the outage costs little.
Failure modes and detection
- A single gateway concentrates risk in one route target. A mistaken edit to a private route table can stop egress for every zone, so review those routes like any other production change.
- An AZ failure removes egress for the zones that depend on the gateway there. Gateway metrics can look healthy from the surviving zones, so run a synthetic egress probe from each AZ.
ErrorPortAllocationrising means the gateway is out of source ports. Extra gateways spread the load, but they do not fix a connection pool that leaks sockets.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97Your service runs in three AZs behind an ALB, with an RDS Multi-AZ primary. Walk through what happens to in-flight requests and new connections during an RDS failover, and what your application must do so the failover is not user-visible for longer than 2 minutes.
The 90-second answer
During an RDS Multi-AZ failover, the primary's endpoint DNS name is repointed to the standby. Every connection that was open to the old primary dies. The database is unavailable for writes until the standby is promoted, and AWS documents that failover typically takes 60 to 120 seconds. The application's job is to notice the dead connections quickly, reconnect against a fresh DNS lookup, and retry only the operations that are safe to retry.
Two things decide whether the user sees a blip or an outage: how long the application keeps using a dead pool connection, and whether a retried write can run twice.
Mechanism, step by step (hypothetical timings)
| Time | Event | Application sees |
|---|---|---|
| t=0 | primary AZ fails | in-flight queries hang or reset |
| t=0 to 5 s | TCP keepalive or query timeout fires | connection reset errors |
| t=5 s | pool hands out a dead connection | more errors if validation is off |
| t=60 to 120 s | standby promoted, DNS repointed | connect succeeds on a fresh lookup |
The client caches the resolved IP for as long as the JVM or resolver keeps it. If the DNS cache TTL is long, the app keeps dialing the old, dead address after the new primary is up. Keep the cache short, and set networkaddress.cache.ttl (Java) or the equivalent for your runtime.
Idempotency. A POST /orders that was in flight when the connection reset may or may not have committed. A retry without an idempotency key can create a duplicate order. Use an idempotency key stored in the same transaction as the write, so the retry finds the earlier row and returns it.
Pool hygiene. Enable connection validation on borrow (SELECT 1 or the driver's validation query) and a max connection lifetime, so dead connections are discarded instead of handed out.
What I check. Force a failover with aws rds reboot-db-instance --db-instance-identifier <id> --force-failover in staging, then measure the error rate and the time from first error to first successful write. If that measured window is under 2 minutes, the design holds. If it isn't, the cause is almost always DNS caching or a pool that never validates, not the database.
This does not cover a bad migration or an accidental delete, because those replicate to the standby. It also does not cover a whole-region outage.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98After a region is restored, which should come back first: the database or the DNS record that sends users to the region, and why?
The 60-second answer
The database comes back first. Users should not be sent to the region until the data layer accepts reads and writes. The DNS record, or the load balancer weight that routes to the region, is the last thing you change.
The rule is dependency order: a component starts only after the things it depends on are healthy. Users depend on the application, the application depends on the database, so routing is the final step.
Why
If DNS points users at a region whose application cannot reach its database, every request fails with 5xx errors. The load balancer marks targets unhealthy, and users see an outage in a region that was supposed to be the recovery site. Sending traffic only after the database accepts writes means the first requests land on a working stack.
Trace (hypothetical figures)
- 00:00 region restored; the database instance reports
availablebut has not yet finished applying recovery. - 00:12 database accepts writes and a test insert succeeds.
- 00:20 application targets pass their health checks.
- 00:25 Route 53 record switched to the restored region.
What to watch
A database that reports running is not the same as one accepting writes. Check a real write and a real read from the application before changing DNS. If you switch early, the failure shows up as a rise in 503 responses at the load balancer and connection errors in the application logs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99A web-tier instance is compromised and the attacker gets its instance role. Using security groups, NACLs and route tables, what can it reach in your three-tier VPC, and how do you shrink that set without breaking the app?
The 90-second answer
Start from the attacker's position: they control the web instance's OS and its instance profile credentials. Blast radius is the set of destination, port and protocol combinations that instance can reach, plus the AWS API calls its role allows. My job is to make that set equal to what the web tier actually needs.
Three controls do most of the work, and each sits at a different layer.
- Security groups reference each other by group ID, not CIDR. The data SG allows 5432 only from
sg-app. A web instance in the same subnet range is still refused, because it does not carrysg-app. - Egress is restricted as well as ingress. A default SG allows all outbound traffic. The web SG should allow 443 to
sg-appand to the S3 prefix list, and nothing else. The data SG should allow no internet egress at all. - NACLs are a coarse subnet backstop. They are stateless, so return traffic needs ephemeral ports 1024-65535 allowed explicitly. Rules evaluate in ascending rule number and the first match wins. I use NACLs to deny 22 and 3389 between tiers, not as the primary control.
Routing caps everything. The data subnet route table holds only the local route. With no 0.0.0.0/0 route, a compromised data-tier instance has nowhere to send packets, and the SG rules never see the attempt.
Trace. The compromised web instance at 10.0.1.23 opens a SYN to the database at 10.0.3.15:5432. The data SG has no rule matching sg-web, so the packet is dropped. A flow log record for that ENI (hypothetical values, default v2 format) looks like:
2 111122223333 eni-0a1b2c3d 10.0.1.23 10.0.3.15 49214 5432 6 1 60 1767000000 1767000060 REJECT OK
The same connection from sg-app gets ACCEPT. Two lines, one field difference, and that field is the blast-radius boundary.
Failure modes
- A shared SG on the wrong instance. Someone attaches
sg-appto a web instance "for the metrics agent", and now the web tier reaches the database. Detect it by listing ENIs per SG in a scheduled check and failing when the set changes. - Open egress from the data tier. A
0.0.0.0/0egress rule in the data SG is the exfiltration path. Detect it with flow logs: any accepted record from a data-tier ENI to an address outside the VPC is a finding. - DNS left open. Egress to any resolver on UDP/TCP 53 enables DNS tunnelling. Restrict DNS to the VPC resolver at the base+2 address (10.0.0.2 in a 10.0.0.0/16 VPC).
- Transit routes that re-open a path. VPC peering is not transitive, but a transit gateway route propagated to the data subnets can silently expose a tier to another VPC. Review propagated routes whenever an attachment changes.
Proof. Run Reachability Analyzer from the web ENI to 10.0.3.15 on 5432 and expect a blocked result naming the security group. Run it from the app ENI and expect reachable. Put both in CI so a change to either SG fails the build.
What this does not cover. Stolen instance role credentials still make AWS API calls from anywhere that can reach the endpoint. Scope the role separately, and treat credential theft and network reach as two controls, not one.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100An Auto Scaling group with ELB health checks replaces every instance whenever the database is unreachable. Explain why that happens, and whether you would switch the group back to EC2 status checks.
The 90-second answer
With ELB health checks enabled, the group uses two signals. It keeps the EC2 status checks, which ask whether the instance and its OS are reachable. It also replaces any instance the target group reports unhealthy. The target group decides health by calling the path configured on each target. If that path calls the database, a database outage makes every target fail at once, and the group replaces the whole fleet. The replacements fail the same way, so the loop continues.
I would not switch back to EC2 checks as the fix. I would change what the target group checks, and keep ELB health checks on for the one failure they detect well: an application process that stops answering.
Trace (hypothetical figures)
Assume grace period 300 s, boot and start takes 90 s, and the DB is unreachable for 10 minutes.
t=0 the DB drops. Each instance's /ready returns 503. t=300 s the grace period on the first instance ends and the target group marks it unhealthy. The group terminates it and launches a replacement. The replacement cannot reach the DB either, so it is marked unhealthy after its own grace period. The group keeps cycling until the DB returns.
Comparing the two approaches
| Setting | Detects | Cost during a DB outage |
|---|---|---|
| EC2 status only | host or OS failure | no replacement from app-level faults |
ELB, /healthz with no dependency calls | process stops answering | none from DB faults |
ELB, /ready calling the DB | any dependency failure | fleet-wide replacement loop |
The main trade-off: EC2 checks never replace for app faults, so a hung process stays in service. A shallow ELB check keeps that detection and removes the DB coupling. The deep check looks safer but turns a shared dependency into a fleet-wide action.
What I change
- Point the target group at a shallow path, and set the grace period above measured boot time with margin.
- Alarm on DB connection errors and page a person. Replacing instances does not fix a bad credential.
- Keep request-level 5xx and latency alarms, because a shallow check passes a worker pool that is up but wrong.
When I review this setup, I check the health check path first, then the grace period against measured boot time.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.