Background
Sections
IntroductionRequirements & Problem AnalysisConstraints & AssumptionsEstimation TechniquesFunctional vs Non-Functional RequirementsMoSCoW PrioritizationSystem Design FundamentalsArchitecture DiagramClass DiagramComponent DiagramData Flow Diagram (DFD)ER Diagram (Entity-Relationship Diagram)High Level Design (HLD)Low Level Design (LLD)Sequence DiagramState DiagramUse Case DiagramData StorageDocument StoresFile StorageGraph DatabasesIn-Memory DatabasesKey-Value StoresNewSQLNoSQL DatabasesObject StorageSQL Databases (RDBMS)Time-Series DatabasesWide-Column StoresDatabase ConceptsACID PropertiesCAP TheoremConsistency ModelsIndexingNormalization & DenormalizationReplicationSharding & PartitioningTransactions & Isolation LevelsScalabilityAuto-Scaling & ElasticityConsensus & Leader ElectionLoad BalancingReplication & Read ReplicasSharding & PartitioningVertical vs Horizontal ScalingAvailability & ReliabilityBackup & Data DurabilityCircuit BreakerData ConsistencyDisaster RecoveryFault Tolerance & FailoverGraceful DegradationHigh AvailabilityNetworkingCDNDNSFirewalls & VPNHTTP & HTTPSLoad Balancer & Reverse ProxyTCP/IP & UDPWebSocketsCachingCache InvalidationCache Read/Write PatternsCaching LayersEviction PoliciesRedis vs MemcachedMessaging & CommunicationDead-Letter QueueIdempotencyKafka vs RabbitMQ vs SQSMessage QueuesPub/SubCompute & ServicesAPI GatewayContainers & OrchestrationMonolith vs MicroservicesServerlessService DiscoveryService MeshWeb Server & App ServerAPI DesignAPI Versioning & IdempotencyAuthentication & AuthorizationGraphQLgRPCPaginationRate Limiting & ThrottlingRESTSecurityAuthentication & AuthorizationData PrivacyEncryptionInput Validation & InjectionOAuth2 & JWTSecrets ManagementXSS & CSRFStorage & File SystemsBackup & RetentionBlock vs File vs Object StorageData Lakes & WarehousesDistributed File SystemsEphemeral StorageObservability & MonitoringDistributed TracingHealth ChecksLoggingMetricsSLI, SLO, SLADesign PatternsBulkhead PatternCircuit Breaker PatternCreational PatternsRate Limiter PatternRetry PatternStructural & Behavioral Patterns

Firewalls & VPN

7 min read

In a Nutshell

Firewalls and VPNs are the two classic tools for controlling who can reach your systems and how traffic travels between them. A firewall is a filter that decides which network traffic is allowed based on rules — source, destination, port, protocol — forming the perimeter that keeps unwanted traffic out. A VPN (Virtual Private Network) creates an encrypted tunnel across an untrusted network (like the public internet), so two endpoints can communicate as if they were on the same private network. Together they answer the network-security questions every architecture must address: what's allowed in, and how do we connect distant private systems safely.

2D minimalistic diagram split in two: left side shows a firewall as a brick-wall filter between the internet and a private network, allowing some arrows (green, port 443) through and blocking others (red X); right side shows a VPN as an encrypted tunnel connecting a remote user to a private network across the public internet

How It Actually Works

Firewalls: Filtering Traffic by Rules

A firewall evaluates each packet or connection against an ordered rule set and permits or denies it. The foundational best practice is default-deny: block everything, then explicitly allow only what's needed.

Example rule set (evaluated top-down, first match wins):
  ALLOW  tcp  from any        to web-tier   port 443   (HTTPS in)
  ALLOW  tcp  from web-tier   to app-tier   port 8080  (web → app)
  ALLOW  tcp  from app-tier   to db-tier    port 5432  (app → db)
  DENY   all  from any        to any                    (default deny)

Types of Firewalls

Type Inspects Notes
Packet-filtering (stateless) Individual packets (IP, port) Fast, simple, no connection context
Stateful Connection state (tracks sessions) Allows return traffic automatically; the common baseline
Application-layer (WAF) HTTP content (payloads) Blocks SQLi, XSS, bad requests (see XSS & CSRF)
Next-gen (NGFW) Deep packet + app + threat intel Combines the above + IDS/IPS

Cloud Firewalls: Security Groups vs NACLs

In cloud environments, firewalling is done with virtual constructs:

Security Group Network ACL
Scope Per instance/resource Per subnet
State Stateful (return traffic auto-allowed) Stateless (must allow both directions)
Rules Allow only Allow and deny
Use Fine-grained instance rules Broad subnet-level guardrails

These are the practical, everyday firewall tools in cloud architecture — you define which tiers can talk to which, on which ports (see VPC & Networking).

Defense in Depth and Network Segmentation

