Thuta Learning
AWS Advanced
Advanced NetworkingDevOpsAdvanced

VPC Design at Scale: CIDR Plans, Subnet Tiers and IPAM

AWS AdvancedLesson 545 min

What you'll walk away with

  • Design a hierarchical CIDR plan that never overlaps across accounts, regions and on-premises
  • Use Amazon VPC IPAM pools so teams allocate VPC ranges instead of typing them
  • Lay out public, private-app and private-data subnet tiers across multiple AZs
  • Choose between one NAT Gateway per AZ and a shared NAT Gateway with clear trade-offs
  • Add IPv6 with an egress-only internet gateway and turn on VPC Flow Logs

Explain it simply

Explain it simply

Think of your company's private IP space as land in a growing city. If every team builds its house on the same plot number, nobody can build a road between those houses later. CIDR planning is the city plan: before anyone builds, you hand out non-overlapping plots to every account, every region and every office network.

Inside each plot you lay out the streets in a fixed pattern. Public subnets face the internet, private-app subnets run your code, and private-data subnets hold databases with no internet route at all. You repeat that pattern in every Availability Zone, so losing one AZ removes only one copy of each street.

Amazon VPC IPAM is the land registry that hands out plots automatically, and VPC Flow Logs are the traffic cameras that show who actually drove where.

Problem → Why → Solution

The problem: everyone picked 10.0.0.0/16

In AWS Fundamentals you created a VPC and accepted 10.0.0.0/16. That is fine for one VPC. Now picture the same default in forty accounts: the payments VPC, the analytics VPC and the office network all use 10.0.0.0/16, because that is what the wizard suggested.

The day someone asks to connect them, you discover that VPC peering refuses overlapping CIDRs, a Transit Gateway cannot route to two networks with the same prefix, and a VPN to the office becomes ambiguous. The real fix is re-addressing: new subnets, migrated instances and databases, and every security group rule and firewall entry that mentions an IP rewritten.

what-went-wrong.sh
# Two teams, two accounts, the same "default" range
aws ec2 create-vpc --cidr-block 10.0.0.0/16   # payments account
aws ec2 create-vpc --cidr-block 10.0.0.0/16   # analytics account

# A year later someone tries to connect them
aws ec2 create-vpc-peering-connection \
  --vpc-id vpc-0a1b2c3d4e5f67890 \
  --peer-vpc-id vpc-0f9e8d7c6b5a43210 \
  --peer-owner-id 111122223333
# -> the peering connection ends in state "failed": overlapping CIDRs

Why this hurts so much

IP addressing is the one network decision you cannot change in place. A VPC's primary CIDR is fixed for its lifetime, and every connectivity option (peering, Transit Gateway, VPN, Direct Connect) needs unique routes. An hour of planning before the first VPC saves months of migration later.

Core concept: plan, tier, egress, visibility

Good VPC design at scale rests on four decisions that you make once and then automate: an address plan, a subnet layout, an egress model and visibility. Each one is cheap to get right on day one and expensive to fix after workloads move in.

CIDR block
A range of IP addresses written as base/prefix. 10.20.0.0/19 fixes the first 19 bits, which leaves 2^13 = 8,192 addresses. A smaller prefix number means a bigger range.

Address plan. Start from one supernet such as 10.0.0.0/8 and split it hierarchically: region, then environment, then VPC. A common shape gives each region a /12, each environment a /14 inside it, and each VPC a /19 or /20. Keep on-premises and partner ranges outside these blocks, and leave at least half of every level unallocated, because new regions and acquisitions always arrive sooner than planned.

Amazon VPC IPAM turns that plan into enforced pools. You create a top-level pool, regional child pools (each has a locale, which is its Region) and environment pools with allocation rules such as allowed netmask lengths and required tags. Teams then create a VPC from a pool instead of typing a CIDR, so overlaps cannot happen. Integrated with AWS Organizations, IPAM also discovers existing VPCs in member accounts and flags overlapping or non-compliant ranges.

Subnet layout. Inside each VPC, use the same three tiers in every AZ you run in, usually three AZs:

  • public: load balancers and NAT Gateways only; 0.0.0.0/0 routes to the internet gateway.
  • private-app: EC2, ECS tasks, Lambda ENIs, EKS pods; 0.0.0.0/0 routes to a NAT Gateway.
  • private-data: RDS, ElastiCache and similar; no internet route at all.

Size each tier by what lives there. Load balancers need few addresses, so public can be a /26. App subnets fill fastest, because every container task, Lambda ENI and EKS pod may take its own IP, so they get the largest blocks. AWS reserves five addresses in every subnet, which matters for small ones.

