Skip to content
Tech Interview Prep
Technical interview guide

Cloud Networking Fundamentals

VPCs, subnets, and security groups: the building blocks every other cloud topic assumes.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Vendor-neutral fundamentals with AWS VPC terminology and official references accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

Explain CIDR longest-prefix matching using a broad transit route and a narrower peering route.

Answer

The 90-second answer. A router forwards on the longest prefix match: among every route whose prefix covers the destination, the one with the most bits in its mask wins. 10.40.0.0/16 via transit and 10.40.8.0/24 via peering both cover 10.40.8.25, so the /24 wins: 24 > 16. 10.40.9.25 matches only the /16, so it goes to transit. Nothing else changes that outcome: administrative distance, BGP attributes and configuration order only break ties between routes of the same prefix length.

Mechanism. A route is a prefix plus a length. A destination matches when addr & mask == prefix. A /24 mask has eight more contiguous 1-bits than a /16, so it constrains eight more bits of the address and matches a strictly smaller set: 256 addresses instead of 65,536. That is the whole reason longest-prefix match exists: it lets you advertise one aggregate and still carve out exceptions underneath it, with no ordering rule and no "most recent wins" semantics. Forwarding tables implement it as a trie walked bit by bit, or a multibit trie (commonly a 24-8-8 split for IPv4), so lookup cost is bounded by prefix length rather than table size. 0.0.0.0/0 is just the length-0 entry that matches everything and loses to every other match.

Worked trace. RIB on the source router:

prefixnext hopAD
0.0.0.0/0transit20 (eBGP)
10.40.0.0/16transit20 (eBGP)
10.40.8.0/24peering20 (eBGP)
10.40.8.25/32static1

FIB lookups:

destinationmatching prefixeswinneregress
10.40.8.25/0, /16, /24, /32/32static
10.40.8.25 (host route withdrawn)/0, /16, /24/24peering
10.40.9.25/0, /16/16transit
10.41.1.1/0/0transit

Bit check on the third octet: 10.40.8.25 is 00001010.00101000.00001000.00011001; 10.40.9.25 is 00001010.00101000.00001001.00011001. They diverge at bit 24, the last bit of the third octet, so 10.40.9.25 fails the /24 match and falls back to the /16.

RIB versus FIB. The RIB holds every route from every protocol, including both the /16 and the /24: BGP does not compare them, because they are different prefixes and both are valid. The FIB holds one selected next hop per prefix. Longest prefix match is a forwarding-plane rule applied at lookup time; administrative distance (Cisco defaults: connected 0, static 1, eBGP 20, OSPF 110, iBGP 200) and then BGP attributes pick between routes for the same prefix before it reaches the FIB. A static /16 with AD 1 still loses to a learned /24 at lookup.

Failure modes. A more specific route always wins, so a leaked /24 from a peer silently overrides your /16 aggregate: the classic traffic-hijack and traffic-engineering hazard. Detect it by diffing the FIB against the intended policy, not by reading configs. Standard mitigations: reject inbound prefixes longer than /24 in the DFZ, and set RPKI maxLength on ROAs (a ROA for 10.40.0.0/16 with maxLength 24 validates 10.40.8.0/24 but not a /25). Also check the return path separately: asymmetric longest-prefix outcomes are common when only one side has the exception route.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

What makes a cloud subnet public, and what else does an IPv4 workload need before it is actually internet reachable?

Answer

The 90-second answer

A subnet is public when its effective route table has a route whose target is an internet gateway attached to the VPC: in practice 0.0.0.0/0 → igw-…. That is the whole definition. The subnet's name, the mere presence of an IGW somewhere in the VPC, and any per-instance setting are irrelevant. "Effective" matters: a subnet with no explicit route-table association uses the VPC's main route table, so editing the main table can make subnets public without touching them.

Reachability then needs four more things, all of which must hold:

  1. A public IPv4 address on the ENI. Either auto-assigned at launch (subnet attribute MapPublicIpOnLaunch: true by default on default-VPC subnets, false on nondefault ones) or an Elastic IP associated afterwards. You cannot assign a public IPv4 to an existing ENI after launch; only an EIP association adds one.
  2. The IGW route, as above, and it must be the longest-prefix match for the destination.
  3. Filters. Security groups are stateful, allow-only, attached to the ENI, and all rules are evaluated: any match allows. NACLs are stateless, subnet-level, numbered, and support deny. A NACL must allow return traffic explicitly (ephemeral ports 1024–65535); a security group does not.
  4. A listening process on the interface address: bound to 0.0.0.0, not 127.0.0.1, and permitted by any host firewall.

For the public DNS name (ec2-…compute.amazonaws.com) to resolve, the VPC needs both enableDnsSupport and enableDnsHostnames true.

Alternatives

OptionInboundCost (us-east-1 list)Use when
Public subnet + IGW + public IPDirect to instance$0.005/hr per public IPv4Few instances, inbound needed
Private subnet + NAT gatewayNone$0.045/hr + $0.045/GB processedOutbound-only egress
Public ALB/NLB, private instancesVia LB onlyLB hourly + LCU/NLCUInbound needed, instances stay private

Crossover on address cost alone: a NAT gateway's $32.85/mo fixed equals 9 public IPv4s at $0.005/hr × 730 h. Below ~9 instances the public IP is cheaper; above it NAT wins on cost, and it wins on security at any scale. One NAT gateway per AZ for availability doubles the fixed cost.

Failure modes and how they look

SymptomCauseDetect
Outbound hangs, no SYN-ACKRoute present, no public IP: the IGW only NATs addresses it ownsdescribe-instances ENI PublicIp empty; curl ifconfig.me times out while private hosts respond
Same hang, ENI has a public IPNo IGW route, or a more specific route shadows itdescribe-route-tables on the associated table
SYN sent, no SYN-ACK, request logged ACCEPTNACL drops the return on ephemeral portsVPC Flow Logs: request ACCEPT, no response record
Connection refused, fastApp bound to 127.0.0.1ss -lntp on the host
IP works, hostname NXDOMAINenableDnsHostnames falsedig the public DNS name

Packet path

