Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·188

Reference Production Architecture

The full request path of a production system, layer by layer and from first principles: DNS (records, TTLs, health-checked routing), CDN (edge caching, cache keys, Cache-Control, invalidation, origin shielding), TLS termination and certificates, WAF and bot management, load balancers (L4 vs L7, algorithms, health checks) and API gateways (authentication, rate limiting, routing), the front end and browser caching, the application tier, cache, database, queue and event bus, search, workers, and the AI path (RAG, tool calls, model providers and GPUs); a latency budget computed end to end, failure domains and blast radius, the same architecture mapped to AWS, GCP, Azure and self-hosted components, and rate limiters in Go, Java, Rust and Python.

29 topics · ~25 min read · 32-question quiz
Updated Suggest a correction

Start here: the boxes a request passes through

When a TiffinBox customer taps "Skip Tuesday", the request crosses a chain of components, each with a job:

Text
phone → DNS (find the address) → CDN / edge (static files, cached pages, DDoS protection)
      → WAF (block attacks) → load balancer / API gateway (TLS, routing, rate limits)
      → application servers → cache (Redis) / database (PostgreSQL) / queue (for later work)
      → workers (emails, kitchen orders) → third parties (payments, SMS, AI models)

A reference architecture is this map, agreed in advance, so that every new feature knows where its pieces go and every engineer knows where to look when something breaks.

Every box costs time, and some cost a lot

The lab measured hops on one machine: the app answering directly took 0.7 ms; through an nginx reverse proxy, about 1 ms; a fresh HTTPS connection (new TLS handshake each time) 2.4 ms; a small PostgreSQL query 2.1 ms, or 0.8 ms when served from a Redis cache. On one machine, everything is fast. Across real networks the budget is dominated by distance: each network round trip from Hyderabad to a server in Mumbai is a few milliseconds, to Singapore tens, to the US over a hundred, and a new HTTPS connection needs one or two round trips before the first byte of the request. That's why CDNs, connection reuse and keeping data near users matter more than micro-optimising code.

Failure domains

Each box can fail. A good architecture knows the blast radius of each failure: if Redis is down, menus are slower but orders work; if the payment provider is down, new subscriptions wait in a queue; if one availability zone is lost, the others carry the load.

How deep to go in reference production architecture

Volume 17 defines six mastery levels; for production architecture they look like this:

Level You can…
L1 name each component on the request path and its job
L2 deploy a service behind a load balancer with TLS, cache and database
L3 build a latency budget and explain each component's failure modes
L4 trace a slow or failing request across components with logs, metrics and traces
L5 design a production architecture with failure domains, budgets and provider choices
L6 own the organisation's reference architecture and its evolution

The map

The roadmap's reference architecture:

Text
Internet
→ DNS / CDN
→ TLS / WAF
→ load balancer / API gateway
→ frontend (browser cache)          → API (auth / rate limit)
→ application service
→ cache        → database        → queue / event bus
→ search       → workers
→ AI / RAG / tool layer
→ model provider / GPU inference

It's a layered defence and a layered performance system at the same time. Each layer has three jobs: serve what it can (so deeper layers do less), reject what it should (so deeper layers are protected), and report what happened (so you can see the system). The deeper a request travels, the more expensive it is, so a good architecture answers as early as possible.

users · browsers · apps DNS (health-checked) CDN edge · cache TLS · WAF · bot rules LB · API gateway frontend bucket static assets api pods (auth, rules) Redis cache Postgres + replicas queue search AI / RAG workers model provider/GPU OTellogsmetricstraces each layer serves, rejects, and reports
The reference production architecture for TiffinBox. Requests enter through DNS and the CDN, pass TLS termination and the WAF, and reach a load balancer and gateway that route static assets to the front-end bucket and API calls to the application. The application reads and writes the cache, the PostgreSQL primary and its replicas, publishes events to a queue consumed by workers, queries search, and calls the AI layer, which retrieves context and calls a model provider. Telemetry from every layer flows to the observability stack.

DNS