Egress model. A NAT Gateway lives in one AZ. With one NAT per AZ, each AZ's private subnets use their local NAT, so an AZ failure removes only that AZ's egress and internet-bound traffic never pays cross-AZ data transfer. One shared NAT saves hourly charges, but if its AZ fails, every private subnet loses internet access, and traffic from the other AZs pays cross-AZ transfer on top of NAT data processing.

IPv6 and visibility. A VPC can get an Amazon-provided /56 and each subnet a /64. IPv6 addresses are globally routable, so for outbound-only access you route ::/0 to an egress-only internet gateway, which allows connections your instances start and blocks ones that start outside. Finally, enable VPC Flow Logs from day one: they record accepted and rejected flows (metadata, not packet contents) and are your evidence when a route or security group is wrong.

text
ONE VPC, THREE TIERS, THREE AZS
-------------------------------
                       VPC 10.20.0.0/19
   +------------------+------------------+------------------+
   |   us-east-1a     |   us-east-1b     |   us-east-1c     |
   |------------------|------------------|------------------|
   | public /26       | public /26       | public /26       |
   |  [ALB] [NAT-a]   |  [ALB] [NAT-b]   |  [ALB] [NAT-c]   |
   |------------------|------------------|------------------|
   | private-app /22  | private-app /22  | private-app /22  |
   |  0/0 -> NAT-a    |  0/0 -> NAT-b    |  0/0 -> NAT-c    |
   |------------------|------------------|------------------|
   | private-data /24 | private-data /24 | private-data /24 |
   |  local only      |  local only      |  local only      |
   +------------------+------------------+------------------+
        public route tables: 0/0 -> internet gateway
Mental model
  1. Reserve one supernet
  2. Split: region > env > VPC
  3. Allocate VPCs from IPAM pools
  4. Same 3 tiers in every AZ
  5. Local NAT per AZ, Flow Logs on

Every later lesson in this chapter (Transit Gateway, endpoints, hybrid) assumes this step is done: unique ranges are what make routing possible at all.

Pattern: an IPAM pool hierarchy

ipam-pools.sh
# 1. One IPAM for the organization, operating in the Regions you use
IPAM_ID=$(aws ec2 create-ipam --description "org IPAM" \
  --operating-regions RegionName=us-east-1 RegionName=eu-west-1 \
  --query 'Ipam.IpamId' --output text)
SCOPE_ID=$(aws ec2 describe-ipams --ipam-ids $IPAM_ID \
  --query 'Ipams[0].PrivateDefaultScopeId' --output text)

# 2. Top-level pool owns the whole AWS supernet
TOP_POOL=$(aws ec2 create-ipam-pool --ipam-scope-id $SCOPE_ID \
  --address-family ipv4 --description "aws-all" \
  --query 'IpamPool.IpamPoolId' --output text)
aws ec2 provision-ipam-pool-cidr --ipam-pool-id $TOP_POOL --cidr 10.0.0.0/8

# 3. Regional pool (locale = Region) with allocation rules for VPCs
US_POOL=$(aws ec2 create-ipam-pool --ipam-scope-id $SCOPE_ID \
  --address-family ipv4 --source-ipam-pool-id $TOP_POOL \
  --locale us-east-1 --description "us-east-1" \
  --allocation-min-netmask-length 16 \
  --allocation-max-netmask-length 22 \
  --allocation-default-netmask-length 19 \
  --query 'IpamPool.IpamPoolId' --output text)
aws ec2 provision-ipam-pool-cidr --ipam-pool-id $US_POOL --cidr 10.16.0.0/12

# 4. Teams ask for a size, never a specific range
aws ec2 create-vpc --ipv4-ipam-pool-id $US_POOL --ipv4-netmask-length 19

The hierarchy mirrors your plan: one IPAM, one top-level pool, one pool per Region, and optionally one per environment below that. Provisioning a CIDR into a pool is asynchronous, so real scripts wait until the pool CIDR state is provisioned before allocating from it. The final create-vpc call names a pool and a netmask length, and IPAM picks the next free range.

Working example: plan the subnets before you build

Before creating anything, compute the layout. This small script carves a /19 into the three tiers across three AZs, biggest tier first so every block stays aligned, subtracts the five addresses AWS reserves, and reports what is left for growth. Teams often keep a script like this, or IPAM itself, as the single source of truth instead of a spreadsheet that drifts.

plan_subnets.py
import ipaddress

