Skip to content

Lesson 18 of 30Modern AWS

Advanced VPC Networking

Plan IP space across accounts, connect VPCs with peering, Transit Gateway or PrivateLink, design NAT and DNS, and debug with Flow Logs.

24 min read0/4 questions

Your company started with one VPC, 10.0.0.0/16, like every tutorial. Two years later there are twelve accounts, an acquired startup whose VPC is also 10.0.0.0/16, a payments team that needs to reach a shared Postgres in another account, an office that wants private access over VPN, and a NAT gateway line on the bill that nobody can explain. None of this is solved by the three-tier VPC from VPC Networking. It is solved by planning address space, choosing the right way to connect networks, and knowing where bytes cost money. This lesson is the part of networking that platform teams own and that senior interviews probe.

IP planning comes first

Every connection option between networks, apart from PrivateLink and VPC Lattice, routes on IP addresses. If two networks overlap, packets for 10.0.4.20 have two possible homes and the route table cannot express that. VPC peering refuses to create a connection between overlapping CIDRs. Transit Gateway, Site-to-Site VPN and Direct Connect gateways need unique ranges to route. Renumbering a live VPC means rebuilding everything in it, so an overlap made on day one is a migration project on day 700.

A workable plan for a company on AWS:

  • Reserve a large private range for AWS, for example 10.0.0.0/8, and keep the office, VPN users and partners out of it (or document exactly which parts they use).
  • Give each Region a slice, such as a /12, and each VPC a /16 to /20 from it. Bigger than you think: EKS pods and Lambda functions in a VPC each consume an IP.
  • Avoid 172.17.0.0/16, Docker's default bridge, which breaks containers that try to reach a VPC on that range.
  • Write the plan down in one place. At scale, that place is VPC IPAM: pools per Region and environment, automatic non-overlapping allocation when a team creates a VPC through IaC, and reports that flag overlaps and VPCs created outside the plan.

The Python standard library's ipaddress module is enough to build a planner. This one hands out a non-overlapping /16 per environment from the Region's /12, skips ranges already taken, and carves each VPC into tiers across three AZs, largest blocks first so nothing fragments.

Pythonplanner.py
import ipaddress as ip SUPERNET = ip.ip_network("10.32.0.0/12") # this Region's share of 10.0.0.0/8TAKEN = [ip.ip_network("10.32.0.0/16"), # legacy prod VPC, cannot move ip.ip_network("10.40.0.0/16")] # partner VPN rangeAVOID = [ip.ip_network("172.17.0.0/16")] # Docker's default bridgeAZS = ["a", "b", "c"]TIERS = [("public", 24), ("app", 20), ("data", 24)] # name, prefix per AZ subnetENVS = ["dev", "staging", "prod"] def free_blocks(prefix): for block in SUPERNET.subnets(new_prefix=prefix): if not any(block.overlaps(t) for t in TAKEN + AVOID): yield block def carve(vpc): plan, cursor = [], [vpc] for tier, prefix in sorted(TIERS, key=lambda t: t[1]): # biggest first, no gaps for az in AZS: for i, block in enumerate(cursor): if block.prefixlen <= prefix: sub = next(block.subnets(new_prefix=prefix)) rest = list(block.address_exclude(sub)) cursor = cursor[:i] + sorted(rest) + cursor[i + 1:] plan.append((f"{tier}-{az}", sub)) break else: raise ValueError(f"{vpc} is too small for {tier}-{az}") return plan, cursor vpcs = free_blocks(16)for env in ENVS: vpc = next(vpcs) TAKEN.append(vpc) plan, spare = carve(vpc) spare_ips = sum(b.num_addresses for b in spare) print(f"{env:<8} {vpc} ({len(plan)} subnets, {spare_ips} addresses spare)") if env == "prod": for name, sub in sorted(plan, key=lambda p: p[1]): print(f" {name:<10} {str(sub):<16} {sub.num_addresses - 5:>5} usable")
Output
Press Run (⌘ Enter) to see what happens.

Change TIERS to give the app tier a /19, or add a fourth AZ, and rerun. Notice the app tier gets /20s: that tier holds containers and pods, which is where address exhaustion actually happens. The spare space is deliberate; you will want a new tier later.

When a VPC does run out, you can attach secondary CIDR blocks (5 per VPC by default, adjustable). You cannot resize an existing block, and there are rules on which ranges can be added: a VPC whose primary block is in 10.0.0.0/8 cannot add blocks from 172.16.0.0/12 or 192.168.0.0/16, but it can add blocks from 100.64.0.0/10. That shared address range is the standard fix for EKS clusters running out of pod IPs: pods get addresses from a 100.64.x.x secondary block that never needs to be routable outside the VPC.