Client → IGW (rewrites dst to the ENI's private IP) → NACL inbound → security group → host firewall → socket. Return: socket → NACL outbound (ephemeral) → security group (stateful, automatic) → ENI → IGW (rewrites src to the public IP) → client.

Other clouds don't share this model. GCP gives every VPC a default route to its internet gateway, so reachability turns on whether the instance has an external IP (or Cloud NAT for egress) plus firewall rules. Azure has no IGW object: a VM needs a public IP, NAT gateway or load balancer, and an NSG rule. Subnets aren't classified public or private at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare security groups and network ACLs, including how each handles response traffic.

Answer

The 90-second answer

Both are packet filters inside a VPC, but they attach at different layers and differ on the one property that decides most designs: security groups are stateful and attach to an ENI; network ACLs are stateless and attach to a subnet.

A security group has allow rules only, there is no deny, and all rules are evaluated together, not in order. A newly created security group starts with no inbound rules and one outbound rule allowing all traffic; the VPC's default security group instead allows inbound from anything that is itself a member of that group, plus all outbound. Because it is stateful, once an allowed SYN is tracked, the SYN-ACK and the rest of the flow are admitted with no rule mentioning the client's ephemeral port. That is why allow 443 from sg-web covers the whole conversation.

A network ACL has allow and deny rules, numbered 1–32766, evaluated lowest number first, first match wins, with an implicit deny-all after the last rule. It is stateless: every packet is judged on its own, in both directions. Return traffic therefore needs its own rules, outbound on the server's subnet and inbound on the client's subnet, covering the ephemeral port range.

Security groupNetwork ACL
Attaches toENI (instance, ALB, RDS)Subnet: every ENI in it
StateStateful, connection trackingStateless
Rule typesAllow onlyAllow and deny
EvaluationAll rules, no orderNumbered, first match wins
Default rulesNew SG: no inbound, all outbound. Default SG: inbound from same SG, all outboundDefault NACL: rule 100 allow all in and out
Default quota60 inbound + 60 outbound rules per SG; 5 SGs per ENI (up to 16)20 rules per NACL (up to 40)
Return trafficAutomatic via trackingExplicit ephemeral-port rules

Ephemeral ranges to allow: Linux clients 32768–60999, Windows 49152–65535. AWS's own NACL guidance for return traffic from an internet-facing load balancer uses 1024–65535, which covers both.

Worked trace. Client 10.0.1.10 in subnet A calls server 10.0.2.20:443 in subnet B. The client kernel picks source port 49152.

  1. SYN 10.0.1.10:49152 → 10.0.2.20:443. NACL A outbound rule 100 allows TCP 443 to 10.0.2.0/24. NACL B inbound rule 100 allows TCP 443 from 10.0.1.0/24. The server's security group allows 443 from sg-client; the flow is now tracked.
  2. SYN-ACK 10.0.2.20:443 → 10.0.1.10:49152. NACL B outbound must allow TCP 49152 to 10.0.1.0/24: covered by 32768–60999. NACL A inbound must allow TCP 49152 from 10.0.2.0/24: covered. The server's security group needs no rule; the tracked entry admits it.
  3. Data continues both ways under the same tracking entry.

Failure mode. Change NACL A's inbound rule to 1024–32767 and step 2 is dropped at the subnet boundary. Linux reuses source port 49152 for the life of the connect() call, so you see repeated SYNs and no SYN-ACK: a black hole, not a reset. VPC Flow Logs show the outbound SYN as ACCEPT and the inbound SYN-ACK as REJECT; that asymmetry points at the stateless layer, since the security group already tracked the flow.

Choosing. Use security groups for workload-to-workload intent, including rules that name another security group as source (works within a VPC and same-Region peered VPCs; cross-Region peering needs CIDRs). Use NACLs for coarse subnet guardrails and for the one thing security groups cannot do: deny a specific source IP. Remember a NACL deny hits every instance in the subnet, and a broad early rule: rule 10 denying 10.0.0.0/8: shadows a narrow allow at rule 200. Neither replaces TLS, identity, host hardening, or application authorization.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What problem does a private service endpoint solve, and what security problems does it not solve?

Answer

A private endpoint (concretely, an AWS PrivateLink interface VPC endpoint) places an elastic network interface with a private IP from your subnet CIDR in front of a supported service. Clients in the VPC reach the service at that IP over the AWS network; the packets never hit the internet gateway or NAT gateway. That buys two things: the service is no longer reachable only via public egress, and you get an endpoint policy, a resource policy attached to the endpoint, that constrains which principals and resources can use that path.

It does not authenticate or authorize the workload. The endpoint policy is evaluated as an intersection with IAM identity policy: it can only subtract permissions, never grant them. A role with no s3:GetObject still gets AccessDenied through the endpoint. It also doesn't encrypt anything, doesn't stop a workload with valid credentials from exfiltrating data to the service, and says nothing about data at rest or tenant isolation on the provider side.

Mechanism. When you create an interface endpoint with private DNS enabled, AWS creates a private hosted zone named for the service (secretsmanager.us-east-1.amazonaws.com, s3.us-east-1.amazonaws.com) with an A record pointing at the endpoint ENIs. Your VPC resolver answers with the private IPs, so existing code that calls the public hostname transparently uses the endpoint. Private DNS requires enableDnsSupport and enableDnsHostnames on the VPC. With it off, clients must use the endpoint-specific name, vpce-0abc123-xyz.secretsmanager.us-east-1.vpce.amazonaws.com.

The default endpoint policy is {"Effect":"Allow","Principal":"*","Action":"*","Resource":"*"}: full access for anyone in the VPC who already has identity permission. Tightening it means naming principals, e.g. a condition on aws:PrincipalArn for arn:aws:iam::111122223333:role/app-prod.

Gateway endpoints for S3 and DynamoDB are a different mechanism: a prefix-list entry in the route table, no ENI, no hourly charge, no per-GB processing charge.

Failure modes.

  • Private DNS off, or a more specific private hosted zone shadowing the service name: resolution returns public IPs and traffic silently egresses through NAT. You believe you're private and you're not. Detect with dig from an instance in the subnet, or VPC Flow Logs showing 443 to public addresses.
  • Endpoint policy too narrow: a batch job running as role/batch gets AccessDenied from the service even though its identity policy allows the action. CloudTrail shows the call with errorCode: AccessDenied and the endpoint ID.
  • AZ coverage: an endpoint ENI exists only in the AZs you selected. A subnet in an uncovered AZ resolves to ENIs in another AZ: it works, but you pay cross-AZ transfer, and if the covered AZs fail, that subnet loses access.
  • On-premises over VPN or Direct Connect: your resolver forwards to public DNS and gets public IPs unless you add a Route 53 Resolver inbound endpoint and forward the service zone.

Trade-offs. The alternative is allow-listed public egress: NAT gateway plus security-group egress rules plus a service-side IP allowlist. That's cheaper for low volume and works for services PrivateLink doesn't support. Interface endpoints cost about $0.01/hour per AZ plus $0.01/GB processed (us-east-1 list); a NAT gateway is $0.045/hour plus $0.045/GB for the first 10 TB. Three AZs of one endpoint is ~$21.90/month. At 1 TB/month the data-processing delta is ~$36 against ~$22 of endpoint hours: thin. At 10 TB/month it's ~$358 against the same $22, clearly worth it. Don't use a private endpoint when you need arbitrary internet destinations, when the service isn't supported, or when volume is low enough that NAT is cheaper and the exposure is acceptable.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

A private DNS name resolves correctly in one VPC but not another. How would you diagnose and fix it?

Answer

First 90 seconds. Clarify three things: are both VPCs in the same account and region, is the name in a Route 53 private hosted zone or forwarded to on-prem DNS, and are the clients using the VPC resolver (CIDR base +2) or a custom one. Then say the answer: an NXDOMAIN in one VPC and NOERROR in the other almost always means the private hosted zone isn't associated with the second VPC, or a Resolver forwarding rule in that VPC is taking the query instead. Query both resolvers, read the status code, and let that pick the branch.

The trace that decides it. VPC A is 10.0.0.0/16, VPC B is 10.1.0.0/16, so the resolvers are 10.0.0.2 and 10.1.0.2.

$ dig @10.0.0.2 db.internal.example.com A +noall +comments +answer
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 41234
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
db.internal.example.com. 300 IN A 10.20.4.11

$ dig @10.1.0.2 db.internal.example.com A +noall +comments +answer
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 51235
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
internal.example.com. 86400 IN SOA ns-1234.awsdns-56.com. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

NXDOMAIN rather than SERVFAIL is the useful signal: the resolver completed the lookup and found nothing, which points at association or rule selection, not at a broken forwarding path. SERVFAIL or a timeout points the other way, at the outbound endpoint.

Symptom from VPC BCheckCommand
NXDOMAINIs the zone associated with VPC B?aws route53 list-hosted-zones-by-vpc --vpc-id vpc-0b1 --vpc-region us-east-1
NXDOMAIN or SERVFAILDoes a forwarding rule match the suffix (or the catch-all .)?aws route53resolver list-resolver-rules --filters Name=VPCId,Values=vpc-0b1
SERVFAIL or timeoutOutbound endpoint security group and route to the targetaws route53resolver get-resolver-endpoint --resolver-endpoint-id rslvr-out-...
Nothing resolves in BenableDnsSupport on the VPCaws ec2 describe-vpc-attribute --vpc-id vpc-0b1 --attribute enableDnsSupport

Fix. If the zone is missing the association:

aws route53 associate-vpc-with-hosted-zone --hosted-zone-id Z0123456789 \
  --vpc VPCRegion=us-east-1,VPCId=vpc-0b1

Cross-account, the zone owner must run create-vpc-association-authorization first or the call fails with VPCAssociationAuthorizationNotFound. If a forwarding rule is shadowing the zone, delete or narrow the rule rather than publishing the record publicly or adding internet egress.

Failure modes and how you catch them.

  • Negative caching hides the fix. The SOA in the authority section carries the negative-cache TTL; Route 53's default SOA minimum is 86400 s, and resolvers may cap it lower. A client that already got NXDOMAIN keeps failing after the association is added. Detect it by querying a name in the zone that hasn't been asked for yet; if that resolves, the fix worked and the rest is cache expiry.
  • Duplicate zones. Two private hosted zones with the same name associated with one VPC is a misconfiguration: don't rely on which one answers. list-hosted-zones-by-vpc shows both.
  • Rule precedence. A forwarding rule whose domain matches the name is applied ahead of the private hosted zone, so a rule for internal.example.com aimed at on-prem will shadow the zone even after association. The rule list is the check.
  • Endpoint path. If the outbound endpoint's security group doesn't allow UDP/TCP 53 to the target, or the subnet route table has no path to it, every forwarded name in that VPC fails, not just this one. Resolver query logs (create-resolver-query-log-config) show the rcode and answers per VPC and separate "this name" from "this VPC".

Validate positive and negative answers from every client network after the change, and record zone ownership and each VPC association so future attachments include DNS in the readiness checklist.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How do you verify and enforce that a managed database subnet has no direct route or ingress from the public internet?

Answer

The 60-second answer. A database host is reachable from the internet only when three things are true at once: its subnet's route table has a 0.0.0.0/0 (or ::/0) route to an internet gateway, its ENI holds a public address, and an SG or NACL permits the port. Remove the route and the other two are inert: a public IP on a subnet with no IGW route is unreachable, and a NAT gateway only carries connections the instance itself initiated. So enforce at the route table, then verify all three layers independently, because each one fails silently on its own.

Enforce

  • Route table: DB subnets get a dedicated route table whose only routes are local plus internal targets (VPC endpoints, TGW, peering). No igw-*, no ::/0.
  • Addressing: MapPublicIpOnLaunch=false and AssignIpv6AddressOnCreation=false on the subnet; no EIPs attached to DB ENIs.
  • NACL: inbound allow only from app-tier CIDRs on 5432. NACLs are stateless, so the outbound side needs 1024–65535 back to those same CIDRs.
  • SG: ingress references sg-app, not a CIDR.
  • Guardrail: an SCP denying ec2:CreateRoute and ec2:ReplaceRoute on the DB route table ARN, and ec2:ModifySubnetAttribute on the DB subnets, conditioned on aws:ResourceTag/Tier=database.

Verify: three checks, all scriptable:

Shell
SUBNET=subnet-0a1b2c3d4e5f60718
RT=$(aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=$SUBNET \
     --query 'RouteTables[0].RouteTableId' --output text)
aws ec2 describe-route-tables --route-table-ids $RT \
  --query 'RouteTables[0].Routes[?DestinationCidrBlock==`0.0.0.0/0` || DestinationIpv6CidrBlock==`::/0`].{v4:DestinationCidrBlock,v6:DestinationIpv6CidrBlock,gw:GatewayId}' \
  --output json
# expect: []  — any igw-* here means the subnet is public

aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=$SUBNET \
  --query 'NetworkInterfaces[?Association.PublicIp].NetworkInterfaceId' --output json
# expect: []

Then prove the path rather than infer it. Reachability Analyzer, with the internet gateway as source and the DB ENI as destination on TCP/5432, must return NetworkPathFound: false:

Shell
aws ec2 create-network-insights-path --source igw-0abc123 --destination eni-0def456 \
  --protocol TCP --destination-port 5432
aws ec2 start-network-insights-analysis --network-insights-path-id nip-0123456789abcdef0
aws ec2 describe-network-insights-analyses --network-insights-analysis-ids nia-0123456789abcdef0 \
  --query 'NetworkInsightsAnalyses[0].NetworkPathFound'

Network Access Analyzer's "Internet access to my resources" scope sweeps every resource in the account on a schedule and flags any path it finds, which catches subnets nobody remembered to tag. For continuous detection, the managed Config rule subnet-auto-assign-public-ip-disabled covers the addressing half; the route-table half needs a custom rule (a Guard policy over AWS::EC2::Route and AWS::EC2::SubnetRouteTableAssociation), since no managed rule asserts "no IGW route."

Failure modes

  • IPv6: a subnet can be private on IPv4 and public on IPv6. ::/0 -> igw-* with AssignIpv6AddressOnCreation=true is a direct path. Check both families.
  • ENIs outlive the attribute: flipping MapPublicIpOnLaunch does not strip addresses from already-running instances, and an EIP attached later re-creates reachability. Verify at the ENI, not the subnet.
  • Peering and TGW: no IGW route, but a route to a transit gateway that lands in an internet-facing VPC or on a corporate network is still an ingress path. Reachability Analyzer follows it; a route-table grep does not.
  • Flow logs are not proof of absence: they miss DHCP, the .2 resolver, 169.254.169.254 and time sync, and default to a 10-minute aggregation interval. Use them to catch ACCEPT records whose srcaddr is outside your internal CIDRs, not to certify isolation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design secure administrative access to private workloads without opening SSH or RDP to the world.

Answer

What I'd say first

Don't expose 22 or 3389 to 0.0.0.0/0. Terminate operator access at an identity-aware broker that authenticates the human, authorizes the specific target and action, and reaches the workload over an outbound-only channel. The workload keeps no inbound management port.

Named options

OptionHow the operator reaches the targetInbound port on workload
AWS SSM Session ManagerSSM Agent dials out to SSM endpoints over 443; operator runs aws ssm start-sessionnone
GCP IAP TCP forwardinggcloud compute ssh --tunnel-through-iap; firewall allows 35.235.240.0/2022 open only to the IAP range
Azure BastionBrowser RDP/SSH via Bastion in AzureBastionSubnet (min /26)none, public IP removed
Teleport / HashiCorp BoundaryBroker issues short-lived certs and proxies the sessionnone

Mechanism

SSM is the cleanest to reason about. The instance role carries AmazonSSMManagedInstanceCore; the agent opens an outbound TLS connection to the SSM service and holds it. When an operator calls StartSession, IAM decides whether that principal may start a session on that instance ID. The service multiplexes the operator's channel onto the agent's existing connection: no listener, no key pair, no security-group rule. Session Manager's idle timeout defaults to 20 minutes, and sessions can be logged to S3 or CloudWatch Logs.

For RDP without a public port:

aws ssm start-session --target i-0abc123 \
  --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["3389"],"localPortNumber":["13389"]}'

This opens localhost:13389 on the operator's machine; the RDP client connects there. The instance never accepts 3389 from the network.

JIT elevation

Standing admin rights are the thing to remove. Bind the broker's authorization to a group that is empty by default and grant membership through an approval flow (IAM Identity Center plus an approval step, or Boundary's session authorization) with a TTL of minutes to hours. The credential is issued per session, so revocation means "stop issuing," not "rotate a shared key."

