Chapter 07 / 15 · Webster International
Backend Services, APIs & Communication
HTTP and REST, JSON contracts, GraphQL, WebSockets, idempotency, versioning, jobs, queues and integration resilience.
The backend is where a system establishes trusted rules, controls data access, coordinates durable changes and communicates with other services.
01 / FIELD NOTE
Request, response, headers and status codes
Mental model: HTTP is a contract over a network boundary, not a function call. A method describes intent, a URI identifies a target, headers carry metadata, a representation carries state, and status codes tell generic clients how to react. Safe GET/HEAD must not intentionally change application state; PUT and DELETE are idempotent in intended effect, while POST is not inherently so. A 202 response means accepted, not completed. Distinguish 400 malformed input, 401 missing/invalid credentials, 403 denied, 404 hidden/missing, 409 state conflict, 429 throttling, and 5xx server failures.
Correct semantics enable caches, retry policies, observability and accessible user feedback. Status and error-body agreement lets assistive technology and frontend clients announce actionable failures instead of a generic 'something went wrong'.
Example A: GET /events/42 returns 200 with a cache policy; GET /events/absent returns 404. Example B: POST /exports returns 202 with a status URL, while an invalid date returns 422 with field-specific guidance. A timeout does not prove the export was not accepted.
// Runnable: node -e with the snippet in a file (Node 18+)
const {Response}=globalThis;
const accepted=new Response(JSON.stringify({jobId:'exp_42',status:'queued'}),{status:202,headers:{'content-type':'application/json','location':'/exports/exp_42'}});
console.assert(accepted.status===202);
console.assert(accepted.headers.get('location')==='/exports/exp_42');
console.log('accepted, not completed');Hands-on exercise · reveal the verification check
For a background PDF export, choose responses for accepted, completed, missing login, invalid date and duplicate version. State which response the UI should announce.
202 + status URL; 200 on completed GET; 401; 422; 409. UI announces queue/progress and errors without relying only on colour.
02 / FIELD NOTE
REST endpoints and resource modelling
Mental model: resources are domain concepts with stable identifiers, not raw tables or controller names. Define collection/member URIs, HTTP methods, pagination, filters and state transitions before implementing persistence. OpenAPI describes the externally observable contract, including auth and error responses; it does not automatically enforce authorization. Model relationships as links or subresources only where their lifecycle warrants it.
Stable contracts let the CRM, customer portal and mobile client evolve independently while avoiding accidental disclosure of internal database structure. Version deliberately, and test backward compatibility before renaming fields.
Example A: GET /clients?cursor=... lists only records authorized for the signed-in tenant, while GET /clients/c_42 checks object ownership. Example B: POST /bookings creates a booking, and PATCH /bookings/b_4 changes only approved fields; avoid /setBookingStatusForUser?admin=true.
// Runnable Node 18+: tiny tenant-scoped resource selection
const clients=[{id:'c1',tenant:'dog'},{id:'c2',tenant:'music'}];
function findClient(session,id){return clients.find(c=>c.id===id&&c.tenant===session.tenant)||null;}
console.assert(findClient({tenant:'dog'},'c1')?.id==='c1');
console.assert(findClient({tenant:'dog'},'c2')===null);
console.log('tenant boundary enforced');Hands-on exercise · reveal the verification check
Design GET /bookings/:id and PATCH /bookings/:id for two tenants; test an ID owned by the other tenant and an unauthorized status field.
Both operations scope the lookup by authenticated tenant; cross-tenant ID is denied or indistinguishable from missing; unapproved status change is rejected; OpenAPI documents 401/403/404/422.
03 / FIELD NOTE
JSON, schemas and runtime validation
Mental model: parsing JSON only proves syntax, not that a payload is safe or meaningful. Validate at runtime at the trust boundary: media type, byte size, depth, required keys, type, ranges, enums and formats. Then apply domain invariants and object/property-level authorization. Schema validation and authorization solve different problems; TypeScript types vanish at runtime. Errors should use stable machine-readable codes and helpful human descriptions without echoing secrets.
Prevents bad writes, hidden privilege escalation and resource exhaustion; produces predictable, localized form errors and accessible inline feedback. Schema changes should be backwards compatible where possible.
Example A: dog booking duration must be an integer between 15 and 180 minutes, not a string '60'. Example B: a news ingestion API accepts a bounded headline but must ignore or reject a caller's isApproved flag.
// Runnable Node 18+: illustrative boundary validator
function parseBooking(input){if(!input||typeof input!=='object'||Array.isArray(input))throw Error('object required');
const keys=Object.keys(input);if(keys.some(k=>!['clientId','minutes'].includes(k)))throw Error('unknown field');
if(typeof input.clientId!=='string'||!/^c_[a-z0-9]{1,20}$/.test(input.clientId))throw Error('clientId');
if(!Number.isInteger(input.minutes)||input.minutes<15||input.minutes>180)throw Error('minutes');
return {clientId:input.clientId,minutes:input.minutes};}
console.assert(parseBooking({clientId:'c_42',minutes:60}).minutes===60);
try{parseBooking({clientId:'c_42',minutes:60,isAdmin:true});throw Error('test failed')}catch(e){console.assert(e.message==='unknown field')}Hands-on exercise · reveal the verification check
Send a valid booking, a string duration, a negative duration and an extra isAdmin field through the validator; then test that an authorized tenant owns clientId.
Only valid shape passes structural validation; three invalid shapes fail before side effects. Authorization separately rejects a valid-looking foreign client ID.
04 / FIELD NOTE
GraphQL, RPC and choosing an API style
Mental model: API style determines coupling and interaction shape. REST maps resource operations onto HTTP; GraphQL resolves a client-selected graph; gRPC defines strongly typed remote methods and streaming via Protocol Buffers. Compare cacheability, tooling, latency, field selection, schema evolution, security and observability. A typed schema is not an authorization policy. Limit GraphQL query depth/complexity and protect gRPC calls with deadlines and authenticated identity.
Choosing the simplest contract that fits real clients reduces integration cost and operational risk. Accessible user interfaces still need stable loading, error and retry states regardless of transport.
Example A: an admin CRUD dashboard uses REST and HTTP conditional requests for straightforward caching. Example B: a music artist screen needs artist, albums and venues together, so GraphQL aggregation can reduce round trips; internal low-latency service calls may instead use gRPC.
// Runnable Node 18+: demonstrate a request-cost guard for graph-like selection
function estimateCost(fields){const weights={artist:1,albums:5,venues:3,videos:12};
if(!Array.isArray(fields)||fields.some(f=>!Object.hasOwn(weights,f)))throw Error('unknown field');
return fields.reduce((sum,f)=>sum+weights[f],0);}
console.assert(estimateCost(['artist','albums'])===6);
console.assert(estimateCost(['artist','videos'])===13);
console.log('enforce a budget before resolver execution');Hands-on exercise · reveal the verification check
Choose REST, GraphQL or gRPC for a public event feed, an artist aggregation page and an internal thumbnail worker; justify caching and auth.
A plausible answer is REST public feed, GraphQL aggregation and gRPC internal worker; other choices pass when supported by latency, team and operations evidence. All require authorization and resource limits.
05 / FIELD NOTE
Polling, WebSockets, Server-Sent Events and webhooks
Mental model: choose the least stateful channel that meets the product's update frequency and direction. Polling is repeated GET; SSE is one-way server-to-browser event stream with reconnection; WebSocket is bidirectional framed messages; a webhook is server-to-server notification. Every channel needs authentication, event IDs, expiry, rate limits, backpressure and an initial snapshot or reconciliation strategy. Real-time delivery is not the same as durable exactly-once processing.
A live route map can update without expensive constant refresh, while webhook processing can remain recoverable after a network outage. Announce status changes accessibly without overwhelming screen readers.
Example A: an export progress panel uses SSE, a status endpoint and a polite aria-live summary. Example B: a payment webhook validates the raw-body signature and event ID before updating an order; the client never trusts a browser redirect as payment proof.
// Runnable Node 18+: idempotent event reducer (not signature verification)
const processed=new Set();let completed=0;
function onVerifiedEvent(evt){if(processed.has(evt.id))return 'duplicate';processed.add(evt.id);if(evt.type==='export.completed')completed++;return 'accepted';}
console.assert(onVerifiedEvent({id:'e1',type:'export.completed'})==='accepted');
console.assert(onVerifiedEvent({id:'e1',type:'export.completed'})==='duplicate');
console.assert(completed===1);
console.log('durable storage required in production');Hands-on exercise · reveal the verification check
Sketch export progress over SSE and payment completion over a webhook. Simulate duplicate events, reconnect and an invalid signature.
SSE client can resync via status endpoint; duplicate webhook is harmless after durable deduplication; invalid signature is rejected before parsing/trusting content; screen reader gets concise progress changes.
06 / FIELD NOTE
Timeouts, retries and idempotency
Mental model: a timeout is uncertainty, not evidence of failure. An operation can commit remotely while the reply disappears. Assign an overall deadline, retry only transient failures with capped exponential backoff and jitter, and preserve a stable idempotency key plus request fingerprint for logical commands. Persist the key and outcome transactionally where possible; reject reuse of a key with a different payload. Retry at one architecture layer, not at every hop.
Protects bookings, charges and message sends from duplicate side effects and prevents retry storms that worsen an outage. Give users a clear pending state and a way to inspect the result before retrying manually.
Example A: checkout times out after a successful provider charge; the same key returns the prior charge result. Example B: booking a dog walker during a database failover retries only a transient 503, but does not retry a 422 invalid time slot.
// Runnable Node 18+: illustrative key + fingerprint guard
const ledger=new Map();
function execute(key,payload){const fingerprint=JSON.stringify(payload);const prior=ledger.get(key);
if(prior){if(prior.fingerprint!==fingerprint)throw Error('idempotency conflict');return prior.result;}
const result={bookingId:'b_'+(ledger.size+1)};ledger.set(key,{fingerprint,result});return result;}
console.assert(execute('request-42',{slot:'09:00'}).bookingId===execute('request-42',{slot:'09:00'}).bookingId);
try{execute('request-42',{slot:'10:00'});throw Error('test failed')}catch(e){console.assert(e.message==='idempotency conflict')}
console.log('demo only: use durable atomic storage in production');Hands-on exercise · reveal the verification check
Model a checkout whose first response is lost. Replay the same key and body, then replay the key with a different amount; specify deadline and retry limits.
Same key+body returns original result, different body conflicts, transient failures use bounded jitter, 4xx validation is not blindly retried, and provider state is reconciled before a second charge.
07 / FIELD NOTE
Queues and durable background processing
Mental model: a queue separates acceptance from completion. Producers publish durable intent; workers claim messages, perform side effects, acknowledge after success and retry failures. At-least-once delivery means the same message can appear again, so handlers need stable event IDs and idempotent state transitions. The transactional outbox records a domain change and an event in the same database transaction; a dispatcher later publishes it. A dead-letter queue is a diagnostic backlog, not a deletion bin.
Slow image generation, email and report jobs should not block HTTP requests or silently disappear after worker crashes. Accessible progress states need persisted job status, not a spinning animation forever.
Example A: image upload returns 202 and queues thumbnail work; a worker crashes after resize and repeats safely. Example B: a booking write and reminder event are stored atomically; the outbox dispatcher retries publication if the broker is down.
// Runnable Node 18+: illustrative idempotent worker reducer
const state=new Map();
function handle(job){if(state.get(job.id)==='done')return 'already done';
if(!['resize','reminder'].includes(job.type))throw Error('unsupported');
state.set(job.id,'done');return 'done';}
console.assert(handle({id:'j1',type:'resize'})==='done');
console.assert(handle({id:'j1',type:'resize'})==='already done');
console.log('demo only: persist status and external side effects atomically');Hands-on exercise · reveal the verification check
Draw an upload → database → outbox → queue → worker sequence. Crash before publishing and after processing but before ack; describe recovery.
Outbox dispatcher republishes after broker outage; worker dedupes redelivery; job status is queryable; dead-letter messages retain diagnostics and a controlled replay path.
08 / FIELD NOTE
API pagination, rate limits and caching
Mental model: a collection endpoint must bound work per request. Offset pagination is simple but shifts under concurrent inserts; keyset/cursor pagination uses a stable sort key and a tie-breaker. Cache validators such as ETag support conditional GET; private tenant data must not leak through shared caches. Rate limits protect scarce work per principal, tenant and endpoint; return 429 and a meaningful Retry-After when possible. Backpressure means refusing or slowing work before queues and memory grow without limit.
A music directory with thousands of artists must stay responsive for keyboard, screen-reader and mobile users. Stable cursors, loading indicators and explicit 'load more' affordances improve usability while protecting database and network budgets.
Example A: /artists?limit=30&after=... uses (createdAt,id) keyset ordering and a next cursor. Example B: an expensive map export is rate-limited per tenant; clients respect 429 Retry-After rather than flooding the service.
// Runnable Node 18+: deterministic keyset page demo
const rows=[{id:'a',time:2},{id:'b',time:2},{id:'c',time:3},{id:'d',time:4}];
function page(after,limit=2){return rows.filter(x=>!after||x.time>after.time||(x.time===after.time&&x.id>after.id)).slice(0,limit);}
const first=page(null),second=page(first.at(-1));
console.assert(first.map(x=>x.id).join(',')==='a,b');
console.assert(second.map(x=>x.id).join(',')==='c,d');
console.log('production cursors must be authenticated and query-scoped');Hands-on exercise · reveal the verification check
Add a new artist between page requests. Compare offset and keyset results; specify an ETag response and a 429 retry plan.
Stable (time,id) cursor avoids duplicates from earlier inserts; conditional GET can return 304; private cache policy is explicit; 429 includes a bounded wait and the UI preserves current results.
RESEARCH EXPANSION · APPLIED ENGINEERING
Structured API errors with RFC 9457
Use HTTP status codes plus stable machine-readable problem types, titles, details and correlation identifiers. RFC 9457 defines application/problem+json; user-facing messages should avoid internal stack traces.
A mobile client needs to distinguish a validation problem from expired authentication or service outage.
Return 409 with problem type 'schedule-conflict' and a request ID; the UI can offer new availability rather than generic failure.
Hands-on exercise · reveal the verification check
Design a 400, 403, 409 and 429 error catalogue.
Each error maps to an appropriate recovery UI and safe test.
ETag concurrency and lost-update protection
Conditional requests can validate caches and prevent stale writes: If-None-Match can avoid downloading unchanged content; If-Match with an ETag can protect an update from overwriting another user's edit.
Concurrent editors can silently erase work when clients always PUT their last loaded copy.
Send an invoice revision ETag on GET, require If-Match on PATCH and return 412 when another editor saved first.
Hands-on exercise · reveal the verification check
Simulate two editors loading the same record then saving.
Second stale update fails with a clear conflict path.
Auth, tenant scoping and BOLA defenses
Every endpoint that accepts an object ID must check whether the caller may access that exact object. Apply role, tenant ownership and field-level rules on the server for lists and individual records.
Broken object-level authorization is a leading API risk and can expose clients when URLs are guessable.
A staff user requests /projects/B/invoices/123; reject even if their login is valid for project A.
Hands-on exercise · reveal the verification check
Write positive and negative cross-tenant tests for reads and writes.
Foreign-tenant IDs never produce another client's data.
Webhooks: signature, replay and ordering
Verify signatures against the raw payload, enforce timestamp tolerance when provided, store unique delivery/event IDs and acknowledge quickly after durable capture. Events may arrive out of order or be retried.
A payment callback may be delivered twice or before an earlier state transition finishes.
Receive payment.succeeded twice; dedupe event ID, validate order state, and create exactly one paid transition.
Hands-on exercise · reveal the verification check
Replay signed duplicate and tampered webhook fixtures.
Only valid unique events change durable state once.
Async request and job API contract
Return 202 Accepted plus stable job ID for long tasks. Track queued/running/completed/failed state with timestamps and safe error codes; make cancellation and retry semantics explicit.
Browsers should not wait on long imports and then guess whether the operation finished.
POST /imports returns /jobs/uuid; GET /jobs/uuid shows progress, last checkpoint and final result link.
Hands-on exercise · reveal the verification check
Simulate worker crash mid-import and restart.
Job resumes or fails clearly without duplicate rows.
API versioning, pagination and compatibility
Treat client contracts as products. Prefer bounded pagination with deterministic ordering and stable cursors for changing feeds. Add fields compatibly and deprecate safely when mobile clients may update weeks later.
An unbounded public endpoint becomes slow, expensive and brittle.
GET /events?limit=40&cursor=X returns 40 ordered records and a next cursor, with a maximum permitted limit.
Hands-on exercise · reveal the verification check
Write tests for page boundaries, invalid cursors and unknown optional fields.
No missing/duplicate IDs when paging through a snapshot.
REST contracts, HTTP semantics, ETags and lost-update protection
HTTP methods, status codes and headers communicate retrieval, mutation, cache and conflict semantics. ETags plus conditional requests help prevent two editors silently overwriting one another; server-side validation and authorization remain mandatory.
A coherent protocol contract reduces surprise across browser, API and proxies.
Require If-Match when editing an event record and return a conflict response if its version has changed.
const res = await fetch('/api/events/42', {method:'PATCH', headers:{'If-Match':'"version-7"','Content-Type':'application/json'}, body:JSON.stringify({title:'New title'})});
if(res.status===412) throw new Error('Conflicting update');Hands-on exercise · reveal the verification check
Specify read, create, edit and delete responses for an event resource.
Every failure has a meaningful status and machine-readable body.
OpenAPI, JSON Schema and contract tests
Document each endpoint's parameters, request schema, success and failure responses, permission requirements and pagination. OpenAPI can generate clients, but the runtime must still validate inbound data; contract tests catch mismatches between producer and consumer.
An API with great code but a vague contract fails during integration.
Define /api/bookings including date format, 400 input failures, 401 auth failures and 409 conflicts.
{ "type":"object", "required":["starts_at"], "properties":{"starts_at":{"type":"string","format":"date-time"}} }Hands-on exercise · reveal the verification check
Write a minimal OpenAPI operation and one invalid payload.
Both implementation and sample payload pass schema tests.
Idempotency, at-least-once delivery and retries
After a timeout the server may have processed the request even though the client never received its reply. Store an idempotency key and outcome for operations such as bookings or payments; queues may redeliver messages and consumers need deduplication.
Correct recovery from network uncertainty prevents duplicate business operations.
Replay the same booking POST twice using the same key and receive one persisted booking.
// Conceptual durable deduplication
BEGIN;
INSERT INTO idempotency_keys(key) VALUES ('request-123') ON CONFLICT DO NOTHING;
-- Perform the booking mutation only when the key is new.
COMMIT;Hands-on exercise · reveal the verification check
Simulate a timeout after commit then retry.
One record exists and the response is consistent.
Webhooks, event ordering and authenticity
External webhooks can be delayed, retried, duplicated and out of order. Verify the sender's documented signature, record unique event identifiers before acknowledging durable work and process asynchronously with bounded retries.
A webhook endpoint is an untrusted entry point with real business consequences.
Record a validated payment event once and enqueue a confirmation job, ignoring duplicate deliveries.
// Verify signature against raw request bytes before parsing JSON.
// Persist provider event ID uniquely before queuing processing.Hands-on exercise · reveal the verification check
Send a valid, duplicate and invalid-signature webhook.
Only one authentic event changes business state.
REST, GraphQL, gRPC, SSE and WebSockets decision guide
REST fits resource operations, GraphQL lets clients select response shape, gRPC supports typed RPC, SSE streams server-to-client messages and WebSockets provide full duplex interaction. Each has different cache, reconnect, permission and operational costs.
The transport should match communication direction and freshness requirements.
Use REST for bookings, SSE for live status and sockets only for genuinely interactive collaboration.
const stream = new EventSource('/api/dispatch/stream');
stream.addEventListener('status', e => console.log(e.data));Hands-on exercise · reveal the verification check
Select transports for three product scenarios and justify them.
Include reconnect, auth, caching and failure behavior.
Deadlines, pagination, rate limits and backpressure
Define upper bounds for requests, worker concurrency, retry count and API page size. Cursor pagination avoids some unstable offset results; cancellation and jittered backoff protect busy upstream systems. Propagate deadlines through network calls where supported.
One aggressive importer should not make the public website unavailable.
Limit a venue importer to four concurrent requests with a deadline and deterministic cursor ordering.
const controller = new AbortController();
setTimeout(() => controller.abort(), 3000);
await fetch('/api/venues', {signal:controller.signal});Hands-on exercise · reveal the verification check
Inject slow and rate-limited dependency responses.
Import slows safely while unrelated endpoints remain responsive.