Predict the outputPython

Team A owns 10.0.0.0/14. Team B asks for 10.3.0.0/16. Can these two VPCs be peered?

import ipaddress as ip
a = ip.ip_network("10.0.0.0/14")
b = ip.ip_network("10.3.0.0/16")
print(a.overlaps(b))
Need a nudge? Hints walk you through it.

IPv6, and why public IPv4 got expensive

AWS charges for every public IPv4 address, attached or not, including the ones on NAT gateways, load balancers and EC2 instances (it did not used to). That pushed IPv6 from "someday" to "worth a look".

The IPv6 model on AWS is different in useful ways. A VPC gets a /56 (Amazon-provided, or your own), each subnet a /64, and every address is globally unique, so there is no NAT. "Private" is enforced by routing instead: an egress-only internet gateway allows outbound IPv6 connections and their replies, and blocks connections initiated from outside, which is the IPv6 equivalent of a NAT gateway's one-way door. Most teams run dual-stack subnets (IPv4 plus IPv6). IPv6-only subnets are possible; to reach IPv4-only services they need DNS64 on the subnet and NAT64 through a NAT gateway.

Connecting VPCs: four options

VPC peeringTransit GatewayPrivateLinkVPC Lattice
ShapeOne-to-one linkHub and spoke routerOne service exposed to consumersService network for many services
TransitiveNoYes, controlled by TGW route tablesNot applicableNot applicable
Overlapping CIDRsNot allowedMust not overlap to routeFineFine
DirectionBoth waysBoth waysConsumer to provider onlyClient to service
Billing shapeData transfer onlyPer attachment per hour plus per GB processedPer endpoint per AZ per hour plus per GBPer service per hour, per GB and per request
Best forA few VPCs that talk a lotDozens of VPCs, VPN and Direct Connect in one placeSharing one service with many accounts, SaaSMany HTTP or gRPC services across accounts, with IAM auth

Peering is the simplest and has no bandwidth bottleneck or processing charge, but it has three rules people trip over. It is not transitive: if A peers with B and B with C, A cannot reach C through B. There is no edge-to-edge routing: A cannot use B's internet gateway, NAT gateway, VPN or S3 gateway endpoint. And both sides need routes: creating the connection does nothing until each VPC's route tables point the other's CIDR at pcx-.... Security groups can reference groups in a peered VPC only when both are in the same Region. Ten VPCs fully meshed is 45 peerings, which is where people give up and move to a Transit Gateway.

Transit Gateway is a Regional router you attach VPCs, VPNs and Direct Connect gateways to. Its power is TGW route tables: each attachment is associated with one route table (which decides where its traffic can go) and propagates its routes into one or more (which decides who can reach it). That is how you segment: prod VPCs and the shared-services VPC see each other, dev VPCs see shared services, and dev and prod never see each other, all on one gateway. TGWs in different Regions can peer with each other. Every byte through a TGW pays a processing charge, so chatty VPC pairs are sometimes peered directly alongside it.

Transit Gateway segmentation with route tables
Prod route tableDev route tableprod-orders: 10.35.0.0/16prod-orders10.35.0.0/16prod-payments: 10.36.0.0/16prod-payments10.36.0.0/16Transit Gateway: regional hubTransit Gatewayregional hubshared-services: 10.38.0.0/16shared-services10.38.0.0/16Office VPN: 192.168.0.0/20Office VPN192.168.0.0/20dev-orders: 10.33.0.0/16dev-orders10.33.0.0/16dev-payments: 10.34.0.0/16dev-payments10.34.0.0/16

Every VPC and the VPN attach once to the hub. With peering, these six networks would need up to 15 separate connections.

1/4

PrivateLink solves a different problem: "let other VPCs call my one service" without joining networks at all. The provider puts the service behind a Network Load Balancer and creates an endpoint service. Each consumer creates an interface endpoint, which places an ENI with a private IP in the consumer's subnets. Traffic only flows consumer to provider, the consumer sees nothing else in the provider's VPC, and overlapping CIDRs do not matter because no routing between the VPCs happens. This is how SaaS vendors offer private connectivity, and it is the same mechanism behind the AWS interface endpoints you met in VPC Networking.

