Lesson 2: Networking 101, CIDR Math & Cloud Security Boundaries
๐ง The Concept (Explain Like Iโm 5)
Imagine the global internet as an international shipping and postal logistics network:
- IP Address (IPv4): The unique physical street address of an office building (e.g.,
192.168.1.50or54.239.28.85). - Packets: Standardized cardboard envelopes containing a slice of data. Every envelope has a Sender Address (Source IP), a Delivery Address (Destination IP), and the Cargo (Payload).
- Port Number: The specific room or desk number inside that building:
- Port
80: The public lobby information counter (HTTP Web Traffic). - Port
443: The encrypted, armored security vault entrance (HTTPS). - Port
22: The locked management server room backdoor (SSH). - Port
53: The building phone directory assistance (DNS).
- Port
- Router: The regional sorting warehouse that reads the destination city on each envelope and forwards it along the fastest highway.
- DNS (Domain Name System): The global contact list that translates human-friendly company names (
api.stripe.com) into physical postal coordinates (54.239.28.85).
๐ข The Enterprise Context: Why Platform Architects Care
You cannot architect enterprise clouds or troubleshoot Kubernetes without deep networking mastery:
- The Subnet Exhaustion Catastrophe: In AWS Elastic Kubernetes Service (EKS), each Pod consumes a real private IP address from your AWS VPC subnet via the AWS VPC CNI. If you pick a
/24subnet (251 usable IPs), a cluster scaling to 300 pods will exhaust the subnet, causing all new deployments and autoscaling to crash! - The Overlapping CIDR Trap: If Team A builds a VPC on
10.0.0.0/16and Team B builds a VPC on10.0.0.0/16, they cannot be connected via Transit Gateway or VPC Peering without complex NAT proxies. Companies have spent millions of dollars re-architecting networks due to poor initial IP planning. - Security Perimeter Isolation: Production databases and internal payment APIs must live in private subnets with zero direct internet access. Misconfigured route tables or security groups can expose your companyโs core crown jewels directly to public internet port scanners in seconds.
๐บ๏ธ Visual Architecture: The OSI Model vs. Modern Cloud Architecture
The 7-Layer Open Systems Interconnection (OSI) model standardizes network communication. Platform architects primarily engineer and troubleshoot at Layer 3 (IP), Layer 4 (TCP/UDP), and Layer 7 (HTTP/DNS):
flowchart LR
subgraph OSIModel ["OSI 7-Layer Reference Model"]
L7["<b>Layer 7: Application</b><br/>(HTTP, HTTPS, gRPC, DNS)"]
L4["<b>Layer 4: Transport</b><br/>(TCP, UDP, Ports, Flags)"]
L3["<b>Layer 3: Network</b><br/>(IPv4, IPv6, ICMP, Routing)"]
L2["<b>Layer 2: Data Link</b><br/>(MAC Addresses, Ethernet)"]
L1["<b>Layer 1: Physical</b><br/>(Fiber Optics, Radio)"]
end
subgraph CloudMapping ["Platform Architect Cloud Mapping"]
T7["AWS ALB, Ingress Controllers, Envoy, Cloudflare"]
T4["AWS NLB, Security Groups, Cilium L4 Filter"]
T3["VPCs, Subnets, Route Tables, Transit Gateway"]
T2["AWS VPC CNI, veth pairs, Hyperplane Fabric"]
T1["AWS Nitro Hardware, Physical Data Center Cables"]
end
L7 --- T7
L4 --- T4
L3 --- T3
L2 --- T2
L1 --- T1
๐ฆ Packet Travel: The TCP 3-Way Handshake & Connection Teardown
Reliable transport on the web is governed by TCP (Transmission Control Protocol). Before a client can transmit a single byte of HTTP data, it must establish a stateful connection via the 3-Way Handshake:
sequenceDiagram
autonumber
actor Client as ๐ป Client (Pod / Browser)
participant Server as ๐ฅ๏ธ Target Microservice (Port 443)
Note over Client,Server: Phase 1: The TCP 3-Way Handshake (L4)
Client->>Server: 1. SYN (Synchronize - Seq=1000)
Server-->>Client: 2. SYN-ACK (Acknowledge - Seq=5000, Ack=1001)
Client->>Server: 3. ACK (Acknowledge - Seq=1001, Ack=5001)
Note over Client,Server: Phase 2: TLS 1.3 Encryption & Application Data (L7)
Client->>Server: TLS ClientHello + Key Exchange
Server-->>Client: TLS ServerHello + Encrypted Session Established
Client->>Server: HTTP GET /api/v1/orders
Server-->>Client: 200 OK + JSON Payload
Note over Client,Server: Phase 3: The TCP Connection Teardown
Client->>Server: FIN (Finish connection)
Server-->>Client: ACK
Server->>Client: FIN
Client-->>Server: ACK (Connection Closed)
TCP vs. UDP: When to Use Which
- TCP (Connection-Oriented, Reliable): Guarantees that every packet arrives in exact sequence. If a packet is lost in transit, TCP automatically detects the missing sequence number and retransmits it. Used for: HTTP/REST, gRPC, databases (Postgres/MySQL), SSH.
- UDP (Connectionless, Low-Latency): โFire-and-forgetโ. Packets are transmitted with zero handshake and zero retransmission. Used for: DNS lookups, video streaming, VoIP, and modern HTTP/3 (QUIC).
๐งฎ Subnetting & CIDR Math Demystified
An IPv4 address is a 32-bit binary integer represented as 4 decimal octets separated by dots: ๐ IP: 192.168.1.50 โบ 11000000 . 10101000 . 00000001 . 00110010
What Does the Slash (/) Mean?
The CIDR (Classless Inter-Domain Routing) Prefix indicates how many bits are locked to identify the Network. The remaining bits identify individual Hosts (machines/pods).
๐ Total IP Addresses = 2^(32 - Prefix)
CIDR Prefix Locked Net Bits Host Bits Total IP Count Usable AWS IPs* Enterprise Cloud Use Case
--------------------------------------------------------------------------------------------------------
/16 16 bits 16 bits 65,536 65,531 Standard Enterprise VPC (e.g. 10.100.0.0/16)
/20 20 bits 12 bits 4,096 4,091 Large EKS Production Workload Subnet
/24 24 bits 8 bits 256 251 Standard Microservice Subnet (e.g. 10.100.1.0/24)
/28 28 bits 4 bits 16 11 Transit Gateway Subnet, Bastion Host
/32 32 bits 0 bits 1 1 Single host / Specific firewall whitelist
Real-Time Terraform Configuration (cidrsubnet Automation)
Cloud architects automate CIDR subnet slicing directly in Terraform using the built-in cidrsubnet() function:
# Automated CIDR Slicing for Multi-AZ EKS Subnets
resource "aws_vpc" "enterprise" {
cidr_block = "10.100.0.0/16" # 65,536 addresses
enable_dns_hostnames = true
}
# Automatically carve three /20 subnets (4,096 IPs each) across 3 AZs:
resource "aws_subnet" "eks_workloads" {
count = 3
vpc_id = aws_vpc.enterprise.id
# cidrsubnet(prefix, newbits, netnum): 16 + 4 = /20
cidr_block = cidrsubnet(aws_vpc.enterprise.cidr_block, 4, count.index)
availability_zone = element(["us-east-1a", "us-east-1b", "us-east-1c"], count.index)
tags = {
Name = "eks-workload-subnet-az-${count.index + 1}"
}
}
The 5 Reserved IP Addresses in AWS Subnets
In standard on-premises networking, only 2 IPs are reserved per subnet (Network ID and Broadcast). In every AWS VPC subnet, AWS reserves exactly 5 IP addresses:
If your subnet CIDR is 10.0.1.0/24:
10.0.1.0: Network Address (identifies the subnet wire).10.0.1.1: VPC Router Address (default gateway).10.0.1.2: Amazon-Provided DNS (Route 53 Resolver) (alwaysVPC base + 2).10.0.1.3: Reserved by AWS for future functionality.10.0.1.255: Network Broadcast Address (AWS does not support broadcast, but reserves the address).
๐ Step-by-Step Subnet Math: Dividing an Enterprise VPC
Scenario
Your enterprise allocates 10.50.0.0/16 for a new Production VPC. You need to divide this space into 4 equal subnets across Availability Zones.
Step 1: Calculate the New Prefix
- To create 4 subnets: 4 = 2^2. You must borrow 2 additional bits from the host portion.
- New Prefix: 16 + 2 = /18.
- IPs per subnet: 2^(32 - 18) = 2^14 = 16,384 total IPs (16,379 usable in AWS).
Step 2: Calculate the Subnet Boundaries
Each subnet spans 16,384 IP addresses (16,384 / 256 = 64 in the third octet):
| Subnet Name | Network CIDR | Usable AWS IP Range | Broadcast Address | Availability Zone |
|---|---|---|---|---|
| Subnet A | 10.50.0.0/18 |
10.50.0.4 โ 10.50.63.254 |
10.50.63.255 |
us-east-1a |
| Subnet B | 10.50.64.0/18 |
10.50.64.4 โ 10.50.127.254 |
10.50.127.255 |
us-east-1b |
| Subnet C | 10.50.128.0/18 |
10.50.128.4 โ 10.50.191.254 |
10.50.191.255 |
us-east-1c |
| Subnet D | 10.50.192.0/18 |
10.50.192.4 โ 10.50.255.254 |
10.50.255.255 |
Spare / DR |
๐ก๏ธ Public vs. Private Subnets: The Ingress/Egress Blueprint
What makes a subnet โPublicโ vs. โPrivateโ? In AWS, subnets are identical by default. Their route table configuration defines their identity:
flowchart TD
Internet(("๐ Public Internet")) <--> IGW["Internet Gateway (IGW)"]
subgraph PublicSubnet ["Public Subnet (10.0.1.0/24)"]
NAT["NAT Gateway (Public Elastic IP)"]
ALB["Application Load Balancer"]
end
subgraph PrivateSubnet ["Private Subnet (10.0.2.0/24)"]
App["EKS Worker Node / Microservice"]
end
subgraph DatabaseSubnet ["Isolated Database Subnet (10.0.3.0/24)"]
DB[("RDS PostgreSQL Database")]
end
IGW <--> ALB
IGW <--> NAT
App -->|"Outbound traffic: 0.0.0.0/0"| NAT
ALB -->|"Inbound requests: :8080"| App
App -->|"TCP :5432"| DB
Route Table Architecture
- Public Subnet Route Table:
- Local:
10.0.0.0/16โlocal - Default Route:
0.0.0.0/0โigw-xxxxxxxx(Internet Gateway)
- Local:
- Private Subnet Route Table (App Tier):
- Local:
10.0.0.0/16โlocal - Default Route:
0.0.0.0/0โnat-xxxxxxxx(NAT Gateway in Public Subnet) - Result: Can download software updates from the internet, but the public internet cannot initiate inbound connections!
- Local:
- Isolated Database Subnet Route Table:
- Local:
10.0.0.0/16โlocal - Zero internet routes! Completely unreachable from the outside world.
- Local:
๐ Security Groups vs. Network ACLs (NACLs)
One of the most critical cloud security concepts and frequent interview questions:
flowchart LR
Client["Client Packet"] --> NACL["<b>Network ACL (Stateless)</b><br/>โข Subnet boundary<br/>โข Numbered rules (100, 200)<br/>โข Explicit Allow & Deny"]
NACL --> SG["<b>Security Group (Stateful)</b><br/>โข ENI / Instance boundary<br/>โข Allow rules only<br/>โข Automated return traffic"]
SG --> Instance["EC2 Host / Pod"]
| Security Dimension | Security Groups (SG) | Network Access Control Lists (NACL) |
|---|---|---|
| Operating Layer | Layer 4 (Instance / ENI Level) | Layer 3/4 (Subnet Boundary Level) |
| Statefulness | Stateful: If an inbound request is allowed, the outbound response is automatically allowed, regardless of outbound rules! | Stateless: Return traffic must be explicitly permitted by outbound rules (including ephemeral ports 1024-65535)! |
| Rule Types | Allow rules only (implicit deny) | Both Allow and Deny rules |
| Rule Order | All rules evaluated simultaneously | Evaluated in strict numerical order (Rule 100 before Rule 200) |
| Primary Use Case | Day-to-day workload firewalling (e.g. Allow port 443 from ALB) | Coarse subnet-level blacklisting (e.g. Block known malicious CIDR block) |
๐ ๏ธ Essential Network Troubleshooting Toolkit
# 1. Test Layer 3 Connectivity (ICMP ping)
ping -c 4 8.8.8.8
# 2. Check Layer 7 DNS Resolution & Query Paths
dig +trace api.stripe.com
nslookup internal.corp.local 10.0.0.2
# 3. Test Layer 4 TCP Port Reachability (Without payload)
nc -zv -w 3 10.0.2.50 5432
# Output: Connection to 10.0.2.50 port 5432 [tcp/postgresql] succeeded!
# 4. Inspect Full Layer 7 HTTP Headers, TLS Handshake & Timings
curl -Iv --trace-time https://api.enterprise.corp
# 5. Trace Route Hops Across Network Gateways
traceroute -n -T -p 443 10.0.5.12
๐จ Real-World Troubleshooting & Tricky Production Scenarios
Scenario 1: AWS NAT Gateway SNAT Port Exhaustion
- Symptom: During peak traffic, microservices in private subnets querying a single external SaaS API (e.g.
api.twilio.com) experience intermittent 30-second connection timeouts, while internal traffic between pods remains fast. - Under-the-Hood Root Cause: A single AWS NAT Gateway Elastic IP supports a maximum of 55,000 concurrent source ports (SNAT ports) to a unique destination IP and destination port tuple. When 100 pods concurrently query the same external API without HTTP keep-alive connection reuse, the NAT Gateway exhausts its source port pool. AWS CloudWatch metric
ErrorPortAllocationspikes above zero, and new connections are dropped! - Triage & Remediation Runbook:
# 1. Check NAT Gateway ErrorPortAllocation in AWS CloudWatch aws cloudwatch get-metric-data --metric-data-queries '[{ "Id": "m1", "MetricStat": { "Metric": { "Namespace": "AWS/NATGateway", "MetricName": "ErrorPortAllocation", "Dimensions": [{"Name": "NatGatewayId", "Value": "nat-0123456789abcdef0"}] }, "Period": 60, "Stat": "Sum" } }]' --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ) --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) # 2. Immediate Remediation: Associate secondary Elastic IPs to the NAT Gateway (up to 8 IPs) aws ec2 associate-nat-gateway-address \ --nat-gateway-id nat-0123456789abcdef0 \ --allocation-ids eipalloc-0123456789abcdef0 # 3. Permanent Architectural Fix: Mandate HTTP Connection Pooling / Keep-Alive in app clients
Scenario 2: Ephemeral Port Exhaustion & TIME_WAIT Socket Accumulation
- Symptom: A high-throughput proxy or API gateway pod suddenly stops accepting connections with:
cannot assign requested address (errno 99: EADDRNOTAVAIL). - Under-the-Hood Root Cause: When a client closes a TCP connection, the socket enters the
TIME_WAITstate for 2 ร MSL (Maximum Segment Lifetime = 60 seconds) to ensure delayed in-flight packets do not corrupt subsequent connections. Under high connection churning, all 28,231 ephemeral ports (32768-60999) become tied up inTIME_WAIT. - Triage & Fix:
# 1. Inspect count of sockets in TIME_WAIT state ss -tan state time-wait | wc -l # 2. Check ephemeral port range sysctl net.ipv4.ip_local_port_range # 3. Enable safe TIME_WAIT socket reuse for outbound connections sudo sysctl -w net.ipv4.tcp_tw_reuse=1 # 4. Expand ephemeral port range sudo sysctl -w net.ipv4.ip_local_port_range="1024 65535"
๐ Knowledge Check & Real-World Interview Scenarios
A team deploys an AWS EKS cluster across two /24 private subnets (2 ร 251 = 502 usable IPs). They run 10 EC2 worker nodes running 35 pods each. When an automated scale-up event attempts to launch 200 additional pods, the pods get stuck indefinitely in ContainerCreating with FailedCreatePodSandBox: no IP addresses available in subnet.
Calculate the exact IP consumption on the subnet and explain why the cluster ran out of addresses. What is the enterprise solution?
โ Answer & Explanation
The Calculation:
- In AWS EKS using the AWS VPC CNI, each Worker Node allocates an Elastic Network Interface (ENI) and secondary private IP addresses for every single Pod.
- 10 worker nodes running 35 pods each consume 10 (node IPs) + (10 ร 35 pod IPs) = 360 IP addresses.
- Furthermore, the CNIโs
ipamddaemon maintains a โwarm poolโ of spare pre-allocated IPs (typically 3โ5 per node), consuming an additional 50 IPs. Total in-use IPs โ 410. - When 200 new pods are scheduled, they require 200 IPs. However, only 502 - 410 = 92 IPs remain.
- The subnet is completely exhausted!
The Enterprise Solution:
- Secondary CIDR Space: Attach a non-routable carrier-grade NAT block (
100.64.0.0/16) to the VPC specifically for Pods, giving the cluster 65,000+ IPs without consuming corporate10.x.x.xspace. - Prefix Delegation: Enable
ENABLE_PREFIX_DELEGATION=trueinaws-nodeso AWS allocates/28blocks (16 IPs) instead of individual/32IPs.
An engineer configures a custom Network ACL on a private subnet. They add an Inbound Rule allowing Port 443 (HTTPS) from 0.0.0.0/0, and an Outbound Rule allowing Port 443 to 0.0.0.0/0.
When an EC2 instance in that subnet attempts to execute curl https://api.github.com, the request hangs and times out. However, if they execute the same test using a Security Group, it works instantly.
Why did the Network ACL block the connection while the Security Group succeeded?
โ Answer & Explanation
The Mechanism (Stateless vs Stateful):
- Security Groups are Stateful: When the EC2 instance initiates an outbound connection on port 443, the Security Group automatically recognizes the incoming response packets and permits them back in, regardless of inbound rules.
- Network ACLs are Stateless: When the EC2 instance connects to GitHub, the operating system chooses a random Ephemeral Port (typically
32768โ60999on Linux) as the client source port. - The outbound request reaches GitHub on destination port 443 (allowed by NACL outbound).
- However, GitHubโs response packet returns with:
- Source Port:
443 - Destination Port:
49152(the clientโs ephemeral port!).
- Source Port:
- The stateless NACL evaluates the inbound rule: it only permits inbound port 443, not port 49152. The NACL drops the response packet!
The Fix: You must add an inbound NACL rule allowing ephemeral ports (1024โ65535) for return traffic!