Route Tables and NAT
Subnets don't decide on their own where packets go. Each subnet is associated with a route table: a list of destinations (CIDR blocks) and targets (where to send matching traffic). Together with gateways, route tables define whether a subnet is public, private or isolated.
Gateways and targets
| Target | Purpose |
|---|---|
local |
Traffic inside the VPC; present in every route table, can't be removed |
| Internet gateway (IGW) | Two-way internet access for resources with public IPs |
| NAT gateway | Lets private subnets make outbound connections to the internet; nothing can connect in |
| Egress-only internet gateway | Outbound-only for IPv6 |
| VPC peering connection | Private route to another VPC |
| Transit Gateway | Hub that connects many VPCs and on-premises networks |
| Virtual private gateway | Site-to-Site VPN / Direct Connect |
| Gateway VPC endpoint | Private access to S3 and DynamoDB without the internet |
Longest prefix match
When several routes match a destination, the most specific one (the longest prefix) wins. This model implements a route table lookup:
import ipaddress
public_rt = [
("10.20.0.0/16", "local"),
("0.0.0.0/0", "igw-0a1b2c3d"),
]
private_rt = [
("10.20.0.0/16", "local"),
("10.30.0.0/16", "pcx-0peer1234"), # peering to the data VPC
("0.0.0.0/0", "nat-0f9e8d7c"),
]
def lookup(table, destination):
ip = ipaddress.ip_address(destination)
matches = [(ipaddress.ip_network(cidr), target) for cidr, target in table
if ip in ipaddress.ip_network(cidr)]
if not matches:
return "no route (dropped)"
net, target = max(matches, key=lambda m: m[0].prefixlen)
return f"{target} (via {net})"
for dest in ["10.20.5.9", "10.30.1.7", "93.184.216.34"]:
print(f"{dest:<14} public: {lookup(public_rt, dest):<30} private: {lookup(private_rt, dest)}")10.20.5.9 public: local (via 10.20.0.0/16) private: local (via 10.20.0.0/16)
10.30.1.7 public: igw-0a1b2c3d (via 0.0.0.0/0) private: pcx-0peer1234 (via 10.30.0.0/16)
93.184.216.34 public: igw-0a1b2c3d (via 0.0.0.0/0) private: nat-0f9e8d7c (via 0.0.0.0/0)
0.0.0.0/0 matches everything but has prefix length 0, so it is only used when nothing more specific matches.
NAT gateways
A NAT (network address translation) gateway sits in a public subnet with an Elastic IP. Instances in private subnets send internet-bound traffic to it; it rewrites the source address to its own public IP, and replies come back through it. Connections can only be started from inside.
aws ec2 allocate-address --domain vpc
aws ec2 create-nat-gateway --subnet-id subnet-0public1a --allocation-id eipalloc-0123abcd
aws ec2 create-route --route-table-id rtb-0private1a \
--destination-cidr-block 0.0.0.0/0 --nat-gateway-id nat-0f9e8d7cModel: NAT translation table
class NatGateway:
def __init__(self, public_ip):
self.public_ip = public_ip
self.table = {} # public port -> (private ip, private port)
self.next_port = 1024
def outbound(self, src_ip, src_port, dst):
port = self.next_port
self.next_port += 1
self.table[port] = (src_ip, src_port)
return f"{src_ip}:{src_port} -> {dst} becomes {self.public_ip}:{port} -> {dst}"
def inbound(self, dst_port, src):
if dst_port in self.table:
ip, port = self.table[dst_port]
return f"reply from {src} to :{dst_port} forwarded to {ip}:{port}"
return f"unsolicited packet from {src} to :{dst_port} dropped"
nat = NatGateway("52.18.40.7")
print(nat.outbound("10.20.32.15", 50122, "pypi.org:443"))
print(nat.outbound("10.20.48.9", 41000, "api.stripe.com:443"))
print(nat.inbound(1024, "pypi.org:443"))
print(nat.inbound(4444, "198.51.100.66:51515"))10.20.32.15:50122 -> pypi.org:443 becomes 52.18.40.7:1024 -> pypi.org:443
10.20.48.9:41000 -> api.stripe.com:443 becomes 52.18.40.7:1025 -> api.stripe.com:443
reply from pypi.org:443 to :1024 forwarded to 10.20.32.15:50122
unsolicited packet from 198.51.100.66:51515 to :4444 dropped
High availability and cost
A NAT gateway lives in one AZ. If that AZ fails, private subnets in the other AZs that route through it lose internet access. The robust design is one NAT gateway per AZ, with each AZ's private route table pointing to its own gateway. NAT gateways are billed per hour and per GB processed, so heavy traffic to S3 or DynamoDB should use free gateway endpoints instead:
HOURLY = 0.045 # example $ per NAT gateway hour (check the AWS pricing pages)
PER_GB = 0.045 # example $ per GB processed
def monthly(nat_gateways, gb_through_nat):
return nat_gateways * HOURLY * 730 + gb_through_nat * PER_GB
s3_gb, other_gb = 3000, 200
print(f"1 NAT, all traffic : ${monthly(1, s3_gb + other_gb):8.2f} (single AZ dependency)")
print(f"3 NATs, all traffic : ${monthly(3, s3_gb + other_gb):8.2f}")
print(f"3 NATs + S3 gateway endpt : ${monthly(3, other_gb):8.2f} (S3 traffic skips the NAT)")1 NAT, all traffic : $ 176.85 (single AZ dependency)
3 NATs, all traffic : $ 242.55
3 NATs + S3 gateway endpt : $ 107.55 (S3 traffic skips the NAT)
Tip: Fully private workloads that only call AWS services can skip NAT entirely by using interface VPC endpoints (AWS PrivateLink) for services like ECR, Secrets Manager and CloudWatch Logs.
Test yourself
A route table has routes for 10.0.0.0/16 (local) and 10.0.5.0/24 (peering). Where does traffic to 10.0.5.20 go?
- local
- The peering connection
- The internet gateway
- It is dropped
Where must a NAT gateway be placed?
- In a private subnet
- In a public subnet with an Elastic IP
- Outside the VPC
- On each instance
How can private instances reach S3 without paying NAT data processing charges?
- Use a gateway VPC endpoint for S3
- Use a bigger NAT gateway
- Open port 443
- Use CloudFront