VPC_CIDR = ipaddress.ip_network("10.20.0.0/19")
AZS = ["us-east-1a", "us-east-1b", "us-east-1c"]
# (tier, prefix length per AZ) - allocate the biggest tier first so
# every block stays aligned and the leftover space is contiguous
TIERS = [("private-app", 22), ("private-data", 24), ("public", 26)]
AWS_RESERVED = 5  # AWS keeps the first four and the last IP of each subnet


def allocate(free, prefix):
    """Take the lowest free block that can hold a /prefix subnet."""
    block = next(b for b in free if b.prefixlen <= prefix)
    free.remove(block)
    subnet = next(block.subnets(new_prefix=prefix))
    free.extend(block.address_exclude(subnet))
    free.sort()
    return subnet


def plan(vpc, azs, tiers):
    free = [vpc]
    rows = []
    for tier, prefix in tiers:
        for az in azs:
            subnet = allocate(free, prefix)
            rows.append((tier, az, subnet, subnet.num_addresses - AWS_RESERVED))
    return rows, free


rows, spare = plan(VPC_CIDR, AZS, TIERS)
print(f"VPC {VPC_CIDR} ({VPC_CIDR.num_addresses} addresses), {len(AZS)} AZs")
for tier, az, subnet, usable in rows:
    print(f"{tier:<13} {az:<11} {str(subnet):<16} {usable:>5} usable")
spare_total = sum(n.num_addresses for n in spare)
print(f"spare: {', '.join(map(str, spare))} ({spare_total} addresses)")

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. Biggest tier firstTIERS = [("private-app", 22), ("private-data", 24), ("public", 26)]

    Allocating /22s before /24s before /26s keeps each block on its natural boundary, so no space is wasted on alignment gaps and the leftover range stays contiguous.

  2. Pick a free blockblock = next(b for b in free if b.prefixlen <= prefix)

    The free list is kept sorted, so this takes the lowest free block big enough to hold the requested prefix. A block with a smaller prefix number is a bigger block.

  3. Return the remainderfree.extend(block.address_exclude(subnet))

    address_exclude splits what is left of the block into the largest possible CIDRs, which go back into the free list. That is exactly how IPAM tracks unallocated space.

  4. Usable addressessubnet.num_addresses - AWS_RESERVED

    AWS reserves the network address, the VPC router, the DNS address, one for future use and the broadcast address. A /28 therefore gives 11 usable IPs, not 16.

You should see
VPC 10.20.0.0/19 (8192 addresses), 3 AZs
private-app   us-east-1a  10.20.0.0/22      1019 usable
private-app   us-east-1b  10.20.4.0/22      1019 usable
private-app   us-east-1c  10.20.8.0/22      1019 usable
private-data  us-east-1a  10.20.12.0/24      251 usable
private-data  us-east-1b  10.20.13.0/24      251 usable
private-data  us-east-1c  10.20.14.0/24      251 usable
public        us-east-1a  10.20.15.0/26       59 usable
public        us-east-1b  10.20.15.64/26      59 usable
public        us-east-1c  10.20.15.128/26     59 usable
spare: 10.20.15.192/26, 10.20.16.0/20 (4160 addresses)

Build the same layout with CDK

The CDK Vpc construct allocates subnets in the order you list them, one per AZ, which reproduces the plan above exactly. Setting natGateways to the number of AZs gives each AZ its own NAT Gateway and a route table pointing at it, and addFlowLog wires Flow Logs to an S3 bucket.

network-stack.ts
import { App, Stack, StackProps } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as s3 from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";

class NetworkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, "AppVpc", {
      ipAddresses: ec2.IpAddresses.cidr("10.20.0.0/19"),
      availabilityZones: ["us-east-1a", "us-east-1b", "us-east-1c"],
      natGateways: 3, // one NAT Gateway per AZ
      subnetConfiguration: [
        {
          name: "private-app",
          subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
          cidrMask: 22,
        },
        {
          name: "private-data",
          subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
          cidrMask: 24,
        },
        { name: "public", subnetType: ec2.SubnetType.PUBLIC, cidrMask: 26 },
      ],
    });

    const flowLogBucket = new s3.Bucket(this, "FlowLogs", {
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      enforceSSL: true,
    });
    vpc.addFlowLog("ToS3", {
      destination: ec2.FlowLogDestination.toS3(flowLogBucket),
      trafficType: ec2.FlowLogTrafficType.ALL,
      maxAggregationInterval: ec2.FlowLogMaxAggregationInterval.ONE_MINUTE,
    });
  }
}