VPC Lattice goes one level up: a service network that VPCs and services join, with routing by host and path, IAM auth policies on each service ("only the orders role may call POST /refunds"), and resource configurations that expose things like an RDS database to other accounts. It handles overlapping CIDRs and has no inter-AZ data charges. Know it exists and when it fits: many internal HTTP services across many accounts, where you want identity-based access instead of network plumbing.

Match the pairs0/4 matched

Match each requirement to the best fit.

Choose an item, then its match on the other side.

NAT gateway design

The classic design is one zonal NAT gateway per AZ, each in a public subnet, with each AZ's private route table pointing at its own NAT. That keeps AZs independent: if eu-west-2a fails, 2b and 2c still reach the internet. The cheaper dev design, one shared NAT, has two costs: an AZ failure takes egress down for everyone, and traffic from other AZs crosses AZs to reach it, paying cross-AZ data charges on top of NAT processing.

Since late 2025 there is also a regional NAT gateway: one NAT ID for the whole VPC that expands into each AZ where you have workloads and needs no public subnet. Every private subnet can share one route table entry. It can take up to an hour to expand into a newly used AZ, and it does not support private NAT, so check the docs before adopting it everywhere.

Whichever you choose, cut what flows through it:

  • Gateway endpoints for S3 and DynamoDB are free and remove that traffic from the NAT entirely.
  • Interface endpoints for ECR, CloudWatch Logs, Secrets Manager, STS and similar services bill per hour per AZ, so they pay off when traffic is heavy or when a subnet must have no internet path at all.
  • Endpoint policies are an underused security control. A gateway endpoint policy that allows only your organization's buckets (using aws:ResourceOrgID) means a compromised task cannot upload stolen data to an attacker's bucket through the free path.

Large organizations often centralize egress: workload VPCs route 0.0.0.0/0 to a Transit Gateway, which sends it to one egress VPC holding NAT gateways and a firewall. That buys one inspection point and fewer NATs, and costs TGW processing on every byte. It is a trade-off to calculate, not a default.

DNS inside a VPC

Every VPC has the Route 53 Resolver at the base of its range plus two (10.35.0.2) and at 169.254.169.253. Two VPC attributes control it: enableDnsSupport turns the resolver on, and enableDnsHostnames gives instances DNS names. Private hosted zones and private DNS for interface endpoints need both set to true; a VPC built with hostnames off is the reason secretsmanager.eu-west-2.amazonaws.com still resolves to a public IP despite an endpoint existing.

A private hosted zone (internal.acme.com) answers only for the VPCs associated with it. You can associate a zone with VPCs in other accounts (authorize in one account, associate in the other), which is how a shared-services account publishes db.internal.acme.com to everyone.

For hybrid DNS, Resolver endpoints bridge AWS and the office. An inbound endpoint gives on-premises DNS servers IPs in your VPC to forward *.internal.acme.com queries to. An outbound endpoint plus forwarding rules send queries for corp.acme.local from your VPCs to the office DNS servers. Rules can be shared to other accounts with AWS RAM so every VPC resolves the same names.

One limit bites busy services: each network interface can send at most 1,024 packets per second to the Resolver, and it cannot be raised. A service that resolves a hostname on every outbound request, with no caching, hits it under load and sees DNS timeouts that look like random network failures. Cache DNS in the client or run a local caching resolver.

Hybrid connectivity

OptionWhat it isUse when
Site-to-Site VPNIPsec tunnels over the internet, two per connection for redundancy, ending on a virtual private gateway or Transit GatewayQuick to set up, modest bandwidth, backup for Direct Connect
Direct ConnectA private physical link from your data center or a colocation facility into AWSSteady high throughput, consistent latency, large data transfer; takes weeks to provision
Client VPNManaged OpenVPN-based access for individual laptopsEngineers reaching private resources from home

Two details interviewers like. Direct Connect is private but not encrypted by default; run MACsec on supported connections or an IPsec VPN over it when you need encryption in transit. And production designs pair Direct Connect with a VPN (or a second Direct Connect location) as a backup path, with BGP deciding which path is active.

Where the bytes cost money

Prices change, so learn the shape instead:

  • Traffic within one AZ over private IPs is free.
  • Traffic between AZs is charged, in each direction. A chatty service talking to a database in another AZ pays on every query and every reply. This is also true across a peering connection.
  • Traffic between Regions costs more than cross-AZ.
  • Traffic out to the internet costs the most per GB; CloudFront's egress is typically cheaper than serving straight from EC2 or S3.
  • NAT gateways, Transit Gateway and interface endpoints add a per-GB processing charge on top of the transfer itself.