What it does. Translates api.tiffinbox.in to addresses. It's the first dependency of every request, and changes to it propagate according to TTLs (cached answers live for the TTL in resolvers worldwide).

Production concerns:

  • Record types: A/AAAA (addresses), CNAME (alias to another name; not allowed at the zone apex), ALIAS/ANAME or provider-specific "alias" records (apex alias to a CDN or load balancer), CAA (which certificate authorities may issue for your domain), TXT (domain verification, SPF/DMARC for email).
  • TTL strategy: short TTLs (60 s) on records you may need to change in an incident (failover); long TTLs on stable ones. Lower TTLs well before a planned migration, since old answers persist for the previous TTL.
  • Health-checked routing: managed DNS (Route 53, Cloud DNS, Azure DNS, Cloudflare, NS1) can return different answers by health (failover), latency, geography or weight. This is the basis of regional failover (chapter 193).
  • DNS is a single point of failure at the provider level; very large sites run two authoritative DNS providers. Protect registrar accounts with MFA and registry lock: hijacked DNS is total compromise.

CDN

What it does. Edge servers close to users cache responses and terminate connections, reducing latency (fewer long-haul round trips) and origin load. Static assets (JS, CSS, images) are the obvious case; cacheable API responses (the public menu) are the high-leverage case.

Cache keys and headers. The CDN caches by a cache key (by default scheme + host + path + query). Responses tell caches what to do via Cache-Control:

Directive Meaning Typical use
public, max-age=31536000, immutable Any cache may store for a year; never revalidate Content-hashed assets app.3f9a1c.js
public, max-age=60, stale-while-revalidate=300 Fresh 60 s; serve stale up to 5 min while refreshing in background Public menu API
s-maxage=300 TTL for shared caches (CDN) only, overrides max-age there Edge cache longer than browsers
no-cache Store but revalidate every time (ETag/Last-Modified) index.html
private, no-store Never store in shared caches / anywhere Account pages, tokens
stale-if-error=86400 Serve stale if origin errors Resilience for read-mostly content

The Vary header adds request headers to the cache key (Vary: Accept-Encoding). Beware Vary: Cookie or Authorization: personalised responses must not be cached publicly; caching a personalised page publicly is a classic data leak.

Invalidation. Hard; avoid needing it. Content-hash static filenames (a new deploy = new names), keep index.html on no-cache, and use short TTLs with stale-while-revalidate for data. Purges (by URL, by tag/surrogate key) exist for emergencies.

Origin shielding. A designated mid-tier cache in front of the origin collapses cache misses from many edges into one request, protecting the origin from a thundering herd when a popular object expires.

Edge compute. CDNs run code at the edge (Cloudflare Workers, CloudFront Functions/Lambda@Edge, Fastly Compute): redirects, header manipulation, A/B assignment, auth token checks. Keep it small; it's a distributed system you can't easily debug.

TLS

What it does. Encrypts and authenticates connections. TLS 1.3 completes the handshake in one round trip (zero with resumption/0-RTT, which has replay caveats so is restricted to idempotent requests).

Where to terminate. At the CDN (for the user-facing connection), again at the load balancer (CDN → origin), and ideally re-encrypt to the pods or use a service mesh with mTLS inside the cluster ("encrypt everywhere"; zero-trust networking).