Failure modes and detection

  • Agent down or role detached → sessions fail for the operator. Detect: Fleet Manager ping status, alarm on ssm:StartSession errors.
  • Egress blocked or missing VPC endpoints → agent can't reach SSM. Detect: agent ping status flips to "Connection lost."
  • IAP firewall rule removed → tunnels fail. Detect: VPC firewall log denials from 35.235.240.0/20.
  • Broker as a pivot: if the broker host can reach every subnet, its compromise is lateral movement. Detect: VPC flow logs showing one source reaching many hosts; scope the broker's reach to tagged targets.
  • Stale standing access: diff IAM policies against expected and alert on long-lived keys.

Emergency path

Test break-glass: a documented, audited procedure that grants time-boxed admin when the broker is down, and confirm revocation works. A private subnet is not administration security: the route still has to be authenticated, authorized and logged.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Why place a public load balancer in front of private application targets, and what controls still remain necessary?

Answer

What I'd say first

Put the load balancer in the public subnets so it owns the only internet-routable addresses and listeners; the application instances sit in private subnets with no route to an internet gateway, so nothing on the internet can open a connection to them. The LB accepts connections, terminates TLS, health-checks targets, and forwards only traffic matching its listener rules. The app never needs a public IP, and replacing an instance doesn't change anything the client sees.

Why the security-group reference is the mechanism, not a formality

An ALB's nodes take IPs from the subnet CIDR and those IPs change as it scales. You don't allow those IPs; you allow the LB's security group as a source. The rule matches on the source being an ENI in that group, the LB node's private IP in the target's subnet, so it keeps working when the LB scales or its public address changes. That's why "allow the LB SG on port 8080" is stable and "allow 1.2.3.4/32" is not.

Private addressing matters for the same reason in reverse: a private subnet has no 0.0.0.0/0 route to an internet gateway, so inbound connections can't be initiated from the internet. Outbound still works through a NAT gateway, which source-NATs to its own elastic IP. That NAT is per-AZ, if one AZ's NAT goes away, that AZ's targets lose egress even though the LB still sends them traffic.

Controls that remain necessary

  • Target SG: inbound only from the LB SG on the app port, plus the health-check port if it differs. Nothing from 0.0.0.0/0.
  • TLS: an ALB security policy such as ELBSecurityPolicy-TLS13-1-2-2021-06 negotiates TLS 1.3 and 1.2 only. Terminate at the LB, and re-encrypt to targets if that hop crosses a shared network.
  • Health checks: ALB defaults are 30 s interval, 5 s timeout, 5 healthy / 2 unhealthy. Two consecutive failures pull a target out; with cross-zone load balancing on (always on for ALB), the other AZs absorb the traffic.
  • Deregistration delay defaults to 300 s. Lower it to match your longest request or deploys stall five minutes per target; raise it for long-lived streams.
  • Idle timeout defaults to 60 s. If the app's keep-alive is longer, the LB closes the connection first and clients see 502s.
  • WAF on the ALB for L7 rules; rate-based rules evaluate over a 5-minute window (2000 requests per 5 min per IP is a common starting threshold).
  • Access logs to S3, and the app reading X-Forwarded-For / X-Forwarded-Proto: trustworthy only because the app is unreachable except through the LB.

Alternatives and when to pick them

  • Direct public instances: simplest, but every instance needs a public IP, host firewall and its own TLS; you lose central cert rotation and WAF. Only for a single throwaway host.
  • NLB: L4, static IPs per AZ, preserves the client source IP, handles TCP/UDP and very high throughput. Pick it when you need static IPs for allowlisting or non-HTTP protocols. Cross-zone load balancing is off by default on NLB, so enable it or AZ capacity skews.
  • Private ALB plus VPN or peering: no public ingress at all. Pick it for internal admin planes.
  • CloudFront and WAF in front of the ALB: edge caching and DDoS absorption; then lock the ALB to CloudFront via a shared secret header or VPC origin so the ALB isn't independently reachable.

Failure modes

  • The health check hits a static /healthz that returns 200 while the database is down, so the LB keeps routing. Use a deep check, or a separate shallow/deep pair.
  • Someone opens the app SG to the VPC CIDR "because it's private": any compromised instance or peered VPC can now reach it.
  • The app trusts X-Forwarded-For from any source; if it is ever reachable directly, clients spoof their IP.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Define a meaningful availability test for redundant site-to-site VPN tunnels.

Answer

A meaningful availability test for redundant site-to-site VPN tunnels proves that the secondary path carries production traffic within your recovery objectives when the primary fails. Two tunnels 'up' in the console only proves configuration exists.

Assume an active/standby setup: two IPsec tunnels to different AWS VPN endpoints (or Azure VPN Gateway instances), running BGP for dynamic failover, or static routes with IPsec DPD health checks. The test runs in a maintenance window with change control.

Core test steps:

  1. Baseline: push representative traffic (e.g., 500 Mbps TCP, 10k UDP packets/s) over the primary. Record latency (p50/p99), loss, throughput, and BGP session state.
  2. Inject failure: on the customer gateway, shut down the BGP session to the primary (or block UDP 500/4500). For static routing, rely on DPD timeout: AWS VPN default is 30 seconds.
  3. Measure recovery: time from failure injection to first packet on secondary. With BGP and no BFD, expect 90s (BGP hold timer) plus convergence; with BFD, sub-second. With DPD, 30s plus route update.
  4. Verify capacity: secondary must carry the same load with loss < 0.1% and latency < 50ms (adjust to your SLA). If secondary is 500 Mbps and primary is 1 Gbps, the test fails if you need 1 Gbps.
  5. Repeat in reverse: fail secondary, verify primary takes over.

Trade-offs:

  • BGP vs static: BGP gives automatic failover and path selection, but requires ASN coordination, more complex firewall rules, and slower convergence without BFD. Static with DPD is simpler but failover depends on DPD timers and may need manual route changes. Choose BGP if RTO < 30s; static if you can tolerate minutes.
  • Windowed test vs continuous chaos: a windowed test is controlled and repeatable, but may not catch real-world failures (e.g., provider outage). Continuous chaos (e.g., weekly failover drills) builds confidence but risks production impact. Start with windowed, then automate a canary failover during low traffic.

Failure modes to test:

  • Asymmetric routing: traffic goes out secondary but returns primary, causing drops. Detect via traceroute and flow logs.
  • MTU/MSS issues: IPsec overhead reduces MTU; large packets drop. Test with ping -M do -s 1400.
  • Capacity mismatch: secondary link smaller than primary. Monitor interface counters.
  • Dependent DNS/firewall: if DNS or firewall path fails, VPN may be up but apps fail. Include in test.
  • BGP flapping: monitor flap count; alert if > 3 in 5 minutes.

Artefacts: Table 1: Test steps and pass criteria. | Step | Action | Pass criteria | | 1 | Baseline load | Loss < 0.1%, p99 < 50ms | | 2 | Fail primary | Secondary receives traffic within RTO (e.g., 30s) | | 3 | Verify capacity | Secondary carries 100% load, loss < 0.1% | | 4 | Fail secondary | Primary takes over within RTO |

Table 2: Trade-off criteria. | Choice | When to use | When not to use | | BGP + BFD | RTO < 5s, multiple paths | Small team, no ASN coordination | | Static + DPD | RTO 30-60s, simple setup | Need automatic path selection | | Windowed test | Regulated, low risk tolerance | Need continuous assurance | | Chaos drills | High availability culture | Production cannot tolerate risk |

This test is meaningful because it measures data plane recovery, not just control plane state.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Design the subnet and routing layout for a highly available three-tier service across multiple zones.

Answer

Core answer (first 90 seconds)

Assume AWS, three AZs, and a three-tier service (edge, app, data). Clarify two things before drawing: peak RPS per tier, and whether the data tier may have any internet egress at all. Then build one VPC, 10.0.0.0/16, with three subnet tiers replicated per AZ.

Tierus-east-1aus-east-1bus-east-1cSizeUsable IPs
Public edge10.0.0.0/2410.0.1.0/2410.0.2.0/24/24251
App private10.0.16.0/2010.0.32.0/2010.0.48.0/20/204091
Data private10.0.64.0/2410.0.65.0/2410.0.66.0/24/24251

AWS reserves 5 addresses per subnet (network, VPC router, DNS, future use, broadcast), so a /24 yields 251 usable, not 254. App subnets are /20 because autoscaling groups and in-VPC Lambda each consume an ENI address; data subnets are /24 because RDS Multi-AZ needs only a handful.

Route tables, one per purpose:

  • Public RT (shared across the three edge subnets): 0.0.0.0/0 → Internet Gateway. The IGW is regional, so one table is enough.
  • App RT, one per AZ: 0.0.0.0/0 → NAT gateway in the same AZ. This is the zonal dependency that matters.
  • Data RT (shared): no default route at all. Local routes plus gateway endpoints for S3 and DynamoDB only.

Security groups reference each other, not CIDRs:

  • alb-sg: ingress 443 from 0.0.0.0/0; egress to app-sg on 8080.
  • app-sg: ingress 8080 from alb-sg; egress to db-sg on 3306 (5432 for Postgres).
  • db-sg: ingress 3306 from app-sg.

An ALB is regional and requires subnets in at least two AZs; it places a node in each and cross-zone load balancing is on by default, so a healthy target in 1b serves traffic that landed on the 1a node.

Trade-offs and when not to use this

One NAT gateway vs three. Three NAT gateways cost 3 × $0.045/hr ≈ $0.135/hr, about $98/month in us-east-1, plus $0.045/GB processed. A single NAT saves roughly $65/month but makes every AZ's egress depend on one AZ, and traffic from the other two crosses AZ boundaries at $0.01/GB each way. Acceptable for a dev VPC; not for production.

Two AZs vs three. Two AZs halve the NAT and subnet cost, but N-1 leaves one AZ carrying 100% of peak. Three AZs let you run each at ≤50% at peak and still survive a loss. If the workload is small and cost-bound, two AZs with a documented RTO is a defensible choice; state it explicitly.

Data tier with no egress. If the DB needs patching, do not add a NAT route: use SSM Session Manager, which needs no bastion and no public IP.

Failure modes and detection

  • AZ loss. ALB health checks (interval 10s, unhealthy threshold 2) drain the failed AZ in ~20s; the other two absorb 2× load. Detect via per-AZ target counts and 5xx rate. This only works if the surviving two have headroom: verify with a load test that kills one AZ at peak.
  • NAT gateway failure. Only that AZ loses egress; the other two keep theirs because each has its own NAT. Detect via NAT ErrorPortAllocation and connection metrics per gateway.
  • Subnet IP exhaustion. A /20 gives 4091 usable addresses; each ENI takes one and each concurrent in-VPC Lambda execution takes one. Detect via the AvailableIpAddressCount metric per subnet and alarm below 20%.

Test three things before trusting the layout: kill one AZ, break one NAT path, and fail the DNS resolver, then confirm scaling still has address capacity in the surviving subnets.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Design outbound internet access for private IPv4 workloads across three availability zones.

Answer

Short answer: one NAT gateway per AZ, in a public subnet of that AZ, and each private subnet's route table points 0.0.0.0/0 at its own AZ's gateway. Add gateway endpoints for S3/DynamoDB so that traffic never touches NAT. Centralized egress through a Transit Gateway is a real option, but it buys you cross-AZ charges and a shared failure domain, so pick it deliberately, not by default.

