VPC Networking

System Design · Cloud Building Blocks · Intermediate · 22 min

Design a VPC with public and private subnets, route tables, NAT and firewalls, and trace exactly why a packet is allowed or dropped.

A gated campus: the address range is the property line, subnets are buildings, route tables are the signposts at each building's door, the internet gateway is the main gate, the NAT gateway is a mail room that sends letters out but accepts no visitors, and security guards stand at each office door.

The idea in everyday words

A company office building. The lobby (public subnet) has a reception desk (load balancer) that strangers can walk up to. The offices upstairs (private subnets) have no street door at all; staff can still send mail out through the mail room (NAT gateway). Each office has a guard (security group) who remembers who they let in, while each floor has a turnstile (NACL) that checks everyone in both directions and remembers nothing.

CIDR in plain words

An IPv4 address is 32 bits, written as 4 numbers from 0-255: 10.0.2.20. CIDR notation (10.0.0.0/16) means "the first 16 bits are fixed, the rest can vary". The number after the slash is the prefix length.

CIDR Fixed bits Addresses Typical use
10.0.0.0/16 16 65,536 A whole VPC
10.0.0.0/20 20 4,096 A large subnet
10.0.1.0/24 24 256 A normal subnet
10.0.1.0/28 28 16 The smallest subnet AWS allows
10.0.1.5/32 32 1 Exactly one host (common in firewall rules)
0.0.0.0/0 0 all of them "Anywhere" (default route)

Bigger prefix = smaller block. Each extra bit halves the block.

AWS reserves 5 addresses in every subnet (network address, VPC router, DNS, one for future use, broadcast), so a /24 gives you 251 usable IPs.

Plan ranges that don't overlap with other VPCs or your office network. Overlapping ranges can't be peered or connected later, and renumbering is painful.

import ipaddress
vpc = ipaddress.ip_network("10.0.0.0/16")
subnets = list(vpc.subnets(new_prefix=24))[:3]
print("VPC size:", vpc.num_addresses)
for s in subnets:
    print(s, "usable in AWS:", s.num_addresses - 5)
print(ipaddress.ip_address("10.0.2.20") in subnets[2])

Subnets, route tables and gateways

A VPC (Virtual Private Cloud) is your private network in one Region. A subnet is a slice of its CIDR that lives in one AZ.

Every subnet uses a route table: a list of destination CIDR → target. AWS picks the most specific match (longest prefix). Every table has a local route for the VPC's own CIDR, so subnets can always talk to each other.

Route table Destination Target Meaning
Public 10.0.0.0/16 local Inside the VPC
Public 0.0.0.0/0 igw-... Everything else → internet gateway
Private 10.0.0.0/16 local Inside the VPC
Private 0.0.0.0/0 nat-... Everything else → NAT gateway
  • Public subnet = its route table sends 0.0.0.0/0 to an internet gateway (IGW). Resources there can have public IPs.
  • Private subnet = no route to the IGW. Nothing on the internet can reach it directly.
  • NAT gateway = sits in a public subnet and lets private resources make outbound connections (download patches, call APIs) by swapping their private source IP for its public Elastic IP. Replies come back; new inbound connections can't. A classic zonal NAT gateway lives in one AZ, so production uses one per AZ (if that AZ fails, subnets routed through it lose outbound access). AWS has also added a regional NAT gateway option that spans AZs; exam questions still assume the zonal model, so check the VPC docs before relying on it.

Debugging rule: if traffic can't leave, look at the route table first. A firewall can't help if there is no path.

Security groups vs network ACLs

Security group (SG) Network ACL (NACL)
Attached to A network interface (instance, ALB, RDS, Lambda in VPC) A subnet
Memory Stateful: return traffic is allowed automatically Stateless: return traffic needs its own rule
Rules Allow only Allow and deny
Evaluation All rules together Lowest rule number first, first match wins; a final * rule denies anything unmatched
A new one you create No inbound rules, allows all outbound A new custom NACL denies all inbound and outbound until you add rules
The VPC's default one Also allows inbound from members of the same default SG The default NACL allows all traffic in and out

Stateful means the guard remembers "I let this connection in, so the reply may go out". Stateless means every packet is judged alone, including replies on ephemeral ports (the random high port, 1024-65535, the client used).

The best SG trick: a rule's source can be another security group. "Allow 5432 from sg-app" means "any instance wearing the sg-app badge", so it keeps working as instances come and go.

A typical 3-tier chain:

  • sg-alb: allow 443 from 0.0.0.0/0.
  • sg-app: allow 8080 from sg-alb.
  • sg-db: allow 5432 from sg-app.

Most teams keep NACLs at their defaults and do real filtering in security groups; NACLs are a coarse extra layer (for example, blocking a bad IP range for a whole subnet).

VPC endpoints and the 3-tier layout

VPC endpoints let private resources reach AWS services without the internet or a NAT:

  • Gateway endpoints for S3 and DynamoDB: a route-table entry; no hourly charge.
  • Interface endpoints (AWS PrivateLink) for most other services (SQS, Secrets Manager, ECR...): a private IP in your subnet.

They improve security (traffic stays on the AWS network) and save NAT data-processing costs.

The classic 3-tier VPC, repeated in 2-3 AZs:

VPC 10.0.0.0/16
  AZ a: public 10.0.1.0/24   (ALB node, NAT gateway)
        app    10.0.11.0/24  (ECS tasks / EC2, private)
        data   10.0.21.0/24  (RDS, ElastiCache, private)
  AZ b: public 10.0.2.0/24 | app 10.0.12.0/24 | data 10.0.22.0/24
  AZ c: public 10.0.3.0/24 | app 10.0.13.0/24 | data 10.0.23.0/24