Certificates. Automate issuance and renewal (ACME/Let's Encrypt, AWS Certificate Manager, cert-manager in Kubernetes). Certificate expiry is still one of the most common causes of outages. Public certificate lifetimes are shrinking: the CA/Browser Forum has approved a phased reduction of maximum validity from 398 days down to 47 days by 2029 (the first step, to 200 days, took effect in March 2026), so manual renewal is no longer viable. Monitor expiry anyway. Use HSTS (Strict-Transport-Security) so browsers refuse plaintext.

WAF and bot management

What it does. A web application firewall inspects HTTP requests against rules: managed rule sets for common attacks (SQL injection, XSS, path traversal, known-bad user agents; OWASP Core Rule Set), rate-based rules, geo rules, IP reputation, and bot detection (challenge pages, fingerprinting).

Production stance. A WAF is defence in depth, not a substitute for parameterised queries and output encoding (Volume 10). Deploy new rules in count/log mode first to measure false positives before blocking; WAF false positives are real outages for the users blocked. DDoS protection (volumetric at L3/L4, application-layer at L7) usually comes with the CDN/WAF provider.

Load balancer and API gateway

Layer 4 vs layer 7. An L4 load balancer forwards TCP/UDP connections by address and port (fast, protocol-agnostic; AWS NLB). An L7 load balancer understands HTTP: routes by host and path, terminates TLS, adds headers, does retries, supports HTTP/2 and gRPC, WebSockets (AWS ALB, Envoy, NGINX, HAProxy).

Algorithms. Round robin; least outstanding requests (better when request costs vary); consistent hashing (session or cache affinity); weighted (canaries, chapter 192). "Power of two random choices" (pick two at random, send to the less loaded) gives near-optimal balance cheaply and is used by Envoy and others.

Health checks. The load balancer only routes to targets passing health checks; in Kubernetes, the readiness probe controls whether a pod is an endpoint (chapter 192). Health checks must be cheap and must not cascade (a health check that queries the database can take a whole fleet out when the database blips).

API gateway. An L7 proxy with API concerns: authentication (validate JWTs/OAuth tokens once, pass identity downstream), rate limiting and quotas, request/response transformation, routing to services and versions, API keys for partners, request size limits, CORS, and analytics. Options: Kong, Envoy Gateway, NGINX, AWS API Gateway, Apigee, Azure API Management; in Kubernetes the Gateway API (Gateway, HTTPRoute) is the standard successor to Ingress.

YAML
# Kubernetes Gateway API: route /v1/* to the api service, /assets/* elsewhere
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: tiffinbox-api, namespace: tiffinbox }
spec:
  parentRefs: [{ name: public-gateway, namespace: gateway-system }]
  hostnames: ["api.tiffinbox.in"]
  rules:
    - matches: [{ path: { type: PathPrefix, value: /v1/ } }]
      backendRefs: [{ name: api, port: 8080 }]
      timeouts: { request: 10s }

Rate limiting from first principles

The token bucket: a bucket holds up to capacity tokens and refills at rate tokens per second; each request takes a token; no token means reject (HTTP 429 with Retry-After). It allows bursts up to capacity while bounding the long-run rate. (The leaky bucket smooths output to a constant rate; sliding-window counters approximate "N per window" with less burstiness at window edges.) Per-key buckets (per user, per IP, per API key) protect against single abusers; a global limit protects the backend's capacity. In a fleet, state lives in Redis (an atomic Lua script) or the gateway does it with a shared store.

// Token bucket (lazy refill), safe for concurrent use
package ratelimit

import (
	"sync"
	"time"
)

type Bucket struct {
	mu       sync.Mutex
	capacity float64
	rate     float64 // tokens per second
	tokens   float64
	last     time.Time
}

func New(capacity, rate float64, now time.Time) *Bucket {
	return &Bucket{capacity: capacity, rate: rate, tokens: capacity, last: now}
}

// Allow reports whether a request may proceed and, if not, how long until a token exists.
func (b *Bucket) Allow(now time.Time) (bool, time.Duration) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.tokens = min(b.capacity, b.tokens+now.Sub(b.last).Seconds()*b.rate)
	b.last = now
	if b.tokens >= 1 {
		b.tokens--
		return true, 0
	}
	return false, time.Duration((1 - b.tokens) / b.rate * float64(time.Second))
}

Front end and the browser cache

The SPA is static files: index.html (no-cache), and content-hashed bundles (immutable, one year). The browser's HTTP cache, plus a service worker if you want offline behaviour, means repeat visits load almost nothing. Performance budgets (LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1 at p75 per Core Web Vitals) are measured in the field with real-user monitoring (RUM), not only in lab tests. The front end is also an observability source: RUM, JS errors, and front-end spans that start the distributed trace (traceparent header propagated to the API).

