Skip to main content

Chapter 1 — What a Backend Is & the Request's Journey

Part I · Foundations | Prerequisites: Ch 0 — How to Use This Book | Builds: the spine diagram you'll reuse in every later chapter

You've already met the reframe: a backend is a shared mutable state machine accessed concurrently over an unreliable network, that must stay correct and observable while individual parts fail. In plain terms — many users hammer one shared pile of data at the same time, over a network that drops packets, and it still has to give right answers and let you see what it's doing when a piece breaks. That sentence is a promise the rest of the book pays off one clause at a time. This chapter cashes the first instalment. By the end you'll be able to draw — from memory — the path a single request takes from a user's thumb to your database and back, name what each hop costs you, name what each hop can do to ruin your night, and explain why a backend has to exist at all. Every later chapter is a zoom-in on one box of the diagram you're about to draw. Get this picture solid and you always know where you are.

This is a concept-dense, low-code chapter on purpose. We are building the map before we walk the territory.


1. The problem: why a backend exists at all​

Let me start with a story that has happened, in some form, to almost everyone who has shipped software.

A team builds a slick patient billing screen for Pulsely. It's a single-page app: the visit's line-item charges, a running balance, a Pay button. To keep it snappy, the amount due is computed right there in the browser — each charge summed, minus what insurance covered, all in JavaScript. It demos beautifully. It ships.

A week later, the billing office notices that someone settled a $1,000 balance for $1.

Nothing was hacked in the movie sense. The patient opened devtools, found the variable holding the amount due, set it to 1, and clicked Pay. The browser dutifully sent { amountDue: 1 } to the payment step, and the payment step — trusting it — took a dollar. There was no server-side authority over the balance, so there was no truth, only a suggestion the patient was free to edit.

Here is the uncomfortable lesson: anything computed only on the client is not a fact. It's a request. The browser is a building you don't own, run by a tenant who can rearrange the furniture. If the balance has to be real — if money or correctness depends on it — something the user cannot edit has to decide it. That something is the backend.

Now a second story, because money isn't the only kind of truth.

Two front-desk staff are looking at the same open appointment slot: Dr. Reyes, 9:00 Monday, one opening left. Both tap Book within the same 40-millisecond window, one from the front desk, one from the patient app. What should happen? Exactly one booking, one patient who has to take another time. But neither client can make that decision, because neither client can see the other. The front-desk browser doesn't know the patient app exists. Somebody has to hold the single, durable copy of "is this 9:00 slot still open" and serialize the two requests into a winner and a loser. That somebody is, again, the backend. Not because backends are fashionable — because the alternative is two patients each told they own the same 9:00 slot.

And a third, quieter story. Pulsely has a provider web app, a patient iOS app, and a partner clearinghouse that submits claims through an API. All three need to "book a visit": check the slot is open, reserve it, verify the patient's coverage is eligible, notify the care team. If that logic lives in each client, you now maintain it in three places, in three languages, written by three teams — which means three subtly different versions, which means three subtly different bugs, one of which is a security hole (a booking path that quietly skips the eligibility check, say). The backend exists so that the rules that guard shared state live in exactly one place, and every client — present and future — is forced to go through them.

Strip these stories to their bones and you get the reason backends exist. A backend is necessary when state must be:

  • Shared across clients that can't see each other (the two staff booking one slot),
  • Durable beyond any single session or device (the appointment still exists after you close the tab, and tomorrow), and
  • Trusted, because the clients touching it can lie, break, or be hostile (the $1 balance).

Remove all three and you may genuinely not need a backend. A pure offline calculator shares nothing, persists nothing important, and trusts no one but its single user — so it has no backend, and rightly so. The moment any one of those three pillars appears, an authority has to appear with it.

🧭 A useful distinction. "Backend" is a role — being the authority over shared state — not a deployment artifact. You can fulfil the role without running your own server (a Backend-as-a-Service like Firebase or Supabase runs the box for you). What you can never do is make the role go away. Someone, somewhere, must be the authority. This book is about being good at that role, wherever the box runs.


2. The mental model: three pillars and a membrane​

Hold two pictures in your head for the rest of the book. The first is structural; the second is spatial.

The three pillars​

