CloudVol. 7 · Part VII
0 / 0

Shelves / Cloud

CL·87

Cloud Networking

Building networks in the cloud: VPCs and VNets, CIDR planning and IPv6, public and private subnets per zone, route tables, internet, NAT and egress gateways, security groups versus network ACLs and managed firewalls, load balancers (L4, L7, global), private endpoints (PrivateLink, Private Service Connect, Azure Private Link), connecting networks (peering, transit gateways, hub-and-spoke, VPN and dedicated links), DNS with Route 53 and its equivalents, CDNs, and service-to-service networking, with Terraform and CLI examples.

30 topics · ~21 min read · 30-question quiz
Updated Suggest a correction

Start here: a private network you can draw

The pieces of a VPC

A virtual private cloud (VPC on AWS and Google Cloud, VNet on Azure) is your own private address space in the provider's network, such as 10.20.0.0/16. Inside it you create subnets, each in one availability zone. A subnet is public if its route table sends internet-bound traffic to an internet gateway (and its instances have public IPs); it's private if it doesn't. Instances in private subnets reach the internet, if at all, through a NAT gateway that sits in a public subnet and makes their requests appear to come from its own public address. Here's the miniature version:

internetserver198.51.100.80 internetgateway +VPC router public subnet 10.20.0.0/24 web110.20.0.10198.51.100.10 NAT gateway10.20.0.20198.51.100.20 private subnet 10.20.10.0/24 app110.20.10.10 route tablespublic: 0.0.0.0/0 → IGWprivate: 0.0.0.0/0 → NATboth: 10.20.0.0/16 → local
The miniature VPC built in this chapter. web1 is in the public subnet with a public IP; app1 is in the private subnet and reaches the internet only through the NAT gateway; the internet can't start connections to app1.

Routes decide what can reach what

Text
$ ip route        # on web1, in the public subnet
  default via 10.20.0.1 dev w1-eth
  10.20.0.0/24 dev w1-eth proto kernel scope link src 10.20.0.10
$ curl -s -m 3 http://198.51.100.80/
  hello from the internet; you came from 198.51.100.10
$ ip route        # on app1, in the private subnet: only the VPC's own range
  10.20.0.0/16 via 10.20.10.1 dev a1-eth
$ curl -s -m 3 http://198.51.100.80/
  no route to the internet (exit 7)
# add the private subnet's route table entry: 0.0.0.0/0 → NAT gateway
$ curl -s -m 3 http://198.51.100.80/
  hello from the internet; you came from 198.51.100.20

