Virtual Private Cloud (VPC) Basics
IP Subnetting
Subnetting – Key Concepts

- Subnetting is the process of dividing a network into smaller segments called subnets.
- Comparable to cutting a larger structure into smaller, manageable parts.
- It can be challenging initially but becomes easier with consistent practice.
- A network is represented using CIDR notation, which combines the base IP address with a prefix length.
- Example:
10.16.0.0to10.16.255.255→10.16.0.0/16
- CIDR (Classless Inter-Domain Routing) defines both the network range and its size.
- Example:
- Key points about prefixes:
- The prefix indicates how many bits (or octets) are fixed for the network portion.
- A larger prefix value results in a smaller network range.
- Examples:
/0represents the entire address space/8corresponds to a large network (Class A)/16corresponds to a medium network (Class B)/24corresponds to a smaller network (Class C)/32represents a single IP address
- Standard subnetting typically involves splitting a network into equal halves:
- Example:
10.16.0.0/16can be divided into two/17subnets:10.16.0.0/1710.16.128.0/17
- Subnets can be further divided repeatedly into smaller segments (2, 4, 8, etc.).
- While uneven splits are technically possible, most designs favor equal-sized subnets for consistency.
- Example:
- Although examples often use IPv4, the same subnetting principles apply to IPv6.
Subnetting Process Step by Step

- It is recommended to follow a visual or guided walkthrough to fully understand the subnetting process.
- Mastery comes through repeated practice and applying subnetting in different scenarios.
Designing Business Networks and IP Plans
Building a reliable infrastructure platform depends as much on strong design decisions as it does on technical implementation.
- Creating an IP plan for a business involves designing one or more networks within that plan.
- In AWS, this typically means designing a VPC.
- Understanding VPC sizing and structure is essential to prevent current limitations and future scaling issues.
- Planning IP ranges ahead of time:
- Done correctly → results in a well-structured and scalable network.
- Done poorly → difficult and costly to fix later.
- Decide early whether to use one or multiple CIDR ranges.
- Ensure that VPCs or networks do not overlap, as this creates major connectivity issues.
Considerations when Designing Business Networks
- Plan with future growth in mind.
- Consider current and future AWS regions.
- Account for existing and additional AWS accounts.
- A practical approach is to reserve multiple networks per region and per account.
- Example: allocate at least two or more networks per region and account.
- It is also beneficial to reserve extra tiers and Availability Zones for future use.
- Identify networks that must not overlap.
- Includes other VPCs, cloud environments, on-premises networks, and partner networks.
- When uncertain, assume conflicts may exist and plan conservatively.
- Gathering this information from internal teams is critical before finalizing the design.
- Two common design approaches:
- Top-down: start with a large IP range and divide it to meet requirements.
- Bottom-up: begin with the smallest required subnet sizes and expand as needed.
VPC Sizing and Structuring – Concepts
VPC Size (CIDR)
- Define the CIDR block for the VPC.
- AWS allows IPv4 VPC sizes ranging from /28 to /16 (16 to 65,536 IP addresses).
- The chosen size determines how many resources and services can be deployed, since each requires an IP address.
VPC Structure (Subnets)
- Determine how the VPC will be divided into subnets.
- AWS resources are deployed within subnets, not directly in the VPC.
- Tiers represent different application layers:
- Common model:
- WEB – frontend servers
- APP – backend application logic
- DB – database layer
- Often, an additional spare tier is included for flexibility.
- Common model:
- Availability Zones (AZs) define resilience:
- The number of AZs impacts availability and fault tolerance.
- A common approach is to use at least three AZs, with an optional fourth as a buffer.
VPC Sizing and Structuring – Example

VPC Sizing & Structuring – Considerations
- Key planning questions:

- How many subnets are required?
- How many total IPs and IPs per subnet are needed?
- Example structure:
- 4 tiers × 4 AZs = 16 subnets
- If VPC = /16 → each subnet = /20
- If VPC = /17 → each subnet = /21
- 4 tiers × 4 AZs = 16 subnets
- Recommended IP range strategy:
- Use the 10.x.x.x private range.
- Avoid commonly used ranges (e.g., 10.1–10.10) to reduce overlap risks.
- Starting at ranges like 10.16.x.x helps avoid conflicts and aligns well with subnetting boundaries.
- Maintain clear documentation:
- Track all IP allocations in a structured format such as spreadsheets or diagrams.
- This improves visibility and simplifies future scaling or troubleshooting.
VPC Design for A4L Scenario