One more trap when aligning AZs across accounts: AZ names like eu-west-2a are mapped differently per account, so your 2a may be another account's 2b. Use AZ IDs such as euw2-az1 when you want two accounts' subnets in the same physical AZ, for example to keep traffic to a shared service free.

Debugging: Flow Logs and Reachability Analyzer

VPC Flow Logs record a summary of each flow per network interface, published to CloudWatch Logs or S3. The default format is 14 space-separated fields: version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status. Protocol is a number (6 is TCP, 17 UDP), action is ACCEPT or REJECT, and NODATA means no traffic in the window. Custom formats add fields like vpc-id, pkt-srcaddr (the original source behind a NAT) and flow-direction.

Pythonflows.py
from collections import Counter # Default format: version account-id interface-id srcaddr dstaddr srcport dstport# protocol packets bytes start end action log-statusLINES = """\2 111122223333 eni-app1 10.1.2.15 10.1.8.20 49152 5432 6 10 840 1761120000 1761120060 ACCEPT OK2 111122223333 eni-app1 10.1.2.15 10.2.4.9 50211 443 6 3 180 1761120000 1761120060 REJECT OK2 111122223333 eni-app1 10.1.2.15 10.2.4.9 50212 443 6 3 180 1761120060 1761120120 REJECT OK2 111122223333 eni-db1 10.1.8.20 10.1.2.15 5432 49152 6 12 4200 1761120000 1761120060 ACCEPT OK2 111122223333 eni-web 203.0.113.50 10.1.0.10 41000 22 6 1 60 1761120000 1761120060 REJECT OK2 111122223333 eni-web 198.51.100.7 10.1.0.10 52000 22 6 1 60 1761120000 1761120060 REJECT OK2 111122223333 eni-idle - - - - - - - 1761120000 1761120060 - NODATA"""PROTO = {"6": "tcp", "17": "udp", "1": "icmp"} rejects = Counter()for line in LINES.splitlines(): f = line.split() if f[13] != "OK" or f[12] != "REJECT": continue src, dst, dport, proto = f[3], f[4], f[6], PROTO.get(f[7], f[7]) inside = dst.startswith("10.") and src.startswith("10.") rejects[(f[2], dst, f"{proto}/{dport}", "internal" if inside else "from internet")] += 1 for (eni, dst, port, where), n in rejects.most_common(): print(f"{n}x REJECT {eni} -> {dst} {port} ({where})")
Output
Press Run (⌘ Enter) to see what happens.

Read the results like an engineer. The SSH rejects from internet addresses are background scanning hitting a closed door, which is the system working. The repeated internal reject from eni-app1 to 10.2.4.9:443 is your bug: the app is trying to reach something in another VPC (10.2.x) and being dropped. Flow logs tell you that a packet was rejected, not which rule did it. A security group reject shows only REJECT; a NACL problem often shows an ACCEPT inbound and a REJECT on the return traffic to the ephemeral port.

To find which component blocks a path, use Reachability Analyzer. You give it a source and destination (an ENI, instance, endpoint, gateway) and a port, and it analyzes configuration (no packets sent) and reports either a full hop-by-hop path or the exact blocking component: "route table rtb-0a1 has no route to 10.2.0.0/16". Network Access Analyzer answers the inverse audit question: which resources are reachable from the internet at all?

Put it in order5 steps

An app in VPC A cannot reach a service in VPC B over a peering connection. Order the checks.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
VPC A peers with shared-services VPC B, which has a NAT gateway and an S3 gateway endpoint. A private subnet in A routes 0.0.0.0/0 to the peering connection. What happens?
Need a nudge? A hint rules out a wrong answer.
Key terms
VPC IPAM
A VPC feature for planning, allocating and auditing IP address space across accounts and Regions from pools.
Transit Gateway
A Regional hub router for VPCs, VPNs and Direct Connect, with route tables for segmentation.
PrivateLink
Exposes a service behind an NLB to other VPCs through interface endpoints, one way, ignoring overlapping CIDRs.
egress-only internet gateway
Allows outbound IPv6 connections from a VPC and blocks connections initiated from the internet.
Resolver endpoint
Inbound or outbound ENIs that let Route 53 Resolver exchange DNS queries with networks outside the VPC.
AZ ID
A stable physical AZ identifier like euw2-az1; AZ names such as eu-west-2a map differently per account.
Reachability Analyzer
Analyzes network configuration between a source and destination and names the component that blocks the path.