const app = new App();
new NetworkStack(app, "NetworkStack", {
  env: { account: "111122223333", region: "us-east-1" },
});
app.synth();

Cheaper dev, resilient prod

Make natGateways a parameter: 1 in dev, where an AZ outage is an acceptable risk, and one per AZ in production. Code review then shows the cost and resilience choice explicitly instead of hiding it in a default.

IPv6 egress and Flow Logs from the CLI

Adding IPv6 to an existing VPC is additive: you associate an Amazon-provided block, give subnets /64s, and add a ::/0 route. For private-app subnets that route goes to an egress-only internet gateway, never to the regular internet gateway, otherwise every instance with an IPv6 address would be reachable from the internet if its security group allowed it.

For Flow Logs, a custom format with flow-direction and traffic-path fields makes it much easier to answer the questions you actually ask, such as whether traffic left through the NAT Gateway, the internet gateway or a Transit Gateway.

ipv6-and-flow-logs.sh
VPC_ID=vpc-0a1b2c3d4e5f67890
APP_RT_ID=rtb-0123456789abcdef0

# IPv6: Amazon-provided /56 for the VPC, egress-only for private subnets
aws ec2 associate-vpc-cidr-block --vpc-id $VPC_ID \
  --amazon-provided-ipv6-cidr-block
EIGW_ID=$(aws ec2 create-egress-only-internet-gateway --vpc-id $VPC_ID \
  --query 'EgressOnlyInternetGateway.EgressOnlyInternetGatewayId' \
  --output text)
aws ec2 create-route --route-table-id $APP_RT_ID \
  --destination-ipv6-cidr-block ::/0 \
  --egress-only-internet-gateway-id $EIGW_ID

# Flow Logs for the whole VPC, 1-minute aggregation, custom fields
FMT='${vpc-id} ${subnet-id} ${srcaddr} ${dstaddr} ${dstport}'
FMT="$FMT"' ${action} ${flow-direction} ${traffic-path}'
aws ec2 create-flow-logs \
  --resource-type VPC --resource-ids $VPC_ID \
  --traffic-type ALL \
  --log-destination-type s3 \
  --log-destination arn:aws:s3:::flow-logs-111122223333/network/ \
  --max-aggregation-interval 60 \
  --log-format "$FMT"

In production

In production

In a typical multi-account organization, a central network team owns IPAM in a delegated administrator account. The account vending process creates every new workload VPC from the right regional and environment pool, so application teams never see or choose a CIDR. On-premises ranges are documented as a separate reserved block, and IPAM's compliance view is checked whenever a VPC is created outside the pipeline.

What breaks first at scale is usually the app tier, not the VPC. EKS clusters give every pod a VPC IP by default, and Lambda functions in a VPC use ENIs in your subnets, so a /24 per AZ that looked generous runs out during a traffic spike. Teams respond by sizing app subnets as /21 or /22, or by adding a secondary CIDR from the 100.64.0.0/10 range for pods.

Flow Logs normally land in a central log archive account as Parquet files in S3 and are queried with Athena during incidents. Many teams also add dedicated /28 subnets per AZ for Transit Gateway attachments, which you will meet in the next lesson, so attachment ENIs never compete with workloads for addresses.

Common mistakes

Common mistakes

Mistake 1: the same CIDR in every account

Letting each team pick 10.0.0.0/16, or running production in the default VPC (172.31.0.0/16 in every Region), guarantees overlaps. Nothing breaks until the day you need to connect two networks, and then the only cure is re-addressing live systems. Allocate from IPAM from the very first VPC.

Mistake 2: one NAT Gateway for a multi-AZ production VPC

Spreading instances across three AZs and then routing all of them through one NAT Gateway quietly reintroduces a single point of failure: when that AZ has trouble, every private subnet loses outbound access, including calls to third-party APIs and package repositories. You also pay cross-AZ transfer for two thirds of your egress.

Mistake 3: undersized app subnets

A /24 per AZ looks large until containers, Lambda ENIs and EKS pods each take an address. Subnets cannot be resized after creation, so plan app tiers for peak scale plus growth and keep spare space in the VPC for new subnets.

Best practices

Best practices

  • Write the address plan down (supernet, per-Region and per-environment blocks) and encode it in IPAM pools with allocation rules.
  • Keep public subnets for load balancers and NAT Gateways only; nothing else needs a public IP.
  • Give private-data subnets no default route; use VPC endpoints (covered later in this chapter) for AWS API access.
  • Use one NAT Gateway per AZ in production and route each AZ to its local NAT.
  • Enable Flow Logs at VPC level for every VPC and centralize them in a log archive account.

