Scale-Out Series · Part 1 of 2

Web Scale-Out & Load Balancing.

Expanded notes from my internal architecture talk on scaling web systems horizontally. We start from the classic three-tier web stack, examine why single machines hit hard limits, and walk through Layer 2, Layer 4 and Layer 7 load balancers along with the five standard traffic distribution algorithms.

  • Scale Up vs Scale Out
  • Stateless Web Tier
  • L2 · L4 · L7 Routing
  • 5 Balancing Algorithms
  • Interactive Simulator

01 · Starting point

Base structure & why single nodes run out of room.

Almost every web product begins with the same straightforward architecture: a browser running the frontend application talks to a single backend web server, which executes SQL queries against a single database. Simple, cheap and fast to ship—until traffic grows.

Baseline Three-Tier Architecture

Slide 2 · Single web server + single database
Browser FE application UI rendering, client state, HTTP/JSON requests Web Server BE application Auth, business logic, API orchestration, CPU & RAM Database SQL storage Disk I/O, buffer pool, connections, transactions

Every machine has finite CPU, memory, disk I/O, network bandwidth and storage. When user concurrency or dataset size outgrows one host, latency spikes and requests queue up.

Vertical scaling

Scale Up (Bigger Machine)

Upgrade the single server with more vCPUs, faster NVMe disks and larger RAM. This is the quickest short-term fix because your application architecture and deployment stay unchanged.

  • Strengths: Zero code changes, no distributed coordination, simple operations.
  • Limits: Steep cost curve at high tiers, hard hardware ceiling, maintenance requires downtime, and the server remains a single point of failure (SPOF).
Horizontal scaling

Scale Out (More Machines)

Add multiple commodity servers working in parallel behind a routing layer. Capacity grows roughly linearly with node count, and losing a single node no longer takes down the service.

  • Strengths: High availability, elastic autoscaling for traffic spikes, rolling zero-downtime deployments.
  • Trade-offs: Requires a load balancer, stateless application nodes, and eventually distributed data strategies for the database tier.

02 · The easiest first win

Scaling out the web server tier.

Putting a load balancer in front of a pool of web servers is the easiest and highest-leverage way to scale out a system. Because web servers primarily execute application logic rather than acting as the source of truth, you can add or remove instances within seconds.

Horizontal Web Tier Behind a Load Balancer

Slide 3 · Stateless web servers sharing one database
Browser / Client Load Balancing Web Server 1 Stateless instance Web Server 2 Stateless instance Web Server N Stateless instance Database (Next Bottleneck)

Adding web nodes immediately absorbs more concurrent HTTP requests, TLS handshakes, JSON serialisation and CPU-bound business logic—while also letting you take any single web host out of rotation for patching without downtime.

Prerequisite 1

Keep Web Nodes Stateless

Never store user sessions or uploaded files only on local disk or in-process memory. Move sessions into Redis or signed JWT tokens, and store files in S3 / Azure Blob so any server can handle any request.

Prerequisite 2

Health Checks & Draining

Expose lightweight /healthz endpoints so the load balancer automatically stops routing to unhealthy nodes, and drain in-flight requests gracefully during deployments.

Prerequisite 3

Redundant Load Balancers

A single load balancer reintroduces a single point of failure. In production, pair balancers with active-passive failover (Keepalived / VRRP) or managed multi-AZ cloud load balancers.

03 · OSI layers in practice

Types of load balancing: Layer 2, Layer 4 & Layer 7.

Load balancers trade raw packet throughput for application awareness. The lower in the OSI stack you route, the less work the load balancer has to perform per packet—and the higher in the stack you go, the smarter your routing decisions become.

The Envelope Analogy (from my talk notes)

Think of an HTTP request as a letter inside a postal envelope: Layer 2 only swaps the forwarding address label on the outside; Layer 4 rewrites the envelope (IP & port); Layer 7 opens the envelope, reads or modifies the letter inside (HTTP headers, cookies, URL path), and puts it into a fresh envelope.

Layer 2 · Data Link (DSR)

Direct Server Return

Ultra-fast local server-based load balancing (~8× faster than Layer 4). Direct routing rewrites only the destination MAC address of incoming Ethernet frames on the fly, leaving IP and TCP headers intact.

  • Envelope analogy: Change the forwarding address on the envelope.
  • Asymmetric return path: Backend servers hold the same Virtual IP (VIP) on a loopback interface (with ARP suppressed) and reply directly to the client—so large response payloads never pass back through the balancer.
  • Constraint: Balancer and backend servers must share the same Layer 2 broadcast domain (VLAN / subnet). Classic tool: LVS-DR.
Layer 4 · Transport (TCP/UDP)

Network Load Balancing

Fast transport-level distribution. Routes traffic using network variables such as source/destination IP address and TCP/UDP port without inspecting or decrypting the application payload.

  • Envelope analogy: Rewrite the envelope.
  • Protocol agnostic: Works equally well for HTTP, raw TCP, gRPC, MySQL, Redis or custom game/IoT protocols, and supports TLS pass-through.
  • Trade-off: Cannot route by URL path, HTTP host header or session cookie. Classic tools: LVS-NAT, HAProxy (TCP mode), AWS NLB.