Firewalls enable segmentation: split the network into tiers (public → web → app → data) where each tier can only talk to its neighbors. If an attacker breaches the web tier, segmentation stops them from directly reaching the database — the blast radius is contained.

Internet ──▶ [Public subnet: LB] ──▶ [Private: web] ──▶ [Private: app] ──▶ [Private: db]
             only 443 exposed        no direct           no direct         no internet
                                     internet access     internet access   access at all

VPNs: Encrypted Tunnels Over Untrusted Networks

A VPN encapsulates and encrypts traffic so it can traverse the public internet privately. Two main use cases:

VPN Type Connects Use
Remote-access VPN A user's device → a private network Employees reaching internal systems
Site-to-site VPN Two networks (e.g., office ↔ cloud VPC) Bridging data centers/clouds

Protocols include IPsec (site-to-site standard), WireGuard (modern, fast, simple), and OpenVPN. The tunnel provides confidentiality and integrity — even over hostile networks, traffic is unreadable and tamper-evident.

The Shift Toward Zero Trust

The traditional model — "trust everything inside the perimeter" — is fading. Once an attacker gets past the firewall, a flat internal network lets them roam freely. Zero Trust flips this: never trust, always verify. Every request is authenticated and authorized regardless of network location, so being "inside" grants no implicit trust. VPNs are increasingly complemented or replaced by identity-aware proxies (e.g., BeyondCorp-style access).

2D minimalistic diagram contrasting two models: left shows the "castle-and-moat" perimeter model with a strong outer wall but a flat, fully-trusted interior where a breached attacker moves freely; right shows the "zero trust" model where every internal service has its own authentication checkpoint, so a breach at one point can't move laterally

Seeing It in Action

Scenario: Securing a three-tier web app in a cloud VPC.

Network layout (segmentation via security groups):

  Internet
     │  (only 443 allowed inbound)
  ┌──▼─────────────────┐
  │ Public subnet       │   SG-LB: allow 443 from 0.0.0.0/0
  │   Load Balancer     │
  └──┬─────────────────┘
     │  (only from SG-LB, port 8080)
  ┌──▼─────────────────┐
  │ Private subnet      │   SG-web: allow 8080 ONLY from SG-LB
  │   Web/App servers   │   no public IP; outbound via NAT gateway
  └──┬─────────────────┘
     │  (only from SG-web, port 5432)
  ┌──▼─────────────────┐
  │ Private subnet      │   SG-db: allow 5432 ONLY from SG-web
  │   Database          │   no internet access at all
  └────────────────────┘

Admin access (no public SSH!):
  Engineer → WireGuard VPN → bastion in VPC → private resources
  Database is never reachable from the internet; only via the VPN + web tier.

Why this layout is safe: the database has no path from the internet — it accepts connections only from the web tier's security group. Admins reach internal systems through a VPN, not by exposing SSH publicly. Each tier's firewall rules reference other security groups rather than IP ranges, so the policy stays correct even as instances autoscale. This is defense in depth: multiple independent layers must all fail for an attacker to reach the data.

Interview Questions

  1. Q: What is a default-deny firewall policy and why is it the best practice? Hint: Deny all traffic by default, then explicitly allow only what's required. It's safer than default-allow because it fails closed — anything not anticipated is blocked rather than permitted. New services/ports must be consciously opened, shrinking the attack surface and preventing accidental exposure from misconfiguration.

  2. Q: What's the difference between a stateful and a stateless firewall (or security group vs NACL)? Hint: Stateful firewalls (security groups) track connection state, so return traffic for an allowed outbound connection is automatically permitted — you only write one direction. Stateless (NACLs) evaluate each packet independently with no session memory, so you must explicitly allow both request and response directions. Security groups are per-instance/allow-only; NACLs are per-subnet and support deny rules.

  3. Q: How does network segmentation limit the impact of a breach? Hint: Splitting the network into tiers (public → web → app → data) with firewall rules that only permit neighbor-to-neighbor traffic means a compromised web server can't directly reach the database. It contains the blast radius — an attacker must breach multiple independent layers, and lateral movement is blocked, buying detection/response time.

  4. Q: What does a VPN provide, and what are the two main types? Hint: An encrypted tunnel over an untrusted network, giving confidentiality and integrity so endpoints communicate as if on a private network. Remote-access VPN connects a user's device to a private network (employees → internal systems); site-to-site VPN connects two networks (office ↔ cloud VPC / data center bridging). Protocols: IPsec, WireGuard, OpenVPN.

  5. Q: What is Zero Trust and why is it replacing the traditional perimeter model? Hint: "Never trust, always verify" — every request is authenticated and authorized regardless of network location, so being inside the perimeter grants no implicit trust. It addresses the weakness of castle-and-moat security: once past the firewall, attackers roam a flat trusted network freely. Zero Trust prevents lateral movement by requiring per-request verification everywhere.

References

Dive Deeper