How a request travels: DNS, load balancers, gateways and open connections
Foundations F01. Follow one request from a tap on the phone to the database and back, and learn each building block as a story you'll remember: DNS, TCP and TLS, CDNs, load balancers, API gateways, service discovery, real-time connections and multi-region routing.
Start here
Every system design starts the same way: a phone or browser sends a request, and something has to get it to the right server quickly, safely and even when machines fail. This page follows one request from the tap to the database and back, and stops at each building block on the way.
You'll meet these pieces in every design in the series. Learn each as a story, and the jargon will stick.
Sending a parcel across the city
Picture sending a parcel to a friend at a big office.
- You look up the office's address (DNS).
- You and the courier agree on how to hand it over safely, and seal it (TCP and TLS).
- If it's something common, a local branch may already have a copy (CDN).
- At the office, the reception desk checks your ID and sends you to the right floor (load balancer and API gateway).
- Inside, staff find the right colleague from the internal directory (service discovery).
- If your friend needs to keep you updated, they keep a phone line open instead of you calling every minute (WebSockets).
Keep this parcel in mind: each concept below is one stop on its route.
DNS: turning names into addresses
DNS is the internet's contact list: it turns a name like api.uber.com into the IP address a phone can connect to, and everyone caches the answer for a while.
Your phone's contact list
You don't remember your friend's number; you tap their name. The first time, you had to ask someone for the number. After that it's saved, so calling is instant.
But if your friend changes their number, your saved contact is wrong until you update it. How long you trust a saved number is the TTL.
DNS (Domain Name System) maps a name to one or more IP addresses.
- The phone asks a resolver (often your ISP's or a public one like 1.1.1.1).
- If the resolver doesn't know, it asks the DNS servers responsible for that domain.
- Every answer comes with a TTL (time to live, in seconds). Phones, browsers and resolvers cache it until the TTL runs out.
A company can return a different IP depending on where you are (GeoDNS), so users in India get servers in Mumbai and users in the US get servers in Virginia.
When a region fails, the company changes the DNS answer to point elsewhere. Anyone who cached the old answer keeps trying the dead region until their TTL expires, so teams use short TTLs (30–60 s) for names they may need to fail over.
- Short TTL: fast failover, but more DNS lookups and more load on DNS servers.
- Long TTL: fewer lookups and faster first requests, but slow to move traffic when something breaks.
DNS gets the user to the nearest healthy region; I'd keep the TTL short on the API hostname so we can fail over in about a minute.
Saying "we'll just update DNS" as instant failover. Cached answers keep sending traffic to the old place until their TTL expires; some clients ignore TTLs entirely.
TCP, TLS and HTTP versions: opening the line
Before any data moves, the phone and server spend round trips agreeing to talk (TCP) and agreeing on encryption (TLS); reusing a connection skips all of that.
Starting a phone call in a noisy room
You dial, the other person picks up and says "hello?", you say "hi, can you hear me?" That's TCP's handshake: both sides confirm they're connected before talking.
Then you agree to switch to a private language only you two understand. That's TLS.
Once the call is set up, you don't hang up after every sentence. You keep the line open (keep-alive). HTTP/2 lets you hold several conversations on the same call; HTTP/3 makes sure one bad crackle doesn't freeze all of them.
- TCP: reliable, ordered delivery. Setting it up costs 1 round trip.
- TLS 1.3: encryption and identity (the padlock). It adds 1 more round trip on a new connection.
- HTTP/1.1: one request at a time per connection, so browsers open several connections.
- HTTP/2: many requests share one TCP connection. But one lost packet stalls everything behind it ("head-of-line blocking").
- HTTP/3: runs over QUIC on UDP. Transport and TLS setup happen together (1 round trip), and a lost packet only delays its own stream. It helps most on flaky mobile networks.
On a mobile network a round trip can easily be 50–150 ms. A brand-new HTTPS connection over TCP needs 2 round trips before the request even leaves: up to 300 ms of nothing.
That's why apps keep connections open, reuse them for every call, and why services inside a data centre use connection pools instead of reconnecting for each request.
- TCP vs UDP: TCP gives order and reliability; UDP gives speed and leaves reliability to you (QUIC, video calls, games).
- Long-lived connections save handshakes but tie up memory on the server and need heartbeats to spot dead ones.
The handshakes cost round trips, so the client keeps one HTTP/2 or HTTP/3 connection open, and services talk over pooled connections.
Treating latency as only server time. On mobile, the network round trips usually dominate; cutting one round trip often beats a week of server tuning.
Try it: Where does the time go?
Follow one request and switch things on and off. Watch which choices remove whole round trips.
| # | Step | Time | Why |
|---|---|---|---|
| 1 | DNS lookup | 50 ms | Phone asks a resolver, which may ask other DNS servers. |
| 2 | TCP handshake | 40 ms | SYN, SYN-ACK: 1 round trip before anything is sent. |
| 3 | TLS 1.3 handshake | 40 ms | Agree keys: 1 more round trip. |
| 4 | Send request, get response | 40 ms | Round trip to the region (40 ms away). |
| 5 | Load balancer | 1 ms | Picks a healthy gateway instance. |
| 6 | API gateway | 3 ms | Checks the token, rate limit; adds a request id. |
| 7 | Service logic | 15 ms | The actual work. |
| 8 | Database query | 5 ms | Indexed read on a pooled connection. |
Try: server abroad + no reuse, then turn on "Reuse open connection". Handshakes cost whole round trips, which is why apps keep connections open and why companies put servers and CDNs near users. Numbers are rounded, typical values for teaching.
CDN and edge caching: keep copies near people
A CDN keeps copies of files in data centres close to users, so most requests never travel to your main servers.
The bookshop chain
A bestselling book is printed at one central warehouse. If every reader had to order from the warehouse, deliveries would be slow and the warehouse would be swamped.
So every local branch keeps a few copies on its shelves. Most readers get theirs from the branch down the road. Only when a branch runs out does it order from the warehouse (the origin).
A CDN (content delivery network) is a fleet of edge servers in many cities.
- The first request for a file goes to the origin; the edge stores a copy (a cache miss).
- Later requests nearby are served from the edge (cache hits).
- Your server controls caching with headers such as Cache-Control: max-age=86400.
- To change a file, either purge it from the CDN or, better, give the new version a new name (app.3f9c.js), so old and new never mix.
Images, app bundles, video segments and map tiles are perfect for a CDN: the same bytes for millions of people.
A user in Bengaluru fetching from a server in the US pays ~220 ms per round trip; from an edge in the same city it's ~10–20 ms. Video streaming at scale is basically impossible without a CDN.
- Great for the same content for everyone; little help for personalised API responses (each user's ride is different).
- Long cache times are fast and cheap but make updates slower to appear; versioned file names solve most of this.
Static files and media go through a CDN with long cache times and versioned names, so the origin only serves dynamic API traffic.
Putting personalised or private responses behind a shared cache without the right headers. One user's data can be served to another.
Load balancers: spreading the work
A load balancer spreads requests across many identical servers and stops sending work to any server that fails its health check.
The restaurant host
A busy restaurant has one host at the door and ten waiters. The host seats each new group with a waiter who has space, so nobody is swamped while others stand idle. If a waiter goes home sick, the host simply stops seating people in their section.
A simple host only counts heads (L4). A smarter one reads the order ("sushi, please") and sends the group to the sushi counter (L7).
- L4 load balancer: routes by IP and port, without looking inside the request. Very fast; good for any TCP traffic.
- L7 load balancer: reads HTTP (path, headers, cookies), so it can send /api/rides to one service and /images to another, and terminate TLS.
- Algorithms: round robin (take turns), least connections (pick the least busy), weighted (bigger servers get more), consistent hashing (same user to the same server).
- Health checks: the balancer pings each server (for example GET /health every 5 s) and removes ones that fail.
Behind the balancer, servers should be stateless: any server can handle any request because session data lives in a shared store (Redis, a database), not in one server's memory. Then adding capacity is just adding servers, and losing one loses nothing.
Load balancers themselves run in pairs or as a managed, replicated service, so they aren't a single point of failure.
- L4 vs L7: L4 is simpler and faster; L7 is smarter (routing by path, retries, TLS termination) but does more work per request.
- Sticky sessions (same user to the same server) help with long-lived connections like WebSockets, but make load uneven and failover harder.
Stateless app servers behind an L7 load balancer with health checks; least-connections routing, and the balancer itself is redundant.
Drawing one load balancer box and never saying what happens when it, or a server behind it, dies.
Reverse proxy and API gateway: the front desk
An API gateway is the single front door for your APIs: it checks who you are, how often you're calling, and sends you to the right internal service.
The office reception desk
Visitors don't wander the building looking for people. Reception checks their ID, gives them a visitor badge, turns away anyone who's been in ten times today, and tells them which floor to go to.
Visitors never learn the internal room numbers, and if a team moves floors, only reception needs to know.
A reverse proxy sits in front of servers and forwards requests to them (NGINX, Envoy). An API gateway is a reverse proxy with API-specific jobs:
- Authentication: check the token (JWT) before anything else runs.
- Rate limiting and quotas: protect services from abuse and retry storms.
- Routing: /v1/rides → ride service, /v1/payments → payments.
- Cross-cutting extras: request ids for tracing, logging, request size limits, sometimes response caching.
A forward proxy is the opposite: it sits in front of clients (a company proxy that employees' browsers go through).
In Part 01, every phone call hit Uber's API gateway. At one point polling made up 80% of its traffic, which is why Uber moved updates to a push system: the gateway is where you see what clients are really doing.
A related pattern is a backend-for-frontend (BFF): a small gateway per client type (rider app, driver app, web) that shapes responses for that screen.
- One gateway gives one place for auth and limits, but it's on every request: keep it thin and stateless, and scale it horizontally.
- Putting business logic in the gateway couples every team to it; keep logic in services.
Clients only see the gateway; it authenticates, rate-limits per user and per city, adds a request id, and routes to services.
Letting services trust any caller because "the gateway checked it". Internal calls still need service identity (mTLS or signed tokens).
Service discovery and connection pools: finding colleagues
Inside the system, services find healthy instances of each other through a registry, and keep pools of open connections so they don't pay for handshakes on every call.
The office directory and the taxi rank
In a big office, people change desks all the time. You don't memorise desk numbers; you check the live directory, which only lists people who are in today.
And instead of calling a taxi company for every trip, the office keeps a few taxis waiting at the rank. Grab one, use it, return it. If all the taxis are out, you wait: that's pool exhaustion.
- Service discovery: instances register themselves (or the platform does it), and callers look up healthy addresses. In Kubernetes, a Service gives a stable name that routes to healthy pods.
- Connection pool: a fixed set of open connections to a database or service, reused across requests.
- Pool size is a real limit: if each request holds a database connection for 50 ms and the pool has 20 connections, that instance can do at most 20 ÷ 0.05 = 400 queries per second.
A classic outage: the database slows down, every request holds its connection longer, the pool runs out, new requests queue, and the whole service looks down even though the database is still answering.
The fixes are timeouts on getting a connection, sensible pool sizes, and a database proxy (such as PgBouncer) when thousands of app instances would otherwise each open their own connections.
- Bigger pools allow more parallel work but can overload the database with too many connections.
- Client-side discovery (caller picks an instance) is flexible; server-side (a load balancer picks) is simpler for callers.
Services find each other through discovery, and every client has a bounded connection pool with timeouts, so a slow dependency can't exhaust it silently.
Ignoring the connection limit of the database. Scaling app servers from 10 to 100 can multiply connections tenfold and take the database down.
Polling, SSE and WebSockets: keeping the line open
When the server needs to tell the client something the moment it happens, keep a connection open (SSE or WebSockets) instead of having the client ask over and over.
"Are we there yet?"
A child in the back seat asks "are we there yet?" every minute. That's polling: lots of questions, almost always the answer is no.
Long polling is the child asking once and the parent only answering when there's news.
Server-Sent Events (SSE) is the parent promising "I'll announce each town as we pass it". WebSockets is a walkie-talkie: both sides can talk any time.
- Short polling: the client asks every few seconds. Simple, but wasteful and slow to notice changes.
- Long polling: the server holds the request open until there's news or a timeout. Better, but each message still needs a new request.
- SSE: one HTTP connection, server → client only, plain text events, automatic reconnect. Great for feeds and notifications.
- WebSockets: one connection, both directions, any time. Right for chat, games, collaborative editing.
Scaling either one means millions of open connections: a connection registry (which server holds which user), heartbeats to detect dead connections, and reconnect with backoff and jitter.
Uber's push platform kept 1.5M+ connections open and sent 250K+ messages a second (2020). Polling had been 80% of their gateway traffic. They later moved from SSE to gRPC bidirectional streams to get real-time acknowledgements. Part 01 walks through it.
- Polling is easy to build and cache, and fine when updates are rare or delay doesn't matter.
- Open connections are fast, but every connection costs server memory and makes deploys harder (you must drain them gracefully).
For updates the user waits on, I'd use a persistent connection with sequence numbers and acks, and fall back to polling if the connection can't be kept.
Choosing WebSockets everywhere. If the server only ever pushes, SSE is simpler; if updates are every few minutes, polling is fine.
Anycast and multi-region routing: the nearest door
To serve the whole world, run in several regions and steer each user to the closest healthy one, with GeoDNS or anycast.
One emergency number, many control rooms
In India you dial 112 wherever you are, and the call reaches a control room near you. Nobody dials a different number per city.
Anycast works the same way: many data centres announce the same IP address, and the internet's routing delivers each user to the nearest one. If one control room closes, calls simply go to the next nearest.
- GeoDNS: DNS answers with a different IP depending on the user's location. Failover speed depends on TTLs.
- Anycast: the same IP is announced from many places; network routing picks the nearest. Failover happens at the network level, without waiting for DNS caches. CDNs and DNS providers rely on it.
- Multi-region apps also need a plan for data: which region owns a user's data, and what happens to writes during a failover. That's covered in the Reliability page.
A ride-hailing app can pin each city to a home region (Bengaluru → Mumbai region) with a backup region, so dispatch data stays close to drivers and riders. The edge (CDN, load balancers) is anycast; the API name uses GeoDNS with a short TTL.
- More regions: lower latency and survivable outages, but more cost and harder data consistency.
- Anycast fails over fast but gives less control over exactly which site a user reaches.
Users reach the nearest region through anycast at the edge and GeoDNS for the API; each city has a home region and a failover region.
Saying "multi-region" without saying where writes go. Routing users is the easy half; the data is the hard half.
Remember it
One line per idea. Read this the night before.
- DNS is the contact list: names to addresses, cached until the TTL runs out, so failover is only as fast as the TTL.
- A new HTTPS connection costs round trips before any data moves; keep connections open and reuse them.
- HTTP/2 shares one connection; HTTP/3 (QUIC) also stops one lost packet from stalling everything.
- A CDN is the bookshop branch: same bytes for everyone, served near the reader; version file names instead of purging.
- A load balancer is the restaurant host: spreads work, drops unhealthy servers; keep servers stateless.
- The API gateway is reception: auth, rate limits, request ids, routing. Keep business logic out of it.
- Connection pools are the taxi rank: bounded, reused, and a common hidden bottleneck.
- Polling asks "are we there yet?"; SSE announces; WebSockets is a walkie-talkie.
- Anycast is 112: one number, nearest control room. Routing users is easy; routing their data is the hard part.
Check yourself
Answer out loud, then open.
Your region fails and you change the DNS record. Why do some users still fail for a few minutes?
Their phones, browsers or resolvers cached the old answer and keep using it until the TTL expires. Some clients also hold an open connection to the old address.
- Use a short TTL (30–60 s) on names you may fail over.
- Prefer anycast or a global load balancer at the edge, which fails over without waiting for DNS caches.
A user abroad says the app is slow, but your servers answer in 20 ms. Where is the time going?
In network round trips. At ~220 ms per round trip, a new connection costs about 440 ms in TCP and TLS handshakes before the request even leaves, plus the request itself.
Fixes: reuse connections, use HTTP/3, serve static files from a CDN, and serve users from a nearer region.
When would you choose an L4 load balancer over an L7 one?
When you don't need to look inside requests: raw TCP or UDP traffic, very high throughput, or when TLS must pass through untouched to the server.
Choose L7 when you route by path or header, terminate TLS, retry failed requests, or need per-request metrics.
Why must app servers behind a load balancer be stateless?
So any server can handle any request. Then you can add servers to scale, and a server dying loses nothing, because session data lives in a shared store (Redis or a database), not in that server's memory.
Chat messages: polling, SSE or WebSockets?
WebSockets (or bidirectional gRPC streams): messages go both ways, constantly, and must arrive instantly.
SSE fits server-to-client only (live scores, notifications). Polling fits rare updates where a few seconds of delay is fine.
The database is healthy, but your service times out under load. What hidden limit might you have hit?
The connection pool. If each request holds a connection for 50 ms and the pool has 20 connections, the instance can do at most 400 queries a second; beyond that requests queue and time out.
Look at pool wait time, add timeouts on acquiring a connection, size pools deliberately, or put a database proxy in front.
Where you'll use this in the series
- Uber: from tap to pickup · load balancer, gateway, push connections, regions
- Rate limiter · runs in the API gateway
- WhatsApp: chat and delivery receipts · millions of WebSocket connections (coming)
- Video streaming (YouTube / Netflix) · CDN and edge caching (coming)
Sources
- What is DNS?, Cloudflare Learning Center
- The Transport Layer Security (TLS) Protocol Version 1.3, RFC 8446 (Aug 2018)
- HTTP/3, RFC 9114 (Jun 2022)
- The WebSocket Protocol, RFC 6455 (Dec 2011)
- What is a CDN?, Cloudflare Learning Center
- What is an anycast network?, Cloudflare Learning Center
- Uber's Real-Time Push Platform, Uber Engineering (Dec 2020)
Protocol facts come from the RFCs; latency figures are rounded, typical values for teaching, not measurements.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.