Why zonal, mechanically

A NAT gateway is a managed SNAT: it rewrites every private source IP to its own public IP and allocates a source port per flow. That port space is the constraint. AWS documents 55,000 simultaneous connections per unique destination, where a destination is the tuple (IP, port, protocol). Exceed it and new flows are dropped, not queued.

Arithmetic that decides a design: 1,000 instances each holding 100 connections to the same third-party API endpoint on port 443 is 100,000 flows against one destination. Roughly 2× the limit. Either shard across multiple NAT gateways/public IPs, or reduce per-instance connection count with pooling.

Two more documented behaviours to design around:

  • 350-second idle timeout. Idle TCP flows are silently reaped. Long-poll or keepalive anything that must stay open.
  • No route-table failover. A VPC route table rejects a second entry for the same prefix, so you cannot express "use AZ-b's NAT if AZ-a's dies" as a lower-priority route. Zonal failover is automation that rewrites the route, or nothing.

Cost, with figures

us-east-1 list prices, which move: verify before quoting in an interview:

ItemPrice
NAT gateway$0.045/hr + $0.045/GB processed
Cross-AZ transfer$0.01/GB each direction
S3/DynamoDB gateway endpointfree
Interface endpoint (PrivateLink)~$0.01/hr per AZ + $0.01/GB
Transit Gateway$0.05/hr per attachment + $0.02/GB

Three zonal NAT gateways cost 3 × $0.045 × 730 ≈ $98/month before data. 1 TB/month through them adds ~$46. Route AZ-b's private subnet through AZ-a's NAT and you add $0.02/GB round trip: $0.065/GB effective instead of $0.045. That is the whole argument for keeping the route local.

Route table, concretely

# private subnet, us-east-1a
0.0.0.0/0        nat-0a1b2c3d
pl-xxxxxxxx      vpce-s3        # com.amazonaws.us-east-1.s3, gateway endpoint

Gateway endpoints are free and keep S3 traffic off NAT entirely; for a workload that reads 50 TB/month from S3, that is the difference between ~$2,300 and $0 in NAT processing.

Failure modes and detection

  • Port exhaustion. Watch ErrorPortAllocation: it counts failed port allocations. Non-zero means shard or pool.
  • Idle reaping. IdleTimeoutCount climbing while application error rates climb means missing keepalives.
  • AZ loss. The gateway in that AZ is gone; workloads there lose egress until automation repoints the route. Decide in advance whether they fail closed or degrade.
  • DNS and TLS. SNAT preserves the destination, so certificates are unaffected, but anything pinning the client's source IP (partner allowlists, some SaaS) breaks. Use a stable egress IP set and tell partners the full range.

Alternatives

A NAT instance (EC2 in an ASG) is cheaper per GB and lets you tune conntrack, but you own patching and the ASG replacement window. AWS Network Firewall (~$0.395/hr per AZ endpoint + $0.065/GB) adds domain and TLS-SNI filtering when the threat model justifies it. Centralized egress via Transit Gateway suits many VPCs under one inspection point, at the cost of cross-AZ transfer and a shared blast radius. For a three-AZ single-VPC workload, zonal NAT gateways plus gateway endpoints is the default that survives an AZ loss without a redesign.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design the address plan for a new production VPC that must later connect to on-premises and several other cloud networks.

Answer

The plan, in the first minute

Take one /16 per region out of 10.0.0.0/8 and never reuse it. For us-east-1 that's 10.20.0.0/16: 65,536 addresses. Split it into one /19 per AZ (8,192 each), and inside each /19 carve four /21s: public/ingress, private-app, private-data, and a spare you don't allocate until you need it. A /21 is 2,048 addresses; AWS reserves five per subnet (network, router, DNS, future use, broadcast), so you get 2,043 usable.

Then size the app subnets from ENIs, not instances. An m5.large gives 3 ENIs × 10 IPv4 addresses = 29 pod slots, so one node burns 30 addresses once the VPC CNI hands every pod a real IP. 2,043 / 30 ≈ 68 nodes per /21. If the cluster is planned at 200 nodes, one /21 is not enough: you need three, and that calculation decides the plan, not "we have plenty of room in a /16."

If dual stack is required, AWS hands the VPC a /56 and every subnet a /64. Allocate it in the same IPAM scope so v4 and v6 don't drift apart.

Overlap is what actually kills you

Write the connection matrix before you deploy: every VPC, every on-prem site, every VPN client pool, every partner network. Two ranges to avoid by default: 172.17.0.0/16, which is Docker's default bridge, and 172.16.0.0/12 generally, because it's the default pool for most VPN concentrators. If a client laptop gets 172.16.5.x and the VPC also uses it, that user silently loses access to half the estate.

When ranges do collide, three options

Re-IP the cloud side: cheapest when greenfield, brutal once security groups, DNS and firewall rules reference addresses. NAT at the transit gateway or edge: 1:1 translation for a specific prefix pair, works, but breaks anything that embeds IPs in the payload (SIP, FTP, Kerberos) and makes the return path something you reason about per flow. Isolate: no route at all, reach the service through a proxy or API in a shared-services VPC. Pick by asking how many hosts need direct reachability and whether identity is IP-based. If the answer is "a handful" and "no", isolate. If it's "thousands" and "yes", re-IP.

Failure modes and how you see them

Overlap shows up as asymmetric connectivity: the forward path matches one attachment, the return path matches another, so ping works one way and TCP handshakes hang. Detect it before deploy by diffing every CIDR in the inventory; detect it after by comparing the transit gateway route table's prefix list against the source of truth. The cost is days, because the symptom looks like a security group.

Exhaustion shows up as InsufficientFreeAddressesInSubnet on ENI creation, or pods stuck Pending with "failed to assign an IP address" while the node itself looks healthy. Alarm at 70% subnet allocation, computed from the ENI inventory or IPAM's per-scope usage, not at 95%, when you have no room to react.

Routing

Transit gateway route tables are non-transitive: a route learned from one attachment isn't propagated to another unless it's in that attachment's route table. So decide explicitly which prefixes are propagated (VPC attachments), which are static (on-prem over Direct Connect or VPN), and which are summarized. Summarize on-prem into one aggregate per site where you can: it keeps the route table readable and turns the overlap check into a single comparison.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you prevent subnet address exhaustion from becoming an autoscaling outage?

Answer

The 90-second answer

Address exhaustion is a capacity problem with a hard ceiling: unlike CPU you cannot burst a subnet, and on AWS you cannot resize one. Three numbers decide it: usable addresses per subnet, addresses each unit of capacity consumes, and the peak concurrent footprint including rollout surge and a lost AZ.

Usable addresses are not the CIDR size. AWS and Azure reserve 5 per subnet (network, gateway, two for DNS, broadcast); GCP reserves 4. A /24 is 251 usable on AWS, 252 on GCP.

ConsumerAddresses taken
EC2 node1 primary IP
EKS node, default VPC CNI1 primary + 1 secondary per pod; m5.large caps at 29 pods (3 ENIs × (10 IPs − 1) + 2), so ~29
Interface VPC endpoint1 per subnet per AZ
EKS control plane1 cross-account ENI per subnet
ALBsubnets must be /27 or larger; one IP per AZ node
RDS Multi-AZ2 (primary + standby)
Lambda in a VPCshared Hyperplane ENIs per subnet + security group, not one per function

Arithmetic: 251 ÷ 29 ≈ 8 nodes per /24. A 100-node cluster needs 100 × 29 = 2,900 addresses, so a /20 (4,091 usable) fits 141 nodes and a /21 (2,043) fits 70. Add surge: Deployment maxSurge defaults to 25%, so a 100-pod rollout peaks at 125 pod IPs. Then require survival of one AZ loss: with three AZs, each subnet must hold the full peak, not a third of it.

What actually buys headroom

  • Do not plan on resizing. AWS subnets are fixed at creation; you attach a secondary CIDR to the VPC (default quota 5 IPv4 CIDRs per VPC, adjustable) and create new subnets, then attach them to node groups and route tables. GCP subnets expand in place; Azure resizes a subnet only while it holds no resources. Know which regime you are in before you are at 90%.
  • EKS prefix delegation is the highest-leverage change: ENIs take /28 prefixes instead of individual addresses, and an ENI carries as many /28 prefixes as it can carry addresses. An m5.large goes from ~29 pod IPs to hundreds, which moves the binding constraint off the subnet.
  • Dual-stack removes the IPv4 ceiling for pod traffic that can be IPv6: an AWS VPC gets a /56 and each subnet a /64.
  • Monitor free addresses per subnet, not node count. VPC IPAM tracks pools and publishes utilization metrics; alert on free-address percentage and forecast from the autoscaler's maximum node count × addresses per node.

Failure modes and how you see them

  • Node group stuck below desired: EC2 returns InsufficientFreeAddressesInSubnet when the CNI creates the ENI.
  • Nodes Ready but pods stuck ContainerCreating with failed to assign an IP address to container: the node is out of secondary IPs.
  • Autoscaler refuses to scale because the ASG maximum is capped by subnet capacity, not by instance quota.
  • The quiet one: one AZ's subnet exhausts first because the ASG balances unevenly. The cluster looks healthy until that AZ's nodes are replaced.

Test by scaling each node group to its maximum inside a single AZ, not just cluster-wide, and confirm the surge path fits.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you organize route tables so that subnet intent remains explicit as the environment grows?

Answer

One route table per routing intent, not per subnet, and not one shared table for everything. In AWS that means keep the VPC's main route table closed (no 0.0.0.0/0, no ::/0) and give each intent class its own table with explicit subnet associations. Reuse a table only when two subnets genuinely share the same next hops and the same failure domain; if they differ in either, they get separate tables. The cost is table count, and AWS's documented default quota is 200 route tables per VPC and 50 routes per route table, both adjustable, so table count is rarely the binding constraint. Review is: a shared table means one change touches every subnet associated with it.

Concrete layout for a 10.0.0.0/16 VPC:

intentexample CIDRroute tablekey routes
public-edge10.0.1.0/24rtb-edge0.0.0.0/0 → igw-0a1b, ::/0 → igw-0a1b
private-app10.0.10.0/24rtb-app0.0.0.0/0 → vpce-0g4h (firewall endpoint), 10.0.0.0/8 → tgw-0e3f
data10.0.20.0/24rtb-datalocal only; no default route
inspection10.0.30.0/24rtb-fw0.0.0.0/0 → igw-0a1b

The app table's default route points at the Network Firewall endpoint rather than a NAT gateway, so egress is inspected by construction, not by convention. The firewall subnet's own table sends 0.0.0.0/0 to the internet gateway.

Trace: what "no explicit association" actually does. An engineer creates 10.0.40.0/24 for a batch tier and never calls aws ec2 associate-route-table. The subnet is implicitly associated with the VPC main route table. If that main table carries 0.0.0.0/0 → igw-0a1b (common in small VPCs), the batch subnet now has a path to the internet. aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-0xyz shows the association, and AWS Config records the AWS::EC2::RouteTable and AWS::EC2::Subnet configuration items. The fix is a dedicated rtb-batch with 0.0.0.0/0 → nat-0c2d and an explicit association, not a tag.

