30 min read Full-Stack System Architecture Lesson 22
Part 4 — Modern Web Infrastructure & System Integration

Lesson 22 — How a Modern Web Application Works End-to-End

The Complete System: From Browser to Database, Cache, Storage, Queue & Email

Throughout Course 08, we have systematically dissected every foundational building block of the Internet: DNS, IP, BGP Routing, TCP, UDP, QUIC, HTTP, HTTPS, CDNs, Load Balancers, Application Servers, Caching, Databases, Object Storage, Queues, Workers, Email Protocols, Cloud Infrastructure, and Containers.

DNS → IP → Routing → TCP/QUIC → TLS → CDN → Load Balancer → App Server → Cache/DB/Queue/Worker → Email

Yet the most critical engineering question remains:

“How do all these isolated components operate together in harmony to deliver a high-performance, resilient, modern web application?”

Imagine you have engineered a modern SaaS (Software as a Service) project management platform called TaskFlow (app.taskflow.com). When an end-user navigates to the site, logs in, views their dashboard, creates a project, uploads assets, and invites teammates, an extraordinary multi-layered choreography unfolds across browser engines, edge points of presence, and cloud data centers. In this grand lesson, we dissect every single layer.

What We Will Learn (Part 1 — Sections 1 to 27)

  • 1. The Complete Application Model: TaskFlow SaaS anatomy
  • 2. Surface vs Reality: Browser simplicity vs backend orchestration
  • 3. Step 1: User Enters URL: Scheme, domain name, and resource path
  • 4. Step 2: DNS Resolution: Finding Anycast IPs and edge destinations
  • 5. Step 3: Global Internet Routing: BGP, AS transit, and IXP hops
  • 6. Step 4: TLS / HTTPS Connection: Cipher suites and cryptographic handshake
  • 7. Step 5: CDN & Edge Layer: Cached assets vs dynamic origin routing
  • 8. Static Content Mechanics: JavaScript bundles, stylesheets, and SVG hits
  • 9. Dynamic API Requests: Forwarding requests to origin infrastructure
  • 10. Step 6: Load Balancing: Distributing traffic across app clusters
  • 11. Load Balancer Decision Engine: Health checks and distribution algorithms
  • 12. Step 7: Application Server: Routers, controllers, and service layers
  • 13. Frontend vs Backend Boundaries: Client React vs server-side Go/Node/Laravel
  • 14. The Login Lifecycle: Structure of POST /api/login
  • 15. Backend Database Queries: SQL execution and relational fetching
  • 16. Password Security & Hashing: Why plaintext is forbidden; Argon2 & Bcrypt salts
  • 17. Authentication State: Secure cookies vs stateless JWT tokens
  • 18. The Need for In-Memory Caching: Preventing relational database saturation
  • 19. Cache Hit Mechanics: Sub-millisecond retrieval from RAM via Redis
  • 20. Cache Miss & Population: Database fallbacks and write-back cycles
  • 21. Database vs Cache Roles: Single source of truth vs volatile speed boost
  • 22. Dashboard Aggregation: Serving GET /api/dashboard
  • 23. Browser Rendering Pipeline: DOM, CSSOM, Render Tree, Layout, Paint, Compositing
  • 24. Project Creation Request: Handling POST /api/projects
  • 25. Two-Tier Validation: Client UX validation vs server security enforcement
  • 26. Authentication vs Authorization: Identity verification vs role permissions
  • 27. Database Transactions (ACID): BEGIN, COMMIT, and ROLLBACK guarantees
1 Real-World Architecture Model

1. Imagine a Complete Application: TaskFlow

To comprehend the intricate machinery of a modern distributed web application, let us ground our exploration in a concrete system. Suppose we are building a collaborative project management SaaS platform called:

TaskFlow
Domain: app.taskflow.com

A cloud application where users create workspaces, invite team members, upload attachments, track tasks, and receive real-time notifications and automated emails.

TaskFlow consists of several core capabilities:

Authentication: Secure login, cryptographic password hashing, and session management.
Project & Task CRUD: Reading and writing project state with strict relational transactional integrity.
Asset Uploads: Securely storing cover images, documents, and media without choking application servers.
Async Messaging & Email: Dispatching team invites and notifications in the background without blocking the browser.

Now, picture a user sitting in a coffee shop in Dhaka. They open their laptop browser, type https://app.taskflow.com, and press Enter. What happens at this exact moment?

2 Surface vs Reality

2. What the User Sees vs What Actually Happens

To an end-user, the web appears deceptively simple:

Browser → Website

The user believes their laptop communicates directly with a website server that immediately paints the page. In reality, an astonishing cascade of coordinated systems executes behind the scenes:

// Synchronous Request Path (Direct Response Flow)
Browser (Client Device)
↓ 1. Local Network, Wi-Fi & OS Stub Resolver
DNS Resolver Hierarchy (Root → TLD → Authoritative DNS)
↓ 2. Global BGP Anycast Routing across Autonomous Systems
CDN / Edge Point of Presence (Edge Cache, TLS Termination)
↓ 3. Dedicated Origin Tunnel across Backbone Fibers
Cloud Load Balancer (Health Probing, Algorithmic Traffic Balancing)
↓ 4. Containerized App Server Fleet
Application Server (Routing → Middleware → Business Logic)
↓ 5. In-Memory Acceleration & Relational Persistence
Cache (Redis) & Database (PostgreSQL / MySQL)
// Asynchronous Background Pipeline (Decoupled Processing)
Application Server → Message Queue (Redis Streams / RabbitMQ / SQS)
↓ Background Task Consumption
Worker Fleet → External Infrastructure (Email SMTP / Push Gateways / S3)

Let us trace this entire journey link by link—from the user's keystroke to the silicon in the cloud data center.

3 First Step

3. Step 1 — User Enters URL

The user enters the target address into the browser's address bar:

https://app.taskflow.com

The browser immediately parses this Uniform Resource Identifier into three distinct components:

