Chapter 12 — Beyond REST: GraphQL, gRPC, Webhooks & Integration Security
Part III · APIs as Contracts | Prerequisites: Ch 10–Ch 11 | Builds: a gRPC internal call and a signed inbound webhook for Pulsely
For two chapters you've treated REST as the shape of an API: a client pulls a resource by URL, the server hands back a representation it chose, JSON travels as text over HTTP/1.1, and the only party who ever initiates a call is the client. That model is excellent, and it is also one specific point in a much larger design space. Each of its four defaults — client pulls, server shapes the response, text on HTTP/1.1, trust the network — is a knob, and turning each one gives you a different protocol with a different bargain. GraphQL turns the "server shapes" knob and lets the client shape its own response. gRPC turns the "text on HTTP/1.1" knob and gives you typed binary calls with a compile-time contract. Webhooks turn the "client pulls" knob and let the server initiate — which inverts who carries the burden of reliable delivery. And the moment any of these crosses an organizational boundary, the "trust the network" default has to die, because the caller is no longer you.
This chapter derives each alternative from the REST pressure it relieves, then spends its back half on the part most tutorials skip and most outages come from: securing the boundary where another company's bytes arrive at your door. We'll build two concrete Pulsely increments — an internal gRPC call between two services, and a signed inbound claim-status webhook with replay protection and idempotent posting — and write the two ADRs that justify them. Learn the constraint each protocol relaxes, not the logo.
1. The problem: REST shows its seams
Let me give you four felt failures, each one the moment a team stops believing REST is the only answer.
The chatty mobile worklist. Pulsely's rounding app opens to a clinician's worklist of 20 encounters. With a clean REST surface that's one call to GET /worklist — and then, because each encounter needs its patient's name and MRN, the lab order it references, and that order's latest result, the app fires off a flurry of follow-up requests: GET /patients/{id} per patient, GET /orders/{id} per encounter, GET /orders/{id}/result. Twenty encounters becomes roughly forty round trips to paint one screen. On a tablet on hospital wifi between rooms, the screen's load time is dominated not by computation but by latency — forty serial-ish round trips at 80ms each is wall-clock seconds of spinner. The mobile lead files a ticket: "Can we get one endpoint that just returns everything the worklist screen needs?" This is under-fetching: the resource-shaped server forced the client to make many calls to assemble one view.
The forking field set. You say yes and build GET /worklist-screen. It returns encounters, patients, orders, results — a fat denormalized blob. The web charting team complains: they don't render the coverage summary in their worklist, so they're shipping 30-field patient objects over the wire for nothing — over-fetching. Meanwhile the mobile team is back, now wanting three problem-list fields the blob doesn't include. You add ?fields=. Then ?include=. Then /v2/worklist-screen. Then a second bespoke endpoint for the patient chart screen, and a third for patient search. Each is a hand-rolled view that rots the instant a screen's design changes. You've discovered that the server choosing the response shape doesn't scale across many clients with diverging needs.
The untyped internal call. Behind the scenes, Pulsely's worklist service calls the orders service to get each encounter's latest result. It's a same-datacenter, east-west hop — but it's serialized as JSON over HTTP/1.1 with no shared schema. One day someone renames value_num to valueNum in the orders service. The call still returns 200 OK; the worklist service reads body.value_num, gets undefined, and renders "NaN mg/dL" — and because nothing failed, the bug surfaces three services and two hours downstream, on a screen a clinician is reading. There was no contract that both ends compiled against, so a rename became a silent runtime corruption.
The unauthenticated knock. Pulsely integrates a billing clearinghouse. When a claim is adjudicated, the clearinghouse POSTs claim.status_changed to https://api.pulsely.health/webhooks/claims. Useful — except REST taught you request/response where you are always the caller. Here they call you, on a public URL, and nothing in HTTP says who's knocking. Anyone who learns that URL can POST { "event": "claim.status_changed", "claim_id": "clm_1234", "status": "paid" } and mark an unpaid claim as paid — booking phantom revenue and corrupting the ledger. The network is no longer between you and a client you wrote; it's between you and the entire internet, and one of the callers is hostile.
🧭 Mental model. REST is not "how APIs work" — it's one set of defaults: client-pull, server-shaped, text-on-HTTP/1.1, trust-the-network. Each alternative in this chapter relaxes exactly one default. GraphQL: the client shapes the response. gRPC: binary, typed, HTTP/2, compile-time contract. Webhooks: the server initiates. Integration security: the network is no longer trusted, so identity and integrity must ride inside the message. When you reach for one of these, name the default you're relaxing — that's the whole decision.
2. The mental model: four axes and three boundaries
Every network interface you'll ever design or consume sits at a coordinate on four axes. Hold these and the zoo of protocols collapses into a grid.
- Who initiates — client-pull (REST, GraphQL, gRPC unary) vs. server-push (webhooks, server-streaming, SSE). This decides who owns the reliability problem. When the server pushes, the receiver inherits retries, duplicates, and ordering.
- Who shapes the response — server-defined (REST returns what it decides) vs. client-queried (GraphQL returns exactly the tree the client asked for). This trades server simplicity for client flexibility.
- Where the contract lives — at runtime / in docs (REST, GraphQL introspection) vs. compile-time in an IDL both ends generate from (gRPC/Protobuf). This trades human-readability for type safety and codegen.
- The transport — text over HTTP/1.1 (REST, GraphQL) vs. binary frames over HTTP/2 (gRPC). This trades debuggability for throughput, multiplexing, and streaming.
Now the three alternatives in one line each:
- GraphQL = one POST endpoint exposing a typed graph the client traverses. You move response-shaping authority from server to client; you pay for it in resolver fan-out (and a new N+1 hazard).
- gRPC = function calls across the wire with a shared, versioned type contract. The
.protoIDL is the single source of truth; both client and server are generated from it. - Webhook = an HTTP callback that inverts initiation. The integration becomes event delivery, so every distributed-delivery problem — retries, duplicates, ordering, idempotency — lands on you, the receiver.
And the load-bearing reframe for the security half:
🧭 Protocol is a property of a boundary, not of a system. A real backend has at least three boundaries, each wanting a different answer. North–south, client-facing (browser/mobile → your edge): cacheable, public, evolvable — REST or GraphQL. East–west, internal (service → service in your own cluster): low-latency, typed, sometimes streaming, you own both ends — gRPC. Inbound partner (another company → you): untrusted, push-based, money on the line — a signed webhook, possibly under mTLS. One system, three boundaries, three protocols. Designing "the API" as if it had one answer is the mistake.
🧭 Integration security in one sentence. Once a message crosses an org boundary, you can no longer infer the caller from the network — so identity, integrity, and freshness must be carried inside the message itself and verified before any business logic runs. A signature proves the message came from the secret-holder unmodified (identity + integrity); a timestamp/nonce proves it isn't a replay of an old-but-valid message (freshness). Both, or you're exposed.
3. Theory & invariants
Over-fetching and under-fetching are two faces of one problem
When the server fixes the response shape, it is guessing at every client's needs at once. Guess too generous and clients over-fetch (the web team's unused 30-field patient). Guess too lean and clients under-fetch (the rounding app's forty round trips). REST gives you ?fields= and bespoke BFF endpoints as patches, but they're patches. GraphQL's core move is to collapse both failure modes into a single declarative query: the client states the exact tree of fields it wants, the server returns exactly that — no more, no less.
🔑 The response-shape invariant. With server-defined responses, every client pays for the union of all clients' needs (over-fetch) or makes up the difference in round trips (under-fetch). With client-queried responses, the wire payload matches the client's actual need — at the cost of moving response-shaping work, and a new failure mode, onto the server.
GraphQL: schema as contract, query as tree
GraphQL's contract is its schema, written in SDL (Schema Definition Language): a typed graph of objects and the fields that connect them. The invariants that matter:
- The schema is the contract. Types, fields, and their nullability are what clients depend on. Removing a field or making a nullable field non-null is breaking, exactly like the compatibility algebra you've already met — the rules transfer, only the wire format changes.
- Every field resolves independently. A resolver is a function attached to a field: given its parent value, it produces the field's value. The engine walks the query tree depth-first, calling resolvers and awaiting their promises.
- The response mirrors the query shape exactly. Ask for
{ encounter { reason patient { name } } }and you get back that nested object, nothing else. The query is the response schema.
That per-field, independent resolution is GraphQL's power and its trap:
🔑 N+1 is structural, not a bug. A list query returns M parents (say, 20 encounters). The
patientfield resolver then fires once per parent — 20 independentSELECT patient WHERE id = ?queries — plus the 1 query that fetched the encounters. That's M+1 backend hits for one screen, and it gets worse with nesting. This is not a mistake you can code-review away; it's the default behavior of independent field resolution over a list. The only fix is batching: collect all the patient keys requested within one event-loop tick and issue a singleSELECT ... WHERE id IN (...). Caching doesn't fix it (the first uncached load still fans out); batching does.
📎 The GraphQL-specific N+1 is mine; the general one is borrowed. The N+1 pattern — one query that begets N more — shows up everywhere data access happens in a loop (ORMs, REST aggregation, plain SQL in a
for). The general phenomenon, how to spot it in query logs, and how to reason about it as a performance defect is developed in Chapter 30 (performance engineering). What I own here is its appearance inside GraphQL's resolver model and the DataLoader batching that neutralizes it. When you hit N+1 outside GraphQL, that's a 📎 forward reference to Ch 30.
gRPC and Protobuf: the IDL is the truth
gRPC is RPC — remote procedure calls — done well. You write a service and its messages in a .proto IDL; a code generator emits a typed client stub and a server interface in your language. The client calls await orderClient.getOrder({ id }) and it feels like a local method; the runtime marshals it to a binary Protobuf message over HTTP/2.
The invariants are mostly about wire compatibility, and they're sharper than REST's because the format is positional:
- Field tags, not names, are the wire identity. In
int64 value_num = 3;, the3is what travels on the wire; the namevalue_numis a local label the codegen uses. So renaming a field is a non-event on the wire (the tag is unchanged) — which solves the silent-rename bug from §1 outright. But reusing or renumbering a tag is corruption: an old client reading tag 3 as a string while a new server writes tag 3 as an int produces garbage with no error. - Adding fields is backward-compatible; removing requires
reserved. New optional fields with new tags are invisible to old readers (they're "unknown fields," preserved on round-trip). When you remove a field, you mark its tagreservedso no future field can reuse it. requiredis banned (proto3 has norequired). A field marked required can never be removed without breaking every reader forever — it's a one-way door, and the Protobuf designers removed the foot-gun entirely.- Four call shapes: unary (one request, one response — a normal function call), server-streaming (one request, a stream of responses), client-streaming (a stream of requests, one response), and bidi (both stream). REST has only the first shape; streaming is a genuine new capability.
🔑 The deadline-propagation invariant. In plain terms: instead of each service getting its own fresh stopwatch, the whole request shares one countdown that started at the edge. A gRPC deadline is an absolute point in time ("respond by 12:00:03.250"), and it propagates through the call chain. If the edge sets a 250ms deadline and calls service A, which calls service B, the remaining budget is passed along and decremented at each hop; when it expires, the entire subtree cancels together. If you've wired an
AbortControllersignal down through a set of nestedfetchcalls, this is the same idea — when the signal aborts, every in-flight call below it aborts too. Contrast REST, where each hop has its own independent per-hop timeout that doesn't compose — a chain of three 5-second timeouts can hang for 15 seconds. Deadlines compose; per-hop timeouts don't. This is why a slow leaf can't silently hang every request above it in a gRPC mesh — provided you actually set deadlines (most outages here are a missing deadline).
Delivery semantics: the receiver owns correctness
Webhooks make you a receiver of pushed events, and that drags in the vocabulary of distributed delivery. In healthcare these callbacks are everywhere — a clearinghouse posting a claim's adjudicated status, a lab posting a finalized result, a pharmacy hub posting an e-Rx acknowledgment, a payer returning a 271 eligibility response — and every one of them is a partner pushing to you, at-least-once:
- At-most-once (fire and forget; may lose messages), at-least-once (retry until acked; may duplicate), exactly-once (the unicorn). Networks and honest senders give you at-least-once at best — a sender that doesn't get a
2xxack must retry, and retries duplicate. - Therefore the receiver must be idempotent. "Exactly-once processing" is simulated, not delivered: the sender retries (at-least-once on the wire), and the receiver deduplicates so the side effect happens once.
🔑 The idempotent-receiver invariant. For a side effect
fkeyed by a stable event id,f(f(x)) == f(x). Posting the remittance for claim #1234 twice must equal posting it once. The receiver — not the sender — owns deduplication, because the receiver is the only party that knows whether the side effect already happened. You enforce this with a dedup store keyed on the provider's event id: first time, do the work and record the id; replay, see the id, no-op.
📎 Borrowed on credit: idempotency keys. The full mechanism — idempotency-key storage, request fingerprinting, the create-once-then-replay-the-stored-response pattern, and the delivery-semantics theory in depth — is owned by Chapter 25 (idempotency & delivery semantics). I use it here operationally to make the webhook receiver safe; treat the dedup table below as the applied form of Ch 25's machinery.
Integrity, authenticity, freshness — three different guarantees
These get conflated constantly, so pin them apart:
- Integrity — the message wasn't altered in transit.
- Authenticity — it came from who it claims (the holder of the shared secret).
- Freshness — it isn't a replay of a genuine, older message.
A signature (HMAC, below) gives you the first two together. It gives you nothing about freshness — a captured-and-replayed valid message has a perfectly valid signature. Only a timestamp (within a tolerance window) and/or a nonce gives you freshness.
📎 Borrowed on credit: HMAC and crypto primitives. What HMAC is, why a keyed hash gives integrity+authenticity, the difference between hashing and signing, and why comparisons must be constant-time, are all derived in Chapter 31 (security & cryptography). In this chapter I use them as operational tools —
HMAC-SHA256to sign,timingSafeEqualto compare — and show how to wire them into a webhook. When you want the cryptographic why, that's Ch 31.
4. Under the hood
GraphQL resolution and DataLoader
In Node, a GraphQL server (Apollo Server, GraphQL Yoga) is middleware over a single POST /graphql route. You define a schema and a resolver map: each field maps to a function (parent, args, context, info) => value.
// SDL — the contract
const typeDefs = `
type Encounter { id: ID!, reason: String!, patient: Patient!, order: Order! }
type Patient { id: ID!, name: String! }
type Query { worklist: [Encounter!]! }
`;
const resolvers = {
Query: { worklist: () => encounterRepo.recent() }, // 1 query → M encounters
Encounter: {
patient: (enc, _a, ctx) => ctx.loaders.patient.load(enc.patientId),
order: (enc, _a, ctx) => ctx.loaders.order.load(enc.orderId),
},
};
Walk the execution. Query.worklist runs once and returns 20 encounters. The engine then resolves patient and order for each of the 20 encounters — 40 child resolver invocations. Naively, that's 40 separate DB round trips on top of the 1 for the worklist: the N+1 made concrete.
DataLoader is the fix, and its mechanics are the clever bit. A loader wraps a batch function (keys: ID[]) => Promise<Value[]>. When you call loader.load(id), it doesn't query immediately — it stashes the key and returns a promise. It's the same trick React uses when it batches several setState calls fired in one event handler into a single re-render: every load(id) call in the current tick piles up its key, and then — once the synchronous work for this tick finishes — DataLoader collects every key requested during that tick and calls your batch function once with all of them:
// One loader per request, built in context (see the warning below)
const patientLoader = new DataLoader(async (ids: readonly string[]) => {
const rows = await patientRepo.findByIds(ids); // ONE query: WHERE id IN (...)
const byId = new Map(rows.map(r => [r.id, r]));
return ids.map(id => byId.get(id)); // MUST return in key order
});
The 40 individual load() calls collapse into 2 batched queries (one for all patients, one for all orders). M+1 becomes ~2. DataLoader also memoizes within the request, so load(id) for a repeated id is free.
🛑 DataLoader must be request-scoped — this is the one rule people break. Instantiate the loader per request, inside
context, never as a module-level singleton. A loader memoizes; a shared loader memoizes across requests, which means one clinician's loaded patient can be served to another clinician's query — one patient's chart handed to the wrong clinician. That's not a cache bug dressed up as a leak; in healthcare it's a reportable HIPAA breach. The batch function is global and stateless; the loader instance is per-request and stateful. Build it in the per-requestcontextfactory.
In Express you mount Apollo as middleware and pass a context factory that builds fresh loaders per request. In NestJS the same engine hides behind decorators — @Resolver(), @Query(), @ResolveField() — but the resolution model and the per-request loader rule are identical; Nest's DI gives you request-scoped providers to hold the loaders cleanly. Whichever framework draws your clinical-service boundaries, the loader lives with the request, not with the module.
gRPC: from .proto to a call
You write the contract once:
syntax = "proto3";
package pulsely.orders.v1;
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order);
}
message GetOrderRequest { string id = 1; }
message Order {
string id = 1;
string test_name = 2;
int64 value_num = 3; // the 3 is the wire identity — rename freely, never renumber
}
protoc (or ts-proto / @grpc/grpc-js) generates a typed client stub and a server interface. The server implements the interface; the client calls a typed method that returns a promise (unary) or a stream. On the wire, messages are length-prefixed Protobuf frames multiplexed over a single HTTP/2 connection — binary, compact, not human-readable. You debug it with grpcurl, not curl; there's no JSON to eyeball.
The Protobuf wire format is, intuitively, a sequence of little headers, each followed by a value. Each header is a varint — a compact, variable-length way to write an integer, where small numbers take one byte and big ones take more — and it packs two things: the field's tag number and its wire-type (is this an integer, a length-delimited blob, and so on). So each field reads on the wire as: here's field #3, it's an integer, here's its value. The field's name never travels — which is exactly why renaming is free and renumbering is corruption. Two more consequences fall out of that encoding:
- Unknown fields are preserved on a round-trip — an old proxy can forward a message carrying new fields it doesn't understand without dropping them.
- A default value is indistinguishable from "unset" in proto3 — a
value_numof0and an absentvalue_numlook identical on the wire. Use theoptionalkeyword or a wrapper type when you genuinely need to tell "zero" from "missing" (a real hazard for a lab value that legitimately reads0).
Webhook receiver: verify over raw bytes, then dedup, then ack
The receiver is where the security mechanics live, so go slowly. The clearinghouse sends:
POST /webhooks/claims
X-Pulsely-Signature: t=1718800000,v1=4a7f...e2
Content-Type: application/json
{"event":"claim.status_changed","claim_id":"clm_1234","status":"paid","event_id":"evt_abc"}
The signature is HMAC-SHA256(secret, "1718800000" + "." + rawBody). The single most common implementation bug is signing over the parsed-then-re-serialized body: JSON re-serialization reorders keys, changes whitespace, and rewrites numbers, so the bytes you hash no longer match the bytes the sender hashed — and verification fails intermittently on exactly the payloads that happen to round-trip differently. You must capture and verify over the raw request bytes, before any JSON parsing.
// 1. Capture raw body ONLY on the webhook route (not globally — other routes want parsed JSON)
app.post('/webhooks/claims',
express.raw({ type: 'application/json' }), // req.body is now a Buffer
(req, res) => {
const raw = req.body as Buffer;
const header = req.header('X-Pulsely-Signature') ?? '';
const { t, v1 } = parseSigHeader(header);
// 2. Freshness: reject anything outside a tolerance window (replay defense, part 1)
const ageSec = Math.abs(Date.now() / 1000 - Number(t));
if (!Number.isFinite(ageSec) || ageSec > 300) return res.sendStatus(400);
// 3. Integrity + authenticity: recompute and constant-time compare
const expected = crypto
.createHmac('sha256', signingSecretForCurrentKey())
.update(`${t}.${raw.toString('utf8')}`)
.digest();
const provided = Buffer.from(v1, 'hex');
if (expected.length !== provided.length ||
!crypto.timingSafeEqual(expected, provided)) {
return res.sendStatus(401); // fast reject BEFORE any DB work
}
// 4. Parse only AFTER the bytes are trusted
const evt = JSON.parse(raw.toString('utf8'));
// 5. Replay defense part 2 + idempotency: dedup on event_id, then ack fast
enqueueIfNew(evt.event_id, evt) // store-then-ack; worker does the work
.then(() => res.sendStatus(202)) // ACK FAST — don't post the remittance inline
.catch(() => res.sendStatus(500)); // no ack → provider retries (good)
});
Three mechanics deserve a callout. timingSafeEqual compares the full buffer in constant time; a plain === (or any short-circuiting compare) leaks, via response timing, how many leading bytes matched, which an attacker can use to forge a signature byte-by-byte. The 300-second window bounds replay: a captured request older than five minutes is rejected outright; combined with event-id dedup it makes replay useless even inside the window. And ack-fast-then-process: you respond 202 the instant the event is durably enqueued, and a worker does the actual remittance posting and claim reconciliation. If you posted the remittance inside the handler and it took 8 seconds, the clearinghouse would time out, never see your ack, and retry — double-posting the payment. Store, ack, process async.
The dedup store is one small table, the applied form of the idempotency machinery:
CREATE TABLE webhook_events (
event_id TEXT PRIMARY KEY, -- provider's stable id; the dedup key
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed BOOLEAN NOT NULL DEFAULT false
);
-- INSERT ... ON CONFLICT (event_id) DO NOTHING → "new?" is one atomic write
🏭 In production this is exactly how Stripe, GitHub, and Shopify webhooks work — and it's the same shape a healthcare clearinghouse or lab interface uses for its callbacks: a timestamped
HMAC-SHA256over the raw body, a tolerance window, an event id you dedup on, and an expectation that you ack in milliseconds and post the result out-of-band. If you've ever wondered why their docs scream "verify the signature over the raw body" and "respond quickly," now you know which bug each sentence is preventing.
JVM contrast where it teaches
(Skip this if you don't do Java — the transferable point is the last sentence of each half.) Spring's @GrpcService over proto-gen-grpc-java gives you the same IDL-first contract with a different runtime — the .proto is identical, only the generated host language differs, which proves the contract is the portable artifact and the framework is incidental. For webhooks, Spring's HandlerInterceptor plays the exact role of the Express raw-body-plus-verify middleware: a pre-handler hook that rejects unverified requests before your controller runs. The transferable lesson is verify at a single chokepoint before business logic; the annotations are not.
5. In production: operating each protocol
Each protocol has a set of operational concerns the "hello world" tutorial never mentions, and they're where the chapter earns its keep.
GraphQL ops. A naked GraphQL endpoint lets any client author server workload — that's a liability. In production you (1) use persisted queries / an allowlist: clients register their queries ahead of time and send a hash, so the server only ever executes known queries, not arbitrary ones; (2) enforce query depth and complexity limits so a deeply nested or aliased query can't melt the DB; (3) set per-resolver timeouts and tracing (Apollo traces show you which field ate the latency); and (4) run a schema registry with breaking-change CI checks — the same compatibility discipline you've already built, gated on every deploy.
gRPC ops. The big ones, starting with the one people get wrong. Reuse the channel. A channel is like one open, reusable connection — think of a single React Query client you create once and share everywhere, versus new-ing one up on every request. One long-lived channel multiplexes (carries many independent calls at once over) a single HTTP/2 connection. Each fresh connection costs you two things: a file handle (the OS caps how many open connections a process may hold at once — the file-descriptor limit), and a TLS handshake's worth of latency. Spin up a new channel per call under load and you exhaust that cap — a connection storm. Set keepalive pings so a router or proxy sitting in between (a middlebox) doesn't quietly close a connection it decides is idle. Then: put retry and hedging policy in the service config, and set deadline budgets at the edge and decrement them inward (the propagation invariant from §3, operationalized). Run the health-check and reflection services so your mesh and grpcurl can introspect. And know that gRPC load balancing is L7, not L4: because many streams ride one connection, a naive TCP load balancer pins all of them to one backend — you need an L7 proxy (Envoy, Linkerd) that balances requests, not connections.
Webhook receiver ops (this chapter's increment). Ack 2xx fast, then process async — repeated because it's the rule everyone breaks. Keep the dedup table keyed on event id. Store-then-ack: durably persist before you acknowledge, so a crash between ack and work can't lose the event — losing a claim remittance or a finalized lab result is not an option. Manage per-partner signing secrets with rotation — verify against current or previous during the overlap window so a rotation never drops in-flight valid deliveries. Never log raw secrets or full signatures. And instrument the integration: log event_id + verification result + dedup hit/miss (this doubles as your immutable audit trail for every partner event that touched a claim), and alert on signature-failure-rate spikes (a probe or attack) and on retry-storm patterns (a provider or network problem).
🏭 Pulsely will eventually be a webhook sender too — notifying referral partners and downstream apps when a result finalizes or a claim status changes — and the sender's concerns are the mirror image: a durable outbox (don't send from inside the transaction that created the event — write the event to an outbox table and let a worker deliver it), exponential backoff with jitter, max-attempts plus a dead-letter queue, signed payloads, a delivery dashboard, and replay tooling. The sender side leans on Chapter 26 (queues & background processing); this chapter owns only the receiver.
6. Common pitfalls
N+1 resolver explosion. Signature: a GraphQL worklist query that's fine for 1 encounter and catastrophic for 20; query logs show one SELECT patient per encounter. Fix: DataLoader batching in request context; verify by counting queries in the log before and after — M+1 should drop to ~2.
DataLoader as a module singleton. Signature: intermittent wrong data — a clinician occasionally sees another patient on an encounter; works fine under single-user testing. Fix: instantiate loaders per request inside the context factory, never at module scope. The shared memoization is the leak.
Unbounded GraphQL query. Signature: one crafted request — deeply nested, cyclic, or alias-amplified — pins the database and tanks p99 for everyone. Fix: depth + complexity limits, a persisted-query allowlist, and per-field timeouts; disable introspection on the public edge.
Signature verified over the parsed body. Signature: verification fails on a random subset of genuine requests; works in tests, flakes in prod. Fix: capture and HMAC over the raw bytes before JSON parsing; register a raw-body parser only on the webhook route.
Non-constant-time compare. Signature: signatures "work," but the compare uses === or Buffer.equals semantics that short-circuit. Fix: crypto.timingSafeEqual on equal-length buffers (and check length first, since timingSafeEqual throws on length mismatch).
No replay protection. Signature: an attacker re-POSTs a captured valid claim.status_changed and the remittance is posted again — the signature checks out because it's a real old message. Fix: timestamp tolerance window and event-id dedup; a valid signature is necessary, not sufficient.
Side effects inside the webhook handler. Signature: the provider's dashboard shows retries and your claims get double-posted under load. Fix: ack fast (202), process via an idempotent worker; posting never runs inside the HTTP request.
Protobuf tag reuse on a rename. Signature: after a "harmless" field rename-and-renumber, old clients read corrupted values with no error. Fix: never renumber a tag; renaming is free (tags are the identity), and removed tags get marked reserved.
gRPC channel-per-call. Signature: connection storms, exhausted FD limits, and per-call handshake latency under load. Fix: one long-lived shared channel; many calls multiplex over it.
Missing deadline on an internal gRPC call. Signature: one slow orders-service instance hangs every worklist request that touches it, cascading up the tree. Fix: propagate absolute deadlines from the edge inward so the whole subtree cancels together when the budget expires.
7. Tradeoffs
REST vs. GraphQL vs. gRPC — the decision framework. Map it to the boundary, not to taste. Public, third-party, cacheable read surface → REST (the uniform interface and HTTP caching you've already built are exactly what you want). One server, many clients with diverging and volatile screen shapes, aggregation is the dominant pain → GraphQL. Internal east–west, low latency, strong typed contract, possibly streaming, you own both ends → gRPC. Pulsely's ADR below pins each edge explicitly.
GraphQL's costs. You largely lose HTTP caching (everything is POST /graphql, opaque to CDNs and ETags). Authorization moves to per-field (each resolver must check, which is easy to get wrong — and in healthcare a missed check is a PHI exposure). Query cost is unbounded by default, so you inherit depth/complexity defense as table stakes. And server complexity rises. Reverse the choice when you have one client and stable screens — a plain REST surface or a single BFF endpoint wins on simplicity, and you skip the whole resolver-security surface.
gRPC's costs. It's not browser-native (browsers can't speak raw gRPC; you need grpc-web plus a translating proxy). Payloads are binary and undebuggable without grpcurl. You need an L7 proxy for load balancing. And the IDL forces schema-deploy coordination across services. Reverse toward REST/JSON at any public or browser-facing edge — gRPC earns its keep behind the wall, not in front of it.
Webhooks vs. polling vs. an internal queue. Webhooks (push) give low latency but hand you delivery reliability and a public ingress to defend. Polling is dead simple and needs no inbound endpoint, but it's lossy on latency and wasteful at scale. An internal message queue gives the best delivery guarantees — but only when you own both ends, which you don't with a third-party clearinghouse or lab. The partner boundary is why you accept a webhook's burdens: you can't make a clearinghouse poll you, and you can't put your queue in their datacenter.
HMAC vs. mTLS vs. asymmetric signatures for partner auth. HMAC is simple and fast but symmetric — both sides hold the same secret, so it gives weak non-repudiation (either party could have produced any message). mTLS authenticates the connection, not the payload — it proves who you're talking to at the transport layer but says nothing about a specific message's integrity once decrypted. Asymmetric signatures (the provider signs with a private key, you verify with their public key) give true non-repudiation at the cost of key-management complexity. Choose per partner trust model; layer them for defense in depth (mTLS proves the connection, HMAC proves the payload — see §8).
When you'd reverse course over time. Start a partner integration on REST (everyone speaks it, easy to debug, fast to ship). Move it to gRPC only once it's internalized and the contract churns enough that codegen pays for itself. Adopt GraphQL only when client-shape divergence is genuinely the dominant pain — not because it's modern. Protocol choice is reversible and boundary-specific; treat it as an evolving decision, not a one-time religion.
🚫 A framing this book rejects. "gRPC is faster, so use it everywhere" — and its cousin, "GraphQL is modern, so REST is legacy." Both mistake a boundary-specific tradeoff for a global ranking. gRPC is faster for east–west binary calls between services you control and actively worse at a browser edge. GraphQL is better when many clients need divergent shapes and worse when you have one stable client and want CDN caching. There is no "best protocol," only a best protocol for this boundary. Anyone who ranks them without naming the boundary is selling a logo, not engineering.
8. Security & scale notes
The threat surface you just introduced. Three new doors. A public inbound webhook anyone can POST to (forgery, replay, flooding). A new internal binary protocol (a different fleet to secure and observe). And a query language that lets clients author your server's workload (GraphQL DoS). Each gets a specific mitigation, below.
Webhook ingress threats. Spoofed events (forged claim.status_changed) → signature verification. Replayed captures → timestamp window + event-id dedup. Amplification/DoS on an unauthenticated handler → reject unverified requests fast, before any DB work (the order of operations in §4 is itself a defense: cheap checks first), plus rate-limit the endpoint. A webhook handler that does database work before verifying the signature is a DoS amplifier — an attacker floods it and your DB falls over.
mTLS as transport-layer partner auth. Layer it under HMAC for defense in depth: mTLS proves the connection (this TLS session is with a client holding a cert you trust), HMAC proves the payload (this specific message is unmodified and from the secret-holder). Neither subsumes the other — mTLS won't stop a replay of a captured request over a fresh valid connection, and HMAC won't stop a flood at the connection layer. Watch the operational pitfalls: certificate rotation and pinning are where mTLS integrations break in practice.
GraphQL DoS at scale. Complexity and depth attacks, alias-based amplification (asking for the same expensive field 100 times under 100 aliases), and introspection exposed in production (handing attackers your full schema). Mitigations: cap complexity/depth, allowlist persisted queries, and disable introspection on the external edge (keep it internal for tooling).
gRPC under load. HTTP/2 multiplexing concentrates many streams on one connection — great for latency, bad for a naive connection-counting load balancer that sees "one connection" and routes all the traffic to one backend (hence the L7 proxy requirement). Be aware of head-of-line and flow-control behavior on a saturated connection. And lean on deadline budgets to prevent cascading hangs across the call tree — the propagation invariant is a scale-safety property, not just a correctness one. The tail-latency reasoning behind all of this is developed later, in the performance chapter.
Secret rotation under load. Rotate signing secrets with overlapping validity windows — verify against current OR previous for the overlap so an in-flight delivery signed with the old key during rollout still passes. A hard cutover drops valid deliveries the instant you rotate. And keep signature-failure rate as a first-class alarm: a sudden spike is either a misconfigured rotation (your bug) or a probe (their attack), and you want to know which within minutes.
9. Interview lens & exercises
Interview questions
"Why does GraphQL cause N+1, and how does DataLoader fix it?"
- Junior answer: "You add caching." (Wrong fix — the first uncached load still fans out.)
- Senior answer: "It's structural to per-field resolution: a list of M parents triggers M independent child resolvers, so M+1 backend hits. DataLoader batches all the keys requested within one event-loop tick into a single
WHERE id IN (...), collapsing M+1 to about 2 — and it must be request-scoped incontext, or its memoization leaks data across users."
"When would you pick gRPC over REST, and what do you give up?"
- Junior answer: "gRPC is faster."
- Senior answer: "Internal, east–west, low-latency calls between services I own, where I want a strong typed contract and maybe streaming. I give up browser-native access (needs grpc-web + a proxy), human-debuggable payloads, HTTP caching, and a plain L4 load balancer — I now need an L7 proxy because many streams share one HTTP/2 connection. So I keep REST at the public edge and use gRPC behind the wall."
"Design a secure inbound webhook receiver."
- Junior answer: "Check an API key in a header."
- Senior answer: "HMAC-SHA256 over the raw body plus a timestamp, compared with
timingSafeEqual(constant-time). Reject anything outside a ~5-minute timestamp window, and dedup on the provider's event id to stop replays inside it. Ack2xxfast and post the remittance in an idempotent worker so a slow handler doesn't trigger provider retries and double-work. Per-partner secrets with overlapping-key rotation; alert on signature-failure spikes."
"How do you make a claim-status webhook safe to retry?"
- Junior answer: "It won't retry." (It will — at-least-once is the default.)
- Senior answer: "Assume at-least-once delivery and make the receiver idempotent: dedup on the event id with a store, so re-processing a duplicate is a no-op. Exactly-once processing is simulated by at-least-once delivery plus a dedup store, not delivered by the network."
"HMAC vs. mTLS for a partner integration — which and why?"
- Junior answer: Picks one as strictly better.
- Senior answer: "Different layers, often both. HMAC proves payload integrity and authenticity but is symmetric, so weak non-repudiation. mTLS proves the connection's identity but says nothing about a specific message. Layer mTLS under HMAC for defense in depth; reach for asymmetric signatures when you genuinely need non-repudiation and can bear the key management."
Exercises & the Pulsely increment
-
See the N+1, then kill it. Build a Pulsely GraphQL
worklistquery that returns encounters + patients + latest lab results in one request. Turn on query logging and count the DB hits — you should see M+1. Add per-request DataLoaders for patients and orders, re-run, and confirm it drops to ~2. Then deliberately make the loader a module singleton and find the cross-patient leak. -
Bound the query. Add depth and complexity limits plus a persisted-query allowlist. Confirm a hostile deeply nested query is rejected, and that an unregistered query is refused in "production" mode.
-
Pulsely increment A — gRPC internal call. Write
order.protowithGetOrder, codegen client and server stubs, and replace the worklist→orders HTTP/JSON call with a unary gRPC call that carries a propagated deadline from the edge. Then break it: renumber thevalue_numtag and watch an old client read corruption with no error. Fix it by restoring the tag and marking the removed onereserved. (This single exercise teaches the wire-identity invariant better than any paragraph.) -
Pulsely increment B — signed claim-status webhook. Implement the
claim.status_changedreceiver: raw-bodyHMAC-SHA256verification withtimingSafeEqual, a timestamp tolerance window, and event-id dedup; ack fast and post the remittance in an idempotent worker. Write a test that replays a captured valid payload and asserts the claim is reconciled exactly once. Write a second test that tampers with one byte of the body and asserts a401. -
Write both ADRs.
- ADR-012a — "Interface protocol per boundary." Map each Pulsely edge to a protocol with explicit rejection rationale: browser/mobile client edge → REST (and GraphQL for the aggregation-heavy worklist screen) — rejected gRPC: not browser-native; internal worklist↔orders → gRPC — rejected REST/JSON: no shared type contract, the silent-rename bug; partner claim inbound → signed webhook (optionally under mTLS) — rejected polling: latency, and we can't make the clearinghouse poll us.
- ADR-012b — "Inbound webhook signature scheme." Record:
HMAC-SHA256overtimestamp + "." + rawBody; a 300-second tolerance window; event-id dedup table; constant-time compare; per-partner secrets with overlappingcurrent/previousrotation; rejected: plain API key (no integrity, no replay defense), signing over the parsed body (re-serialization breaks it).
🛑 What we deliberately did not explain. The cryptographic internals of HMAC and why constant-time compare matters (Chapter 31). The full idempotency-key machinery and delivery-semantics theory (Chapter 25). The general N+1 problem outside GraphQL and the tail-latency reasoning behind gRPC's connection behavior (Chapter 30). The webhook sender side — outbox, backoff, dead-letter (Chapter 26). The authorization model behind per-field GraphQL auth and partner identity (Chapter 32). We used each of these operationally and pointed at where it's derived; we didn't open the box. That restraint keeps this chapter about protocols and boundaries, not about re-deriving cryptography.
Key takeaways
- REST is one point in a design space defined by four knobs: who initiates, who shapes the response, where the contract lives, the transport. GraphQL, gRPC, and webhooks each relax exactly one. Learn the constraint, not the logo.
- GraphQL lets the client shape the response, collapsing over- and under-fetching into one query — and introduces a structural N+1 that only request-scoped DataLoader batching fixes (caching does not).
- gRPC is typed RPC over HTTP/2 from a
.protoIDL: field tags, not names, are the wire identity (rename freely, never renumber), and deadlines propagate so a slow leaf can't hang the whole call tree — provided you set them. - Webhooks invert initiation, so the receiver inherits at-least-once delivery and must be idempotent (dedup on event id) — exactly-once processing is simulated, never delivered.
- Integration security carries identity, integrity, and freshness in the message: verify HMAC over the raw body with a constant-time compare, reject outside a timestamp window, dedup to stop replays, and ack fast so a slow handler doesn't trigger retry-driven double-work.
- Protocol is a property of a boundary, not a system. Public edge → REST/GraphQL; internal east–west → gRPC; partner inbound → signed webhook. Pick per boundary, and reverse the choice as boundaries evolve.
← Previous: Ch 11 — API Evolution at Scale · Up: Part III overview · Master TOC · Next: Ch 13 — Express From First Principles →