Failure modes worth naming:

  • Propagation creep. Enable route propagation on a VPC route table for a Transit Gateway attachment and every route in the TGW route table lands in that VPC table: including a propagated 0.0.0.0/0. One TGW change silently widens every VPC that propagates.
  • More-specific bypass. A 10.0.20.0/24 → local or peering route beats 0.0.0.0/0 → firewall for that prefix, so data-subnet traffic skips inspection. Longest-prefix match is the mechanism; the check is "does any route in this table have a prefix longer than the default and a next hop that isn't the firewall".
  • IPv6 gap. ::/0 is a separate route; a table that looks locked down for IPv4 can still be open on IPv6.
  • Drift. Console edits and Terraform state divergence.

Manage as code: aws_route_table, aws_route_table_association, and aws_main_route_table_association in Terraform. Assert in CI that no table associated with a subnet tagged tier=private has 0.0.0.0/0 → igw, that no table has an unexpected default, and that propagated prefixes match an allowlist. AWS Config custom rules or a conftest/OPA policy over terraform plan JSON both work; pick one and run it on every PR.

When changing a shared table, enumerate associations first (aws ec2 describe-route-tables --route-table-ids rtb-x lists them), stage the change in a non-prod VPC, and keep the previous route as a rollback. After deploy, confirm return paths: a route that sends traffic to the firewall with no route back is a black hole that only shows up in flow logs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How would you isolate a database network while still supporting application, backup, and operations traffic?

Answer

First 90 seconds. Assume AWS, RDS/Aurora PostgreSQL 15, app and database in the same VPC or a peered one, single region. Isolation here is per-flow allow-listing at the security group; subnet placement only removes the route to the internet, it authorizes nothing. So: private subnets with no 0.0.0.0/0 route, a database security group that accepts 5432 only from the application security group, and a separately named flow for each of backup, monitoring, patching and admin. Then prove each flow works, because a database nobody can back up is not isolated, it is broken.

The flows, one row per traffic class.

TrafficSourceDestinationPortControl
Applicationsg-appsg-db5432SG reference, not CIDR
Logical replication / self-managed replicasg-dbsg-replica5432SG reference
Logical backup host (pg_basebackup)sg-backupsg-db5432SG reference, time-boxed
Snapshot export to S3service-sideS3443Gateway endpoint + route-table prefix list
Custom metrics exportersg-monsg-db9187SG reference
Patching / agentsg-dbSSM, KMS, Secrets Manager, CloudWatch Logs443Interface endpoints
Adminsg-adminsg-db5432SSM Session Manager port-forward; no inbound 22
DNSsg-dbRoute 53 Resolver53VPC resolver at 10.0.0.2

Two distinctions that matter. RDS Multi-AZ and cross-region replica traffic is service-internal: you open nothing for it. What needs a path is a logical replication subscriber or a self-managed standby. Likewise RDS publishes CloudWatch metrics without a network path from your VPC; the flow you must open is for your own exporter or agent-based APM.

What one connection actually traverses. App instance 10.0.1.14:41236 → 10.0.2.9:5432:

  1. App subnet route table: 10.0.0.0/16 → local. No default route is needed for this flow.
  2. App SG outbound: allow 5432 to sg-db (default is allow-all; tighten it).
  3. DB subnet NACL inbound: allow TCP destination 5432 from 10.0.1.0/24. NACLs are stateless.
  4. DB SG inbound: allow 5432 from sg-app. Stateful: the SYN-ACK and every later packet on this connection pass without an outbound rule.
  5. DB subnet NACL outbound: allow TCP destination 1024–65535 to 10.0.1.0/24. Omit this and the SYN-ACK is dropped; the client's connect() fails after its SYN retries, roughly 127 s on Linux with the default tcp_syn_retries=6.
  6. DB SG outbound: 443 to sg-endpoints, 53 to 10.0.0.2.

With interface endpoints for ssm, ssmmessages, ec2messages, kms, secretsmanager and logs, plus a gateway endpoint for S3, the database subnet route table needs no 0.0.0.0/0 at all: no NAT gateway, no egress path to the internet.

Failure modes and how you catch them.

FailureSymptomDetection
NACL ephemeral range missingconnect() hangs, times out ~127 sFlow Logs show the SYN ACCEPTed with no SYN-ACK record
Interface endpoint private DNS offApp resolves the public IP, egresses via NAT or failsdig from the app subnet; Flow Logs show a NAT gateway
SG reference silently replaced by a CIDR after cross-region peeringRule widens to a whole subnet, nobody noticesConfig drift check on SG rules; alert on rule count
Backup host path never exercisedRestore drill fails at the logical-backup stepQuarterly timed restore from the real path, not from a snapshot
PubliclyAccessible left onDB gets a public IP; the SG is the only controldescribe-db-instances flag check

Trade-offs. Security groups are the primary control: stateful, referenceable, and they survive address changes. NACLs are a coarse second layer: stateless, easy to break, and worth it only as a subnet-wide backstop. Where SG referencing is unsupported (cross-region peering, on-premises over VPN), fall back to managed prefix lists and accept that the rule is CIDR-based and needs re-review when addressing changes. Network isolation is orthogonal to encryption and database authorization: TLS and IAM/database auth still have to be on, and neither substitutes for the other.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

What changes when an existing IPv4 VPC becomes dual stack with IPv6?

Answer

Dual-stack does not convert anything. It adds a second address family that is routed and filtered independently of the first, and almost every failure comes from treating it as a rename of IPv4.

On AWS the concrete changes are: the VPC gets an IPv6 CIDR (Amazon-provided /56, IPAM, or BYOIP), each subnet gets a /64 carved from it, ENIs get IPv6 addresses, and route tables need explicit ::/0 entries. 0.0.0.0/0 never matches an IPv6 packet. Every filter needs IPv6 rules of its own: a security group rule for 0.0.0.0/0 does not admit ::/0, and a custom NACL carrying only IPv4 rules drops IPv6 traffic. The protection model also shifts. IPv6 addresses are globally routable, so there is no NAT boundary by default: an instance in a public subnet with ::/0 → igw is directly reachable, and the security group is the only thing in front of it. Use an egress-only internet gateway where you want outbound-only semantics.

LayerIPv4-only todayWhat dual-stack adds
VPC10.0.0.0/16IPv6 CIDR, Amazon-provided /56 (or IPAM/BYOIP)
Subnet10.0.1.0/24/64 from the VPC range
ENIprivate IPv4, optional EIPone or more globally routable IPv6 addresses
Route table0.0.0.0/0 → igw/nat::/0 → igw or egress-only igw; VPC-local IPv6 route added automatically
Security grouprules on IPv4 CIDRsseparate rules on IPv6 CIDRs
NACLstateless IPv4 rulesstateless IPv6 rules, ICMPv6 included
DNSA recordsAAAA records, dual-stack service endpoints
Load balancerIPv4 addressdualstack IP address type, IPv6 targets

Worked trace. Instance i-1 sits in subnet 10.0.1.0/24 + 2600:1f18:1234:5601::/64, ENI addresses 10.0.1.10 and 2600:1f18:1234:5601::10. The route table has ::/0 → igw-0abc. The app connects to 2606:4700:4700::1111:443.

  1. Source selection picks the ENI's IPv6 address. Nothing on the path translates it.
  2. Longest-prefix match on ::/0 → igw-0abc. The VPC-local route for 2600:1f18:1234:5600::/56 was added when the CIDR was associated.
  3. Egress security group: the rule must match 2606:4700:4700::1111/128 or ::/0. An egress rule of 0.0.0.0/0 does not match, and the SYN dies at the ENI.
  4. Outbound NACL: stateless, so it needs its own TCP 443 rule for that destination. A custom NACL with only IPv4 rules drops the packet, and VPC Flow Logs record it as REJECT.
  5. Return path: the NACL needs an inbound rule for the ephemeral range from 2606:4700:4700::1111/128. Security groups are stateful, so the reply needs no inbound SG rule.
  6. If the path MTU drops, a router returns ICMPv6 Packet Too Big. Block ICMPv6 and PMTUD fails: TCP connects, then the TLS handshake stalls on the first full-size packet. IPv6 routers never fragment, so this is fatal rather than slow.

Failure modes. IPv4-only SG or NACL rules give you an instance that reaches IPv4 endpoints and silently fails on IPv6: compare reachability over both families, and read REJECT records in flow logs. Blocked ICMPv6 breaks neighbour discovery and PMTUD, presenting as connect-then-hang. Publishing AAAA before the IPv6 path works strands clients that prefer IPv6 under RFC 6724; Happy Eyeballs fallback is around 250 ms and not universal. Scanners, host firewalls and observability that only cover IPv4 leave the new family unmonitored. Some older instance types do not support IPv6 at all.

Trade-offs. Keep IPv4. Plenty of dependencies are IPv4-only, and an IPv6-only subnet needs NAT64/DNS64 (Route 53 Resolver DNS64 plus a NAT gateway) to reach them. Cost cuts the other way: since 1 February 2024 AWS charges $0.005/hour per in-use public IPv4 address, so 200 instances is 200 × 0.005 × 730 ≈ $730/month, while IPv6 addresses carry no charge. That is a real reason to move egress to IPv6, and a real reason to check you are not still paying for IPv4 you no longer need.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design DNS for services that need different private and public answers.

Answer

Assume you need split-horizon DNS: the same service name resolves to a private IP inside your VPC and a public IP on the internet. The strong answer picks separate public and private zones with explicit suffix ownership, sets TTLs from failover requirements, and monitors answer correctness from each network view.

Mechanism. A resolver selects the zone with the longest matching suffix. If you have a public zone example.com and a private zone internal.example.com, a query for db.internal.example.com matches the private zone. If both a public and a private zone share the same name (example.com), the private zone wins for clients in associated VPCs: that is how Route 53 private hosted zones and Cloud DNS private zones implement split-horizon. Route 53 allows up to 100 VPC associations per private hosted zone by default (a soft limit you can raise).

Negative caching breaks failover. When a private zone returns NXDOMAIN, the resolver caches that answer for the SOA minimum TTL (RFC 2308). If your SOA minimum is 900 s, a newly added private record stays invisible for 15 minutes. Set SOA minimum to 60 s on zones that change.

Trade-offs.

ApproachHow it worksProsConsChoose when
Separate public + private zonesRoute 53 private hosted zones, Cloud DNS private zonesClear IAM separation, no internal records leakDuplication, drift riskYou need strict isolation and managed service
One zone with viewsBIND views, CoreDNS view pluginSingle source of truth, minor overridesView config error-prone, not in Route 53Same zone data with small per-client differences
Service mesh DNSIstio, ConsulHealth-aware, no TTL cachingRequires sidecar, not for external clientsAll clients are in the mesh and need health routing

Failure modes.

  • Forwarding loop: on-prem resolver forwards example.com to cloud, cloud forwards internal.example.com back. Detect via query logs showing repeated queries and resolver CPU spike. Fix: conditional forwarding with explicit suffix ownership, no wildcard forwards.
  • Cache divergence: different resolvers hold different TTLs, so failover is not simultaneous. Detect by querying multiple resolvers. Fix: low TTLs for failover records (30–60 s) and monitor.
  • Fallback to public: if the private zone is misconfigured or the resolver fails, the client may fall back to public DNS and get a public IP. Detect by monitoring answer correctness from each network view. Fix: use separate public and private names (internal.example.com vs example.com) so public DNS never has the internal name.