Scheme (https://): Dictates that communication must use encrypted TLS transport over default TCP port 443.
Hostname (app.taskflow.com): The human-readable domain name. However, physical Internet routers cannot route packets using domain names; they only understand IP addresses (IPv4 / IPv6).
Resource Path (/): The default root path requesting the primary index document or application shell.
Key Takeaway: At this initial instant, the browser has zero knowledge of where the server is located or which IP address corresponds to app.taskflow.com. It must first initiate a DNS lookup.
4 Name Resolution

4. Step 2 — DNS Resolution

The browser inspects its internal memory cache, queries the operating system DNS cache, and, if not found, delegates the query via the OS stub resolver to a recursive DNS resolver (such as 1.1.1.1 or an ISP resolver).

app.taskflow.com → Recursive Resolver → Root (.) → TLD (.com) → Authoritative DNS → Destination IP

In modern architectures, the domain name does not point directly to a single physical server in a back room. Instead, it points to a CDN (Content Delivery Network) or Anycast Edge IP:

# DNS Resolution Result:
app.taskflow.com. 300 IN A 104.21.58.112
app.taskflow.com. 300 IN AAAA 2606:4700:3033::6815:3a70
Core Principle: The sole purpose of DNS is resolving hostnames to network endpoints. DNS never executes application business logic or backend code. It is the Internet's global telephone directory.
5 Packet Transit

5. Step 3 — Internet Routing

Armed with the destination IP address, the browser delegates packet transmission to the operating system's TCP/IP stack. How does the packet traverse the physical globe?

Computer (Dhaka) → Wi-Fi Router → Local ISP (AS) → National IXP (BDIX) → Submarine Cable → Edge PoP

Recall BGP (Border Gateway Protocol) from Lesson 12. Global routers exchange autonomous system routing tables to compute optimal transit paths. If TaskFlow utilizes an Anycast edge provider (such as Cloudflare or Fastly), the user's packet does not travel thousands of miles to an overseas server. Instead, it terminates at the nearest local Edge Point of Presence (PoP) in Dhaka within 5 to 10 milliseconds!

6 Cryptographic Security

6. Step 4 — TLS / HTTPS Connection

Once the TCP three-way handshake establishes transport connectivity with the edge server, the browser and server negotiate cryptographic parameters:

HTTPS = HTTP (Plaintext Application Data) + TLS (Cryptographic Tunnel)

Under TLS 1.3, this handshake finishes in a single round trip:

  • ClientHello: The browser announces supported cipher suites and transmits its Diffie-Hellman key share.
  • ServerHello & Certificate: The server responds with its key share and digital certificate verifying ownership of app.taskflow.com.
  • Symmetric Session Key Computation: Both parties derive identical symmetric encryption keys (e.g., AES-GCM or ChaCha20).

From this point forward, no intermediate Wi-Fi sniffer, ISP, or adversary can eavesdrop on or tamper with user traffic.

7 Edge Filtering

7. Step 5 — CDN / Edge Layer

The browser now dispatches its HTTP requests. Crucially, these requests do not hit the origin backend directly; they arrive at the CDN Edge Server.

Browser → CDN Edge Node (Local PoP) → [Edge Routing Decision Engine]

The edge node inspects request headers, paths, and methods to make an instant architectural choice:

Static Asset?

Is the request targeting a CSS file, JS bundle, font, or image? If yes, serve it instantly from local edge SSD cache. Do not wake up origin servers!

Dynamic Request?

Is the request an API mutation such as POST /api/login? Forward it immediately over optimized private cloud backbones to the origin data center.

8 Static Content Delivery

8. What is Static Content?

When the browser launches TaskFlow, it must download the client-side user interface. These assets are identical for every user worldwide:

GET /assets/index.js (Compiled React Bundle)
GET /assets/styles.css (Tailwind CSS Stylesheet)
GET /assets/logo.svg (Vector Brand Icon)
GET /favicon.ico (Browser Tab Icon)

These are Static Assets. Once cached at the edge, they produce an instant Cache HIT, delivering responses to the browser in just 15 to 20 milliseconds without ever touching the origin application server.

Browser → CDN Edge → [Local Cache HIT] → Browser (Latency: 15ms)
9 Live Transactions

9. What is a Dynamic Request?

Once static assets render the login screen, the user enters their email and password and clicks “Sign In”.

POST /api/login HTTP/1.1

This is a Dynamic Request. The CDN edge cannot cache an answer to this request because it contains unique user credentials that must be authenticated against the live database.

Recognizing this, the CDN routes the request over persistent TCP tunnels directly to the origin cloud infrastructure:

Browser → CDN Edge → [Origin Tunnel] → Cloud VPC → Load Balancer
10 Traffic Distribution

10. Step 6 — Load Balancer

In production, TaskFlow never runs on a solitary server. A single server would represent an immediate single point of failure. Instead, the entry gate to the cloud virtual private cloud (VPC) is a high-availability Load Balancer (such as AWS Application Load Balancer, NGINX, or HAProxy).

Load Balancer (Traffic Director)
App Server 1
Healthy (22% load)
← distribute →
App Server 2
Healthy (18% load)
← distribute →
App Server 3
Healthy (31% load)

The load balancer distributes incoming concurrent traffic across multiple active application instances, preventing any individual server from being overwhelmed.

11 Health Monitoring

11. What Does a Load Balancer Look For?

A load balancer does not route traffic blindly. It actively evaluates server vitality:

Active Health Checks Every 5 seconds, it queries /health on each target. If an instance responds with 200 OK, it is marked healthy.
Balancing Algorithms Round Robin, Least Connections (allocating requests to servers with the fewest active tasks), or IP Hashing for stickiness.

If App Server 2 crashes or suffers out-of-memory errors:

App 1: Healthy ✓ (Traffic Active)
App 2: UNHEALTHY ✗ (Instantly Isolated by Load Balancer)
App 3: Healthy ✓ (Traffic Active)

The user never experiences a failed connection because the load balancer seamlessly re-routes traffic to healthy nodes.

12 Core Processing

12. Step 7 — Application Server

The load balancer forwards the login request to App Server 1. The application server is the brain of the system, structured into clear architectural tiers:

HTTP Request (POST /api/login)
↓ 1. Router (Matches path and HTTP verb to the appropriate controller)
AuthController.login(req, res)
↓ 2. Middleware & Validation (Sanitizes input, enforces rate limiting)
AuthService.authenticate(email, password)
↓ 3. Business Logic & Domain Security Rules
UserRepository.findByEmail(email)
↓ 4. Data Access Layer (Executes optimized SQL or ORM queries)
JSON Response Generation & Secure Cookie Serialization

The application server interprets client intent, applies business logic, communicates with persistence layers, and synthesizes structured responses.

13 Architectural Boundaries

13. Where Do Frontend and Backend Live?

In modern decoupled architectures, the separation between client and server is absolute:

Frontend (Client-side)

Executes in the user's browser memory (React, Vue, Svelte). Responsible for rendering controls, forms, animations, and handling user inputs.

Runs on: Client Hardware / Browser CPU
Backend (Server-side)

Executes in secure cloud data centers (Go, Node.js, Python, Laravel). Holds exclusive access to databases, secrets, and business policies.

Runs on: Cloud VPC / Container Fleet

Their only bridge of communication across the Internet is the HTTP REST API / JSON Interface.

14 Login Request Payload

14. The Login Request

When the client-side React code submits the login form, it transmits an explicit HTTP POST request:

POST /api/login HTTP/1.1
Host: app.taskflow.com
Content-Type: application/json
User-Agent: Mozilla/5.0 ...
{
"email": "salim@example.com",
"password": "SuperSecretPassword123!"
}

Because this payload travels within the TLS tunnel, the credentials remain completely encrypted across the global Internet until decrypted inside App Server 1's memory.

15 Database Query

15. Backend Queries the Database

App Server 1 holds no permanent state in memory. It initiates an internal TCP query across the private VPC network to the PostgreSQL Database Server:

-- Internal VPC Query over TCP Port 5432
SELECT id, email, password_hash, status, role
FROM users
WHERE email = 'salim@example.com' LIMIT 1;

Using a B-Tree index on the email column, PostgreSQL locates the user record in under 0.5 milliseconds and streams the result back to App Server 1.

16 Password Security

16. What Does the Database Store for Passwords?

Here lies a non-negotiable rule of security engineering: A production database must NEVER store plaintext passwords! In the event of a breach, attackers must not obtain raw credentials. Instead, databases store salted cryptographic one-way hashes:

// One-way salted hash stored in database column:
$argon2id$v=19$m=65536,t=3,p=4$qN8kZ2...$L9p1F0xW9qC...

During verification, the application executes:

Entered Password + Stored Salt → [Argon2id Hash Function] → Generated Hash == Stored Hash?

Only if the derived hash matches the stored hash character-for-character does the application confirm valid authentication.

17 Authentication Tokens

17. When Authentication Succeeds

Once verified, the server establishes proof of identity for subsequent requests. This is typically issued as a cryptographically signed JWT (JSON Web Token) or an encrypted session cookie:

HTTP/1.1 200 OK
Set-Cookie: session_token=eyJhbGciOiJIUz...; Secure; HttpOnly; SameSite=Strict
{
"user": { "id": 123, "name": "Salim", "role": "admin" },
"message": "Authentication successful"
}

The HttpOnly flag ensures malicious JavaScript scripts (XSS attacks) cannot read the session token. The browser will automatically attach this cookie to future requests.

18 In-Memory Caching

18. Does Every Request Query the Database?

Absolutely not! Relational databases provide durability on disk, but disk I/O and complex SQL joins are resource-intensive. If 10,000 active users refresh their screens simultaneously and every query hits the database, database CPU will spike to 100%, grinding the system to a halt.

The Solution: In-Memory Data Store (Redis / Memcached)

Frequently read, rarely modified data is stored directly in server RAM for instant retrieval.

19 Cache Hit

19. Cache Hit

When the application checks the cache for user data and finds it present in RAM:

App Server → Redis.get("user:123:profile") → [FOUND IN RAM: 0.8ms] → Return Response

The database was completely bypassed. The client receives its response in under a millisecond.

20 Cache Miss

20. Cache Miss

If the key does not exist in memory (for instance, following a first-time login or cache expiration):

1. App Server → Redis.get("user:123:profile") → [NOT FOUND / MISS]
2. App Server → PostgreSQL Database Query (Disk Read: 8ms)
3. PostgreSQL → User Profile Data Returned to App
4. App Server → Redis.set("user:123:profile", data, ttl=3600) // Repopulate cache
5. App Server → Send JSON to Browser

All subsequent reads will now enjoy instant Cache Hits. This classic design is known as the Cache-Aside Pattern.

21 Database vs Cache Relationship

21. Database vs Cache: Complementary Roles

A cache never replaces a database; they are complementary engineering partners:

Attribute Database (PostgreSQL) Cache (Redis)
Storage Medium Persistent NVMe SSD / Disk Volatile RAM (Memory)
Architectural Role Single Source of Truth (Canonical) Transient High-Speed Accelerator
Query Latency 5 to 50 milliseconds 0.1 to 2 milliseconds
On Server Restart 100% durable, zero data loss Memory may clear (repopulated on miss)
22 Dashboard Loading

22. The User Opens the Dashboard

Upon successful login, the browser redirects to the dashboard view. The client-side React application dispatches an aggregation query:

GET /api/dashboard HTTP/1.1

The request traverses the load balancer into the application tier. Combining cached metrics with fresh database counts, the server returns structured JSON:

{
"projects_count": 12,
"active_tasks": 83,
"unread_notifications": 4,
"recent_activity": [ ... ]
}
23 Browser Rendering Pipeline

23. What Does the Browser Do With This JSON?

Recall the browser engine mechanics from Lesson 13. The JSON string is merely raw text. How does the browser convert it into interactive UI?

// Critical Rendering Pipeline (CRP) Execution:
1. JSON Payload parsed → React Component State Updated
2. React Virtual DOM Reconciliation → Real DOM Tree Mutation
3. Real DOM + CSS Rules → Render Tree Construction
4. Layout / Reflow (Geometry, coordinates, and pixel bounding boxes computed)
5. Paint (Text glyphs, colors, borders, and shadows rasterized)
6. Compositing (Layers composited via GPU and pushed to display panel)

In milliseconds, abstract data from the cloud transforms into millions of illuminated pixels on the user's screen.

24 Project Creation

24. The User Creates a Project

The user clicks “New Project”, inputs “Byteion Platform”, and clicks Submit.

POST /api/projects HTTP/1.1
Authorization: Bearer eyJhbGciOi...
{
"name": "Byteion Platform",
"description": "Next-Gen Tech Academy"
}

The request traverses the browser, edge network, and load balancer into the application layer. Before writing a single byte to the database, two critical checkpoints must be satisfied.

25 Validation Layers

25. Where Does Validation Occur?

Should validation happen in the browser or on the server? The answer is both, but for entirely different reasons!

Client-Side Validation (UX)

Highlights empty fields instantly with red borders. Saves user time and avoids unnecessary network round trips. However, an attacker can bypass this easily via curl or Postman.

Server-Side Validation (Security)

Non-negotiable security enforcement. Checks character encodings, sanitizes strings, defends against SQL injection, and enforces domain rules.

Golden Rule of Architecture: “Never trust user input from the client!” Client validation is purely for user experience; true security is strictly enforced on the server.
26 Authorization Enforcement

26. Why Authorization is Required Here

Understanding the distinction between Authentication and Authorization is vital:

Authentication (Who are you?): Verification that the user is indeed Salim.
Authorization (What can you do?): Does Salim hold permission to create a project or delete workspace resources?

Suppose TaskFlow's free tier permits a maximum of 3 active projects. If Salim already owns 3 projects, the authorization middleware intercepts the request and terminates it with HTTP 403 Forbidden before touching the database.

27 Database Transactions (ACID)

27. Database Transactions (ACID Guarantees)

Creating a project requires atomic updates across multiple related tables:

1. Insert project record into the projects table.
2. Insert owner association into the project_members table.
3. Insert tracking entry into the audit_logs table.

If a power outage or database error occurs between step 1 and step 2, an unowned orphan project is created. To prevent corrupt state, we wrap these mutations in a Database Transaction:

BEGIN TRANSACTION;
INSERT INTO projects ...;
INSERT INTO project_members ...;
INSERT INTO audit_logs ...;
COMMIT; -- All mutations made permanent atomically
// If any single statement fails:
ROLLBACK; -- Discard all intermediate changes; revert to clean state

This guarantees that database state remains 100% consistent under all operating conditions.

What We Will Learn (Part 2 — Sections 28 to 54)

  • 28. The Image Upload Dilemma: Heavy binary files vs relational databases
  • 29. Pre-Signed S3 URL Pattern: Direct client-to-storage uploads
  • 30. Database Metadata vs Object Binaries: Pointers in SQL, raw bits in S3
  • 31. CDN Media Delivery: Edge caching of uploaded assets
  • 32. Asynchronous Notifications: The danger of synchronous email dispatch
  • 33. What is a Message Queue?: Decoupled FIFO buffer queues
  • 34. What is a Background Worker?: Headless background job processors
  • 35. Complete Async Email Lifecycle: Decoupled SMTP delivery
  • 36. Mental Model for Queues: Restaurant order ticket analogy
  • 37. Worker Failures & DLQs: Exponential backoff and Dead Letter Queues
  • 38. Multi-Channel Notification Fanout: Email, push, and in-app alerts
  • 39. Event-Driven Architecture (EDA): Domain event publishers and subscribers
  • 40. Distributed Topology: Why the app server is not the center of the universe
  • 41. Full Architecture Version 1: Master integrated schematic
  • 42. Production Observability: Gaining visibility into live systems
  • 43. Active Health Checking: /health endpoints and auto-eviction
  • 44. Structured Logging: Immutable forensic event histories
  • 45. Quantitative Metrics: RPS, P95 latency, error rates, and queue depths
  • 46. Distributed Tracing: Spans and trace IDs isolating microservice delays
  • 47. Bottleneck Isolation: Diagnosing slow requests along the pipeline
  • 48. Horizontal Scale-Out: Elastic clustering behind load balancers
  • 49. Stateless Applications: Decoupling sessions into Redis or JWTs
  • 50. Alleviating Database Bottlenecks: Read replicas, connection pools, and sharding
  • 51. Traffic Surge Absorption: Using queues as buffers against flash traffic
  • 52. Object Storage Scalability: Infinite capacity and 11 9s durability
  • 53. Resilience & Failover: Self-healing nodes and replica promotion
  • 54. Eliminating Single Points of Failure (SPOF): Comprehensive redundancy
28 Binary Data Challenge

28. The User Uploads an Image

After initializing their project, the user wants to upload a cover image: project-cover.jpg (file size: 4.5 Megabytes).

A frequent novice architectural mistake is attempting to store raw binary image data directly inside a relational database table using BLOB (Binary Large Object) columns. In production systems, this proves disastrous:

Why Raw Files Do Not Belong in Relational Databases:
• Database storage bloats rapidly into hundreds of gigabytes, causing backups to take hours.
• Large binary chunks evict hot relational rows from database RAM buffer caches, degrading SQL query speeds.
• Serving binary files through application server threads exhausts connection pools and bandwidth.

The industry standard solution, as studied in Lessons 15 and 16, is Cloud Object Storage (e.g., AWS S3, Cloudflare R2, Google Cloud Storage).

29 Pre-Signed Upload Pattern

29. The Pre-Signed S3 Upload Flow

Historically, browsers uploaded binary files to an application server, which in turn streamed them to S3. This wasted precious app server CPU and memory. Modern high-scale architectures adopt the Direct-to-S3 Pre-signed URL Pattern:

1. Browser → App Server API: “I intend to upload a 4.5 MB image for Project 12”
↓ Permission and quota validated
2. App Server → AWS S3 SDK: “Generate a temporary cryptographically signed PUT URL valid for 5 minutes”
↓ Generates signed URL
3. App Server → Browser: Returns Pre-signed URL
↓ 4. Direct Upload (App server completely bypassed!)
Browser → S3 Bucket: PUT https://s3.amazonaws.com/taskflow-bucket/projects/12/cover.jpg?...

Heavy binary upload traffic streams directly into cloud storage; the application server remains completely unburdened and free to handle lightning-fast API transactions.

30 Metadata vs Raw Binary

30. What Lives in the Database?

The physical bytes reside in S3, but how does TaskFlow associate the file with the project? The database stores structured Metadata:

-- PostgreSQL "files" Table
id: 91
project_id: 12
storage_path: "projects/12/cover.jpg"
file_size_bytes: 4718592
mime_type: "image/jpeg"
uploaded_by_user_id: 123
created_at: "2026-09-23T11:45:00Z"
Database = Structured Metadata & Relations | Object Storage = Mass Raw Binary Bits
31 Media Caching

31. What Does the CDN Do Next?

When team members subsequently navigate to the project overview, their browsers request the image: https://cdn.taskflow.com/projects/12/cover.jpg.

Browser → CDN Edge Node (Local PoP)
↓ 1st Request: Edge Cache Miss → Fetches from S3 → Caches on Edge NVMe SSD
↓ 2nd & Subsequent Requests: Edge Cache HIT (Delivered in 8ms)

Cloud storage (S3) handles raw durability, while the CDN handles high-speed global delivery. Neither burdens the origin application cluster.

32 The Necessity of Asynchronous Processing

32. Now a Notification Must Be Sent

With the project established, the user invites 5 collaborators. The system must dispatch invitation emails and push alerts to all 5 recipients.

Fundamental engineering question: Should the application send these 5 emails synchronously inside the user's HTTP request handler?

// Catastrophic Synchronous Flow:
1. Insert invitations into PostgreSQL: 20ms
2. Open SMTP socket to Mail Provider: 500ms
3. Dispatch Email 1: 800ms
4. Dispatch Email 2: 750ms
5. Dispatch Email 3: 900ms
6. Dispatch Email 4: 850ms
7. Dispatch Email 5: 1100ms
Total User Waiting Time: 4.9 seconds! The browser spins endlessly.

Even worse: If the external email provider times out on the 3rd email, the entire HTTP request fails, presenting an error screen to the user despite the project having been created. To solve this, we introduce Queues & Workers.

33 Message Queues

33. What is a Queue?

A Queue is a durable FIFO (First-In, First-Out) or prioritized buffer. The application server declares:

“I have committed the invitations into the database. I will now push 5 job tickets onto the queue. I can immediately return a 201 Created response to the user!”
App Server → [Push 5 Jobs to Queue (Redis / SQS)] → Immediate Response to User (Total: 25ms!)
34 Background Workers

34. What is a Worker?

A Worker is an independent, headless background daemon process. Workers never accept direct HTTP requests from clients. Their sole lifecycle consists of:

while (true) {
job = queue.pop(); // Dequeue next pending task
process(job); // Execute background work (e.g., SMTP dispatch)
job.ack(); // Acknowledge completion
}

Workers consume jobs smoothly in the background without affecting API responsiveness.

35 Complete Async Email Lifecycle

35. Complete Async Flow of Email

Recalling Lesson 21, the system bifurcates into two completely decoupled timelines:

// Timeline 1: Live User Interaction (25 milliseconds)
Browser → API → App Server → Database → Push Job to Queue → HTTP 201 Created to Browser
The user instantly sees: “Invitations Sent!”
// Timeline 2: Background Delivery (Next 3 to 5 seconds)
Queue → Worker Fleet → Amazon SES / Postmark API → SMTP Handshake → MX Lookup → Recipient Mailbox

Client API latency is fully shielded from the latency and unreliability of third-party mail delivery networks.

36 Mental Model for Queues

36. A Powerful Mental Model for Queues

Consider a bustling restaurant:

Synchronous Model (Flawed)

The waiter takes your order, walks to the kitchen, and stands there idle for 20 minutes until the chef finishes cooking. No other tables can place orders.

Asynchronous Queue Model (Modern)

The waiter writes your order ticket, clips it to the kitchen wire (Queue), hands you a receipt, and attends to the next customer. Line chefs (Workers) prepare dishes in parallel.

37 Worker Failure & Dead Letter Queues

37. What Happens When a Worker Fails? (DLQ)

What if a worker encounters a network glitch or a mail server rate limit while processing a job?

Job: SendEmail(rahim@example.com)
↓ Worker 1 encounters network timeout [FAIL]
↓ Exponential Backoff (Wait 10s before re-attempting)
↓ Attempt 2 fails: 503 Service Unavailable [FAIL]
↓ Attempt 3 (Wait 60s) → SUCCESS! [ACK]

If a job continues failing beyond a maximum retry limit (e.g., 5 attempts), it is safely sequestered rather than dropped:

Repeatedly Failing Job → Dead Letter Queue (DLQ) → Engineer Alert & Forensic Review
38 Multi-Channel Fanout

38. Adding a Multi-Channel Notification System

A user comments on a task: “Updated design specs are ready for review.”

Task Commented Event → Message Broker
Email Worker
Dispatches SMTP email to offline members
Push Worker
Sends FCM/APNs push notifications to phones
WebSocket Worker
Broadcasts live UI alerts to active browser tabs

A single user action fans out into multiple asynchronous channels simultaneously without adding latency to the original HTTP POST request.

39 Event-Driven Architecture (EDA)

39. The Emergence of Event-Driven Architecture

This illustrates one of modern software engineering's most powerful paradigms: Event-Driven Architecture (EDA).

The application server does not care which systems care about the comment. It merely publishes a domain event:

Domain Event: TASK_COMMENTED
{ task_id: 83, user_id: 123, comment: "..." }

Audit logging services, search indexing engines, analytics pipelines, and notification workers consume this event independently. None block each other.

40 Distributed Topology

40. Is the Application Server the Center of the Universe?

No. While the application server contains business logic, modern web infrastructure is an inherently Distributed System:

CDN Edge = Delivery, Caching & DDoS Shielding
Load Balancer = Ingestion, TLS Offload & Health Routing
App Server = Business Orchestration & API Policies
Cache = In-Memory Latency Reduction
Database = Canonical Persistent Truth
Object Storage = Mass Binary Asset Retention
Queue & Workers = Decoupled Background Execution
41 First Consolidated Diagram

41. Full Architecture — Version 1

Let us unite all the components discussed thus far into an integrated architectural blueprint:

                           [ USERS / BROWSER ]
                                    |
                            (Internet Routing)
                                    |
                           [ DNS Anycast PoP ]
                                    |
                           [ CDN Edge Cache ] <-- Static Assets (CSS, JS)
                                    |
                              (HTTPS / TLS)
                                    |
                         [ Cloud Load Balancer ]
                                    |
             +----------------------+----------------------+
             |                      |                      |
             v                      v                      v
      [ App Server 1 ]       [ App Server 2 ]       [ App Server 3 ]
             |                      |                      |
             +-----------+----------+                      |
                         |                                 |
         +---------------+---------------+                 |
         |               |               |                 |
         v               v               v                 v
   [ Redis Cache ]  [ PostgreSQL ]  [ Message Queue ]  [ Object Storage (S3) ]
                                         |                      |
                                   [ Worker Fleet ]             |
                                  /       |        \            |
                                 v        v         v           |
                            ( Email )  ( Push )  ( Video )      |
                                                                |
                                 +------------------------------+
                                 | (Direct CDN Media Delivery)
                                 v
                            [ USERS ]
      

This single diagram demonstrates how the first 21 lessons of Course 08 coalesce into a unified production platform.

42 Production Observability

42. What Else Does Production Require? (Observability)

Deploying an architecture is only half the battle. How do Site Reliability Engineers (SREs) and backend developers know if the live system is thriving or collapsing?

The Three Pillars of Observability
Logs + Metrics + Traces (+ Health Checks)
43 Active Health Checks

43. Health Checks

Every production service exposes an internal probe endpoint: GET /health.

Load Balancer → GET http://10.0.1.15:8080/health
← HTTP/1.1 200 OK {"status": "UP", "db": "connected", "redis": "connected"}

If a container experiences deadlock or database disconnects, it returns 500 Internal Server Error. The load balancer instantly evicts the sick node from active routing pools.

44 Structured Logging

44. What Are Logs?

Logs provide an immutable, timestamped forensic record of discrete internal events:

{"timestamp":"2026-09-23T11:42:15Z","level":"INFO","method":"POST","path":"/api/projects","user_id":123,"status":201,"duration_ms":34}
{"timestamp":"2026-09-23T11:42:19Z","level":"ERROR","service":"email-worker","error":"SMTP Connection Refused: mail.example.com:587"}

Aggregated logging platforms (such as Elasticsearch, Grafana Loki, or Datadog) ingest logs across all servers, empowering engineers to query anomalies instantly.

45 Quantitative Metrics

45. What Are Metrics?

While logs record textual events, metrics represent time-series numeric telemetry:

Requests / Sec
12,450 RPS
P95 Latency
180 ms
Error Rate
0.02%
Queue Depth
14 Jobs

Tools like Prometheus and CloudWatch aggregate these metrics to drive automated scaling and trigger operational alarms.

46 Distributed Tracing

46. What is Tracing?

As requests navigate through CDNs, load balancers, API gateways, caches, and databases, Distributed Tracing (OpenTelemetry) tracks the journey using a unique Trace ID:

[TraceID: 4bf92f3577b34da6a3ce929d0e0e4736]
• HTTP Ingestion (Load Balancer): 5ms
• Auth Token Validation: 3ms
• Redis Cache Lookup: 1.2ms
• PostgreSQL Query (Unindexed JOIN): 450ms <-- Bottleneck Spotted!
• JSON Serialization & Return: 2ms

Tracing eliminates guesswork, pinpointing exact performance bottlenecks like an X-ray.

47 Bottleneck Isolation

47. Why is a Request Slow?

When a user complains, “The dashboard is sluggish!”, an inexperienced developer might blindly upgrade the server RAM. An experienced engineer profiles the entire request path:

1. DNS Lookup: 15ms
2. TLS Handshake: 35ms
3. CDN Edge Transit: 20ms
4. Load Balancer: 2ms
5. Application Business Logic: 15ms
6. Database Query (Missing index on user_id): 850ms (Bottleneck!)
7. Browser DOM Layout & Paint: 25ms

Adding RAM would accomplish nothing. Adding a simple database index (CREATE INDEX) immediately drops the query from 850ms to 2ms!

48 Horizontal Scaling

48. Scaling the System (Horizontal Scale-out)

TaskFlow surges in popularity. Daily traffic skyrockets from 100 users to 5,000,000 active users (5,000,000 users/day)!

Vertical scaling (buying a bigger machine) hits physical and economic ceilings. Modern systems scale via Horizontal Scale-Out:

Load Balancer → [App 1, App 2, App 3, App 4, App 5, ... App 50 Instances]

Cloud auto-scaling groups dynamically provision 20 new container instances when traffic spikes, and terminate them when demand cools to minimize costs.

49 Stateless Applications

49. Why Stateless Applications Are Crucial

Horizontal scaling functions only if application servers are strictly Stateless:

Stateful (Fragile):

Storing user session state in App 1's local RAM. If the load balancer routes the next request to App 2, the user is abruptly logged out!

Stateless (Scalable):

Sessions are externalized into a shared Redis cluster or encrypted JWT tokens. Any server instance can process any request seamlessly!

50 Database Scaling Strategies

50. Alleviating Database Bottlenecks

Scaling to 50 application servers creates a new bottleneck: 50 servers bombarding a single primary database. How do we scale the data tier?

1. Read Replicas: In web SaaS, 95% of queries are reads. We deploy 1 Primary (Write) and multiple asynchronous Read Replicas. All read traffic shifts to replicas.
2. Connection Pooling (PgBouncer): Multiplexing thousands of client connections onto a fixed pool of persistent database sockets.
3. Aggressive In-Memory Caching: Serving 90% of repeated queries directly from Redis RAM.
4. Database Sharding: Partitioning tables across distinct database clusters by user or workspace ID under extreme workloads.
51 Traffic Surge Absorption

51. Why Queues Re-Emerge During Scaling

During sudden promotional campaigns or viral events, 1,000,000 tasks might be submitted in seconds. This sudden surge is known as Flash Traffic.

Attempting to execute all downstream processing synchronously would crash the cluster. The queue acts as a resilient shock absorber:

Flash Surge (1,000,000 Jobs) → [Buffered in Queue] → 50 Workers steadily draining at optimal pace

Client requests are immediately accepted and buffered; workers process the surge reliably without dropping a single task.

52 Object Storage Scalability

52. Object Storage Scaling

TaskFlow users accumulate 10 Terabytes (10 TB) of assets. The power of cloud object storage includes:

  • Infinite Elasticity: No disks to resize or partition; storage expands automatically to petabytes.
  • 99.999999999% (11 9s) Durability: Objects are redundantly stored across multiple physical availability zones.
  • Direct CDN Integration: Assets are cached at the edge, ensuring storage reads never compete with application traffic.
53 Failure Management & High Availability

53. What Happens During Failures?

Murphy's Law dictates that in distributed systems, components will fail. A mature architecture anticipates and mitigates every point of breakdown:

• App Container Crash: Load balancer reroutes traffic instantly; container orchestrator boots a replacement pod in seconds.
• Primary Database Failure: Managed cloud DB triggers automated failover, promoting a synchronized Read Replica to Primary within 60 seconds.
• Worker Crash: Unacknowledged jobs time out and are automatically reassigned to healthy workers.
54 Single Point of Failure (SPOF)

54. Single Point of Failure (SPOF) Elimination

A Single Point of Failure (SPOF) is any individual component whose failure halts the entire system:

All Users → [Single Server] → [Single Database] <-- CATASTROPHIC SPOF!

A principal duty of a software architect is systematically eradicating SPOFs through multi-zone redundancy: Anycast edge PoPs, multi-AZ load balancers, multi-instance stateless app clusters, and replicated databases.

What We Will Learn (Part 3 — Sections 55 to 79 & Interactive Labs)

  • 55. Cloud Infrastructure: IaaS, PaaS, and managed cloud primitives
  • 56. Containers & Orchestration: Docker images and runtime environments
  • 57. CI/CD Deployment Pipelines: Git push, automated tests, and registry builds
  • 58. Zero-Downtime Deployments: Rolling updates from v1 to v2 without user disruption
  • 59. Instant Rollback Mechanisms: Rapid recovery from production regressions
  • 60. The 16-Step Complete Journey: Complete traversal for project creation
  • 61. File Upload Architecture Walkthrough: Direct pre-signed S3 storage
  • 62. Login Request Flow: Secure credential verification to cookie issuance
  • 63. Email & Notification Lifecycle: Decoupled queues and SMTP delivery
  • 64. Static Asset Delivery Flow: Edge cache hits delivering sub-20ms assets
  • 65. Dynamic API Request Flow: Origin routing and execution
  • 66. Master Consolidated Blueprint: Unifying all 4 flows into one topology
  • 67. The 14-Layer Mental Model: User to external service breakdown
  • 68. Why So Many Layers?: Workload-driven specialization of components
  • 69. Small App vs Large App: Evolution from single VPS monolith to multi-region
  • 70. The Peril of Premature Complexity (YAGNI): Keeping architectures lean
  • 71. Core Architectural Principle: Strict single responsibility per layer
  • 72. Course 08 Panoramic Synthesis: Connecting Lessons 1 through 22
  • 73. Unifying Mental Model: The end-to-end request lifecycle
  • 74. The 5 Grand Architectural Questions: Where, Connect, Speed, Data, Scale
  • 75. Master Internet-to-Application Map: Final topological blueprint
  • 76. Separation of Concerns: Designing resilient, evolvable systems
  • 77. Final End-to-End Hierarchy: The complete software stack
  • 78. Lesson Summary: Key engineering takeaways
  • 79. Our Milestone & Lesson 23 Preview: Microscopic packet journey
55 Cloud Infrastructure

55. Where Does the Cloud Fit In?

As explored in Lesson 18, modern engineering organizations rarely operate physical data centers. Instead, they compose systems from managed cloud primitives:

Cloud Provider (AWS / GCP / Cloudflare / Azure)
↓ Managed Storage & Data: RDS, S3, ElastiCache, SQS, CloudFront
↓ Compute Platform: Elastic Kubernetes Service (EKS) / Autoscaled VMs

Cloud providers absorb physical maintenance, facility power, hardware failures, and cooling. Developers focus on system design and business value.

56 Containerization

56. Where Do Containers Live?

TaskFlow's backend code does not run directly on host operating systems. It is packaged into an immutable Docker image:

Image: registry.taskflow.com/api:v1.7.2

From this identical image, the cluster can spin up 3, 30, or 300 container instances. Every container shares the exact same binaries, libraries, and runtime environment, eliminating “it worked on my laptop” bugs permanently.

57 Deployment Automation

57. How Deployments Happen (CI/CD Pipeline)

Recalling Lesson 19, code changes move through an automated Continuous Integration / Continuous Deployment (CI/CD) pipeline:

Git Push (main) → GitHub Actions CI → Unit Tests Pass → Build Docker Image → Push to Registry → Trigger Kubernetes CD

No human developer manually SSHs into servers to copy files. Every release is automated, repeatable, and auditable.

58 Zero-Downtime Releases

58. Deploying New Versions (Rolling Updates)

Version 1 (v1) is serving live traffic. Version 2 (v2) is ready. Does the site go down for maintenance? Never!

Step 1: Replace App 1 (v1) with App 1 (v2) → Pass Health Check → Route traffic.
Step 2: Replace App 2 (v1) with App 2 (v2) → Pass Health Check → Route traffic.
Step 3: Replace App 3 (v1) with App 3 (v2) → Cluster 100% updated to v2!

Users experience zero interruption during the update (Zero-Downtime Deployment).

59 Instant Rollback

59. Handling Regressions: Rollback

Five minutes post-release, observability alerts trigger: HTTP 500 errors spike to 15%!

ALERT: Error Threshold Exceeded → Automated Instant Rollback to v1 → Full Recovery in 20 seconds!

Engineers debug the issue safely in staging while production users continue unhindered.

60 The 16-Step Complete Journey

60. Tracing a Single User Action Across the Entire Architecture

A user clicks “Create Project”. Here is the complete 16-step sequence that executes across the globe:

01. User Clicks Button in Browser
02. Browser validates form inputs locally (Frontend UX)
03. HTTP POST request serialized into JSON payload
04. Packet leaves OS via Wi-Fi → ISP → Global BGP Transit
05. CDN Edge terminates TLS & routes request to Origin VPC
06. AWS Load Balancer selects healthiest Container (App 2)
07. App 2 parses JWT Bearer Token (Authentication)
08. App 2 verifies project creation quota & roles (Authorization)
09. App 2 starts PostgreSQL ACID Transaction: BEGIN
10. INSERT INTO projects & INSERT INTO project_members
11. Database Transaction COMMIT successful
12. App 2 fires Event: PROJECT_CREATED → pushes job to Redis Queue
13. App 2 responds HTTP 201 Created with project JSON to Load Balancer
14. Packet travels back to Browser → React state updates → DOM re-rendered
15. [Background] Worker pops job from Queue → connects to Amazon SES
16. [Background] SMTP Handshake → Team members receive invitation emails

A single mouse click triggers a synchronized performance across 16 specialized technologies!

61-65 Four Architectural Core Flows

61-65. Comparative Dissection of the Four Fundamental Flows

All web interactions decompose into four foundational architectural patterns:

1. File Upload Flow (Section 61)
Browser → API → Pre-signed URL → Direct Upload to S3 → DB Metadata Written → CDN Caches for Users

Bypasses application compute entirely, streaming directly to scalable object storage.

2. Login Flow (Section 62)
Browser → TLS → App Server → DB Query User → Argon2 Hash Verification → Generate JWT → Return HttpOnly Cookie

Cryptographic verification establishing stateless authentication state.

3. Email & Notification Flow (Section 63)
User Action → App Server → Push Job to Queue → Instant 200 OK → Background Worker → SMTP / Mail Provider

Asynchronous decoupling shielding users from third-party delivery latencies.

4. Static vs Dynamic Flows (Sections 64-65)
Static: Browser → CDN Edge Cache HIT (15ms)
Dynamic: Browser → Edge Forward → LB → App → DB/Cache (70ms)

Edge caching efficiency contrasted with stateful origin execution.

66 Master Consolidated Diagram

66. All Four Flows Operating in Harmony

                        +----------------------------+
                        |      USER / BROWSER        |
                        +--------------+-------------+
                                       |
                +----------------------+----------------------+
                | (Static & Media)                            | (APIs & State)
                v                                             v
     +--------------------+                       +--------------------+
     |   CDN Edge Cache   |                       |    HTTPS / TLS     |
     +----------+---------+                       +----------+---------+
                |                                            |
                | (Edge Miss)                                v
                |                                 +--------------------+
                |                                 |   Load Balancer    |
                |                                 +----------+---------+
                |                                            |
                |                          +-----------------+-----------------+
                |                          v                                   v
                |                 +-----------------+                 +-----------------+
                |                 |  App Server 1   |                 |  App Server 2   |
                |                 +--------+--------+                 +--------+--------+
                |                          |                                   |
                |         +----------------+----------------+------------------+
                |         |                                 |                  |
                |         v                                 v                  v
                |  +--------------+                  +--------------+   +--------------+
                |  | Redis Cache  |                  |  PostgreSQL  |   |  Redis Queue |
                |  +--------------+                  +--------------+   +-------+------+
                |                                                              |
                |                                                              v
                |                                                      +---------------+
                |                                                      |  Worker Pool  |
                |                                                      +-------+-------+
                |                                                              |
                |   +-------------------+                                      v
                +-->|   S3 Storage      |                             +-----------------+
                    | (Upload & Media)  |                             | Mail Provider   |
                    +-------------------+                             +-----------------+
      
67 14-Layer Hierarchy

67. The 14-Layer Mental Model of a Web Request

Every web interaction can be classified across 14 distinct specialized tiers:

Layer 1: User (Human intention & input)
Layer 2: Browser (DOM, JS V8 Engine, CRP)
Layer 3: DNS (Global telephone directory)
Layer 4: Internet Routing (BGP, Autonomous Systems)
Layer 5: TLS (Cryptographic session encryption)
Layer 6: CDN (Edge caching & DDoS shielding)
Layer 7: Load Balancer (Health checks & traffic shaping)
Layer 8: Application (Routing & business policies)
Layer 9: Cache (RAM-speed sub-millisecond lookups)
Layer 10: Database (ACID canonical persistence)
Layer 11: Object Storage (Infinite durable binary blobs)
Layer 12: Queue (Asynchronous decoupled buffers)
Layer 13: Worker (Autonomous background executors)
Layer 14: External Service (SMTP, SMS, payment APIs)
68-71 Architectural Wisdom

68-71. Why So Many Layers? The Value of Simplicity

68. Why So Many Layers? (Workload-Driven Specialization)

No single piece of software can simultaneously maximize in-memory cache speed, transactional ACID guarantees, global edge caching, and heavy file streaming. Specialization unlocks maximum performance at each stage.

69. Small App vs Large App

Small Application: For 100 users, a single $10 VPS running a modular monolith with SQLite/Postgres is ideal.
Large Application: For 5,000,000 users, multi-region Kubernetes clusters, Aurora replicas, and Kafka queues become essential. Architecture must grow with actual demand.

70. More Components Do Not Mean Better Architecture (YAGNI)

Starting a basic CRUD project with 10 microservices, Kafka, and Kubernetes does not make you Google—it introduces catastrophic operational friction. Golden Rule: Keep it as simple as possible until traffic forces complexity.

71. Core Architectural Takeaway

Clear Single Responsibility per Layer: DNS only resolves names. Databases only manage relational data. Storage only holds binary files. Application handlers never perform synchronous external mail delivery.

72 Course Synthesis

72. Panoramic Synthesis of Course 08

Reviewing our entire curriculum in a single panoramic trajectory:

L01: Network → L02: Physical Cable → L03: IP/MAC → L04: Packets/Routing
L05: TCP/UDP → L06: DNS → L07: HTTP → L08: HTTPS/TLS → L09: Load Balancers
L10: NAT/Firewall → L11: WebSockets/RTC → L12: BGP → L13: Browser Rendering
L14: REST APIs → L15: Databases → L16: Caches/Storage → L17: Scale/Dist. Systems
L18: Cloud/Containers → L19: CI/CD/Ops → L20: CDN/Edge → L21: Email Protocols
→ L22: The Complete Living Modern Web Application!
73-77 The 5 Grand Questions

73-77. The 5 Grand Questions of System Architecture

1. Where? DNS, Anycast, BGP, and Global Internet Routing.
2. How to Connect? TCP, QUIC, TLS Encryption, and HTTP Protocols.
3. How to Serve Fast? CDN Edge Caching, Load Balancing, and Redis RAM.
4. Where is Data? PostgreSQL (Metadata), S3 (Files), and Redis (State).
5. How to Scale? Queues, Workers, Containers, CI/CD, and Observability.
78-79 Conclusion & What's Next

78-79. Lesson Summary & Next Horizons

The central insight of this lesson is: A modern web application is not a solitary server. It is a harmonious, distributed living ecosystem composed of specialized components cooperating across time and space.

When an end-user taps a button on their device, electricity, fiber-optic photons, cryptographic algorithms, reverse proxies, in-memory stores, relational tables, and message brokers work in tandem to deliver that experience in milliseconds.

Upcoming Milestone

Lesson 23 — The Journey of an Internet Request: From Data to Signal and Back

Having mastered high-level system architecture, we will zoom in microscopically: how application data is transformed into bytes, frames, and physical electrical and photonic signals traversing the globe, and reconstructed back into data at the destination!

Interactive Laboratory

System Architecture Simulation Lab

Explore end-to-end request journeys, failure resilience, and architectural scaling dynamics across 3 live sandbox tabs.

Hop-by-Hop Trace and Timing Latency: -- ms
Click “Run Simulation” to observe the complete request waterfall across edge caches, load balancers, and persistence tiers.
Architecture Check

System Architecture Knowledge Check (3 Questions)

1. Why do modern architectures use Pre-signed URLs for file uploads directly to Object Storage rather than streaming files through application servers?

2. What is the fundamental advantage of pushing email notifications and PDF generation onto an asynchronous Queue rather than executing them inside the live HTTP request handler?

3. Why must application servers behind a load balancer be designed to be Stateless?