web1 reached the internet, and the server saw its public IP: the internet gateway translated 10.20.0.10 to 198.51.100.10 (private addresses like 10.x aren't routable on the internet). app1 initially had no route out at all. After its subnet got a default route to the NAT gateway, it could make outbound requests, and the server saw the NAT gateway's address.

And what can reach in

Text
$ curl -s -m 3 http://198.51.100.10:8080/     # from the internet, to web1's public IP
  web1 public IP: nothing listening yet (exit 7)
$ curl -s -m 3 http://10.20.10.10:8080/       # from the internet, to app1
  app1 private IP: unreachable from the internet (exit 28)

web1's public IP was reachable (a connection was refused only because nothing listened on 8080); app1 couldn't be reached at all: it has no public address, and a NAT gateway only lets replies to app1's own outbound connections back in. That's the standard layout: load balancers in public subnets, applications and databases in private subnets, and nothing private exposed directly.

Cloud concept What it is Linux equivalent used here
VPC / VNet Your private address space A set of namespaces and bridges
Subnet (in one AZ) A slice of the range in one zone A bridge with a /24
Route table Where each destination goes, per subnet ip route, policy routing
Internet gateway Edge with 1:1 public-IP translation Router with DNAT/SNAT
NAT gateway Outbound-only translation for private subnets Namespace with MASQUERADE
Security group Stateful firewall on an instance's interface iptables with conntrack in the instance
Network ACL Stateless filter at the subnet boundary iptables rules on the router without conntrack

How deep to go in cloud networking

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain VPCs, subnets, route tables, gateways, security groups and load balancers
L2 Build a multi-AZ VPC with public and private subnets, NAT and load balancers as code
L3 Explain stateful vs stateless filtering, NAT, private endpoints, peering vs transit, DNS and CDNs
L4 Diagnose unreachable instances, asymmetric routes, DNS resolution and NAT/egress cost problems
L5 Design address plans, multi-account and hybrid connectivity, and egress controls
L6 Operate enterprise networks with central inspection, IPAM, IPv6 and network observability

Virtual networks

What a VPC is

A Virtual Private Cloud (AWS VPC, Azure VNet, Google VPC network) is a logically isolated, software-defined network inside the provider's infrastructure. You choose its IP address range, divide it into subnets, control routing, and attach gateways. Under the hood it's an overlay (encapsulation on the provider's fabric, e.g. AWS's Nitro-based "Hyperplane" and Mapping Service), so there's no broadcast, and ARP is answered by the hypervisor.

Scope differs:

  • AWS VPC: regional; subnets are zonal (one AZ each).
  • Azure VNet: regional; subnets span all zones in the region.
  • GCP VPC: global; subnets are regional (span zones), so one VPC can have subnets in Mumbai and Frankfurt with internal routing between them.

Address planning

VPC ranges come from private IPv4 space (RFC 1918):

Block Range Size
10.0.0.0/8 10.0.0.0–10.255.255.255 16.7 M addresses
172.16.0.0/12 172.16.0.0–172.31.255.255 1 M
192.168.0.0/16 192.168.0.0–192.168.255.255 65 K

CIDR notation: /16 = 65,536 addresses, /20 = 4,096, /24 = 256. Each subnet loses a few addresses to the provider (AWS reserves 5 per subnet: network, router, DNS, future use, broadcast).

Plan carefully, because ranges are hard to change later and overlapping ranges can't be peered or routed together:

  • Allocate non-overlapping ranges per VPC, environment and region from an organisation-wide plan (IP address managers: AWS VPC IPAM, Azure IPAM, NetBox).
  • Leave room: Kubernetes with VPC-native pod networking (AWS VPC CNI, GKE VPC-native) consumes an IP per pod, so clusters can exhaust /24 subnets quickly. Use large subnets, secondary ranges, prefix delegation, or overlay CNIs.
  • Avoid ranges likely to clash with on-premises networks, partner VPNs or home networks (192.168.0.0/16, 10.0.0.0/16).
  • IPv6: VPCs can be dual-stack or IPv6-only with globally unique /56 (AWS) or /64 subnets; public IPv4 addresses now cost money on AWS (since 2024), which pushes more designs toward IPv6 and private connectivity.

Subnets and the standard layout

A subnet is a slice of the VPC range in one zone (on AWS). It's public or private only by its route table:

  • Public subnet: has a route 0.0.0.0/0 → internet gateway. Resources with public IPs are reachable from the internet (subject to firewalls). Put load balancers and NAT gateways here, and very little else.
  • Private subnet: no route to the internet gateway. Outbound internet (if needed) goes through a NAT gateway. Put application servers, containers and functions in VPC here.
  • Isolated (data) subnet: no internet route at all. Databases and caches.
internet gateway VPC 10.20.0.0/16 (ap-south-1) AZ a public 10.20.0.0/24ALB node · NAT GW private 10.20.16.0/20app tasks / pods isolated 10.20.64.0/24DB primary AZ b public 10.20.1.0/24ALB node · NAT GW private 10.20.32.0/20app tasks / pods isolated 10.20.65.0/24DB standby AZ c public 10.20.2.0/24ALB node · NAT GW private 10.20.48.0/20app tasks / pods isolated 10.20.66.0/24(replica)
A standard three-tier VPC across three availability zones. Public subnets hold load balancers and NAT gateways; private subnets hold application instances; isolated subnets hold databases. Each AZ has its own NAT gateway so an AZ failure doesn't cut egress for the others.

Routing and gateways

Route tables

Every subnet is associated with a route table: destination CIDR → target. The most specific route wins. A VPC always has an implicit local route for its own CIDR (all subnets can reach each other, subject to firewalls).

Subnet Routes
public 10.20.0.0/16 → local, 0.0.0.0/0 → igw-…
private (AZ a) 10.20.0.0/16 → local, 0.0.0.0/0 → nat-a, pl-s3 → vpce-s3 (gateway endpoint)
isolated 10.20.0.0/16 → local only
shared-services routes 10.0.0.0/8 → tgw-… (to other VPCs and on-premises via a transit gateway)

Azure routes by default between subnets and to the internet (via system routes) and uses user-defined routes (UDRs) to override (e.g. force all egress through Azure Firewall). GCP uses VPC-wide routes with tags and priorities.

Gateways

Gateway Purpose
Internet gateway (IGW) Two-way internet access for resources with public IPs in public subnets (AWS). Horizontally scaled and highly available; no bandwidth limit
NAT gateway Outbound-only internet for private resources: translates private source IPs to the NAT's public IP; inbound connections can't be initiated. Zonal on AWS: deploy one per AZ, and route each private subnet to its own AZ's NAT (otherwise one AZ failure breaks egress everywhere, and cross-AZ traffic costs extra). Charged per hour and per GB processed, often a surprisingly large bill line. Azure NAT Gateway and Cloud NAT (GCP, a distributed software service) are the equivalents
Egress-only internet gateway IPv6 outbound-only (IPv6 has no NAT)
VPC endpoints Private access to cloud services without the internet (below)
Virtual private gateway / VPN gateway Site-to-site IPsec VPN to on-premises
Transit gateway Regional hub routing between many VPCs, VPNs and Direct Connect (below)

Reducing NAT cost and exposure: use gateway endpoints for S3 and DynamoDB (free), interface endpoints for other AWS services, egress through a central inspection VPC, and pull container images from a regional registry (ECR) via endpoints.

Firewalls

Security groups versus network ACLs

Security group (AWS SG, Azure NSG applied to NIC, GCP firewall rules with tags or service accounts) Network ACL (AWS NACL; Azure NSG on subnet is the closest equivalent)
Attached to Network interfaces (instances, ENIs of load balancers, Lambda in VPC, pods with SG-per-pod) Subnets
Statefulness Stateful: return traffic for an allowed connection is allowed automatically Stateless: you must allow return traffic explicitly (ephemeral ports 1024–65535)
Rules Allow only (AWS); Azure NSGs and GCP firewalls also support deny with priorities Allow and deny, evaluated in numbered order
References Can reference other security groups as sources ("allow 5432 from sg-app"), not just CIDRs CIDRs only
Typical use Primary, fine-grained control per workload Coarse subnet guard-rails (block a range), rarely needed

Security group design:

  • One SG per role (load balancer, app, database), with rules referencing other SGs: sg-db allows 5432 from sg-app; sg-app allows 8080 from sg-alb; sg-alb allows 443 from 0.0.0.0/0. When instances scale, rules don't change.
  • Never open SSH/RDP (22/3389) or database ports to 0.0.0.0/0. Use SSM Session Manager, Azure Bastion, IAP TCP forwarding (GCP) or EC2 Instance Connect Endpoint for shell access with IAM authentication and audit logs, and no inbound ports at all.
  • Egress rules: default "allow all outbound" is common; restrict for sensitive workloads (data exfiltration).
HCL
# Terraform (AWS provider): chained security groups
resource "aws_security_group" "alb" {
  name   = "orders-alb"
  vpc_id = aws_vpc.main.id
}
resource "aws_vpc_security_group_ingress_rule" "alb_https" {
  security_group_id = aws_security_group.alb.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_security_group" "app" {
  name   = "orders-app"
  vpc_id = aws_vpc.main.id
}
resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.alb.id   # source = another SG, not an IP range
  ip_protocol                  = "tcp"
  from_port                    = 8080
  to_port                      = 8080
}