Worked trace. Client in VPC queries db.internal.example.com. Resolver checks zones: internal.example.com (private, associated) is more specific than example.com (public). It returns the private A record 10.0.1.5, TTL 60 s. If the private zone lacks the record, it returns NXDOMAIN and caches for SOA minimum 60 s. If the VPC is not associated with the private zone, the resolver uses the public zone; if that zone has no such name, NXDOMAIN, but if it has a wildcard or public record, the client gets a public IP. That is the silent leak you must prevent.

Arithmetic. With TTL 300 s, failover takes up to 5 minutes for cached clients. With TTL 60 s, up to 1 minute. Negative caching with SOA minimum 900 s means a new record takes 15 minutes to appear. Set TTLs from your failover SLA: 60 s for active/standby, 300 s for stable records.

CoreDNS snippet (checked against CoreDNS 1.11):

.:53 {
    view internal {
        expr incidr(client_ip(), '10.0.0.0/8')
        forward . 10.0.0.2
    }
    view external {
        forward . 8.8.8.8
    }
}

This routes internal clients to a private resolver and external clients to a public one. Test real client caching: recursive resolvers and runtimes (Java, Go) may retain records differently. Monitor resolver latency, failures, response codes, and answer correctness from each network view. Protect zone changes through review and audit. During migration, verify every client population receives the expected address.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How would you design and validate hybrid connectivity between a VPC and an on-premises network?

Answer

Clarify first. Bandwidth now and in 18 months, the latency budget for chatty protocols (DB replication, AD, NFS), RTO/RPO, whether traffic must be encrypted in transit, and who owns change control on each side. Assume an AWS VPC, an on-prem network with BGP-capable routers, and a requirement that production traffic survives a single transport failure.

Design. Two transports, one preferred. Direct Connect as primary: dedicated 1/10/100 Gbps, no internet dependency, single-digit-ms latency for same-metro locations. Site-to-Site VPN as backup: up to 1.25 Gbps per tunnel, IPsec over the internet, provisioned in minutes. Terminate both on the same VGW, or a Transit Gateway once you have several VPCs or need segmented route tables.

Routing: BGP over both. AWS's side of a VGW is ASN 64512 by default; give on-prem a private ASN (65000). Advertise only the VPC CIDR and the specific on-prem prefixes: never a default route in either direction unless you mean it. Make the preference explicit on-prem: local preference 200 on routes learned over the DX neighbor, 100 over the VPN neighbor. Do not ECMP across DX and VPN: per-flow hashing sends the two directions of a TCP connection down different paths, and any stateful firewall in the middle drops the return.

MTU: a DX private VIF is 1500; a transit VIF supports 8500 jumbo. The VPN tunnel's outer MTU is 1500, but IPsec overhead leaves roughly 1400 usable, so clamp TCP MSS to 1379 on the on-prem tunnel interface (AWS's documented recommendation) and let PMTUD handle the rest. If traffic must be encrypted over DX, run an IPsec VPN over the transit VIF or use MACsec on a supported dedicated connection: DX itself is not encrypted.

Validate. Failover is what you're buying, so test the two failure shapes separately.

  • Hard failure: shut the DX VIF or pull the cross-connect. The interface goes down, the BGP session drops immediately, routes are withdrawn, and the VPN path takes over in seconds. Measure it with a continuous ping and a timestamp.
  • Soft failure: the link stays up but stops forwarding. Carrier-side failure, a black-holing device. BGP won't notice until the hold timer expires. Enable BFD on the DX VIF so this is detected sub-second instead of after tens of seconds. Without BFD, tune the hold timer down (keepalive 10 / hold 30) on both ends; BGP negotiates the smaller of the two hold times, so one side at 30 pulls the session to 30 s. Cisco's default is keepalive 60 / hold 180, which is three minutes of black-holed traffic.

MTU: from on-prem, ping -M do -s 1472 (a 1500-byte IP packet) passes over DX and fails over VPN; -s 1372 (1400 bytes) passes over VPN. That only proves the ICMP path: MSS clamping is what protects TCP.

Monitor: DX VirtualInterfaceBgpStatus and ConnectionState, VPN TunnelState, BGP session state and received-prefix count on the on-prem router, and a synthetic canary. A Lambda in the VPC pinging a known on-prem host every 30 s, alarming on three consecutive failures. VPC Flow Logs plus on-prem firewall logs to catch asymmetry.

Failure modes. Session up, no routes: prefix-list or route-map mismatch. Compare received prefixes against expected, per neighbor. Asymmetric routing: forward over DX, return over VPN, stateful firewall drops the return. Detect with traceroute from both ends and flow logs. MTU black hole: small packets pass, large ones vanish, TCP hangs after the handshake. Detect with the DF ping above. Tunnel down but a static route still pointing at it: monitor tunnel state, not just the route table. BGP flapping: check hold/keepalive agreement and router CPU.

