A Virtual Private Cloud is the private, isolated network your cloud workloads run inside, and almost every production incident that involves "why can this thing reach that thing" comes down to four controls: the address plan, the subnets, the routing, and the two very different firewalls. This lesson builds small runnable models of each so that reachability becomes something you can compute rather than guess, and it ends on the single most common networking mistake -- treating a stateless control as if it were stateful.
The Analogy: The Leased Container Port
Think of a large container port that a shipping line leases as a self-contained, fenced estate on the coast. The whole estate is marked out on the harbour master's chart with a single block of berth numbers -- say berths 10.0.0.0 through 10.0.255.255 -- and nothing outside that block belongs to this operator. Inside the fence the estate is divided into zones: some are quayside yards that open directly onto the sea lane, and others are inner bonded warehouses set back from the water with no sea frontage at all. A Virtual Private Cloud is that leased estate, its address block is the VPC CIDR range, and the zones are subnets: the quayside yards are public subnets and the inner warehouses are private subnets.
Only one dredged channel connects the estate to open water, and it is the sole way anything reaches the sea. That channel is the internet gateway. Which zones may actually use it is not decided by the fence but by the harbour master's routing chart: a yard whose chart entry sends unknown destinations out through the dredged channel is genuinely sea-facing, while a warehouse whose chart sends everything to an internal transshipment quay can ship goods outward but can never be reached directly from the sea. That transshipment quay is the NAT gateway -- it lets the inner warehouses send cargo out to the world while offering the open sea no way to sail in and tie up alongside them.
Two very different guards control who may approach a warehouse. The first is the badge lock on each individual warehouse door: it lists exactly which trucks may enter, and crucially it remembers each truck it admitted, so when that truck drives back out with a reply it is waved through automatically without a separate exit permit. The second is the customs post on the road at the boundary of a whole zone: it inspects every vehicle in both directions against a numbered list of rules, takes the first rule that matches, and keeps no memory whatsoever -- a truck it happily waved inbound is inspected again, from scratch, when it tries to leave. The badge lock is a security group; the customs post is a network ACL.
The two guards fail in opposite ways, and the second failure is the quiet one. Set a warehouse's badge lock to admit any truck from the open sea and you have parked your database on the public quay for anyone to rifle through. But the subtler disaster is treating the stateless customs post as if it remembered things: you write a rule allowing the inbound delivery, watch it pass, and declare the route open -- yet because the customs post forgot the truck the moment it entered, the loaded reply truck is stopped at the gate on its way out, and the connection mysteriously hangs. The lesson is that a security group and a network ACL are not two spellings of the same control: one tracks the conversation and one does not, and a rule set that is exactly right for the first can silently strand every reply under the second.
Syntax or Core Structure
A VPC starts as a block of addresses written in CIDR notation, and every subnet is a smaller block carved out of it. Two numbers decide almost everything: how many usable addresses a block holds, and whether a subnet's route table sends unknown traffic to the internet gateway (public) or only to a NAT gateway (private). The model below carves a /16 VPC into one public and one private /24, computes the usable host count for each -- remembering that the provider reserves five addresses in every subnet -- and locates an address by CIDR membership.
def ip_to_int(ip):
a, b, c, d = (int(x) for x in ip.split('.'))
return (a << 24) | (b << 16) | (c << 8) | d
def in_cidr(ip, cidr):
net, bits = cidr.split('/')
mask = (0xFFFFFFFF << (32 - int(bits))) & 0xFFFFFFFF
return (ip_to_int(ip) & mask) == (ip_to_int(net) & mask)
def usable_hosts(cidr):
bits = int(cidr.split('/')[1])
return (1 << (32 - bits)) - 5 # the provider reserves 5 per subnet
VPC = '10.0.0.0/16'
SUBNETS = [
('public', '10.0.1.0/24', True), # default route -> internet gateway
('private', '10.0.2.0/24', False), # default route -> NAT gateway
]
print('VPC %s -> %d usable host addresses' % (VPC, usable_hosts(VPC)))
for name, cidr, public in SUBNETS:
print('%-7s %s usable=%d internet-facing=%s' % (name, cidr, usable_hosts(cidr), public))
probe = '10.0.2.15'
hit = [name for name, cidr, _ in SUBNETS if in_cidr(probe, cidr)]
print('address %s lives in subnet: %s' % (probe, hit[0]))
Output:
VPC 10.0.0.0/16 -> 65531 usable host addresses
public 10.0.1.0/24 usable=251 internet-facing=True
private 10.0.2.0/24 usable=251 internet-facing=False
address 10.0.2.15 lives in subnet: private
Notice the arithmetic that trips people up: a /24 holds 256 addresses but only 251 are usable, because the provider claims the network address, the broadcast-equivalent, and three more for routing and DNS. The public and private subnets are identical in size and differ only in one fact -- where their route table points -- which is why "public" and "private" are properties of routing, not of the address range.
Technical Depth: Two Firewalls That Look Alike
Security groups versus network ACLs
The port has two guards, and confusing them is the single most common source of "the rule looks right but traffic is blocked" tickets. A security group wraps an instance and tracks connections; a network ACL wraps a subnet and forgets everything. The table below is the distinction worth memorising before you ever open a rule editor.
| Aspect | Security Group | Network ACL |
|---|---|---|
| Attaches to | An instance or its network interface | An entire subnet |
| State | Stateful: the reply is auto-allowed | Stateless: allow each direction explicitly |
| Rule types | Allow rules only | Allow and deny rules |
| Evaluation | All rules at once, any match allows | Numbered, lowest first, first match wins |
| Default posture | Denies all inbound until you open it | The default NACL allows everything |
Because a security group only holds allow rules and is evaluated as a set, you cannot express "everyone except this one address" with it -- that is exactly the job a network ACL's deny rules do at the subnet edge. The two are meant to be layered, not chosen between.
# Security group: allow HTTPS ONLY from the load balancer's security group
aws ec2 authorize-security-group-ingress --group-id sg-app --protocol tcp --port 443 --source-group sg-alb
# Network ACL is stateless: you must ALSO allow the outbound reply on ephemeral ports
aws ec2 create-network-acl-entry --network-acl-id acl-app --egress --rule-number 100 --protocol tcp --port-range From=1024,To=65535 --cidr-block 10.0.1.0/24 --rule-action allow
What "stateful" buys you
The word stateful has a precise, testable meaning: once an inbound connection is allowed, the security group remembers it, so the reply travelling back out on some high-numbered ephemeral port needs no rule of its own. The model below encodes an app server whose only ingress rule admits the load balancer, and shows both that the reply is free and that a request straight from the internet is refused.
INGRESS = [
{'proto': 'tcp', 'port': 443, 'source': 'sg-alb'}, # only from the load balancer
]
def sg_allows_inbound(proto, port, source):
for r in INGRESS:
if r['proto'] == proto and r['port'] == port and r['source'] == source:
return True
return False
req = sg_allows_inbound('tcp', 443, 'sg-alb')
reply_needs_rule = False # stateful: the return is tracked
print('inbound 443 from sg-alb allowed: %s' % req)
print('reply on ephemeral port needs its own rule: %s' % reply_needs_rule)
print('connection succeeds: %s' % (req and not reply_needs_rule))
internet = sg_allows_inbound('tcp', 443, '0.0.0.0/0')
print('inbound 443 from 0.0.0.0/0 allowed: %s' % internet)
Output:
inbound 443 from sg-alb allowed: True
reply on ephemeral port needs its own rule: False
connection succeeds: True
inbound 443 from 0.0.0.0/0 allowed: False
Two facts fall out of this. First, the source of an ingress rule can be another security group, not just an address range, which is how "only the load balancer may talk to the app" is expressed without hardcoding IPs. Second, the connection works with a single inbound rule because the reply is implicit -- and it is precisely that implicitness that a network ACL does not give you, which is where the next section goes wrong on purpose.
Real World Example: A Reachability Check That Trusts the Wrong Firewall
A team runs a pre-deploy script that answers one question: can the load balancer reach the app on 443? The security group is correct -- one ingress rule admitting the balancer -- and traffic flows in test. So someone adds a network ACL on the private subnet for a second layer of defence, copies the security group's logic into it, and moves on. The ACL admits inbound 443 and, mirroring the SG, permits outbound 443. The pre-deploy check still says "reachable" and the change ships.
The subtle part is that a network ACL is stateless. Admitting the inbound request on 443 says nothing about the reply, which leaves the instance from a high-numbered ephemeral port (roughly 1024 to 65535) chosen per connection. The outbound rule permits port 443, not 51000, so the return packet hits the implicit final deny and is dropped. The connection hangs. The model below runs two checks over the same rules: a naive one that assumes the ACL behaves like the stateful SG, and a correct one that evaluates the stateless return path.
NACL_INBOUND = [
(100, 'allow', 'tcp', 443, 443), # the request from the load balancer
(32767, 'deny', 'tcp', 0, 65535), # implicit final deny
]
NACL_OUTBOUND = [
(100, 'allow', 'tcp', 443, 443), # MISTAKE: mirrors the SG, forgets the reply
(32767, 'deny', 'tcp', 0, 65535),
]
def nacl_allows(rules, port):
for num, action, proto, lo, hi in sorted(rules):
if lo <= port <= hi:
return action == 'allow'
return False
request_ok = nacl_allows(NACL_INBOUND, 443)
reply_port = 51000 # a representative ephemeral port
reply_ok = nacl_allows(NACL_OUTBOUND, reply_port)
naive_reachable = request_ok # assumes the NACL is stateful
correct_reachable = request_ok and reply_ok # evaluates the stateless return path
print('inbound request on 443 allowed: %s' % request_ok)
print('outbound reply on %d allowed: %s' % (reply_port, reply_ok))
print('naive check (assume stateful): %s' % naive_reachable)
print('correct check (stateless both ways): %s' % correct_reachable)
print('naive and correct agree: %s' % (naive_reachable == correct_reachable))
Output:
inbound request on 443 allowed: True
outbound reply on 51000 allowed: False
naive check (assume stateful): True
correct check (stateless both ways): False
naive and correct agree: False
The two checks disagree, and the disagreement is the whole story. The naive check looks only at whether the request is admitted and, seeing the inbound 443 rule, declares the path open -- exactly the reasoning that felt safe when the ACL was copied from the SG. The correct check also asks whether the reply is admitted on its actual ephemeral port, finds no matching outbound rule, and reports the path closed. In a real VPC the symptom is a connection that establishes nothing and eventually times out, which is far harder to diagnose than an outright refusal.
The design flaw is in the checker, not the network: modeling a stateless NACL as if it were stateful makes the check invariant under the very failure it exists to catch. Because naive_reachable never consults the return path, it prints True whether the outbound ephemeral range is allowed or denied -- the flaw is silent precisely when it matters. The honest fix is a rule that admits the ephemeral range outbound (1024-65535), and the honest check evaluates both directions, as correct_reachable does. Note the model's own limits: it uses one representative port (51000) rather than the whole range, ignores rule ordering beyond a numeric sort, and says nothing about the security group layer that must also pass -- a full reachability analysis has to clear every stateful and stateless hop on both legs of the round trip.
Common Mistakes
- Treating a network ACL as if it were stateful. Security groups track connections and admit the reply automatically; NACLs do not. If you open an inbound port on a NACL you must also open the outbound ephemeral range (
1024-65535), or the return traffic is dropped and the connection hangs.
- Opening a security group to
0.0.0.0/0when a source group would do. Referencing another security group as the source ("allow 443 from sg-alb") ties the rule to a role rather than an address, survives IP changes, and keeps the app unreachable from the open internet. Reaching for0.0.0.0/0out of habit is how databases end up publicly exposed.
- Sizing subnets by counting the addresses, not the usable ones. The cloud reserves the network address, the broadcast-equivalent, and three more per subnet -- five in total on AWS. A
/24gives 251 usable hosts, not 256, and undersized subnets run out silently as autoscaling grows.
- Putting everything in public subnets. A subnet is public only because its route table sends
0.0.0.0/0to an internet gateway. Databases and app servers belong in private subnets whose default route is a NAT gateway (egress only) or nothing at all; being in a private subnet is the difference between "unreachable from outside" and "one misconfigured rule from exposure".
- Forgetting that a NAT gateway is egress-only and costs per hour and per gigabyte. It lets private instances reach the internet for updates; it does not let the internet reach them. Teams are surprised both by inbound connections that never work through it and by the bill from routing bulk traffic through one.
- Overlapping CIDR ranges between VPCs you later need to peer. Two VPCs that both use
10.0.0.0/16cannot be peered or joined over a VPN, because routing becomes ambiguous. Allocate non-overlapping ranges up front; renumbering a live VPC is a migration, not an edit.
- Assuming security group rules are ordered or can deny. Security groups have no rule order and no explicit deny -- they are a pure allow-list, and traffic is permitted if any rule matches. Ordering and explicit deny live only on NACLs, which are evaluated by rule number.
- Editing the main route table instead of an explicit one. Subnets with no association use the VPC main route table, so a change there silently affects every unassociated subnet. Associate each subnet with an explicit route table so a "make this one public" edit cannot leak to others.
- Debugging a black-hole connection at the wrong layer. A request that is admitted but whose reply is silently dropped looks like an application timeout. Before touching code, confirm the return path: the security group is stateful, but every NACL on both subnets must allow the ephemeral range outbound and inbound for the round trip to complete.
Best Practices
- Default to private subnets and add public exposure deliberately. Put a subnet's
0.0.0.0/0route to an internet gateway only where you truly need inbound reach, and front everything else with a load balancer or NAT gateway so instances are not directly addressable.
- Reference security groups as sources instead of IP ranges. "Allow 443 from sg-alb" and "allow 5432 from sg-app" describe the intended topology, survive scaling and IP churn, and read as documentation of who may talk to whom.
- Plan CIDR ranges once, globally, and never overlap them. Reserve distinct blocks per VPC and environment up front so future peering, VPN, and transit-gateway connections stay unambiguous; treat renumbering as a migration to avoid.
- Use security groups for host-level allow-listing and NACLs sparingly for coarse subnet-level guards. Layering both is fine, but remember only the NACL is stateless -- keep its rules simple and always pair an inbound allow with the matching outbound ephemeral range.
- Associate every subnet with an explicit route table. Leaving subnets on the VPC main table makes one edit leak across all of them; explicit associations keep "public" and "private" decisions local and auditable.
- Right-size subnets with a margin and account for the five reserved addresses. Pick prefix lengths from the usable-host count you actually need under peak autoscaling, not the raw block size, and leave headroom so growth does not force a re-carve.
- Test the return path, not just the request, when validating connectivity. Any check or diagram that models a NACL as stateful is lying; verify both legs of the round trip so a silently dropped reply cannot masquerade as success.
- Keep egress deliberate. Send private-subnet outbound traffic through a NAT gateway or VPC endpoints, restrict security group egress where the workload allows it, and monitor NAT data-processing charges so a chatty service does not quietly dominate the bill.
Practice Exercises
- Classify a subnet from its route table. Given three route tables (one with
0.0.0.0/0to an internet gateway, one to a NAT gateway, one with only the local route), label each subnet public, private-with-egress, or isolated, and write one sentence on what can and cannot reach the internet in each.
- Fix the stateless drop. Take the
NACL_OUTBOUNDlist from the Real World Example and add the rule that makes the reply flow, then extend the model to test three ephemeral ports (1024, 51000, 65535) and confirmcorrect_reachablebecomes True for all three while the request rule is unchanged.
- Size a three-tier VPC. For a
10.0.0.0/16VPC, carve one public, one app-private, and one data-private subnet across two availability zones (six subnets), choose prefix lengths, and compute the usable hosts per subnet using thetotal - 5rule. Show that your ranges do not overlap.
- Write the minimal security group set. For an internet-facing load balancer, an app tier, and a database, define the ingress rules using security-group sources (not IP ranges) so that only the balancer reaches the app on 443 and only the app reaches the database on 5432. State why no egress or return rules are needed given that security groups are stateful.