resource "aws_security_group" "db" {
  name   = "orders-db"
  vpc_id = aws_vpc.main.id
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}

Managed firewalls and inspection

For organisation-wide policies (egress filtering by domain, intrusion prevention, TLS inspection): AWS Network Firewall (Suricata-compatible rules), Azure Firewall, Cloud NGFW (GCP), or third-party appliances inserted via Gateway Load Balancer. Typically deployed in a central inspection VPC/hub through which spoke traffic is routed. Web application firewalls (AWS WAF, Azure WAF on Front Door/Application Gateway, Cloud Armor) protect HTTP endpoints from common attacks and bots, and rate-limit at the edge. DDoS protection: AWS Shield (Standard is automatic; Advanced adds response team and cost protection), Azure DDoS Protection, Cloud Armor.

Load balancers

Need AWS Azure GCP
L7 HTTP(S) regional ALB (Application Load Balancer): host/path/header routing, HTTP/2, gRPC, WebSockets, OIDC auth, WAF Application Gateway (+ WAF) Regional external/internal Application LB
L7 global with edge CloudFront + ALB origins Front Door (global anycast, WAF, CDN) Global external Application LB (anycast IP, Cloud CDN, Cloud Armor)
L4 TCP/UDP/TLS NLB (Network Load Balancer): static IPs, extreme throughput, preserves client IP, PrivateLink provider Azure Load Balancer External/internal passthrough Network LB, proxy Network LB
Inline appliances GWLB (Gateway Load Balancer, GENEVE) Gateway Load Balancer —
DNS-level global steering Route 53 routing policies, Global Accelerator (anycast to regional endpoints) Traffic Manager Cloud DNS routing policies