Site-to-Site VPNDirect Connect
Max bandwidth1.25 Gbps per tunnel1/10/100 Gbps per connection
LatencyVariable, over the internetSingle-digit ms for same-metro
EncryptionIPsecNone by default; MACsec on supported dedicated connections
ProvisioningMinutesWeeks (days via a partner's hosted connection)
Failure detectionBGP hold timerBFD, sub-second

On-prem Cisco IOS-XE, both neighbors on one router:

router bgp 65000
 bgp log-neighbor-changes
 neighbor 169.254.10.1 remote-as 64512
 neighbor 169.254.10.1 description DX-private-VIF
 neighbor 169.254.10.1 timers 10 30
 neighbor 169.254.11.1 remote-as 64512
 neighbor 169.254.11.1 description VPN-tunnel
 neighbor 169.254.11.1 timers 10 30
 !
 address-family ipv4 unicast
  neighbor 169.254.10.1 activate
  neighbor 169.254.10.1 route-map FROM-AWS-DX in
  neighbor 169.254.10.1 route-map TO-AWS out
  neighbor 169.254.11.1 activate
  neighbor 169.254.11.1 route-map FROM-AWS-VPN in
  neighbor 169.254.11.1 route-map TO-AWS out
 exit-address-family
!
ip prefix-list AWS-PREFIXES seq 10 permit 10.0.0.0/16
ip prefix-list ONPREM-PREFIXES seq 10 permit 192.168.0.0/16
!
route-map FROM-AWS-DX permit 10
 match ip address prefix-list AWS-PREFIXES
 set local-preference 200
route-map FROM-AWS-VPN permit 10
 match ip address prefix-list AWS-PREFIXES
 set local-preference 100
route-map TO-AWS permit 10
 match ip address prefix-list ONPREM-PREFIXES

Failover trace:

  • Steady state: both sessions Established. On-prem RIB holds 10.0.0.0/16 via 169.254.10.1 (local pref 200) and via 169.254.11.1 (local pref 100). Best path is DX. AWS receives 192.168.0.0/16 from both neighbors.
  • Hard failure: the DX port goes down, the session to 169.254.10.1 drops, its routes are withdrawn, the VPN path (local pref 100) becomes best, FIB updates. Seconds, not minutes.
  • Soft failure: the port stays up, packets are black-holed. BFD tears the session down sub-second; without it the hold timer (30 s here) expires and the same withdrawal happens. With an untuned 90 s hold, that is up to 90 s of dropped traffic.
  • Recovery: DX returns, the session re-establishes, local pref 200 wins again. Verify traffic actually returns: a stale static route or a route-map that only matches inbound is the usual reason it doesn't.

Name the on-call for both ends and the rollback step for a route change before you need either.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

When should an organization use VPC peering versus a transit hub?

Answer

What a strong answer says first. Peering for a handful of VPCs where each connection has one owner and you never need to route through a VPC. A transit gateway once the number of VPCs and on-prem sites makes the pairwise mesh, and the route-table bookkeeping that comes with it, cost more than the hub's hourly bill. The decision usually turns on a count, not on architecture taste.

The count decides it. A full peering mesh of n VPCs is n(n-1)/2 connections and n-1 peer routes in every VPC's route table. Six VPCs: 15 connections, 5 peer routes each, trivial. Ten VPCs: 45 connections, 9 routes each. Fifty VPCs: 1,225 connections and 49 routes each, which is exactly where the two defaults run out. 50 active peering connections per VPC, and 50 routes per route table (local + 49 peers fills it). Past roughly 50 VPCs the mesh is not expressible without quota increases, and it stops being operable well before that, because every new VPC means editing every existing route table. On a transit gateway the same change is one attachment plus one association, and the VPC CIDR propagates into the TGW route table automatically.

Where a transit gateway earns its cost. Multiple TGW route tables give you route domains: prod, dev and shared each get their own associations and propagations, with one inspection VPC that all inter-domain traffic is forced through. On-prem enters once, a Direct Connect gateway or VPN attachment on the TGW, and every attached VPC sees it. Peering cannot do this at all; a peering connection is VPC-to-VPC, and a VPN attaches to a single VPC.

Cost arithmetic (us-east-1 list prices; verify current pricing). A peering connection has no hourly charge: you pay data transfer, roughly 0.01 USD per GB in each direction for cross-AZ traffic, so 0.02 USD per GB round trip. A transit gateway bills about 0.05 USD per hour per attachment (about 36 USD per attachment-month) plus about 0.02 USD per GB processed. Two hundred attachments: 200 * 0.05 = 10 USD/hour, roughly 7,300 USD/month; 100 TB/month through it is 102,400 GB * 0.02 = about 2,050 USD/month. Under about ten VPCs with light east-west traffic, that floor usually loses to peering; at 50-plus VPCs it is cheaper than the engineering time the mesh consumes.

VPC peeringTransit gateway
Transitive routingNo: A-B and B-C give no A-to-CYes, across attachments
Per-network connection cap50 active peering connections per VPC (default)5,000 attachments per TGW (default)
Route managementExplicit peer route in every VPC route tableOne attachment plus association; CIDR propagates
On-premNot possible over a peering connectionVPN or Direct Connect gateway attaches once
MTU9,001 bytes same Region, 8,500 inter-Region8,500 bytes
Cost modelData transfer onlyHourly per attachment plus per-GB processing

Failure modes and how you detect them.

  • Peering is not transitive. A-to-C fails with both A-B and B-C up. Reachability Analyzer reports no path, or flow logs on B show A's traffic terminating there. Security groups are not the cause and cannot fix it.
  • Route drift in a mesh. One missing reverse route gives you A-to-C working and C-to-A timing out: TCP connects, then stalls. Diff describe-route-tables against the intended peer inventory, or run Network Access Analyzer.
  • Asymmetric flow through a centralized appliance. In a TGW inspection VPC with appliance mode off, a flow can reach the firewall in a different AZ from the source and the stateful return path is dropped. Symptom: SYN with no SYN-ACK, firewall logs showing asymmetric-flow drops. The fix is the attachment setting, not the firewall policy.
  • MTU regression on migration. Same-Region peering carries 9,001-byte frames, a TGW carries 8,500. NFS reads or replication tuned for jumbo frames break as small requests succeeding while large transfers hang.
  • Quota ceilings arriving mid-project. The 50-connection and 50-route defaults surface as "no route to host" for the newest VPC, not as a planning-time error. Alarm on the AWS/Usage quota-utilization metrics for those VPC quotas before you reach them.
  • Cross-Region peering and security group references. Referencing a peer's security group works only for same-Region peering; cross-Region designs fall back to CIDR rules, so in-Region trust does not carry over.

Decide on the attachment count you expect in 24 months, how many trust boundaries need separate route domains, whether on-prem must reach every VPC, whether inter-VPC traffic needs inspection, the MTU your workloads assume, and which team owns route changes. Everything else is topology fashion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How does a centralized transit hub route inter-VPC traffic to ensure network isolation and mandate firewall inspection?

Answer

What a strong candidate says first

A transit hub separates two things a peering mesh conflates: which attachment a packet arrives on, and which route table decides where it goes. Each attachment is associated with exactly one route table: that table is consulted for traffic entering from that attachment. Each attachment also propagates its CIDRs into whichever tables you choose. Isolation and inspection both fall out of those two knobs.

Isolation: Prod and Non-Prod spokes are associated with the same pre-inspection table, and neither propagates into a table the other can reach. There is no route between them.

Inspection: the pre-inspection table holds a static default route to the inspection attachment. The inspection attachment is associated with a different table, post-inspection, which holds the propagated spoke CIDRs. A spoke's traffic can only leave toward the firewall; the firewall's traffic can only leave toward a spoke. Two tables, two directions: the hairpin is structural, not a policy someone can forget to apply.

Trace: Prod (10.1.0.0/16) → Non-Prod (10.2.0.0/16)

  1. Prod subnet route table: 10.0.0.0/8 → TGW attachment.
  2. TGW consults the table associated with the Prod attachment: pre-inspection. It has 0.0.0.0/0 → inspection attachment. Packet enters the inspection VPC.
  3. Inspection ingress subnet route table: 0.0.0.0/0 → firewall ENI (or GWLB endpoint). Firewall evaluates policy.
  4. Firewall forwards to the egress subnet; that subnet's route table: 0.0.0.0/0 → TGW.
  5. TGW now consults the table associated with the inspection attachment: post-inspection. It has 10.2.0.0/16 → Non-Prod attachment. Delivered.
  6. Return traffic from Non-Prod hits the pre-inspection table (Non-Prod's association) and takes the same path in reverse.
Route tableAssociated withRoutes
Pre-inspectionProd spoke, Non-Prod spoke0.0.0.0/0 → inspection attachment (static)
Post-inspectionInspection attachment10.1.0.0/16 → Prod spoke, 10.2.0.0/16 → Non-Prod spoke

Enable appliance mode on the inspection attachment. Without it the hub can send the return direction through a different AZ's firewall ENI, and a stateful firewall drops a flow whose SYN it never saw.

Trade-offs

Hairpinning is not free. Every inspected packet crosses the hub twice and the firewall twice, so you pay the hub's per-GB data processing twice. Illustratively, 100 TB/month of east-west traffic at roughly $0.02/GB (us-east-1 list; check current pricing) is about $2,050 per traversal, ~$4,100/month before firewall instance-hours. Latency adds two hub hops plus the firewall's own processing: the firewall dominates, so measure it rather than assuming.

Alternatives, and when each wins:

  • GWLB endpoints in each spoke VPC. The spoke's subnet route table redirects to a local endpoint, so traffic never hairpins through the hub. GWLB hashes the 5-tuple (GENEVE, UDP 6081), so symmetry is the load balancer's job rather than appliance mode's. Costs an endpoint per VPC per AZ plus the fleet; buys lower latency and per-VPC scaling, gives up the single choke point.
  • Distributed firewalls, or security groups and NACLs alone. No hairpin, lowest latency, but N policy sets to keep in sync and no single audit point.
  • Inspect egress only. Default route to the internet through the inspection VPC, east-west direct. Cheaper and faster; you accept uninspected lateral movement.

Don't centralize when east-west traffic is high-volume and inside one trust boundary, when the latency budget is tight, or when the firewall fleet can't scale to aggregate throughput. Per-VPC firewalls or GWLB endpoints are the answer there.

Failure modes

  • Asymmetric loop. If the inspection VPC's egress subnet points 0.0.0.0/0 back to the hub without passing the firewall, or the firewall returns traffic to an attachment associated with the pre-inspection table, the packet re-enters pre-inspection and loops. Detect: hub bytesIn/bytesOut climbing with no matching application throughput, and 100% TCP timeouts between spokes.
  • Silent bypass. A spoke attachment associated with the post-inspection table, or a spoke propagating into it, gets direct routes to every other spoke and skips the firewall with no error. Detect by auditing associations and propagations, or by hub flow logs showing spoke-to-spoke traffic that never touched the inspection ENI.
  • AZ mismatch. Appliance mode off, return traffic lands on a different firewall instance, stateful drop. Detect: SYN out, no SYN-ACK, no matching flow in the firewall log.
  • MTU. GWLB's GENEVE encapsulation eats into the path MTU; without MSS clamping, large flows black-hole while pings succeed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How does an egress proxy or next-generation firewall differ from a standard cloud NAT gateway when restricting outbound traffic to third-party APIs?

Answer

The 90-second answer. A cloud NAT gateway is a Layer 4 translator with no policy engine: it rewrites source addresses so private subnets can reach the internet, and it will forward port 443 to any address in the world. An egress proxy or NGFW decides per connection at Layer 7 whether api.stripe.com is allowed. If the requirement is "workloads may reach exactly these third-party APIs and nothing else," NAT cannot express it: the only L4 lever is IP plus port, and API providers publish CDN ranges that change without notice. The proxy expresses it as a hostname allowlist.

Cloud NAT gatewayEgress proxy / NGFW
LayerL4 translation onlyL4–L7 policy
What it can matchIP + port (via SG/NACL)FQDN, SNI, HTTP method/path (path needs TLS termination)
Config surfaceRoute table 0.0.0.0/0 → nat-xxxxHTTPS_PROXY env var, or route-table redirect to a firewall endpoint
ScalingAutomatic; 45 Gbps, 55k concurrent connections per unique destinationYou size the fleet; saturation shows up as ECONNRESET
Visibility5-tuple flow logs, no hostnameHostname per connection; full URL only if decrypting

How each one enforces. With NAT, the route table points 0.0.0.0/0 at the gateway and the security group allows TCP 443 out. Any process can open a socket to any IP on 443. VPC Flow Logs give you the destination IP after the fact, never the hostname.

An explicit proxy (Squid, Envoy) is configured on the workload as HTTPS_PROXY=http://proxy.internal:3128. For HTTPS the client sends CONNECT api.stripe.com:443; the proxy matches the hostname against its ACL, resolves the name itself, and opens the upstream connection. Squid:

acl allowed_apis dstdomain .stripe.com .github.com
acl ssl_ports port 443
http_access deny !ssl_ports
http_access allow allowed_apis
http_access deny all

The proxy sees the hostname but, without TLS interception, not the path: CONNECT is followed by a blind byte tunnel. Filtering on URL path or HTTP method requires terminating TLS with an internal CA, which breaks any client that pins certificates.

A transparent NGFW is redirected by route table or firewall endpoint and reads the SNI field from the TLS ClientHello. The difference from the explicit case matters: the client never names the host, so the appliance must decide using SNI and the original destination IP.

The spoofing failure mode, traced. A client wants to reach 203.0.113.9 (attacker-controlled) but sets SNI to api.stripe.com. A firewall that checks SNI against the allowlist and then forwards to the original destination IP permits the connection: the allowlist checked a string the client controls. The fix is to ignore the client's destination: resolve the SNI yourself and connect to that address, or reject when the original destination IP is not in the current A/AAAA set for that SNI. Log both values so you can alert on the mismatch.

Other failure modes and how to detect them.

  • No SNI at all. TLS 1.3 Encrypted Client Hello hides the hostname, and QUIC (UDP 443) carries the ClientHello in a packet most L7 filters don't parse. Default-deny connections with no SNI and block UDP 443 to force TCP fallback; count both, because a rising no-SNI rate means clients are evading.
  • Proxy saturation. NAT gateways scale to 45 Gbps and 55,000 concurrent connections per unique destination with no action from you. A proxy fleet is compute you size: when the pool saturates you get ECONNRESET and p99 spikes on bursty batch jobs. Watch Envoy's upstream_rq_pending_overflow and the TCP SYN retransmit rate, not just CPU.
  • Non-HTTP protocols. Postgres 5432, Kafka, and gRPC over raw TCP cannot use CONNECT. They need L4 passthrough rules or CIDR-scoped routes that bypass the proxy, which reopens the hole the proxy was built to close.

Cost and when not to. NAT bills per GB processed (AWS list $0.045/GB in us-east-1 at time of writing) plus an hourly charge; a proxy fleet bills for instances and no per-GB egress processing. For bulk egress to a known IP range, NAT plus a tight security group is cheaper and simpler. Reach for the proxy when the allowlist is hostname-shaped and the traffic is API calls, not bulk transfer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Explain how ordered network ACL rules can create a production incident and how you would test them.

Answer

Assume AWS-style VPC network ACLs: numbered rules 1–32766, evaluated in ascending order, first match wins, implicit * deny at the end, and stateless. The return path needs its own rule. Azure NSGs use the same first-match, lower-number-wins model with priorities 100–4096; GCP VPC firewall rules use priorities 0–65535.

Two ordering bugs cause incidents. A broad allow at a low number shadows a later specific deny: the deny is unreachable and the traffic you meant to block still flows. A broad deny at a low number blocks a later intended exception: legitimate traffic dies. Because the ACL is stateless, a third variant bites: the inbound rule is correct but the outbound rule for the response to the client's ephemeral port is missing or ordered after a deny, so the SYN is allowed and the SYN-ACK is dropped. The client sees a connect timeout, not a reset.

Worked trace. Subnet 10.0.1.0/24, server 10.0.1.20, client 10.0.9.7. Inbound ACL:

ruleactionprotosourcedestport
100ALLOWtcp0.0.0.0/00.0.0.0/0443
110DENYtcp10.0.9.0/240.0.0.0/0443
*DENYall0.0.0.0/00.0.0.0/0all

SYN from 10.0.9.7:40000 → 10.0.1.20:443. Evaluation starts at rule 100. Rule 100 matches: source wildcard includes 10.0.9.7, dest port 443, so the packet is ALLOWed and evaluation stops. Rule 110 is never reached. The operator who added 110 to block 10.0.9.0/24 believes the block is live, and describe-network-acls confirms the rule exists; only the ordering makes it dead. The fix is to renumber the deny below the allow (rule 90) or narrow the allow to specific source ranges.

Now the stateless return path. Outbound ACL on 10.0.1.0/24:

ruleactionprotosourcedestport
100DENYtcp0.0.0.0/010.0.9.0/241024–65535
110ALLOWtcp0.0.0.0/00.0.0.0/032768–60999
*DENYall0.0.0.0/00.0.0.0/0all

The SYN-ACK from 10.0.1.20:443 → 10.0.9.7:40000 hits rule 100 first: dest 10.0.9.7 falls in 10.0.9.0/24 and dest port 40000 falls in 1024–65535, so it is DENYed. The client hangs until connect timeout. Server logs show the request completed; the client never sees the response. That asymmetry (server-side success, client-side timeout) is the fingerprint of a stateless return-path ordering bug.

Ephemeral ranges matter for the outbound rule. Linux default net.ipv4.ip_local_port_range is 32768–60999; IANA/BSD and Windows Vista+ use 49152–65535. An outbound allow covering 32768–60999 therefore misses Windows clients; 1024–65535 covers both but is broad.

Testing: express intended flows as cases covering both directions and the real ephemeral ranges, then evaluate the compiled ordered rules offline in CI (Batfish, or aws ec2 describe-network-acls plus a first-match simulator) and fail the build on shadowed or unreachable entries. After a staged change, verify from real source subnets with hping3 -S -p 443, nc -vz, tcpdump -ni eth0 'tcp port 443', and conntrack -L.

Keep rule sets coarse and documented; use stateful security groups for detailed service relationships. During an incident, inspect the effective ACL association and rule numbers, not just the rule text: a rule can exist and still be unreachable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What network telemetry would you enable for a production VPC, and what can it fail to tell you?

Answer

Assumptions: AWS VPC, EC2/ECS workloads behind an ALB, one NAT gateway per AZ, and no agent on every host. The shape holds elsewhere.

What I'd turn on, in priority order.

  1. VPC Flow Logs, ENI scope, format v2, 1-minute aggregation (10 minutes is the maximum), delivered to S3 for retention and CloudWatch Logs for alerting. ENI scope rather than VPC scope because it carries interface-id and instance-id, which is what lets you attribute a flow to a workload. v2 adds pkt-srcaddr/pkt-dstaddr, tcp-flags and type: the fields that tell you whether a SYN ever got a SYN-ACK.
  2. Route 53 Resolver query logs, for DNS. This is where exfiltration-over-DNS and lookups to newly registered domains show up.
  3. NAT gateway metrics: ActiveConnectionCount, ConnectionAttemptCount, ConnectionEstablishedCount, ErrorPortAllocation, PacketsDropCount.
  4. ALB/NLB access logs and target health, for HTTP status and latency: the layer flow logs cannot see.
  5. CloudTrail and AWS Config for the control plane: route table edits, SG/NACL changes, flow log deletion.

What a flow record actually is. One record per flow per aggregation interval: version, account-id, interface-id, srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, start, end, action, log-status. That single fact explains every blind spot. It is a five-tuple aggregate, not a packet:

  • No payload. You cannot tell a 200 from a 500, or a benign request from an exploit. That is ALB access logs or an agent.
  • No per-packet timing. 10,000 packets in a 60-second record is equally consistent with a steady 167 pps or a 200 ms burst that dropped packets. Microbursts vanish.
  • No rule attribution. A REJECT says the five-tuple was denied, not whether a security group or a NACL did it, and not which rule.

What it cannot see at all. Flow logs do not record traffic to 169.254.169.254 (instance metadata), 169.254.169.123 (NTP), DHCP, or the VPC resolver at the CIDR-base-plus-2 address. So an SSRF that reaches IMDS and steals credentials leaves no flow-log record: you catch that with IMDSv2 enforcement and CloudTrail, not here. Traffic dropped by a blackhole route never reaches an ENI, so it is absent too; that is VPC Reachability Analyzer or a route-table diff.

Failure modes and how I'd detect them.

failuresignaldetection
Records dropped under loadlog-status = SKIPDATAalarm on SKIPDATA rate > 0
No traffic in intervallog-status = NODATAexpected on idle ENIs; do not alarm
NAT port exhaustionErrorPortAllocation > 0, gap between ConnectionAttemptCount and ConnectionEstablishedCountalarm on ErrorPortAllocation
Delivery lagrecords arrive minutes after the interval closescompare record end to ingest time
Silent telemetry lossflow log deleted or destination policy changedCloudTrail alarm on DeleteFlowLogs

NAT is the one worth arithmetic: a NAT gateway allows 55,000 simultaneous connections to a single unique destination (IP + port + protocol). An app that opens a fresh connection per request to one downstream endpoint can hit that ceiling; the symptom is ErrorPortAllocation climbing while ConnectionEstablishedCount falls behind ConnectionAttemptCount, and the app sees connection timeouts.

Trade-offs. Flow logs are cheap, unsampled, and cover every ENI: that is why they are the default, and why they give you metadata only. Traffic Mirroring gives full packets with no sampling, but it is billed per GB processed and needs a target appliance, so I scope it to one ENI and a time window during an incident, not fleet-wide. An eBPF/agent collector gives application context (which syscall, which request) but only on hosts you control and only if you can deploy it. Deciding criterion: if the question is "who talked to whom, and was it allowed," flow logs; if it is "what was in the bytes," mirroring or app logs.

Escalation path. Keep Traffic Mirroring pre-approved for a named set of ENIs so it can be switched on mid-incident without a fresh legal review, and test that flow logs still arrive while the NAT gateway is saturated: the failure you most want telemetry for is the one most likely to drop it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Walk through diagnosing a TCP timeout between a private application and an on-premises database.

Answer

A strong candidate opens by pinning down the failure shape, because the kernel has already encoded which side dropped the packet.

Clarify before touching anything. Is it every app replica or one? Does it fail at connect or after the query runs? Which port: Postgres 5432, Oracle 1521, SQL Server 1433? I'll assume one app in a private VPC subnet reaching an on-prem DB over a site-to-site VPN or Direct Connect, all replicas failing, and the driver reporting a timeout rather than a refusal.

The decisive split is the error and its duration.

App reportsWhat the kernel didFault domain
ECONNREFUSED in ~1 msGot a RST backPackets reach the host. Listener bound to 127.0.0.1 instead of 0.0.0.0, or host firewall rejecting.
Connect hangs, ETIMEDOUT at ~127 sSent 7 SYNs, no SYN-ACKSYN dropped somewhere on the path.
Runs fine, then RST or hang mid-queryEstablished flow reapedStateful firewall/NAT idle expiry, not reachability.
Connect fine, stalls on first large packetMSS/PMTU failureMTU blackhole: ICMP "frag needed" is blocked.

The 127 s is arithmetic, not a guess. Linux net.ipv4.tcp_syn_retries defaults to 6: the SYN goes at 0 s, then retries at 1, 2, 4, 8, 16, 32, 64 s. Your app usually dies first: HikariCP connectionTimeout defaults to 30000 ms and PostgreSQL JDBC connectTimeout to 10 s. So "times out at 10 s" points at the driver, "at 127 s" at the kernel. For the mid-query case, Linux conntrack defaults established flows to 432000 s, but managed firewalls and VPN gateways commonly idle out at 1800–3600 s, which is the number that matters here.

Now localise the hop. Capture on both ends at once, tcpdump -i any -nn tcp port 5432 on a DB-side host and on the app side, plus nmap -Pn -p 5432 or tcptraceroute to see where forwarding stops. A half-open handshake reads cleanly:

  • SYN arrives at the DB host, no SYN-ACK leaves → DB host. Check ss -ltnp 'sport = :5432' for the bind address, then the host firewall and listener state.
  • SYN never arrives at the DB host → the path. Walk it in order: app subnet route (ip route get, the DB IP), security group or NSG, VPN/DX tunnel state, on-prem inbound firewall and the route table returning your cloud prefix.

Cloud-side, VPC Flow Logs show ACCEPT versus REJECT per ENI, and AWS Reachability Analyzer or Azure Network Watcher connection troubleshoot will trace the route without you logging into a box.

Capture at the DB host or at the tunnel? Capture at the DB host when many app replicas fail against one DB: a single capture proves arrival and whether the SYN-ACK left, but it needs an on-prem operator. Capture at cloud egress when exactly one replica fails: self-serve, but it only proves you emitted the packet. Default to the DB host; it kills the most hypotheses per capture.

When to escalate. Escalate to the network team the moment you have shown the SYN leaving your last controlled hop and not arriving: you hand over a one-line fact, not a symptom. Do not escalate while a second source succeeds: a working/failing pair is config you own, and the usual causes are asymmetric routing, overlapping RFC 1918 CIDRs, stale advertised routes, split-horizon DNS, or MTU.

MTU arithmetic if it connected then stalled. A 1500-byte MTU gives MSS 1460; IPsec ESP adds roughly 50–73 bytes, so a 1400-byte tunnel MTU gives MSS 1360. Confirm with ping -M do -s 1472 (succeeds at 1500) versus -s 1372 (succeeds at 1400), then clamp MSS at the tunnel.

Change one thing per hypothesis and tear down any temporary ACL you added.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

An acquired company uses the same private CIDR as your production VPC. Propose a safe integration plan.

Answer

What I'd say in the first two minutes

Clarify: which direction the flows go, how many distinct services actually need to talk, and whether the acquired estate will be renumbered or kept as-is. Then answer: you cannot route between two 10.0.0.0/16s, so the integration runs over a boundary that terminates the IP layer. PrivateLink for service-to-service, a private NAT gateway where you need IP-level reachability. With renumbering as the exit.

Why routing fails

Prod host 10.0.1.10 dials 10.0.2.20 in the acquired VPC. Prod's route table has a local route for 10.0.0.0/16 that always wins, and AWS won't let you add a route matching your own CIDR. The SYN lands on prod's own 10.0.2.20: a different machine. You get a completed TCP handshake to the wrong service, not a timeout. VPC peering won't even be created between overlapping CIDRs. A transit gateway will attach both VPCs, but its route table resolves 10.0.0.0/16 to one attachment, so one side is unreachable and the other is misdelivered.

Design against silent misdelivery, not blackholes. Detect it with TLS SNI/cert mismatch, application errors that make no sense for the target, and VPC Flow Logs showing the connection landing on an ENI you didn't expect.

Options

OptionHandles overlapMechanismCost / limit
PeeringNo—creation rejected on overlap
TGW routeNoone route per prefixone side unreachable
PrivateLinkYesconsumer ENI in own subnetNLB hourly + per-GB; TCP only
Private NAT GWYesSNAT to NAT GW private IPhourly per AZ + per-GB; 55k conn/dest
RenumberYes, permanentlychange CIDRdowntime, hard-coded IPs

PrivateLink: default for service-to-service. NLB in the acquired VPC fronting the target, registered as an endpoint service, shared with the prod account. Prod creates an interface VPC endpoint in a subnet; it gets an IP from prod's own CIDR, say 10.0.1.55. Prod's route table never learns the acquired 10.0.0.0/16: the endpoint ENI is local, so overlap is irrelevant. Limits: TCP only, no multicast or arbitrary IP protocols; endpoints are per-AZ, so create one in each AZ you need; NLB hourly plus data processing.

Private NAT gateway, when you need IP-level reachability. A legacy app that dials an IP, or database replication. It SNATs the source to the gateway's private IP, so the peer sees 10.0.0.5, not 10.0.1.10. Run one per side for bidirectional. The documented ceiling is 55,000 simultaneous connections per unique destination, so a chatty replication stream can exhaust it. SNAT breaks anything that embeds addresses in the payload: FTP active mode, SIP, some Kerberos and database replication setups. Detection: the connection establishes but the app fails at the payload stage; captures show the NAT IP where the app expects the real one.

Renumbering: the exit. Give the acquired estate a non-overlapping block, 172.16.0.0/16 or 10.100.0.0/16. Inventory hard-coded addresses, DNS records, certs with IP SANs, firewall rules, security-group references. Stand the new CIDR up alongside, migrate service by service, keep translation for the tail. Hard-coded IPs are the long pole; expect them to outlive the migration by a year.

Curated: · Written: · Reviewed:

Difficulty: Hard