Everything a backend does rests on three pillars. Name them, because we'll keep pointing at them:

  1. Shared application logic — the rules. "A visit can be booked only if the slot is still open." "Only the authoring provider can amend a signed note." This is the behavior you'd be horrified to see duplicated or bypassed.
  2. Durable state — the record of what happened. The encounters, the claims, the slot bookings. It outlives every process and every request. When everything else is rebooted, this is what remains.
  3. The trust boundary — who is allowed to do what. The line where untrusted input from anyone on the internet is checked, authorized, and only then allowed to change pillar 2 by way of pillar 1.

A "backend" with no shared logic is a file store. With no durable state, it's a calculator. With no trust boundary, it's a liability. The interesting engineering lives where all three meet.

The membrane​

Now the spatial picture. Imagine a vertical membrane down the middle of the world:

UNTRUSTED │ TRUSTED
(you do not control this) │ (you do control this)
│
┌─────────────┐ │ ┌──────────────────────┐
│ browsers │ ──── claim ─────▶ │ ──validate──▶ │ application logic │
│ mobile apps│ │ authorize │ (the rules) │
│ partners │ ◀─── ruling ───── │ ◀────────── │ durable state (DB) │
│ bots, etc. │ │ └──────────────────────┘
└─────────────┘ │
the TRUST BOUNDARY
(every endpoint is a door in it)

Everything on the left is a claim: "I am provider 42," "the amount due is $1," "sign encounter 99." Everything on the right is truth you are willing to stand behind. The backend's whole job is to run the membrane: take claims, validate and authorize them against durable state, and emit a ruling. The ruling — "appointment booked," "403 forbidden," "slot taken" — is the product. Not the JSON formatting; the decision.

🧭 Mental model. The client asks; the server decides. A request is a question posed across the membrane; a response is the ruling that comes back. The client is an untrusted, replaceable presentation of state. The server is the authoritative, singular owner of state. Once this is reflexive, an enormous amount of backend design becomes obvious — including most security, because security is just "did we actually run the membrane, or did we let a claim through as if it were truth?"

The spine​

The third picture is the one you'll redraw most. When a question crosses the membrane, it doesn't teleport. It travels a path — a series of hops — and so does the ruling on the way back. That path is the book's spine:

browser ─▶ DNS ─▶ TCP ─▶ TLS ─▶ load balancer ─▶ server ─▶ handler ─▶ database
▲ │
└────────────────────────── response travels back ◀─────────────────┘

Memorize this lane. We are going to spend the next thirty-odd chapters zooming into one box at a time — later chapters live inside TCP, inside TLS and the load balancer, inside the server, inside the handler, inside the database — but the lane never changes. When you feel lost later in the book, come back here and ask: which box am I in?


3. Theory & invariants​

A mental model tells you how to picture things. Invariants tell you what must stay true no matter what. These are the load-bearing rules of the whole book; the rest of Part I exists to make them feel inevitable.

🔑 The authority invariant. Anything that affects shared state, money, or trust must be (re)validated server-side, regardless of what the client claims to have already done. Client-side checks are a convenience for the user — they make the UI feel responsive and catch honest mistakes early — but they are UX, not enforcement. The $1 balance happened because someone mistook a UX feature for an enforcement mechanism. Every time you're tempted to trust a value from the request, ask: if the user set this to anything they wanted, what would break? If the answer is "money" or "someone else's data," that value must be re-derived from durable state on the server.