Concepts (chapter 82 covers algorithms and behaviour):

  • Listeners (port + protocol + certificate) → rules → target groups (instances, IPs, Lambda functions, pods via the AWS Load Balancer Controller).
  • Health checks per target group; deregistration delay (connection draining) for graceful deployments.
  • Cross-zone load balancing spreads evenly across all AZs' targets (default on ALB; optional on NLB, with cross-AZ data charges).
  • TLS certificates from ACM (free, auto-renewed, for AWS load balancers and CloudFront), Azure Key Vault certificates, Google-managed certificates.
  • Internal load balancers serve private traffic between tiers or for PrivateLink services.

Private endpoints

Reaching cloud services privately

By default, calling S3, DynamoDB, SQS, Secrets Manager or a managed database's public endpoint from a private subnet goes through NAT to a public endpoint (still on the provider's network, but via public addresses). Private endpoints put the service on private IPs inside your VPC:

Type How Examples
Gateway endpoints (AWS) A route-table entry (prefix list → endpoint); free S3, DynamoDB
Interface endpoints (AWS PrivateLink) An ENI with a private IP in your subnets, private DNS overrides the public name Most AWS services, your own services, SaaS partners
Azure Private Endpoint (Private Link) A NIC in your VNet for a specific resource (one storage account, one SQL server) + private DNS zone Storage, SQL, Cosmos DB, Key Vault…
GCP Private Service Connect / Private Google Access Endpoints in your VPC for Google APIs or producer services Cloud Storage, BigQuery, Cloud SQL, partner services

Benefits: no internet path or NAT charges for that traffic, endpoint policies to restrict which buckets/resources can be reached (data-exfiltration controls), and the ability to disable public access on the resource entirely (e.g. storage accounts and databases that accept traffic only from private endpoints).

PrivateLink also lets you publish a service (behind an NLB) to other VPCs and accounts without peering their networks: consumers create an interface endpoint; only that one service is reachable, overlapping CIDRs don't matter, and traffic is one-directional (consumer → provider). This is how SaaS vendors offer private connectivity, and how platform teams share internal services across many accounts.

consumer VPC 10.0.0.0/16 app endpoint ENI10.0.3.15 provider VPC 10.0.0.0/16 NLB svc svc PrivateLink no peering · overlapping CIDRs OK · consumer → provider only
PrivateLink. A consumer VPC reaches one service in a provider VPC through an interface endpoint with a private IP in its own subnet; the networks aren't peered, CIDRs may overlap, and the consumer can reach nothing else in the provider VPC.

Connecting networks