💰 Cost & Cleanup

VPCs, subnets, route tables and egress-only internet gateways have no hourly charge. NAT Gateways are billed per hour each plus per GB processed, so three NATs cost three times the hourly part; this is the main cost of the lab. Public IPv4 addresses (including the Elastic IPs on NAT Gateways) are billed hourly. IPAM's Free Tier covers basic use, while the Advanced Tier is billed per active IP address managed. Flow Logs charge for log ingestion and storage. Run the CDK stack only as long as you need it and delete everything afterwards; check the pricing pages for current rates.

Clean up when you are done

bash
# CDK stack: VPC, subnets, 3 NAT Gateways, Flow Logs bucket
cdk destroy NetworkStack

# VPC created from the IPAM pool, then the IPAM and all its pools
aws ec2 delete-vpc --vpc-id $VPC_ID
aws ec2 delete-ipam --ipam-id $IPAM_ID --cascade

Mini challenge

Mini challenge: grow the plan

The business is adding a fourth AZ, and the network team wants a dedicated /28 per AZ for Transit Gateway attachments. Extend the planner and check that everything still fits in the /19 with room to spare.

  • Add us-east-1d to the AZ list
  • Add a tgw-attach tier with a /28 per AZ, allocated last
  • Print the plan and the remaining spare space

Expected: Sixteen subnets: four /22 app subnets (10.20.0.0 to 10.20.12.0), four /24 data subnets, four /26 public subnets in 10.20.20.0/24, four /28 attachment subnets in 10.20.21.0/26 with 11 usable IPs each, and 2752 spare addresses.

Show hint

Only the AZS and TIERS constants change. Keep the tiers ordered from biggest to smallest prefix so alignment still works.

Show solution
plan_subnets_v2.py
import ipaddress

VPC_CIDR = ipaddress.ip_network("10.20.0.0/19")
AZS = ["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d"]
# (tier, prefix length per AZ) - allocate the biggest tier first so
# every block stays aligned and the leftover space is contiguous
TIERS = [
    ("private-app", 22), ("private-data", 24),
    ("public", 26), ("tgw-attach", 28),
]
AWS_RESERVED = 5  # AWS keeps the first four and the last IP of each subnet


def allocate(free, prefix):
    """Take the lowest free block that can hold a /prefix subnet."""
    block = next(b for b in free if b.prefixlen <= prefix)
    free.remove(block)
    subnet = next(block.subnets(new_prefix=prefix))
    free.extend(block.address_exclude(subnet))
    free.sort()
    return subnet


def plan(vpc, azs, tiers):
    free = [vpc]
    rows = []
    for tier, prefix in tiers:
        for az in azs:
            subnet = allocate(free, prefix)
            rows.append((tier, az, subnet, subnet.num_addresses - AWS_RESERVED))
    return rows, free


rows, spare = plan(VPC_CIDR, AZS, TIERS)
print(f"VPC {VPC_CIDR} ({VPC_CIDR.num_addresses} addresses), {len(AZS)} AZs")
for tier, az, subnet, usable in rows:
    print(f"{tier:<13} {az:<11} {str(subnet):<16} {usable:>5} usable")
spare_total = sum(n.num_addresses for n in spare)
print(f"spare: {', '.join(map(str, spare))} ({spare_total} addresses)")

Quick quiz 1 / 3

Two VPCs in different accounts both use 10.0.0.0/16 and now must talk to each other. What is true?

Quick quiz 2 / 3

A production VPC spans three AZs but has one NAT Gateway in us-east-1a. us-east-1a has an outage. What happens?

Quick quiz 3 / 3

Private-app instances have IPv6 addresses and must reach IPv6 APIs on the internet without accepting inbound connections. What do you add?

What to remember

  • Overlapping CIDRs block peering, Transit Gateway and VPN routing; the cure is painful re-addressing.
  • Plan a hierarchy (supernet > Region > environment > VPC) and enforce it with IPAM pools.
  • Use public, private-app and private-data tiers in every AZ, sized by what lives in them.
  • One NAT Gateway per AZ trades hourly cost for resilience and no cross-AZ egress charges.
  • Use an egress-only internet gateway for IPv6 outbound and turn on Flow Logs everywhere.

Amazon VPC: VPC CIDR blocks — AWS Documentation

What is IPAM? — AWS Documentation

Logging IP traffic using VPC Flow Logs — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

VPC Design at Scale: CIDR Plans, Subnet Tiers and IPAM | Thuta Learning