Application tier

Stateless service instances behind the load balancer (state lives in data stores), so any instance can serve any request and instances can be added, removed and replaced freely (horizontal scaling, rolling deploys). Responsibilities: authorisation (the gateway authenticates; the service decides what this identity may do with this resource), business rules (chapter 185's skip rules), transactions, timeouts and retries on every outbound call with budgets (Volume 9), circuit breakers, bulkheads (separate pools for separate dependencies), idempotency.

Cache

Redis (or Valkey, the open-source fork) for: read-through/cache-aside of hot reads (today's menu by office), session or token denylists, rate-limit state, distributed locks (with care; Volume 5), and short-lived computed results. Rules from Volume 3: set TTLs, plan for cold caches (the system must survive a flush; protect the DB with request coalescing), avoid caching what must be strongly consistent (credit balances come from the ledger), and watch hit ratio and memory eviction.

Database

PostgreSQL as the system of record: managed (RDS/Aurora, Cloud SQL/AlloyDB, Azure Database for PostgreSQL) or operated with an operator (CloudNativePG, Crunchy). Production elements: primary + synchronous or asynchronous standby in another availability zone for failover; read replicas for read scaling (with replication lag awareness: read-your-writes for the user who just skipped); connection pooling (PgBouncer, RDS Proxy; Postgres connections are processes and expensive); point-in-time recovery from continuous WAL archiving (chapter 193); migrations with lock safety (chapter 191).

Queue and event bus

Asynchronous work decouples request latency from slow work and absorbs bursts. Queues (SQS, RabbitMQ) deliver each message to one consumer; logs/streams (Kafka, Kinesis, Pub/Sub, Redpanda) retain ordered events for many consumer groups and replay. Delivery is at least once: consumers must be idempotent (dedupe on event id). Publish from the transactional outbox (chapter 187) so events match committed state. Dead-letter queues for poison messages, with alerts.

OpenSearch/Elasticsearch (or Postgres full-text search for modest needs, or Meilisearch/Typesense) for menu search with typo tolerance and facets. It's a derived store: rebuilt from the system of record via events or CDC (Debezium); never the source of truth. Index changes use aliases (build a new index, swap the alias): zero-downtime reindexing.

Workers

Background consumers (the Go dispatch worker): process events, send notifications, generate invoices, run scheduled jobs (Kubernetes CronJobs; at 07:00 IST lock tomorrow's deliveries and publish kitchen prep). Scale on queue depth/lag (KEDA) rather than CPU. Make jobs idempotent and resumable; a job that crashes midway must be safe to rerun.

AI, RAG and tool layer

The assistant ("why was I charged?", "skip all Fridays this month") from Volume 14: an orchestration service that retrieves (vector search over help docs + the user's own data via authorised APIs), builds a prompt, calls a model, and executes tools (e.g. skip_delivery) through the same API and authorisation as the app, never with privileged shortcuts. Production concerns specific to this layer:

  • Latency and streaming: model calls take seconds; stream tokens to the client; set timeouts; show progress.
  • Cost controls: per-user/per-tenant token budgets, caching of identical prompts (provider prompt caching for long static prefixes), smaller models for routing/classification.
  • Safety: prompt-injection defences (retrieved text is data, not instructions), tool-call confirmation for consequential actions, output filtering, logging for evaluation (with PII controls).
  • Fallbacks: provider outages happen; degrade to search/help-centre links, or a secondary provider.
  • Evaluation and observability: traces of each step (retrieval hits, prompt, tool calls, tokens, latency), offline eval sets, online feedback (Volume 14, chapters 175–178).

Model provider and GPU inference

Either a hosted API (Anthropic, OpenAI, Google; or via a cloud's managed service such as Amazon Bedrock, Vertex AI, Azure AI Foundry, which helps with data residency, private networking and consolidated billing) or self-hosted inference on GPUs (vLLM, TGI, SGLang, TensorRT-LLM on Kubernetes GPU nodes) for open-weight models. Self-hosting trades API cost for GPU capacity planning (memory for weights and KV cache, batching, autoscaling on queue depth/tokens per second), cold starts (loading tens of GB of weights), and operational burden. Most teams start hosted.

The latency budget

A latency budget allocates the end-to-end target across layers, so every team knows its share. TiffinBox's NFR: skip confirmation p95 ≤ 800 ms on 4G (chapter 185). Budgets add for sequential steps; percentiles don't add exactly, but summing p95s gives a conservative estimate.

Python
# Latency budget for "skip a delivery" (p95, ms) — sequential steps sum; parallel steps take the max
steps = [
    ("DNS (cached after first visit)",          0),
    ("TCP+TLS to CDN edge (resumed, 1 RTT)",   60),
    ("edge → origin (Mumbai region)",          25),
    ("WAF + LB + gateway (JWT verify)",         8),
    ("api: authz + validation",                 5),
    ("api: Postgres transaction (skip+credit+outbox)", 25),
    ("api: serialise + respond",                3),
    ("response back to device (1 RTT on 4G)",  60),
    ("client render",                          50),
]
total = sum(ms for _, ms in steps)
for name, ms in steps:
    print(f"{name:<48}{ms:>5} ms")
print(f"{'total (sum of p95s, conservative)':<48}{total:>5} ms  vs budget 800 ms → headroom {800 - total} ms")
# Parallel fan-out example: menu page calls menu, credits and announcements concurrently
fan_out = {"menu (cache hit)": 4, "credit balance (ledger query)": 18, "announcements (cache)": 3}
print("fan-out step contributes max =", max(fan_out.values()), "ms, not the sum", sum(fan_out.values()), "ms")
Text
DNS (cached after first visit)                      0 ms
TCP+TLS to CDN edge (resumed, 1 RTT)               60 ms
edge → origin (Mumbai region)                      25 ms
WAF + LB + gateway (JWT verify)                     8 ms
api: authz + validation                             5 ms
api: Postgres transaction (skip+credit+outbox)     25 ms
api: serialise + respond                            3 ms
response back to device (1 RTT on 4G)              60 ms
client render                                      50 ms
total (sum of p95s, conservative)                 236 ms  vs budget 800 ms → headroom 564 ms
fan-out step contributes max = 18 ms, not the sum 25 ms

The headroom is deliberate: tail latency under load (queueing grows non-linearly as utilisation approaches 100%; Volume 9), retries, and slow networks eat it. The budget also shows what not to add to the synchronous path: calling the kitchen system or sending an SMS inside the request would blow the budget, so those are async via the outbox.

Failure domains and blast radius

A failure domain is the set of things that fail together: a process, a node, an availability zone (a data centre group with independent power and networking), a region, a provider, a deployment (a bad release), a configuration (a bad flag), a dependency. Architecture limits blast radius by placing redundancy across domains and isolating them:

Domain Typical failure Mitigation
Pod / process Crash, OOM, deadlock Multiple replicas; liveness restarts; PodDisruptionBudget
Node Hardware, kernel, eviction Spread pods across nodes (topology spread constraints, anti-affinity)
Availability zone Power/network event Multi-AZ: pods, DB standby, cache replicas, LB in ≥ 2–3 AZs
Region Large provider incident Multi-region (warm standby or active-active; chapter 193)
Release Bug in new version Canary, automated rollback (chapter 192)
Config / flag Bad value pushed globally Staged config rollout; validation; kill switches
Dependency Payment provider, model API down Timeouts, circuit breakers, fallbacks, queues to retry later
Tenant / user One customer's traffic spike Per-tenant rate limits, quotas, cell-based architecture

Cells. At scale, partition the whole stack into independent cells (each serving a subset of customers, e.g. by office or city), so a failure or bad deploy affects one cell. AWS uses cell-based architecture widely; TiffinBox could cell by city when it expands beyond Hyderabad.

region ap-south-1 AZ a api api worker PG primary AZ b api api worker PG standby (sync) AZ c (failed) api api worker PG read replica N+1 per zone: two healthy zones must carry the full load
Failure domains nest: processes inside nodes, nodes inside availability zones, zones inside a region. Spreading replicas across zones means a single zone failure removes one third of capacity rather than all of it, provided each zone has headroom to absorb the shift. The database primary and standby sit in different zones.

The arithmetic of zone headroom: with three zones each running at utilisation u, losing one shifts load to two, so each runs at 1.5u. To stay under 70% after a zone loss, run at most about 47% per zone in normal operation. This is why "multi-AZ" without spare capacity is not resilience, and why autoscaling's reaction time matters.

Mapping to providers

Layer AWS Google Cloud Azure Self-hosted / portable
DNS Route 53 Cloud DNS Azure DNS Cloudflare, NS1, PowerDNS
CDN / edge CloudFront Cloud CDN Azure Front Door Cloudflare, Fastly, Akamai
WAF AWS WAF, Shield Cloud Armor Front Door WAF Cloudflare WAF, ModSecurity + CRS
L7 LB / gateway ALB, API Gateway Cloud Load Balancing, Apigee App Gateway, APIM Envoy, NGINX, HAProxy, Kong
Kubernetes EKS GKE AKS kubeadm, k3s, Talos, OpenShift
PostgreSQL RDS, Aurora Cloud SQL, AlloyDB Azure DB for PostgreSQL CloudNativePG, Patroni
Cache ElastiCache (Redis/Valkey) Memorystore Azure Cache for Redis Redis, Valkey
Queue / stream SQS/SNS, MSK, Kinesis Pub/Sub Service Bus, Event Hubs RabbitMQ, Kafka, NATS
Search OpenSearch Service (Elastic Cloud) (Elastic Cloud), AI Search OpenSearch, Elasticsearch
Object storage S3 Cloud Storage Blob Storage MinIO, Ceph
Secrets Secrets Manager, KMS Secret Manager, Cloud KMS Key Vault Vault, OpenBao, Sealed Secrets
Model API Bedrock Vertex AI Azure AI Foundry vLLM/TGI on GPU nodes

Managed services move operational work (patching, backups, failover) to the provider at a price premium and some lock-in; Volume 15's build-vs-buy reasoning applies. Kubernetes, PostgreSQL, Redis, Kafka, OpenTelemetry and Terraform are the portable core: an application built on them moves between providers with moderate effort.

Reading the architecture as a request

Trace one request, "skip Thursday", with what each layer does:

  1. DNS: browser already has api.tiffinbox.in cached; nothing.
  2. CDN: request is POST, not cacheable; edge forwards to origin over a kept-alive, pre-warmed connection (saving a TLS handshake to the origin).
  3. TLS/WAF: decrypted at the edge; WAF rules pass; bot score fine.
  4. LB/gateway: JWT signature and expiry verified (JWKS cached); rate limit for user 1234 has tokens; routed to an api pod with fewest outstanding requests; traceparent added if absent.
  5. API: authorisation (subscription 77 belongs to user 1234); validation (date format, Idempotency-Key present); one Postgres transaction (chapter 187's SQL); response 200 with credit balance.
  6. Async: the outbox relay publishes DeliverySkipped to the queue; the dispatch worker removes the lunch from Thursday's prep list and rider batch.
  7. Telemetry: one trace spans browser → gateway → api → Postgres → (linked) worker; metrics increment skips_total; logs carry the trace id.

Lab: measuring the request path

Setup. On the lab machine: nginx 1.24 as the reverse proxy (plain HTTP on one port, HTTPS with a self-signed 2048-bit RSA certificate on another, keepalive to the upstream), a FastAPI app under uvicorn with a psycopg connection pool to PostgreSQL 16 and a Redis cache. A Python client made 300 sequential requests per row after one warm-up. Scope: everything runs on one machine, so network distance is zero; the lab isolates the cost each component adds, and the analysis adds distance with typical round-trip times.

Experiment 1: what each hop adds

Path p50 p99
app directly, /health 0.73 ms 1.46 ms
via nginx, HTTP, /health 1.00 ms 1.77 ms
via nginx, HTTPS on a reused connection 0.88 ms 1.57 ms
via nginx, HTTPS with a new connection per request 2.43 ms 4.51 ms
app, menu from PostgreSQL (aggregate over 6,000 rows) 2.06 ms 5.50 ms
app, menu from Redis (cache hit) 0.81 ms 1.42 ms
  • A reverse proxy cost a fraction of a millisecond; on a reused connection, TLS was free within measurement noise (the HTTPS row came out slightly faster than plain HTTP, which is noise, not a finding). A new TLS connection cost about 1.5 ms of CPU here, before any network delay.
  • The cache saved about 1.3 ms at the median and 4 ms at p99 over a small query; on heavier queries or a loaded database, the gap grows by orders of magnitude.

Experiment 2: the latency budget with distance added

The same path for a user in Hyderabad, using the measured component costs plus typical round-trip times (RTTs) to each region; these RTTs are typical figures, not measured here:

Server location Typical RTT New HTTPS connection (TCP + TLS 1.3 + request ≈ 3 RTT) Reused connection (1 RTT) Components (measured, cached)
Hyderabad / Mumbai ~5–20 ms ~15–60 ms ~5–20 ms ~1 ms
Singapore ~40–60 ms ~120–180 ms ~40–60 ms ~1 ms
US East ~200–250 ms ~600–750 ms ~200–250 ms ~1 ms

The components were a rounding error next to distance. The levers that matter, in order: put compute and data near users (or at least the cacheable parts, via a CDN), reuse connections (HTTP keep-alive, HTTP/2 and HTTP/3, TLS session resumption), avoid sequential round trips (batch API calls, don't chain requests from the client), then cache. Per-hop timings still matter for tail latency and capacity: a database at p99 5.5 ms becomes 500 ms when it's saturated.

Try it yourself

  1. Add tc qdisc add dev lo root netem delay 25ms (if permitted) and remeasure new vs reused HTTPS connections.
  2. Make the app call PostgreSQL three times sequentially per request, then once with a combined query; compare p99.
  3. Stop Redis and measure /menu/cached with and without a short client timeout.
  4. Draw TiffinBox's architecture with a blast-radius note on each box: what fails, what degrades, what keeps working.

Revision sheet: reference production architecture

Key ideas

  • The map: DNS → CDN → TLS termination → WAF/bot management → load balancer/API gateway → front end → app tier → cache, database, queue/event bus, search → workers → AI/RAG/tool layer → model providers.
  • Each component has a job, a failure mode and a degradation plan.
  • Latency budget: distance (RTTs) and round-trip count first; then handshakes; then per-component costs; budget p99, not just p50.
  • Failure domains: instance, zone, region, provider; design so one domain's loss has a bounded blast radius.
  • Stateless app tier; state in managed stores; async work on queues; idempotent workers.
  • Map components to providers (AWS, GCP, Azure, Cloudflare and others) without changing the design.
  • Read the architecture as a request: follow one user action through every box, including what happens when each fails.

Numbers to remember

  • Lab: proxy hop ~0.3 ms; new TLS connection ~1.5 ms CPU; cache hit 0.8 ms vs query 2.1 ms (p99 1.4 vs 5.5).
  • New HTTPS connection ≈ 3 RTT before the response; reused ≈ 1 RTT.

Pitfalls

  • Serving users from a far region without a CDN or edge caching.
  • Opening a new connection per request (client to server or server to database).
  • Chains of sequential calls on the request path.
  • No degraded mode when the cache or a third party is down.
  • Latency budgets set on medians.

Glossary

  • TLS termination: decrypting HTTPS at the edge or load balancer.
  • API gateway: entry point with routing, auth, rate limiting.
  • Failure domain: a set of components that can fail together.
  • Latency budget: allocation of an end-to-end latency target across components.
  • Connection pool: reused connections to a backend.