Option Topology Notes
VPC peering (AWS, GCP), VNet peering (Azure) Point-to-point between two networks Simple, no bandwidth bottleneck; non-transitive (A↔B and B↔C doesn't give A↔C); CIDRs must not overlap; becomes a mesh at scale
Transit Gateway (AWS), Virtual WAN / hub VNet (Azure), Network Connectivity Center (GCP) Hub and spoke: many VPCs, VPNs and dedicated links attach to a regional hub with route tables for segmentation Central inspection, scales to thousands of attachments; per-attachment and per-GB charges
AWS Cloud WAN Global network policy across regions Large multi-region estates
Shared VPC (GCP), VPC sharing via RAM (AWS) Central network team owns the VPC; app accounts/projects deploy into shared subnets Fewer networks to manage
Site-to-site VPN IPsec over the internet to on-premises Quick, cheap, limited bandwidth (~1.25 Gbps per tunnel on AWS), internet-dependent
Dedicated connections: Direct Connect (AWS), ExpressRoute (Azure), Cloud Interconnect (GCP) Private circuits from your data centre or a colocation facility Predictable latency, high bandwidth (1–100 Gbps), lower egress pricing; use two connections at two locations for resilience, often with VPN as backup
Service-level connectivity: PrivateLink, VPC Lattice (AWS), service mesh Connect services, not networks Avoids network-level coupling and CIDR coordination

DNS

Cloud DNS services

Route 53 (AWS), Azure DNS and Cloud DNS (GCP) host authoritative zones with very high availability (Route 53's data plane has a 100% availability SLA):

  • Public hosted zones: your internet-facing domains.
  • Private hosted zones: names resolvable only inside associated VPCs (orders.internal.acme), used with internal load balancers and private endpoints.
  • Alias records (Route 53): point a name (including the zone apex example.com) at AWS resources (ALB, CloudFront, S3 website) and follow their IP changes; free to query. Azure alias records and GCP equivalents exist.
  • Resolvers: each VPC has a built-in resolver (VPC CIDR + 2, or 169.254.169.253); Route 53 Resolver endpoints and Azure DNS Private Resolver forward queries between cloud and on-premises DNS; DNS Firewall blocks lookups of malicious domains.

Routing policies

Policy Behaviour Use
Simple One answer Default
Weighted Split by weights Gradual migrations, canary between stacks
Latency-based Answer with the region of lowest measured latency to the resolver Multi-region active-active
Geolocation / geoproximity By user's location Data residency, localisation
Failover Primary unless its health check fails, then secondary Active-passive DR
Multivalue Several healthy IPs Simple client-side spreading

DNS-based failover is limited by TTL caching (and resolvers that ignore TTLs): use short TTLs (30–60 s) on records involved in failover, and remember that clients with long-lived connections or cached results won't move immediately. Anycast-based options (Global Accelerator, Front Door, GCP global LB) fail over faster.

Content delivery networks

A CDN (CloudFront, Azure Front Door, Cloud CDN / Media CDN, Cloudflare, Akamai, Fastly) caches content at hundreds of edge locations close to users:

  • Origins: S3 buckets, load balancers, any HTTP server. With Origin Access Control (CloudFront), the S3 bucket stays private and only the CDN can read it.
  • Cache behaviour: path patterns, TTLs (respecting or overriding Cache-Control), cache keys (which headers, cookies and query strings vary the cache; including too many destroys the hit ratio), compression, HTTP/2 and HTTP/3.
  • Invalidation is slow and costly at scale; prefer versioned, content-hashed asset names (app.3f9c2e.js) with long TTLs and immutable, and short TTLs for HTML.
  • Dynamic content benefits too: TLS termination near users, persistent optimised connections to the origin, and request collapsing.
  • Edge compute: CloudFront Functions (lightweight JS at the edge), Lambda@Edge, Cloudflare Workers, Fastly Compute: header rewrites, auth checks, A/B routing, redirects.
  • Security at the edge: WAF, bot management, DDoS absorption, geo-restriction, signed URLs and cookies for private content, and (since re:Invent 2025) mutual TLS to the edge on CloudFront.

Service-to-service networking

Inside a cloud estate, services must find and call each other securely:

  • Within one VPC: internal load balancers, Kubernetes Services, ECS Service Connect (Envoy-based discovery and retries), Cloud Map, private DNS.
  • Across VPCs and accounts: PrivateLink services, Amazon VPC Lattice (service network with IAM auth policies, no CIDR concerns), GCP Private Service Connect, Azure Private Link services, service meshes spanning clusters.
  • Identity over network location: modern practice (zero trust, Vol. 10) authenticates every request with workload identity (mTLS with SPIFFE IDs, IAM-signed requests via SigV4, OIDC tokens) rather than trusting anything inside the VPC. Network controls remain as defence in depth.

Building a VPC as code

HCL
# Terraform: a VPC with public and private subnets in three AZs, a NAT gateway per AZ, and an S3 gateway endpoint,
# using the community module (common in practice)
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 6.0"

  name = "shop-prod"
  cidr = "10.20.0.0/16"
  azs  = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]

  public_subnets   = ["10.20.0.0/24", "10.20.1.0/24", "10.20.2.0/24"]
  private_subnets  = ["10.20.16.0/20", "10.20.32.0/20", "10.20.48.0/20"]
  database_subnets = ["10.20.64.0/24", "10.20.65.0/24", "10.20.66.0/24"]

  enable_nat_gateway     = true
  one_nat_gateway_per_az = true          # resilience: no cross-AZ dependency for egress
  enable_dns_hostnames   = true
  enable_ipv6            = true

  enable_flow_log                      = true    # VPC Flow Logs for troubleshooting and security
  create_flow_log_cloudwatch_log_group = true
  create_flow_log_cloudwatch_iam_role  = true
}