🔑 Single source of truth. For any fact — an encounter's status, a claim's balance, how many slots are left — exactly one authoritative owner exists. Everything else that holds a copy of that fact (the browser's cached view, a Redis cache, a search index, a number on a dashboard) is a copy that may be stale. When two sources disagree, you must already know which one is the truth. Designs go wrong the moment two systems both believe they own the same fact.

A few more invariants follow from the simple physics of the spine, and they'll shape your intuition for performance and reliability before we ever tune anything.

Request/response is synchronous and bounded. When a client sends a request, it holds a connection open and waits for exactly one answer. That has two consequences you'll feel forever. First, there is a deadline: the caller will not wait indefinitely, so every request implicitly has a timeout, and a request that hangs is often worse than one that fails. Second, making the caller wait has a cost — a held connection, a blocked user, finite resources tied up. This single fact is why, later, we'll split slow work out of the request path and into background jobs (Chapter 26). For now just hold the shape: a request is a question with a deadline.

Latency is additive and largely serial along the path. "Serial" just means the hops happen one-after-another, like a chain of sequential awaits in JavaScript: you can't start the database call until the TLS handshake has finished, so the total time is the sum of the steps, not the max of them. Concretely, the total time to answer a request is roughly the sum of each hop's contribution, plus time spent waiting in queues at each box:

total ≈ DNS + TCP_setup + TLS_setup + LB + (server queue + handler) + DB_round_trip + (return trip)

You cannot subtract your way under the speed of light on the network legs — a packet from London to Virginia and back has a floor of roughly 70–90 ms no matter how good your code is. This is why senior engineers talk about a latency budget: if you have 200 ms to answer, and the network legs eat 90, your code and database share what's left. You spend latency; you don't conjure it.

🔑 Failure is independent per hop. Each box on the spine can fail or slow down on its own — DNS can fail to resolve, TCP can't connect, TLS certificate expired, the load balancer marks every instance unhealthy, the handler throws, the database is overloaded. The reliability of the whole request is therefore a property of the entire chain, not of your best link. A system is only as available as the product of its dependencies' availabilities. In plain terms: if each of five hops is up 99% of the time, the whole chain is up 0.99 × 0.99 × 0.99 × 0.99 × 0.99 ≈ 95% — you multiplied five "pretty reliable" boxes and got something noticeably less reliable. More boxes in series always drags the total down. This is the seed of everything in Part VI: you don't get reliability by writing flawless handler code; you get it by designing for the fact that every box will eventually misbehave.

Finally, a preview we will name but not yet build:

📎 Borrowed on credit: statelessness. We will design servers so that each request is self-contained — the identity and context needed to answer it travel inside the request (a token, an ID), not in the server's memory between requests. Durable state lives in the database; the server process holds nothing important across requests. Why it matters here: it's the reason "the server" can be many identical machines behind a load balancer, any of which can answer any request. The full treatment is later (it threads through Chapters 6, 29, and 32). For now, just absorb the assertion: don't put per-user truth in a process; put it in the database.


4. Under the hood: the request's journey, hop by hop​

Let's walk the spine once, slowly, with just enough mechanics to kill the magic. Each hop gets a full chapter later; here we only learn what it is, what it costs, and how it fails, so the later deep dives have somewhere to land.

Our example request: a logged-in Pulsely clinician opens the app, and it calls GET /worklist to load their list of patients and tasks for the day.

1. DNS — turn a name into an address. The app wants to talk to api.pulsely.health, but the network only routes to IP addresses. So the very first thing that happens is a lookup: what IP is api.pulsely.health? That lookup is itself a network round trip to a DNS resolver (though the answer is usually cached at several layers, so it's often free).

  • Cost: one round trip on a cold cache; ~0 when cached.
  • Failure mode: the name doesn't resolve — "server not found." Your code never even runs; the request died before it began.

2. TCP — establish a reliable pipe. Now we have an IP, but we can't just throw HTTP at it. HTTP rides on TCP, which first performs a three-way handshake (SYN → SYN-ACK → ACK) to set up an ordered, reliable byte stream between the two machines. Think of it as a two-line phone greeting before anyone talks business: the client says "can you hear me?" (SYN), the server says "yes — can you hear me?" (SYN-ACK), the client says "yes" (ACK). Only after that little hello do the two machines trust the line enough to send real data. Only after the pipe exists can a single byte of HTTP flow.

  • Cost: one full round trip spent just saying hello, before any useful data.
  • Failure mode: can't connect (nothing listening, firewall, network down); or the connection establishes but is slow/lossy.

3. TLS — make the pipe private. https:// means the TCP pipe is wrapped in TLS: another handshake, on top of TCP, that authenticates the server (via its certificate) and negotiates encryption keys. With modern TLS 1.3 this is one additional round trip (and resumed connections can be near-zero); older TLS 1.2 took two.

  • Cost: one (or more) round trips on a cold connection.
  • Failure mode: expired/invalid certificate, name mismatch, protocol mismatch — the browser refuses to proceed and shows a scary warning.

🏭 This is why the first request to a site after being idle feels sluggish: DNS + TCP + TLS can be two or three round trips of setup before your server does anything. It's also why connection reuse (keep-alive) matters so much — pay the setup once, then send many requests over the warm pipe. We'll return to this in §5 and master it in Chapter 6.

4. Load balancer — one address, many servers. The request arrives not at a server but at a load balancer: a single public entry point that fans traffic out across many identical backend instances. This is your first concrete encounter with a truth that surprises beginners: "the server" is plural. There isn't one process answering everyone; there are N interchangeable ones, and the load balancer picks a healthy member of the herd for each request.

  • Cost: a small amount of routing latency; usually negligible.
  • Failure mode: no healthy instances to route to (everything's down → 503), or the LB itself is misconfigured.
  • Implication: because any instance might get your request, no instance can rely on having handled your previous request. (There's the statelessness preview again, now concrete.)

5. Server + handler — your code, at last. One backend instance accepts the connection, reads the bytes, parses them into an HTTP request (method, path, headers, body), and routes GET /worklist to the function you wrote to answer it. That function is the handler. This is the first box where your code runs. Everything to the left was infrastructure carrying the question to your door.

In Node with Express, the wiring looks like this — and notice how thin it is:

// "GET this path" → "run this function". That's the whole idea of routing.
app.get('/worklist', async (req, res) => {
const providerId = req.user.id; // who is asking (established at the boundary)
const worklist = await worklistService.forProvider(providerId); // the handler consults durable state
res.json({ items: worklist }); // the ruling, issued back across the membrane
});

req is the parsed question — the claim that crossed the membrane. res is how you issue the ruling. The handler's job is to run the three pillars: apply logic, touch durable state, respect the trust boundary. Everything else in this book is in service of writing that function well and operating it safely.

The same idea is universal. Here it is in Java with Spring:

@GetMapping("/worklist")
public WorklistResponse worklist(@AuthenticationPrincipal User user) {
return worklistService.forProvider(user.getId()); // identical shape: path → handler → state → ruling
}

🧭 The mapping path → handler → state → ruling is the same in Express, NestJS, Spring, Django, Rails, and a server you'd write by hand in C. What differs between them is mostly the concurrency model — how the runtime juggles thousands of these at once (Node's single event loop vs. the JVM's classic thread-per-request). That's a genuinely important and separate axis, and we develop it carefully in Part II. The point right now: routing is not magic, and frameworks are ergonomics layered over this same skeleton. You'll prove that to yourself by building the skeleton by hand in Chapter 2.

6. Database — the durable state, over yet another network hop. To build the worklist, the handler reads from the database. And here is the single most common thing beginners get wrong about the spine: the database is almost always a separate machine. When your handler runs a query, it opens (or reuses) a connection across a network to a different box, sends the query, waits, and gets rows back. The database is its own box on the spine, with its own latency and its own failure modes.

  • Cost: a network round trip plus the query's execution time. For many endpoints, this is the dominant cost — your code is fast; you're mostly waiting on the database.
  • Failure mode: the DB is slow, overloaded, deadlocked, out of connections, or down. When people say "my endpoint is slow," the time is very often here, not in their code.

7. The response travels back. The handler assembles a response from what the database returned, and that response retraces the path: server → load balancer → back across the TLS-encrypted TCP pipe → to the client, which finally renders the worklist. Every latency and failure surface on the way in applies again on the way out.

🛑 What we deliberately did not explain. How the OS turns a socket into bytes your process can read (Ch 2–4). How the event loop schedules thousands of concurrent connections (Ch 7). How routing and middleware actually dispatch (Ch 13–14). How the database executes that query and decides whether to use an index (Ch 18–19). Each is a later chapter. We located them on the spine; we didn't open them. That restraint is the whole point of a foundations chapter — no forward dependencies, just a map with labeled rooms we'll furnish later.


5. In production: the path that actually runs​

The spine we just walked is the teaching version. The version that runs in production has more boxes, and you should know the real shape now so nothing later feels like a surprise.

client ─▶ CDN / edge ─▶ load balancer ─▶ [API gateway] ─▶ app instance #1 ─┐
├─ app instance #2 ─┼─▶ database
└─ app instance #N ─┘ │
└─▶ cache, queue, search, 3rd-party APIs…

You don't need to understand these boxes yet — most get their own chapter. But absorb the shape: real traffic crosses a CDN/edge layer, a load balancer, often an API gateway, then lands on one of many identical, stateless application instances, which talk to a database and usually several other backing services. Three production realities fall out of this, and they're worth internalizing on day one:

Connection reuse is the default, not the exception. Because TCP+TLS setup is expensive (those round trips from §4), clients and infrastructure keep connections alive and send many requests over each warm pipe. The "cold" first request pays setup; the rest don't. This is one reason operators obsess over p99 latency (the slowest 1% of requests) rather than the average — cold paths, cache misses, and unlucky queuing live in that tail, and the tail is what users actually feel as "the app is janky." Averages lie; we'll make this rigorous in Chapter 30.

Timeouts exist at every hop, and they should be budgeted. The client has a timeout, the load balancer has one, your HTTP server has one, the database driver has one. If they're not set deliberately, a single slow database query can leave requests hanging all the way up the chain — connections held, resources pinned, users staring at a spinner. A senior engineer thinks in end-to-end latency budgets: "we have 1 second; the DB call gets at most 300 ms, after which we give up and fail fast." Failing fast is usually kinder than hanging. (Mechanics: Chapter 33.)

Health checks make instances interchangeable. The load balancer continuously asks each instance "are you healthy?" and routes only to the ones that say yes. This is the operational machinery behind statelessness: because any instance might vanish (deploy, crash, scale-down) and any instance might receive your next request, no instance may hold state another instance would need. Put durable truth in the database; keep the app tier disposable.

🏭 Two framing ideas to carry forward. First, in production you reason about a request as a trace — a single identity followed across every box on the spine — precisely so you can answer "which hop ate the latency?" (Chapter 34 builds this; just know the vocabulary exists.) Second, the same code runs in dev, staging, and production against different databases purely via configuration, not code changes. That reinforces the deepest theme of this book: logic is shared and stable; the target (which database, which secrets, which region) is injected. Code is the constant; environment is the variable.


6. Common pitfalls​

These are the mistakes this chapter exists to prevent. Each is written as signature → fix: the symptom you'll observe, then the principle that resolves it.

Trusting the client. Signature: a charge amount, role, patient ID, or ownership flag is read from the request body and used as-is; a user manipulates it and settles a $1,000 balance for a dollar, or opens another patient's chart. Fix: treat every value in a request as a claim, never a fact. Re-derive authoritative values server-side from durable state. The request may say amountDue: 1; the server re-computes the real balance from the encounter's posted charges and ignores what the client sent.

Putting business logic in the frontend "to be fast." Signature: the rules drift between web and mobile; an exploit appears on whichever client got the looser copy. Fix: logic that guards shared state lives behind the membrane, in one place. The frontend may mirror a rule for instant UX feedback, but the backend re-checks it. Two copies, one of them authoritative — never two authorities.

Assuming the database is "inside" the server. Signature: you're blindsided by latency and failures from a network hop you didn't know existed; you tune your code for hours while the time is actually in the DB round trip. Fix: model the database as a separate machine across a network, with its own latency and failure box on the spine. Your handler's wall-clock time often = (a little of your code) + (a lot of waiting on the database).

Ignoring TLS/TCP setup cost in latency budgets. Signature: the first request after an idle period is mysteriously slow; benchmarks look great but real cold-start users complain. Fix: account for handshake round trips, and reuse connections (keep-alive, connection pools) so the setup cost is amortized across many requests rather than paid per request.

Storing per-user state in server memory between requests. Signature: it works flawlessly in development (one process) and breaks intermittently in production the moment the load balancer routes you to instance #2, which has never heard of you. Fix: keep durable, cross-request state in the database (or a shared store); keep the app process stateless. Identity travels in the request. (Fully developed later — flagged here because it's the pitfall beginners hit first when they scale past one box.)

Treating a slow downstream as your own bug. Signature: "my handler is slow," but a measurement shows the time is in the database or a third-party API your handler calls — a clearinghouse, an eligibility service, a lab interface. Fix: locate latency per hop before optimizing. Measure where the time actually goes; don't optimize the box that isn't the problem. (This instinct — measure, don't guess — is the soul of Chapter 30.)


7. Tradeoffs​

Foundational as it is, even "where does logic live?" is a decision with a spectrum, not a single right answer. Senior engineering is the ability to name the spectrum and say why you're standing where you stand.

Thin client + thick backend ↔ thick client + thin backend. A thick backend gives you authority, consistency, and one place for logic (the slot can't be double-booked; the balance can't be edited). A thick client gives you offline capability and fewer round trips (the app works on the subway). You lean backend-thick when correctness, money, or multi-user consistency dominate — which is most products with real stakes. You lean client-thick when offline-first or extreme interactivity dominates and the data isn't safety- or money-critical (a note-taking app, a drawing tool). You'd reverse the choice the day your "offline-first" app grows a feature where two users edit the same shared, authoritative record.

Synchronous request/response ↔ background work (preview). Answering inside the request is simple: the caller asks, waits, gets the ruling. But it ties up a connection for the whole duration, so it's a poor fit for slow or expensive work (render a large imaging study, submit a claim through a flaky clearinghouse, send appointment reminders to ten thousand patients). The alternative is accept now, do later: acknowledge the request immediately and perform the work in the background, reporting results through some other channel. That buys responsiveness at the cost of complexity — you now need a way to track and surface the eventual result. Choose synchronous for fast, must-be-immediate answers; defer to background for slow or expensive work. (Full machinery: Chapter 26. Flagged here, not built.)

More hops ↔ fewer hops. Each box you add to the spine — CDN, load balancer, API gateway — buys you scalability, isolation, and resilience. Each box also adds latency, another thing that can fail, and more to operate. A tiny internal tool with ten users should collapse hops mercilessly: one process, one database, done. A platform serving millions across teams earns every hop. The skill is adding boxes when the scale or organizational complexity justifies them, not because an architecture diagram online had them.

Run your own server ↔ Backend-as-a-Service. Owning the box gives you control and better economics at large scale; BaaS gives you speed-to-ship and far less operational burden. But notice what doesn't change either way: the trust-boundary responsibility is yours regardless. BaaS runs the machine; it does not decide your authorization rules. Outsourcing the server never outsources the role.

🚫 A framing this book rejects. "The frontend is the real app; the backend is just a database wrapper." It's a common and seductive view, and it's wrong, because it silently discards two of the three pillars — the authority and the trust boundary. A "database wrapper" that trusts its callers is exactly how you settle a $1,000 balance for a dollar. The backend is not plumbing attached to the database; it is the authority that stands between hostile, uncoordinated callers and the truth.


8. Security & scale notes​

We weave security and scale into every chapter rather than quarantining them, because in real systems they are properties of everything. Here's how this chapter's ideas first touch each.

The threat surface is the trust boundary. Every endpoint is a door in the membrane, reachable by anyone on the internet, including people who wish you harm and bots that never sleep. So the first security question for any operation is not "is my code clever?" but "who is allowed to do this, and did we verify it server-side?" The $1 balance, mass scraping of patient records, and "I opened another patient's chart by changing the ID in the URL" are all the same failure: a claim was allowed through the membrane as if it were truth. (In healthcare that last one has a name and a cost — an unauthorized chart access is a reportable breach, not just a bug. Authentication and authorization get their full chapter, 32 — named here, not built.)

Encryption in transit is non-optional. The TLS box on the spine isn't decoration. Without it, every hop on a shared network — coffee-shop Wi-Fi, an ISP, a compromised router — can read the question and the ruling (for a healthcare system, that's PHI in the clear on the wire — itself a reportable breach), and worse, alter them in flight. TLS is what lets you assume the bytes that arrive are the bytes that were sent, to the server they were meant for. That assumption underpins everything else.

Input is hostile by default. Anything that crosses the membrane — request body, query string, headers, cookies — must be validated before it's allowed to influence durable state. "Validate at the boundary" is a refrain you'll hear all book; this is its first statement. (Injection and validation: Chapters 11 and 31.)

Now scale, where the spine itself teaches the first lesson:

Saturation is a chain property. Because latency is additive and the resources at each box (connections, threads, memory) are finite, a single slow downstream poisons everything upstream. Picture the database slowing down: handlers wait longer on each query, so they hold their connections longer, so the connection pool drains, so new requests queue, so the load balancer's queue grows, so users see timeouts — all triggered by one slow box. This is your first encounter with backpressure / saturation as a property of the whole chain, not of the slow box alone. (Mechanics: Chapters 30 and 33.) The intuition to keep: in a chain of finite-capacity stages, the slowest stage sets the pace for everyone, and when it slows, the queue grows behind it.

The load balancer is both your scale lever and a concentration of risk. Spreading load across identical, stateless instances is the primary way you scale horizontally (Chapter 29). But it also concentrates trust and availability at a single entry point — which is why, in production, even the "single" load balancer is itself redundant. Scaling and reliability are two views of the same design.

🔑 One slow hop sets the floor. Because the hops are largely serial, your end-to-end latency can never be faster than its slowest serial hop. You cannot out-code a 300 ms database query sitting in the middle of your request. This is why you measure per hop before you optimize anything: the spine tells you that effort spent on a fast box is wasted.


9. Interview lens & exercises​

Interview questions​

Backend interviews probe whether you reason about systems or merely recite them. The same question separates levels by the quality of the narration.

"What happens when you type a URL and press enter?" The classic.

  • Junior answer: a memorized list — DNS, then TCP, then TLS, then the server, then the database. Correct and forgettable.
  • Senior answer: the same path, but narrated as a reasoning tool — "DNS may be cached so often it's free; TCP and TLS cost round trips, which is why connection reuse matters and why cold requests are slow; the load balancer means the server is plural and therefore stateless; the database is a separate machine, so that hop has its own latency and failure budget." Same path, but every hop is annotated with cost and failure. That's the signal.

"Why does this feature need a backend at all?"

  • Junior: "to store data."
  • Senior: names the three pillars and identifies which ones this feature actually requires — sometimes concluding a backend is unnecessary, which is a stronger answer than reflexively adding one. Knowing when not to build something is senior judgment.

"Where do you put the validation and business logic, and why?"

  • Junior: "in the API."
  • Senior: "client-side validation is UX so the user gets instant feedback; authoritative validation is server-side because the client can be edited or bypassed. The rule that guards shared state lives behind the trust boundary, in one place, and every client goes through it." Mentions the authority invariant by reasoning, not by name-drop.

"Is the database part of your server?"

  • Junior: treats it as local, in-process.
  • Senior: "almost always a separate machine across a network — its own latency, its own failure modes, its own connection limits — which is why DB round trips dominate many endpoints and why timeouts and connection pooling matter."

"Why can't you just keep the logged-in user's data in a variable on the server between requests?"

  • Junior: "you can."
  • Senior: "you can on one box in development, and it breaks the instant a load balancer routes your next request to a second, stateless instance that has never seen you. Durable cross-request state belongs in the database; the app tier stays disposable so it can scale and fail over." Narrates the scale/failover tradeoff.

Exercises & the Pulsely increment​

Do these with pen and paper, then a text file. The goal is fluency, not perfection.

  1. Draw the spine from memory for GET /worklist. Label every hop (DNS → TCP → TLS → LB → server → handler → database → back). Against each box, write one latency contributor and one failure mode. If you can't do this without looking, reread §4 — this diagram is the backbone of the entire book.

  2. Write Pulsely's responsibility charter. Make a one-page table. For each Pulsely capability — patients, encounters and notes, appointment slots, clinical orders and claims, worklist, alerts, search — record what the backend owns (authoritative logic and durable state) versus what the client or a third party owns (presentation, device-local state, an external clearinghouse or payment processor, etc.). Justify each row in a single sentence using the three pillars. (Example row — Appointments: backend owns slot reservation, the eligibility check, and the appointment's state, because all three pillars apply; the client owns only the "book" gesture and the optimistic UI.)

  3. Sketch Pulsely's first concrete request path. Take GET /worklist, draw its path browser → database → back, and color each hop by ownership: shared infrastructure (DNS, TLS, load balancer) vs. Pulsely's own code (the handler, the queries). Circle the single trust boundary. This is the seed of the system you'll build for the rest of the book.

  4. Trust-boundary attack drill. Take a naïve POST /claims that trusts a client-supplied chargeAmount and patientId. Write three distinct ways a client could abuse it (inflate the charge, submit against another patient's encounter, replay the same claim twice), and for each, the one server-side rule that neutralizes the abuse by re-deriving the value from durable state. (If you can do this drill reflexively for every endpoint you ever write, you have already prevented most of the security bugs in this book.)


Key takeaways​

  • A backend exists when state must be shared, durable, and trusted. Remove all three and you don't need one; add any one and an authority must appear.
  • Picture it three ways: the three pillars (logic, durable state, trust boundary), the membrane (claims in, rulings out), and the spine (browser → DNS → TCP → TLS → LB → server → handler → database → back).
  • The authority invariant: anything touching shared state, money, or trust is re-validated server-side. Client checks are UX, not enforcement.
  • Single source of truth: every fact has exactly one owner; everything else is a copy that may be stale.
  • Latency is additive and serial; failure is independent per hop; the chain is only as reliable as the product of its parts, and only as fast as its slowest serial hop.
  • The database is a separate machine on the spine — usually the dominant cost and a common source of "my code is slow."
  • The spine you drew here is the map for the whole book. Every later chapter zooms into one box.

← Previous: Ch 0 — How to Use This Book & The Frontend→Backend Mindset Shift · Up: Part I overview · Master TOC · Next: Ch 2 — The Server as a Process: Sockets, Ports & the Accept Loop →