Layer 7 · Application (HTTP/S)

Application Load Balancing

Content-aware routing; more processor-intensive. Terminates TLS/HTTPS on the balancer so it can read HTTP methods, URL paths, host headers and cookies before picking a backend.

  • Envelope analogy: Rewrite the whole thing—both the content and the envelope.
  • Rich capabilities: Required for cookie-based session persistence inside HTTPS streams, path routing (/api vs /static), canary weights, WAF filtering, compression and HTTP/2 multiplexing.
  • Classic tools: Nginx, HAProxy (HTTP mode), Envoy, AWS ALB.

Packet Path: Why Layer 2 (DSR) Scales Outbound Bandwidth So Well

Inbound requests are small; outbound responses are typically 10×–100× larger
LAYER 2 DIRECT ROUTING (DSR) Client L2 LB Server MAC swap only Direct response (bypasses LB) LAYER 4 / LAYER 7 PROXY Client L4 / L7 LB Server Both request & response traverse LB Enables NAT, TLS termination & HTTP rules
Layer Inspects Relative Speed Typical Use Cases Key Trade-off
Layer 2 (DSR) Ethernet MAC address Fastest (~8× L4) Ultra-high throughput ingress, media/CDN edge, large response payloads Same L2 network required; VIP loopback setup; no HTTP/cookie visibility
Layer 4 (TCP/UDP) IP address & port Very fast Non-HTTP protocols, TLS pass-through, front-tier in front of L7 Nginx clusters Connection-level only; cannot inspect URLs, headers or cookies
Layer 7 (HTTP/S) URL, headers, cookies, body CPU-intensive Microservice path routing, HTTPS cookie stickiness, WAF, canary releases Terminates TLS & parses HTTP; lower raw PPS per core than L2/L4
Real-World Pattern: Combining L4 + L7

Large internet platforms rarely pick just one layer. A common architecture places an ultra-fast L4 balancer (e.g. LVS or cloud NLB) at the front to absorb raw TCP traffic and distribute it across a horizontally scaled pool of L7 reverse proxies (Nginx / Envoy) that terminate TLS and route to backend services.

04 · Traffic distribution

Industry standard load balancing algorithms.

Once a load balancer receives a request, it needs a deterministic or state-aware rule to choose a healthy backend server. Selecting the right algorithm depends on whether your servers are identical, how evenly requests behave, and whether clients benefit from sticking to the same node.

Static · Equal nodes

1. Round Robin

Relies on a simple rotation across servers of equal capacity. Each new request goes to the next available server, which then moves to the back of the queue.

  • Best for: Homogeneous instances handling fast, roughly uniform requests.
  • Watch out: Ignores slow or overloaded requests—one server stuck on heavy reports keeps receiving new work.
Static · Mixed hardware

2. Weighted Round Robin

Extends Round Robin by assigning a numeric weight to each backend server according to its CPU/RAM capacity (for example, a 16-core host gets weight 4 while a 4-core host gets weight 1).

  • Best for: Mixed instance sizes, hardware migrations, or gradual canary rollouts (e.g. 5% traffic to a new release).
Dynamic · Peak resilience

3. Least Connections

Directs each new request to the server with the fewest active open connections. Especially effective during peak hours when some requests take milliseconds and others hold connections open much longer.

  • Best for: Variable request durations, long-lived API calls, WebSockets or database-backed endpoints.
Dynamic · Latency aware

4. Least Response Time

Builds on Least Connections by factoring in each server’s recent response latency, prioritizing the healthy server with both low active connections and the fastest average response time.

  • Best for: Multi-zone deployments or environments where noisy neighbours or GC pauses temporarily slow down one node.
Deterministic · Affinity

5. IP / URL Hash

Hashes the client’s IP address (or requested URL) to assign traffic consistently to a fixed backend server.

  • Best for: Maximizing local in-memory cache hit rates (URL hash) or lightweight session stickiness (IP hash).
  • Watch out: Plain modulo hashing (hash % N) remaps almost all clients when a server is added or removed—which is why Consistent Hashing (covered in Part 2) is used at scale.

05 · Hands-on intuition

Interactive load balancer simulator.

Switch between the five algorithms below and send requests against a heterogeneous 3-node cluster (where Server A has higher capacity and lower latency, while Server C is smaller and slower) to see how each policy behaves in real time.

Select algorithm & dispatch traffic

Rotates evenly: A → B → C → A…
Server AWeight 4 · 18 ms
Handled: 0Active: 2
Server BWeight 2 · 36 ms
Handled: 0Active: 5
Server CWeight 1 · 85 ms
Handled: 0Active: 3
$ Ready. Click "Send 1 request" or "Send burst" to observe routing decisions.

Next in the Scale-Out Series · Part 2 of 2

You scaled the web tier. Now the database is on fire.

Once 10 stateless web servers sit behind a load balancer, all of their queries converge onto a single database. Continue to Part 2 for Read Replicas, Directory/Range/Key Sharding, Consistent Hashing, 2ⁿ bitwise scaling, Azure MySQL connection limits, and real EXPLAIN SQL tuning benchmarks.