resource "aws_vpc_endpoint" "s3" {
  vpc_id            = module.vpc.vpc_id
  service_name      = "com.amazonaws.ap-south-1.s3"
  vpc_endpoint_type = "Gateway"
  route_table_ids   = module.vpc.private_route_table_ids
}

VPC Flow Logs (AWS, Azure, GCP) record accepted and rejected connections per interface: indispensable for "why can't A reach B?" (combined with Reachability Analyzer or Azure Network Watcher / GCP Connectivity Tests) and for security investigations.

Lab: filters, NAT, addresses and egress costs

The miniature VPC from the on-ramp (Linux network namespaces, a router with policy routing, a NAT gateway namespace), the tiffin service listening on 8443 in web1, and Python's ipaddress module for address planning. NAT gateway prices are AWS us-east-1 list prices in October 2026 ($0.045 per hour and per GB processed).

Experiment 1: a stateful security group

web1 gets the equivalent of a security group: allow TCP 8443 in, allow everything out, drop the rest; replies are matched by connection tracking:

Text
internet → web1:8443/healthz: HTTP 200
internet → web1:22 (not allowed): timeout (2 s)
web1 → internet (reply allowed back automatically): HTTP 200

Only the allowed port was reachable, and web1's own outbound request worked without any inbound rule for its reply, because a stateful firewall remembers the connection and admits its return packets. Note the failure mode: a blocked port times out (packets silently dropped) rather than being refused, which is what you'll see when a security group is wrong. Security groups can also reference other security groups ("allow 5432 from the app tier's group"), which keeps rules correct as instances come and go.

Experiment 2: a stateless network ACL

The public subnet gets a network ACL: inbound allow TCP 8443; outbound allow TCP 80 and 443; deny everything else:

Text
internet → web1:8443/healthz: timeout (2 s)   (the response leaves from port 8443 to an ephemeral port: not allowed out)
web1 → internet:80: timeout (2 s)             (the response arrives on an ephemeral port: not allowed in)
after adding ephemeral-port rules (out: sport 8443 → 1024-65535; in: → 1024-65535):
internet → web1:8443/healthz: HTTP 200
web1 → internet:80: HTTP 200

With no connection tracking, every reply is just another packet that needs its own rule. Requests got in, and responses were dropped on the way out. The fix is to allow the ephemeral port range clients use for their side of connections (Linux uses 32768–60999; AWS recommends allowing 1024–65535 to cover all operating systems). This is the classic NACL mistake. Most teams leave NACLs at their default "allow all" and do their filtering in security groups, using NACLs only as coarse subnet-level guard rails (blocking a known-bad range, isolating a subnet).

Experiment 3: what NAT hides

Text
app1's request as seen by the internet server: hello from the internet; you came from 198.51.100.20
the internet server trying to reach app1 back through the NAT gateway's public IP: timeout (2 s)

The internet saw only the NAT gateway's address, and couldn't start a connection back in. The same property means third parties that allowlist your IPs need the NAT gateways' Elastic IPs, and that many private instances share a NAT's ports: each NAT gateway supports about 55,000 simultaneous connections to one destination IP and port, a limit busy services can reach when they all call one external API.

Experiment 4: planning addresses before you need them

Text
10.20.0.0/16 split per AZ (/18 each, one spare), then public /22 + private /20 per AZ:
   ap-south-1a: public 10.20.0.0/22 (1019 usable)  private 10.20.16.0/20 (4091 usable)
   ap-south-1b: public 10.20.64.0/22 (1019 usable)  private 10.20.80.0/20 (4091 usable)
   ap-south-1c: public 10.20.128.0/22 (1019 usable)  private 10.20.144.0/20 (4091 usable)
   spare for later: 10.20.192.0/18