- This architecture represents a complete VPC design example.
- Understanding each component will become easier after covering all VPC-related concepts.
Amazon VPC (Virtual Private Cloud) 101
Amazon VPC – Core Concepts
- Provision and manage private networks within an AWS account
- A Virtual Private Cloud (VPC) is a logically isolated virtual network inside AWS
- The VPC CIDR block defines the IP address range of the network (e.g.
172.31.0.0/16)
- The VPC CIDR block defines the IP address range of the network (e.g.
- Most AWS services and resources—especially private ones like EC2—operate within a VPC
- A Virtual Private Cloud (VPC) is a logically isolated virtual network inside AWS
- VPC scope: single account and single region
- VPCs are regionally scoped and resilient
- Subnets (smaller network segments) can be distributed across multiple Availability Zones (AZs)
- If one AZ fails, workloads in other AZs within the same VPC remain available
- A subnet CIDR is a subdivision of the VPC CIDR
- Once assigned, subnet CIDR ranges cannot be modified
- Types of VPCs
- Default VPC (0–1 per region)
- Automatically created with a predefined configuration
- Custom VPCs (0 or more per region)
- Fully configurable and private by default
- Default VPC (0–1 per region)
- Isolation and connectivity
- Custom VPCs are isolated by default
- No inbound or outbound communication is allowed unless explicitly configured
- Additional setup is required to enable communication with:
- Other VPCs
- On-premises networks (hybrid setups)
- Other cloud providers (multi-cloud)
- The public internet
- The Default VPC is an exception and does not follow strict isolation by default
- Custom VPCs are isolated by default
Default VPC
- Automatically provisioned by AWS with a standard configuration
- Provides a ready-to-use environment, ideal for quick testing and basic deployments
- Limited flexibility makes it unsuitable for production use cases
- Fixed CIDR block
- Always uses
172.31.0.0/16(constant across all regions)
- Always uses
- Availability
- Only one Default VPC per region
- Can be deleted and later recreated
- Recreating the Default VPC is a separate action from creating a new (custom) VPC

- Subnet distribution
- Automatically creates one
/20subnet per Availability Zone in the region
- Automatically creates one

- Preconfigured components
- Includes:
- Internet Gateway (IGW)
- Security Groups (SGs)
- Network ACLs (NACLs)
- Includes:
- Public accessibility by default
- Resources launched in the Default VPC are typically assigned a public IPv4 address
- This allows direct internet access unless restricted
- Unlike Custom VPCs, the Default VPC is not isolated by default

Custom VPCs
Amazon VPC – Refresher
- Builds on the foundational concepts of Amazon VPC
- A regional service: when a VPC is created in a region, it can span all Availability Zones within that region, providing regional resilience
- Enables creation of logically isolated networks within AWS:
- No inbound or outbound traffic is allowed unless explicitly configured
- Provides an isolated blast radius, meaning any compromise is contained within the VPC and its connected environments
- Supports hybrid networking architectures
- VPCs can integrate with on-premises environments and other cloud networks
- Offers a modular design approach
- Start with a basic setup and incrementally add components as needed
Amazon VPC – Custom VPCs
- Fully configurable, customer-managed VPCs
- Can range from simple designs to complex multi-tier architectures
- In contrast to Default VPCs, which have a fixed configuration
- Tenancy options
- Default Tenancy: resources run on shared hardware
- Dedicated Tenancy: resources run on dedicated hardware
- Default Tenancy allows flexibility to choose dedicated hardware at the resource level later
- Dedicated Tenancy at the VPC level enforces dedicated hardware for all resources and cannot be changed
- Default Tenancy is generally the safer and more flexible option
Custom VPC IP Addressing (Quotas)
IPv4
- Private CIDR blocks are required and form the primary communication range
- Minimum size:
/28(16 IP addresses) - Maximum size:
/16(65,536 IP addresses) - A primary private IPv4 CIDR block is mandatory
- Minimum size:
- Additional secondary IPv4 CIDR blocks can be added after creation
- Up to 5 by default
- More can be requested through AWS support
- Public IPv4 addresses can be assigned when external access is required
IPv6
- No distinction between private and public addresses
- All IPv6 addresses are inherently routable
- Access is still controlled through security configurations
- Optional /56 IPv6 CIDR block
- IPv6 support is still evolving, but adoption is increasing
- Recommended to enable for forward compatibility
- Address allocation:
- Use AWS-assigned IPv6 ranges or bring your own IPv6 addresses
- AWS-assigned ranges do not allow selection of specific addresses
- Custom VPCs can be configured as:
- IPv4-only, or
- Dual-stack (IPv4 + IPv6)
DNS in VPCs
- VPCs include integrated DNS capabilities, powered by Amazon Route 53
- DNS is accessible at the base IP address + 2
- Example: for
10.16.0.0, DNS resolver is10.16.0.2
- Example: for
- Two key configuration settings:
enableDnsSupport- Enables DNS resolution within the VPC
enableDnsHostnames- Assigns DNS hostnames to resources with public IP addresses
- These settings are common root causes for DNS-related issues and should be verified during troubleshooting
Demo: Custom VPC Design (Course Scenario)
- Demonstrates designing a custom VPC aligned with real-world architecture requirements
- Focuses on structuring subnets, tiers, and connectivity within a scalable and resilient environment

VPC Subnets & DHCP Options Set
VPC Subnets – Core Concepts
- Definition: A subnet is a logical subdivision of a VPC that exists within a single Availability Zone (AZ)
- Subnets are the deployment layer where private AWS resources and services operate
- The design, behavior, and resilience of a VPC are largely determined by how its subnets are structured
- Common diagram conventions
- Blue represents private subnets (default state)
- Green represents public subnets
- A subnet becomes public only after specific configurations are applied
- Availability Zone dependency
- Subnets are AZ-scoped, meaning each subnet is tied to one AZ
- If the AZ becomes unavailable, the subnet and all hosted resources are impacted
- For high availability, workloads should be distributed across multiple subnets in different AZs
- The AZ assignment of a subnet is permanent and cannot be changed
- Each AZ can host multiple subnets
- Intra-VPC communication
- Subnets within the same VPC can communicate by default
- Network isolation is enforced at the VPC boundary, not between subnets
- Internal communication is unrestricted unless explicitly controlled
VPC Subnets – IP Addressing
- IPv4 CIDR
- Required for all subnets
- Must be a subset of the VPC’s IPv4 CIDR range
- IPv6 CIDR
- Optional and only available if the VPC has an IPv6 CIDR assigned
- Each subnet receives a /64 block, derived from the VPC’s /56 range
- A VPC can support up to 256 IPv6 subnets
- CIDR constraints
- Subnet CIDR blocks must not overlap with other subnets in the same VPC
- IP assignment settings
Auto-assign public IPv4- Automatically assigns a public IPv4 address to resources upon launch
- Required for enabling internet-facing resources in a subnet
Auto-assign IPv6- Automatically assigns IPv6 addresses to resources
- Reserved IP addresses
- AWS reserves 5 IP addresses per subnet
- Example:
10.16.16.0/20- Network address (first IP):
10.16.16.0 - VPC router:
10.16.16.1 - DNS resolver (provided by Amazon Route 53):
10.16.16.2 - Reserved for future use:
10.16.16.3 - Broadcast address (last IP):
10.16.31.255
- Network address (first IP):
- These reserved addresses reduce the number of usable IPs
- Example: a
/28subnet (16 IPs) provides only 11 usable addresses
- Example: a
DHCP Options Set
- Dynamic Host Configuration Protocol (DHCP)
- Automatically assigns IP configuration to resources within the network
- DHCP Options Set
- A VPC-level configuration object that defines:
- DNS servers
- NTP (time synchronization) servers
- NetBIOS settings
- Applies to all subnets within the VPC
- Only one DHCP options set can be associated with a VPC at any time
- Cannot be modified after creation; changes require creating and associating a new set
- A VPC-level configuration object that defines:
Network Address Translation (NAT)
NAT – Core Concepts
- Network Address Translation (NAT) enables the mapping of private IPv4 addresses to public IPv4 addresses, and vice versa
- Multiple private resources can share a single public IPv4 address
- Public IPs are routable on the internet, while private IPs are only routable within internal networks
- Initially introduced to mitigate IPv4 address exhaustion
- Also provides an indirect security advantage
- Blocks unsolicited inbound connections from external sources
- Not required in IPv6 environments due to the vast address space
- Also provides an indirect security advantage
- NAT is implemented by network devices (such as routers), which maintain translation tables (NAT tables)
- These tables track mappings between private and public addresses
- Normally, IP addresses remain unchanged across Layer 3 boundaries—except when NAT is applied
Types of NAT
Static NAT

- One-to-one mapping between private and public IP addresses
- The association is fixed and persistent
- In AWS, similar behavior is achieved via an Internet Gateway (IGW)
- Outbound flow
- A private resource sends traffic using its private IP as the source
- The NAT device replaces the source IP with its public IP and forwards the packet
- The destination system perceives the request as originating from the NAT device
- Inbound flow
- The external system responds to the NAT device’s public IP
- The NAT device consults its translation table and maps the destination back to the private IP
- The response is delivered to the originating resource
- Private resources do not possess public IPs; they rely on predefined NAT mappings
Dynamic NAT

- Many-to-many mapping using a pool of public IP addresses
- Private resources are temporarily assigned a public IP from the pool when initiating connections
- Allocation behavior
- When a connection is initiated:
- If a public IP is available, it is assigned and recorded in the NAT table
- If no IP is available, the connection request fails
- Once the session ends, the public IP is released back into the pool
- When a connection is initiated:
- Enables reuse of public IPs across multiple devices over time
Port Address Translation (PAT)
(also known as IP masquerading or NAT overload)

- Many-to-one mapping: multiple private IPs share a single public IP
- Differentiation is achieved using port numbers
- Each NAT table entry includes:
- Private IP + private port
- Public IP + unique public port
- This is the most widely used form of NAT
- Common in home routers and enterprise environments
- In AWS, implemented via NAT instances and NAT Gateways
- Connection handling
- Multiple internal resources can connect to the same external service using different port mappings
- The NAT device ensures each session remains unique through port translation
- Security characteristic
- Only outbound-initiated connections are permitted
- External systems cannot initiate connections to internal resources unless a mapping already exists
- This behavior enhances security compared to static NAT, where mappings are permanently defined
VPC Routing, Internet Gateway & Bastion Hosts
VPC Router
- Handles traffic routing within a VPC
- By default, it routes traffic within and between subnets
- Additional configuration is required to route traffic outside the VPC
- Exists in every VPC
- Has a network interface in each subnet
- Uses the first usable IP (Network + 1) in each subnet
- Highly available by design
- Operates across all Availability Zones in the VPC
- No need for manual HA configuration
- Routing behavior is controlled using route tables
VPC Route Table (RT)
- Defines how traffic is directed
- A route specifies the destination CIDR and the target location
- Key components:
- Destination
- CIDR block used to match the packet’s destination IP
- If no match, the route is ignored
- Target
- Where matching traffic is forwarded
- Examples:
- local → stays inside the VPC
- Internet Gateway (IGW) → routed to the internet
- Other gateways (VGW, TGW, etc.)
- Destination
- Routing priority rules
- More specific routes (longer prefix) take precedence
- Exception: the local route always has priority
- Subnet association
- Each subnet is linked to exactly one route table
- Default is the main route table
- Custom route tables can be assigned as needed
- Local route
- Automatically present in all route tables
- Matches the VPC CIDR
- Cannot be modified or removed
- Default route
- Used when no other routes match:
- IPv4:
0.0.0.0/0 - IPv6:
::/0
- IPv4:
- Used when no other routes match:
Internet Gateway (IGW)
- Provides connectivity between a VPC and the public internet
- Acts as the boundary between the VPC and AWS public network
- Required for access to:
- Public internet
- Public AWS services (e.g., S3, SNS, SQS endpoints)
- Requirements for usage
- Resource must have:
- A public IPv4 address and/or
- An IPv6 address
- Route table must include a route pointing to the IGW
- Resource must have:

- Association rules
- One IGW can be attached to only one VPC
- A VPC can have zero or one IGW
- Highly available and managed by AWS
- Automatically spans all AZs in the region
- No scaling or maintenance required
IPv4 Behavior with IGW
- Public IPv4 addresses are not assigned directly to instances
- They are mapped at the IGW level using static NAT
- Inside the instance:
- Only the private IPv4 address is visible
- Traffic flow:
- Outbound: private IP → translated to public IP by IGW
- Inbound: public IP → translated back to private IP
- The IGW maintains the mapping between public and private IPs
IPv6 Behavior
- No NAT is performed
- IPv6 addresses are directly assigned to the instance
- Traffic is routed without translation

Bastion Host / Jump Box
- A secure entry point into private networks
- Public-facing instance used to access private resources
- Typically deployed in a public subnet
- External users connect to the bastion
- Then access internal resources from there
- Can enforce:
- IP restrictions
- Authentication controls
- Logging and monitoring
- Traditional approach for managing private EC2 instances
- Still valid, but now often replaced by:
- EC2 Instance Connect
- AWS Systems Manager (SSM)
- Still valid, but now often replaced by:
NAT Gateways & NAT Instances
Common Scenario: Updating Private EC2 Instances
- Private EC2 instances (in a VPC) are isolated from the internet by default
- If these instances need to download updates or patches, several approaches exist:
- Convert the subnet to public
- Allows direct internet access for instances
- Drawback: breaks standard secure multi-tier architecture design, where private subnets are intentionally isolated
- Maintain internal update servers
- Host patch repositories within the VPC
- Drawback: introduces operational overhead
- Requires manually downloading updates and distributing them internally
- Recommended approach: use NAT (Network Address Translation)
- Enables private instances to access the internet without becoming publicly accessible
- Deployment options:
- NAT Instance (self-managed EC2)
- NAT Gateway (NATGW) (AWS-managed service)
Refresher: Network Address Translation (NAT)
- NAT refers to techniques that modify source or destination IP addresses in network packets
- Relevant only for IPv4 (not required for IPv6)
NAT Types
- Static NAT
- One private IP maps to one public IP
- Used by Internet Gateway (IGW)
- Dynamic NAT
- Multiple private IPs share a pool of public IPs
- Port Address Translation (PAT)
- Many private IPs share a single public IP
- Differentiation handled via port numbers
- Also known as IP masquerading
- Most commonly used form of NAT in practice
- PAT enables:
- Outbound-only internet access
- Private instances can initiate connections
- External systems cannot initiate connections back
- In AWS:
- NAT functionality is typically implemented using:
- NAT Instances
- NAT Gateways (NATGW)
- NAT functionality is typically implemented using:
NAT Architecture in a VPC

- NAT Gateway is placed in a public subnet
- Private subnets route outbound traffic to the NATGW
Traffic Flow
- Private subnet sends traffic to NATGW
- Route table default route (
0.0.0.0/0) points to NATGW - NATGW records sessions in a translation table
- Route table default route (
- NATGW modifies source IP
- Replaces private IP with its own private IP
- Traffic is forwarded to Internet Gateway (IGW)
- Via the VPC router
- IGW performs final translation
- Replaces NATGW private IP with a public IP
- Return traffic follows reverse path
- IGW → NATGW → private instance
NAT Gateway (NATGW) – Key Concepts
- AWS-managed NAT-as-a-Service
- Must be deployed in a public subnet
- Associated with an Elastic IP (static public IPv4)
Characteristics
- Fully managed by AWS
- Auto-scales up to high throughput (~45 Gbps)
- Provides high availability within a single AZ
- Minimal administrative effort required
Limitations
- Not regionally resilient by default
- To achieve resilience:
- Deploy one NATGW per AZ
- Use AZ-specific route tables
- To achieve resilience:
- Security Groups are not supported
- Only NACLs can be applied
Billing Model
- Charged based on:
- Hourly usage
- Data processed (per GB)
- Costs increase with:
- Multiple NAT Gateways
- High data transfer volumes
NAT Instances
- EC2 instances configured to perform NAT
- Must be deployed in a public subnet
Special Configuration
- Disable Source/Destination Checks
- Required because NAT instances process traffic not originally addressed to them
NAT Instances vs NAT Gateway
Why NAT Gateway is the default choice
- Better performance and scalability
- AWS-managed → reduced operational overhead
- Built-in high availability (within AZ)
When NAT Instances may be preferred
- Cost considerations
- Lower cost for:
- Small environments
- Low traffic workloads
- Can use small or free-tier instances
- Predictable pricing (fixed instance size)
- Lower cost for:
- Multi-purpose usage
- Can act as:
- Bastion host
- Port forwarding device
- NATGW cannot be customized
- Can act as:
- Security flexibility
- Supports Security Groups and NACLs
- NATGW supports only NACLs
IPv6 Considerations
- NAT is not used with IPv6
- IPv6 addresses are globally routable
Connectivity Options
- Internet Gateway (IGW)
- Enables bidirectional communication (inbound + outbound)
- Egress-Only Internet Gateway (EIGW)
- Allows outbound-only traffic
- Prevents inbound connections from the internet
Stateless vs Stateful Firewalls
TCP Connections, Ports, and Direction
- TCP is a connection-oriented protocol
- Establishes a bi-directional session between a client and a server
- Uses:
- A random (ephemeral) port on the client
- A well-known port on the server (e.g., HTTPS uses port 443)
- Ephemeral port range: typically 1024–65535
- Exact range varies by operating system
- In practice, firewall rules must allow the full range
- Each TCP session consists of:
- A request
- A response
- Traffic direction (inbound vs outbound) is relative
- Depends on whether you are viewing from the client or server perspective

Stateless Firewall

- Evaluates each packet independently
- Operates at Layer 3 (Network) and Layer 4 (Transport) of the OSI model
- Does not track connection state
- Treats request and response as unrelated traffic
- Requires explicit rules for both directions
- One rule for inbound traffic
- One rule for outbound traffic
- When allowing inbound connections:
- Must also allow ephemeral port ranges (1024–65535) for return traffic
- Drawbacks:
- Higher administrative overhead
- Greater risk of misconfiguration
Stateful Firewall

- Tracks active connections (sessions)
- Maintains awareness of request-response relationships
- Operates with awareness beyond basic packet inspection
- Automatically allows return traffic
- Only one rule is needed to permit a connection
- If a request is allowed, the corresponding response is implicitly allowed
- Advantages:
- Simplifies rule management
- Reduces likelihood of configuration errors
- More efficient for handling dynamic traffic patterns
Network Access Control Lists (NACLs)
VPC NACL – Key Concepts

- Subnet-level stateless firewall
- Network Access Control List (NACL) filters traffic crossing the subnet boundary (inbound/outbound)
- Traffic inside the subnet is unaffected
- For traffic between subnets, both NACLs must allow it
- Stateless behavior
- Treats requests and responses as separate traffic
- Requires two rules per connection (IN + OUT)
- Subnet association
- Each subnet has one NACL (default or custom)
- One NACL can be associated with multiple subnets
- Only subnets can have NACLs – not individual resources
- Used alongside Security Groups (SGs)
- SGs allow traffic
- NACLs can explicitly deny traffic → ideal for blocking bad actors or IP ranges
NACL Rules

- Two rule sets per NACL:
- Inbound: affects data entering subnet
- Outbound: affects data leaving subnet
- Rule matching is based on:
- IP/CIDR (inbound:SRC, outbound:DST)
- Port (inbound:SRC, outbound:DST)
- Protocol
- Cannot reference AWS resources (IGW, EC2, etc.)
- Processing order:
- Rules evaluated lowest number first
- First match → stop processing
- Last implicit rule =
*→ DENY if no match
- Connection coverage:
- Each app port + ephemeral port pair requires rules for:
- Within VPC (subnet-to-subnet)
- To VPC (inbound from outside)
- From VPC (outbound to outside)
- Each app port + ephemeral port pair requires rules for:
NACL Types
Default NACL
- Automatically created with VPC
- Associated with all subnets by default
- Catch-all allow inbound/outbound → allows all traffic
- Recommended for beginners; AWS suggests using SGs for security

Custom NACL
- Created manually inside VPC
- Initially not associated with any subnet
- Starts with implicit DENY (
*) only- Associating immediately → all traffic blocked
- Requires custom rules to allow traffic

Security Groups (SGs)
VPC Security Group (SG) – Key Concepts

- Stateful firewall attached to Elastic Network Interfaces (ENIs) of AWS resources
- Unlike NACLs, SGs are not attached to VPC subnets
- SGs are not directly attached to AWS resources
- When you attach an SG to an EC2 instance, it is actually attached to the ENI of the instance
- Conceptually, an SG surrounds the ENI
- Inbound & outbound rules
- Rules apply to traffic entering or leaving the ENI
- Supports IP/CIDR matching like NACLs
- Stateful behavior
- Requests allowed inbound/outbound automatically allow the corresponding responses
- No need to manage ephemeral ports
- Enhanced features
- Operates at Layer 5, more than Layer 4 like NACLs
- Can reference other SGs or itself in rules
- Limitation: no explicit deny
- Only explicit allow or implicit deny
- Traffic not explicitly allowed is implicitly denied
- Cannot block specific bad actors – use NACLs for that
VPC SG – Logical References

- To allow a connection to an EC2 instance, an SG rule can reference:
- IP of the EC2 instance
- Not flexible if IP changes
- Not scalable for many instances
- CIDR of the subnet
- Scalable → new instances in the subnet are automatically allowed
- Limited granularity → cannot easily exclude specific instances
- Security Group of the instance or its subnet
- Very scalable → automatically applies to new instances with the SG
- Very flexible → unaffected by IP or subnet changes
- Maintains granularity and reduces admin overhead
- IP of the EC2 instance
SG Self-References

- SGs can reference themselves to allow traffic between all resources with that SG
- Automatically handles IP changes
- Useful for EC2 instances in Auto Scaling Groups
- Simplifies intra-application communication (e.g., domain controllers or app HA)
Advanced VPC Networking
VPC Flow Logs
- Monitor traffic flow to and from ENIs within a VPC.
- Only capture packet metadata
- Examples: source/destination IPs, ports, and anything related to the flow of data
- Flow Logs do not capture packet contents; a packet sniffer is required for that
- Not real-time
- Logs are delivered with a delay; best-effort capture
- Levels of attachment (captures from the specified point downwards):
- VPC-level → captures flow to/from all ENIs in all subnets of the VPC
- Subnet-level → captures flow to/from all ENIs in a specific subnet
- ENI-level → captures flow to/from a single ENI
- Can capture accepted, rejected, or all traffic metadata
- Log Destinations:
- S3
- Can query with Athena
- Reference: Flow Logs to S3
- CloudWatch Logs (CWLogs)
- Reference: Flow Logs to CloudWatch
- S3
- Traffic excluded from Flow Logs:
- EC2 Metadata service (
http://169.254.169.254) - Time server requests (
http://169.254.169.123) via NTP - DHCP requests inside the VPC
- Communications with Amazon DNS server
- Communications with Amazon Windows license server (for Windows EC2 instances)
- EC2 Metadata service (
- Architecture diagram:

Flow Log Records
- Each row represents the flow of a packet through an ENI
- Important fields:
srcaddr,dstaddr,srcport,dstport,protocol,action - Protocol numbers (IANA-assigned):
1→ ICMP (used by ping)6→ TCP17→ UDP
- Example: ICMP ping flow log

- ICMP does not use ports, so
srcportanddstportare empty - Two rows indicate stateless filtering, likely NACLs (one row for traffic in, one for traffic out, second rejected)
- Single row would indicate stateful filtering, likely a Security Group, showing the whole connection
Egress-Only Internet Gateway (EIGW)
Differences Between IPv4 and IPv6 in AWS
- IPv4
- Addresses can be private or public
- Private resources cannot directly communicate with the public internet or public networks
- Public resources have publicly routable IPv4 addresses
- Without security filtering, public resources can access the internet and be accessed from the internet
- IPv6 (in AWS)
- Addresses are public-only by default
Network Address Translation (NAT) for IPv4
- NAT Gateways (NATGW) and NAT instances:
- Allow resources with private IPv4 addresses to access public services and the internet
- Side effect: do not allow externally initiated connections into private resources
- NAT exists primarily to address IPv4 address space limitations
- NAT does not work with IPv6
- NAT’s behavior of blocking externally initiated connections applies to IPv4 only
Egress-Only Internet Gateway (EIGW)
- Provides outbound-only connections (and responses) for IPv6 resources
- Connections can be initiated from the VPC, but external networks cannot initiate connections into the VPC
- Only required for IPv6, not needed for IPv4
- Architecturally similar to standard IGWs:
- Regionally resilient and highly available across all AZs used by the VPC
- Traffic-based scaling
- Stateful
- Route Table Configuration:
- Default IPv6 route (
::/0) should have the EIGW as the target
- Default IPv6 route (
- Architecture diagram:

VPC Endpoints (VPCEs) – Gateway & Interface Types
VPC Endpoints (VPCEs)
- Allow private access to AWS services in the public zone
- No need to provide additional infrastructure usually required to access public services
- Two types:
- Gateway Endpoints (GWEs) – for S3 and DynamoDB
- Interface Endpoints (IEs) – for other services (S3 now also supported)
- Both types are very different in architecture
VPC Gateway Endpoints (GWEs)
- VPC gateway object that provides private access to S3 and DynamoDB (DDB)
- S3 & DDB are public services, but GWEs allow access privately
- Only S3 and DDB are currently supported by GWEs
- Private resources can access S3/DDB without any public-access infrastructure
- Created inside a VPC, per-service & per-region
- GWEs are regional → cannot access cross-region services
- Associated with one or more subnets in the VPC
- Highly available across all AZs in the region (no need to worry about placement)
- Prefix List added to the route table of associated subnets
- GWE is the target of the prefix list → represents S3/DDB IPs, kept up to date by AWS
- Traffic to S3/DDB goes via GWE instead of IGW
- No application reconfiguration required
- Endpoint policy can control what can be accessed via the GWE
- Example: grant access only to a subset of S3 buckets
- Main use cases:
- Allow resources access to S3/DDB while keeping VPC private
- Support private S3 buckets → prevent leaky buckets
- GWEs are only accessible from the VPC where they are created
Comparison: Access to S3 With and Without GWE
Without GWE

- Public IPv4 or IPv6 resources access S3 via IGW
- Private IPv4 resources go through NATGW → public IP → S3 via IGW
- Problem: private resources accessing S3 also go through the public internet
With GWE

- GWE created in VPC, associated with subnets
- Route tables updated with prefix list pointing to GWE
- Traffic to S3 goes through GWE → no need for NATGW or IGW
- Endpoint policy can further restrict access
VPC Interface Endpoints (IEs)
- ENIs that provide private access to AWS public services
- Similar purpose to GWEs but different architecture
- Historically for services other than S3/DDB; S3 now also supports IEs
- Not HA by default
- Deployed in specific subnets (single AZ)
- To achieve HA, deploy one IE per AZ
- Network access controlled via SGs
- Endpoint policies can further restrict access
- Supports only TCP and IPv4
- Uses AWS PrivateLink
- PrivateLink injects external services into a VPC via ENIs
- IEs have private IPv4 addresses and use DNS
- Provides new DNS names for accessed services
- DNS overrides allow private access without modifying apps
- DNS types:
- Endpoint Regional DNS – works in any AZ
- Endpoint Zonal DNS – resolves to ENI in a specific AZ
- Endpoint Private DNS – replaces default service DNS with IE IP automatically
Comparison: Access to SNS With and Without IE
Without IE

- Private instances cannot resolve or access the service (DNS not in VPC)
- Public instances access SNS via IGW
Without IE (without private DNS)

- Private instances can access the service via regional/zonal DNS
- App modification usually required
With IE (with private DNS)

- Both public and private instances use the service’s default DNS
- DNS resolves to IE → traffic goes through IE
- No app modification needed
Comparison: Gateway Endpoints vs Interface Endpoints
| Gateway Endpoint (GWE) | Interface Endpoint (IE) |
|---|---|
| Implemented as a gateway resource within the VPC | Implemented as an Elastic Network Interface (ENI) inside a subnet |
| Used specifically for S3 and DynamoDB services | Used for most AWS public services except DynamoDB |
| Supports both IPv4 and IPv6, along with TCP and UDP protocols | Supports only IPv4 and TCP |
| Highly available across the region by default | Requires one endpoint per Availability Zone to achieve high availability |
| Does not support Security Groups for controlling traffic | Supports Security Groups for network access control |
| Does not rely on PrivateLink | Built on AWS PrivateLink technology |
| Access is controlled via route tables (prefix lists added to routes) | Accessed through DNS resolution within the VPC (assigned a private IPv4 address) |
| No changes needed in application configuration | May require application updates depending on DNS setup (unless Private DNS is used) |
| Cannot be used for cross-region access to S3 or DynamoDB | Can be used to access services across different regions |
DEMO: VPCEs (IE, GWE) and EIGW
PART 1: Create a VPC Interface Endpoint (IE) to use Instance Connect on a private EC2 instance
- EC2 instance is in private subnet
sn-app-A. By default, we cannot connect via Instance Connect since it has no public IP. - Create a VPC IE in
sn-app-Avia:- Instance Connect UI → “EC2 Instance Connect Endpoint”
- Or directly via VPC → Endpoints
- Option: Preserve Client IP
- Enabled → instance sees your machine’s IP
- Disabled → instance sees the IP of the endpoint’s ENI
- Once the endpoint is created, Instance Connect can access the private instance.
- If client IP is not preserved, the instance shows the endpoint ENI IP in the last login info.

PART 2: Create a VPC Gateway Endpoint (GWE) to access S3 privately
- Private instance in
sn-app-Acannot access the public internet or S3.ping 1.1.1.1failsaws s3 lsshows nothing
- Create a GWE for S3:
- VPC → Endpoints → Create Endpoint → Type: AWS Services → filter by
s3→ Gateway type - Select the main route tables for private subnets (
sn-app-A)
- VPC → Endpoints → Create Endpoint → Type: AWS Services → filter by

3. Once the GWE is created, private instance can access S3:
aws s3 lslists buckets- Example:
aws s3 cp s3://<BUCKETNAME>/supersecret.txt supersecret.txt→cat supersecret.txtshows the content
4. Instance remains private: ping 1.1.1.1 still fails
PART 3: Create an Egress-only Internet Gateway (EIGW) for a private IPv6 instance
- EC2 instance in
sn-app-Ahas an IPv6 address but cannot reach the internetping -6 ipv6.google.comfails
- Create an EIGW:
- VPC → Egress-only Internet Gateway → Create → Attach to
A4L-VPC
- VPC → Egress-only Internet Gateway → Create → Attach to
- Update the Route Table for main subnets:

- Add default IPv6 route
::/0→ target = EIGW
4. Verify IPv6 connectivity:
ping -6 ipv6.google.comresponds
5. Optional test: confirm another EC2 instance in a different VPC cannot ping this IPv6 instance.
VPC Peering
VPC Peering – Concepts and Features
- Direct, private, and encrypted network link between two VPCs
- A logical gateway object is created inside both VPCs, referencing the other VPC
- One peering connection links exactly two VPCs
- Supports same-/cross-region and same-/cross-account peering
- Requirement: VPC CIDRs must not overlap
- Logical gateway objects = Peer gateway objects → routing configuration required
- Routes with destination IPs from the other VPC point to the peer gateway object
- Optional: Public hostnames can resolve to private IPs
- Same DNS names can be used to locate resources regardless of VPC
- Transitive peering is not supported
- Example: VPCA peered with VPCB, VPCB peered with VPCC → VPCA cannot reach VPCC unless a peering is explicitly created
- SGs & NACLs filter traffic
- Same-region SGs can reference peer SGs
- Cross-region SGs require using IP addresses/ranges
- Data travels encrypted
- Cross-region peering uses AWS global secure network
- Architecture diagram:

DEMO: Peering 3 VPCs
- Start with three private VPCs, one EC2 instance in each.
- Connect via Session Manager to EC2 in VPCA
- Ping instance in VPCB → no response (private VPCs by default)
- Create peering between VPCA and VPCB
- VPC → Peering connections → Create → VPCA as sender, VPCB as accepter
- Invitation model: accepter must accept the request
- Peering remains in Pending state until accepted
- Update Route Tables in both VPCA and VPCB
- Add route → destination = other VPC’s CIDR → target = peering object
- Update Security Groups
- Add inbound rules to allow ICMP/IPv4 traffic from the other VPC’s SG
- Ping between VPCA and VPCB instances should now succeed
- Repeat steps 3–6 to create peering between VPCB and VPCC
- Attempt A → C ping → fails
- VPC peering is not transitive; a direct peering between VPCA and VPCC is required
- Create peering between VPCA and VPCC
- Ping from VPCA to VPCC now works
Route 53 – Global DNS
Amazon R53 (Route 53) 101
Amazon Route 53 (R53) – Key Concepts
- DNS-as-a-Service (DNSaaS) → fully managed AWS DNS product
- Global service
- Single database replicated and accessible in all regions
- Globally resilient
- No need to select a region in the console
- Two main functionalities:
- Registered Domains – R53 as a domain registrar
- Hosted Zones – R53 as a DNS hosting provider
- Costs
- Domain registration
- Maintaining ownership
- Hosted zones hosting and query costs
R53 Registered Domains

- Interfaces with TLD registries (
.com,.io,.net,.org)- Example: PIR manages the
.orgregistry
- Example: PIR manages the
Domain registration workflow (e.g., animals4life.org):
- Check if domain is available
- Accept terms and purchase the domain
- R53 creates a ZoneFile (database storing DNS info)
- R53 allocates four AWS-managed name servers (NSs) for this domain
- Creates a hosted zone with the ZoneFile, storing it on the four NSs
- R53 communicates with the TLD (e.g., PIR)
- TLD NS records point to R53’s four servers → these become authoritative
- Transfer lock enabled by default → prevents domain from leaving R53
- If a hosted zone is deleted and recreated, update the NSs in Registered Domains to the new NSs
R53 Hosted Zones
- Hosted on four AWS-managed NSs
- NSs store DNS records (RRSETs)
Network visibility types:
- Public Hosted Zones – accessible from the internet
- Private Hosted Zones – linked to one or more VPCs, only accessible from those VPCs
Billing:
- Monthly fee per hosted zone
- Small fee per DNS query
- Large volume sites can increase query costs significantly
R53 Public and Private Hosted Zones
R53 Public Hosted Zone

- ZoneFile (DNS DB) hosted by four AWS-managed NSs, publicly accessible
- Stores RRSETs for the zone
- Accessibility
- From the public Internet
- Client walks the DNS tree → Root → TLD → R53 NSs
- NS records of TLD point to R53 NSs → zone is connected to global DNS
- From internal VPCs
- Via R53 Resolver
- VPC must have DNS resolution enabled and be linked to the hosted zone
- Direct NS access via VPC+2 address in each subnet
- From the public Internet
- External domains can use R53 public hosted zones
- Example workflow:
- Register domain externally (Namecheap, GoDaddy, etc.)
- Create public hosted zone in R53 → AWS allocates 4 NSs
- Update external registrar to point domain to the 4 R53 NSs
- Example workflow:
R53 Private Hosted Zone

- Not accessible from public internet, only from associated VPCs
- VPC association
- Can be done via console, CLI, or API
- Can associate a VPC in a different account (CLI/API only)
- DNS resolution
- Resources in associated VPCs use VPC+2 address (R53 resolver)
- Non-associated VPCs cannot access the zone
Split-View (Split-Horizon) DNS

- Private + public zone with the same domain name
- Purpose:
- Sensitive/internal records are kept in private zone
- Public records are exposed to the Internet
- Allows internal intranet and public website to share same domain
- Records overlap but private records remain inaccessible externally
CNAME Records vs R53 Alias Records
Limitations of CNAME Records
- Function: maps one hostname to another hostname
- Example:
www.catagram.io → catagram.io
- Example:
- Limitation: cannot be used for the domain apex (naked domain)
- Example:
catagram.io → www.animals4life.orgis invalid - This restriction exists because the DNS standard does not allow CNAME records at the apex
- Example:
- Works correctly for subdomains:
www.catagram.io → ELB DNS nameis validcatagram.io → ELB DNS nameis invalid
- Many AWS services (like ELB or CloudFront) provide access via DNS names rather than IP addresses, which makes apex mapping using CNAME impossible
Route 53 Alias Records
- AWS-specific record type, extending standard DNS functionality
- Function: map a hostname directly to an AWS resource
- Functions like CNAME for subdomains
- Supports apex/naked domains, enabling mapping such as
catagram.io → ELB
- Requirements: must use Route 53 for DNS hosting
- Types of alias records include
A-ALIAS,TXT-ALIAS, etc., determined by the record type returned by the AWS resource - Can point to AWS resources including ELB, CloudFront, API Gateway, Global Accelerator, Elastic Beanstalk, and S3
- Requests for AWS resources using alias records do not incur additional DNS query charges
- Recommended best practice for all DNS records pointing to AWS resources
Key guideline:
Use CNAME for subdomains. Use Alias records for apex/naked domains or when pointing to AWS-managed services.
R53 Simple Routing Policy
Route 53 Routing Policies Overview
- Definition: rules that determine how Route 53 responds to DNS queries for a hosted domain
- Responses can return IP addresses or AWS resources
- Routing decisions can be based on:
- Resource health
- Geographic location of the client
- Testing or deployment phases
- Load distribution or balancing
- Use cases:
- Optimize traffic distribution
- Reduce latency
- Implement failover and resilience strategies
- Route 53 offers multiple routing policies to support regional and global architectures, each with different features
Route 53 Simple Routing

- Architecture: one record per hostname; each record can contain multiple values
- Example: for hostname
www, anArecord can include multiple IPv4 addresses - Route 53 returns all values in random order; the client selects one to connect
- Example: for hostname
- Use case: single service routing (e.g., one web server or load-balanced service)
- Default routing policy in Route 53
- Limitation: does not support health checks
- No automated detection of unavailable resources
- Other routing policies allow intelligent routing based on health status
- Pros & Cons:
- Simple and easy to manage
- Limited flexibility and lacks resilience features
R53 Health Checks
Route 53 Health Checks Overview
- Purpose: monitor and evaluate the health and performance of resources to support intelligent DNS routing
- Types of health checks:
- Endpoint health checks – assess the status of a specific endpoint (internal AWS resource or external IP/domain)
- State: healthy or unhealthy
- Status changes based on repeated checks
- Calculated health checks – aggregate results from multiple health checks to determine overall application health
- CloudWatch Alarm health checks – leverage CloudWatch alarms (configured separately) to reflect application or system-level health
- Endpoint health checks – assess the status of a specific endpoint (internal AWS resource or external IP/domain)

- Integration with routing policies: health checks can influence routing decisions in advanced Route 53 policies
- Health checks are defined independently from DNS records
- Global health checker network:

- Distributed worldwide to ensure reliable evaluation
- Default check frequency: every 30 seconds; optional 10-second interval at additional cost
- Endpoint must allow queries from health checkers to avoid false negatives
- Health considered healthy if ≥18% of checkers report healthy
- Records marked unhealthy are generally excluded from DNS responses
Endpoint Health Checks – Configuration
Basic options:

- Specify endpoint by IP address or domain name
- If using domain name, the resolved IP may vary per health checker
- Protocol:
- TCP: endpoint healthy if TCP connection completes successfully (10-second timeout)
- HTTP/HTTPS: endpoint healthy if:
- TCP connection completes within 4 seconds
- Response returns HTTP 2xx/3xx within 2 seconds
- HTTP/HTTPS checks provide higher accuracy than TCP-only checks
Advanced options:

- Failure threshold: number of consecutive successful/failed checks to change endpoint status, improving stability against intermittent failures
- String matching (HTTP/HTTPS only): endpoint considered healthy only if response body contains specified string within the first 5120 bytes
- Latency measurement: track response times from endpoint to health checker
- Maintenance mode: temporarily disable checks when performing updates or maintenance
- Regional health check control: optionally restrict health checks to specific AWS regions
Health Check Notifications

- Optional integration with CloudWatch Alarms
- Trigger notifications via SNS or other AWS services if endpoint is unhealthy
- Health checks can still influence DNS routing independently of notifications
R53 Failover Routing Policy
Route 53 Failover Routing – Architecture

- Concept: a single DNS hostname can have primary and secondary records, each pointing to a distinct AWS resource.
- Health check dependency:
- If the primary resource is healthy, DNS queries return the primary record
- If the primary resource is unhealthy, queries automatically return the secondary record
- Use case: implement active-passive failover
- Route traffic to the main resource when operational
- Redirect to a backup resource during failures or maintenance
- Example scenario:
- Primary: EC2 instance serving the application
- Secondary: S3 static website acting as a maintenance or fallback page
This architecture ensures minimal downtime and transparent failover at the DNS level.