Internet -> IGW -> ALB (public) -> app (private) -> RDS (private)
app -> NAT (same AZ) -> IGW -> internet      (outbound only)
app -> gateway endpoint -> S3 / DynamoDB      (no NAT needed)

Connecting many VPCs: VPC peering for a few pairs, Transit Gateway as a hub for many. Use VPC Flow Logs to see ACCEPT/REJECT records when debugging.

Other clouds: a GCP VPC is global with regional subnets, firewall rules and Cloud NAT; Azure uses VNets, Network Security Groups and NAT Gateway. Open source: Linux iptables/nftables and Kubernetes NetworkPolicies apply the same ideas.

Debugging 'it can't connect': a checklist

Walk the packet, hop by hop, in both directions:

  1. DNS: does the name resolve to the IP you expect (private vs public)?
  2. Route: does the source subnet's route table have a path to the destination? Longest prefix wins.
  3. Gateway: for internet traffic, is there an IGW (public) or NAT (private)? Does the instance have a public IP if it needs one?
  4. Security group (destination): does an inbound rule allow this port from this source (CIDR or SG)?
  5. Security group (source): does an outbound rule allow it? (Default allows all.)
  6. NACLs: on both subnets, inbound and outbound, including ephemeral return ports.
  7. The app: is it listening on that port and interface?

A security group never sends an error back. A blocked packet is simply dropped, so the client sees a timeout, not "connection refused". A fast "connection refused" usually means the network worked and nothing was listening.

Step by step

  1. Enter:

    A user at 203.0.113.7 hits the ALB's public IP on 443. The IGW maps it to the ALB's private IP 10.0.1.10 in the public subnet.

  2. Check ALB:

    Public NACL allows inbound 443; sg-alb allows 443 from 0.0.0.0/0 → accepted.

  3. Route to app:

    ALB opens a new connection to 10.0.2.20:8080. Route table: 10.0.0.0/16 (local) and 0.0.0.0/0 both match; /16 is longer → local.

  4. Check app SG:

    sg-app allows 8080 from sg-alb → accepted. If that rule is missing the packet is silently dropped and the ALB returns 504 after a timeout.

  5. Data tier:

    App connects to RDS 10.0.3.30:5432; sg-db allows 5432 from sg-app only. The reply needs no rule: SGs are stateful.

  6. Reply leaves:

    The response goes back to 203.0.113.7 on an ephemeral port (e.g. 51514). NACLs are stateless, so the public NACL needs an outbound rule for 1024-65535.

  7. Outbound via NAT:

    The app calls 198.51.100.9:443. Private route table: only 0.0.0.0/0 matches → NAT gateway, which swaps in its Elastic IP and sends it via the IGW.

Code example

def to_int(ip):
    a, b, c, d = (int(part) for part in ip.split("."))
    return ((a * 256 + b) * 256 + c) * 256 + d     # 4 bytes -> one 32-bit number


def ip_in_cidr(ip, cidr):
    base, bits = cidr.split("/")
    block = 2 ** (32 - int(bits))      # addresses in the block (host part)
    return to_int(ip) // block == to_int(base) // block   # same network part?


def route(table, dst):
    # longest-prefix match, exactly how a VPC route table picks a target
    matches = [(int(c.split("/")[1]), target) for c, target in table if ip_in_cidr(dst, c)]
    return max(matches)[1] if matches else "no route (drop)"

private_rt = [("10.0.0.0/16", "local"), ("0.0.0.0/0", "nat-gw"), ("10.1.0.0/16", "pcx-peering")]
for dst in ["10.0.3.30", "198.51.100.9", "10.1.4.7"]:
    print(f"{dst:>14} -> {route(private_rt, dst)}")

sg_db_inbound = [(5432, "10.0.2.0/24")]          # Postgres, only from the app subnet
for src in ["10.0.2.20", "10.0.1.10"]:
    ok = any(ip_in_cidr(src, cidr) and port == 5432 for port, cidr in sg_db_inbound)
    print(f"{src} -> RDS:5432", "ALLOW" if ok else "DROP (no matching rule)")

Complexity

  • Time: O(1): always 4 octets and a couple of divisions
  • Space: O(1)

Interview tips

  • Sketch the standard layout unprompted: public subnets for ALB and NAT, private app and data subnets, repeated across 2-3 AZs.

  • Explain stateful security groups vs stateless NACLs in one sentence each, and that SGs can reference other SGs.

  • Mention a (zonal) NAT gateway per AZ for availability, and gateway endpoints for S3/DynamoDB to cut NAT cost.

  • Know the defaults cold: a new SG has no inbound rules and allows all outbound; the default NACL allows everything; a new custom NACL denies everything until you add rules.

  • When asked to debug connectivity, walk the packet: DNS, route, gateway, SG in/out, NACL in/out, then the app.

  • Plan non-overlapping CIDRs so the VPC can later connect to other VPCs or on-prem via peering, Transit Gateway or VPN.

Challenge: Is This IP in the CIDR?

Write ip_in_cidr(ip, cidr) that returns True if the IPv4 address ip is inside the block cidr.

The block base/n contains every address whose first n bits equal the first n bits of base.

Examples:

  • ip_in_cidr("10.0.1.25", "10.0.0.0/16") → True
  • ip_in_cidr("10.0.16.1", "10.0.0.0/20") → False (a /20 covers 10.0.0.0 - 10.0.15.255)
  • ip_in_cidr("8.8.8.8", "0.0.0.0/0") → True
  • ip_in_cidr("10.0.0.1", "10.0.1.5/16") → True (the base can have host bits set: only its first 16 bits count, so this is really 10.0.0.0/16)

This is exactly the check a route table, security group or NACL rule does for every packet.

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Cloud Building Blocks

Previous: Storage: S3, EBS & EFS · Next: Serverless on AWS