networks to connect: {'payments': '10.0.0.0/16', 'orders': '10.0.0.0/16', 'analytics': '10.30.0.0/16', 'on-prem': '10.0.128.0/17'}
overlapping pairs (can't be peered or routed together): [('payments', 'orders'), ('payments', 'on-prem'), ('orders', 'on-prem')]

Private subnets get the large ranges because that's where instances, containers and (with VPC-native Kubernetes networking) every pod's IP live; public subnets mostly hold load balancers and NAT gateways. The second result is the most common networking regret: teams that each accepted a default 10.0.0.0/16 can never peer or route those VPCs together, or connect them to an office using 10.0.128.0/17, without renumbering or NAT. Allocate ranges centrally (AWS VPC IPAM, a spreadsheet, anything) from the first VPC.

Experiment 5: what egress through NAT costs

Private subnets in three AZs, one NAT gateway per AZ (so one zone's failure doesn't cut off the others):

Text
pulling  0.1 TB/month: $103/month ($99 hourly + $4 processing)
pulling    2 TB/month: $189/month ($99 hourly + $90 processing)
pulling   20 TB/month: $999/month ($99 hourly + $900 processing)
via an S3 gateway endpoint the S3 share is $0

Everything private instances download through NAT is charged per GB, on top of any internet data-transfer charges, including container image pulls, package downloads and calls to the provider's own services like S3. VPC endpoints keep traffic to cloud services on the provider's network: gateway endpoints for S3 and DynamoDB are free; interface endpoints (PrivateLink) for other services cost per hour and per GB but less than NAT, and also let you remove internet access from private subnets entirely.

Try it yourself

  1. Add a second private instance and a "security group reference": allow TCP 5432 into a database namespace only from members of the app group (an ipset).
  2. Make the NAT gateway a single point and break it. Then add one per "zone" and route each private subnet to its own.
  3. In a real account, build this VPC with Terraform or the CDK, enable VPC Flow Logs, and find the rejected packets from experiment 1 in them.
  4. Add IPv6 to the miniature VPC with an "egress-only internet gateway" (allow outbound IPv6, block inbound).

Revision sheet: cloud networking

Key ideas

  • VPC/VNet: CIDR range, subnets per AZ and tier, reserved addresses, IPv4 and IPv6, default VPCs (avoid for production).
  • Routing: route tables per subnet, local routes, internet gateway, NAT gateway, egress-only IGW, virtual private gateway, transit gateway.
  • Firewalls: security groups (stateful, per interface, can reference groups), NACLs (stateless, per subnet, ordered rules), cloud firewalls and inspection VPCs.
  • Load balancers: L7 (ALB, Application Gateway, HTTP(S) LB) vs L4 (NLB, Azure LB, network LB); health checks, TLS, cross-zone balancing, target types.
  • Private endpoints: gateway endpoints (S3, DynamoDB), interface endpoints/PrivateLink, Private Service Connect, Azure Private Link.
  • Connecting networks: peering (non-transitive), transit gateways/hub-and-spoke, VPN, Direct Connect/ExpressRoute/Interconnect, overlapping CIDR problems.
  • DNS: private hosted zones, resolver endpoints, split-horizon, health-checked routing policies (failover, latency, weighted, geolocation).
  • CDNs: edge caching, origin shielding, cache keys, TLS at the edge, signed URLs, WAF at the edge.
  • Service-to-service: service discovery, meshes, VPC Lattice, mTLS.
  • As code: Terraform/OpenTofu, CDK, Pulumi, Bicep modules for VPCs.

Numbers to remember

  • AWS reserves 5 addresses per subnet; ephemeral ports to allow in NACLs: 1024–65535.
  • NAT gateway: ~$0.045/hour + $0.045/GB (us-east-1); ~55,000 simultaneous connections per destination.
  • Lab: stateless NACL broke both directions until ephemeral ports were allowed; three overlapping /16s couldn't be connected; NAT for 20 TB/month cost ~$1,000.

Pitfalls

  • Overlapping CIDRs across VPCs, accounts and offices.
  • NACLs without ephemeral-port rules.
  • Databases in public subnets or with public IPs.
  • A single NAT gateway for all zones.
  • Large S3 or registry traffic through NAT instead of endpoints.
  • Security groups open to 0.0.0.0/0 on admin ports.

Glossary

  • CIDR: notation for an address block, e.g. 10.20.0.0/16.
  • Internet gateway: VPC edge for public traffic with 1:1 NAT.
  • NAT gateway: managed outbound-only address translation.
  • VPC endpoint: private path to a cloud service without the internet.
  • Transit gateway: a regional router connecting many VPCs and on-premises networks.
  • Ephemeral port: the temporary client-side port of a connection.