APIs — REST, gRPC & GraphQL — Primer + 150-Question Drill
"An API is a promise you make to people you will never meet, about code you have not written yet. Interviewers want to see whether you understand what you are promising."
01 · Why this primer existsYou Ship APIs Every Week — Nobody Ever Taught You the Contract
An API is a promise you cannot take back once someone depends on it. This chapter is about making promises you can keep, and changing them without breaking callers.
After nine years of @RestController you can produce a working endpoint in your sleep. The senior interview does not ask whether you can. It asks the questions that separate an endpoint from an API: why did a client get charged twice after a timeout?
Why did the list endpoint that was fast at 10,000 rows fall over at 40 million? What exactly breaks when you rename a JSON field, and what policy would you write so it never breaks a paying customer again?
When should a team pick gRPC over REST, or refuse GraphQL outright?
These questions are answerable from a small set of ideas — the guarantees each HTTP method makes, the idempotency key, keyset pagination, the schema-evolution rules of Protobuf, the resolver model of GraphQL, and the OAuth2 token flows — and this primer teaches them in plain words with runnable code.
The page has two halves. The primer (sections 02–06) walks through HTTP the way an API designer needs it, then REST done properly (resource modelling, pagination, error format, versioning, idempotency, webhooks, rate limits, OpenAPI as a contract), then gRPC and Protobuf, then GraphQL and a decision table for choosing between the styles, and finally security and operations: OAuth2 and OpenID Connect, JWT validation pitfalls, API keys, mutual TLS, gateways, observability, and deprecation. Every chapter ends with a complete code block you can run — a Spring Boot controller, a .proto file with a Python server and client, a GraphQL schema with a batched resolver, an OpenAPI fragment, and the curl commands to exercise them.
The drill (sections 07–10) is 150 senior-level questions in three kinds. Knowledge questions probe mechanism and "why", never definitions. Scenario questions describe a production incident with concrete numbers and expect a diagnosis in order: symptom, evidence to collect, causes ranked, fix, prevention.
Design questions ask you to design a component — a payments API, a 5 GB upload API, a webhook system with guaranteed delivery — and expect requirements, the design, trade-offs, and what you would not do. Every answer is collapsed behind a Reveal answer control.
The method that works: read the question, say your answer out loud as if the interviewer were across the table, and only then reveal. The gap between what you said and what you read is your study list.
This appendix leans on its neighbours. the Distributed Systems primer owns the deep theory of at-least-once delivery and consensus that idempotency keys and webhooks depend on. Chapter E8 owns the index and transaction facts behind cursor pagination and idempotency storage. Chapter E7 owns service-to-service resilience patterns; here we cover the contract between services, not the mesh between them. Where a question crosses into those pages, the answer links to them rather than repeating them.
02 · The primerHTTP the Way an API Designer Needs It
The parts of HTTP an API designer actually decides: which status code says what, which headers carry caching and concurrency, and what changed between HTTP/1.1, 2 and 3.
Start with a number. A payment client sends POST /payments, waits 30 seconds, and gives up because the network dropped the response. The server actually processed the request in 200 milliseconds and moved $500.
The client's retry logic, written by a careful engineer, retries the POST. Now $1,000 has moved. Nothing in this story is a bug in anyone's code — every component did what it was told.
The bug is in the contract: nobody decided what a second identical POST means. HTTP has a vocabulary for exactly this decision, and this chapter is that vocabulary.
You already know HTTP as "the thing Spring handles for me". The bridge is to see it as a set of promises about what the server may assume about a request it has never seen before.
Each method carries two properties defined by the HTTP semantics standard, RFC 9110 (published 2022, replacing the 1999-era RFC 2616 and its 2014 successors).
A method is safe if it is defined as read-only: the client is asking for information and does not expect to change anything. A method is idempotent if sending it once or ten times leaves the server in the same final state. Safe implies idempotent, but not the other way round.
| Method | Safe? | Idempotent? | What it promises | Retry on timeout? |
|---|---|---|---|---|
| GET | yes | yes | Read a representation. Must never change state. | Always safe to retry. |
| HEAD | yes | yes | Like GET but returns headers only — used to check ETag or size. | Always. |
| OPTIONS | yes | yes | Ask what the server supports — used by browsers for CORS preflight. | Always. |
| PUT | no | yes | Replace the whole resource with this body. Sending it twice gives the same result. | Yes. |
| DELETE | no | yes | Remove the resource. The second call may return 404, but the state is the same. | Yes. |
| PATCH | no | not by default | Apply a partial change. "Add 10 to balance" is not idempotent; "set status to shipped" is. | Only if you designed the patch to be idempotent. |
| POST | no | no | Process this body — create, trigger, compute. Two POSTs may create two things. | Only with an idempotency key (next chapter). |
Read the last column carefully, because it is the entire lesson of the payment story. A retrying client, a retrying proxy, or a retrying service mesh may resend any idempotent request without asking. That is why a GET that secretly creates a record is not a style problem but a correctness problem: intermediaries are allowed to replay it. And it is why POST cannot be retried blindly, which is the gap the idempotency key fills.
Status codes that matter, and the ones that lie
A status code is the one part of your response that every intermediary — load balancer, cache, gateway, retry library, dashboard — understands without reading your JSON. So the choice is not cosmetic. The classes: 2xx succeeded, 3xx look elsewhere, 4xx the client did something wrong and retrying the same request will not help, 5xx the server failed and a retry might help. The codes a senior engineer must be able to justify:
- 200 OK with a body; 201 Created with a
Locationheader pointing at the new resource; 202 Accepted meaning "I have queued this, poll the URL inLocationfor progress" — the correct answer for anything that takes longer than a few seconds; 204 No Content for a successful DELETE or a PUT with nothing to say. - 304 Not Modified — the client sent
If-None-Matchwith an ETag and the resource has not changed, so the server sends no body. This is how you make a hot read endpoint nearly free. - 400 Bad Request for malformed input; 401 Unauthorized meaning "I do not know who you are" (badly named — it is about authentication); 403 Forbidden meaning "I know who you are and the answer is no"; 404 Not Found; 409 Conflict for a state clash such as a duplicate unique key or a stale version; 412 Precondition Failed when an
If-MatchETag did not match — the optimistic-locking response; 422 Unprocessable Content for well-formed input that fails business validation; 429 Too Many Requests withRetry-After. - 500 Internal Server Error for a bug; 502 Bad Gateway and 504 Gateway Timeout raised by a proxy in front of you when your service did not answer; 503 Service Unavailable meaning "back off, try later", also with
Retry-After.
The codes that lie are the ones teams return out of laziness: 200 with an error inside the JSON, which makes every cache, retry library, and alert rule believe the call worked; and 500 for a validation failure, which makes clients retry a request that can never succeed and pages your on-call for a typo in someone else's form. If you fix only one thing in an existing API, fix those two.
Headers that carry the design: caching, negotiation, CORS
Caching. An ETag is a short string the server computes to identify one exact version of a resource — a hash of the body, or a version number in quotes such as "v17".
The client stores it and sends it back on the next read as If-None-Match: "v17". If the version still matches, the server answers 304 with no body, and the client uses its stored copy.
On writes the same tag becomes a lock: the client sends If-Match: "v17" with its PUT, and if someone else already moved the resource to v18 the server answers 412, and the client knows to re-read before overwriting.
Cache-Control tells intermediaries how long a response may be reused without asking: max-age=60 means one minute; private means only the end user's browser may cache it, never a shared proxy; no-store means never write it down at all — mandatory for anything with a token or personal data in it.
Content negotiation. The client says what it can read with Accept: application/json and what it is sending with Content-Type: application/json. The server answers with the format it chose in its own Content-Type. Vendor media types such as application/vnd.acme.order+json;version=2 are one way to version an API without touching the URL; the trade-offs are in the next chapter. The correct response to an Accept the server cannot satisfy is 406 Not Acceptable; to a Content-Type it cannot parse, 415 Unsupported Media Type.
CORS. Browsers enforce a rule that a page from app.example.com may not read responses from api.example.com unless the API says so. Cross-Origin Resource Sharing (CORS) is that permission: the browser sends an Origin header, and the API answers with Access-Control-Allow-Origin naming the allowed page origin.
For anything beyond a simple GET, the browser first sends an OPTIONS preflight asking which methods and headers are allowed.
Two facts that come up in interviews: CORS protects users from malicious pages, not your API from scripts — curl ignores it entirely; and Access-Control-Allow-Origin: * combined with credentials is refused by every browser, so an API that needs cookies must echo the specific origin back.
HTTP/1.1, HTTP/2, HTTP/3 in plain words
HTTP/1.1 (1997) sends one request at a time per TCP connection and waits for the answer.
Browsers open about six connections per host to get any parallelism, and each new connection costs a TCP handshake plus a TLS handshake — two to three round trips before the first byte.
HTTP/2 (2015) keeps the same methods, headers, and status codes but changes the wire: it is binary, it compresses headers, and it multiplexes — many requests share one connection at the same time, each on its own numbered stream.
That is why gRPC is built on it. The catch is head-of-line blocking at the TCP layer: because all streams share one TCP connection, one lost packet stalls every stream until it is retransmitted.
HTTP/3 (2022, RFC 9114) fixes that by replacing TCP with QUIC, a transport built on UDP that delivers each stream independently and folds the TLS handshake into the connection handshake, so a reconnecting client can send data in the very first packet.
In practice as of 2026: browsers and CDNs speak HTTP/3 to end users; inside a data centre, HTTP/2 over TCP remains the workhorse, and most Java services still terminate HTTP/1.1 behind a load balancer that speaks HTTP/2 or HTTP/3 to the outside world.
TLS in three paragraphs
Transport Layer Security (TLS) is the layer that makes HTTP into HTTPS. It does three jobs: it proves the server is who the URL says (the server presents a certificate signed by an authority the client trusts), it agrees a secret key with the client using public-key mathematics, and then it encrypts everything with that key.
TLS 1.3 (2018) reduced the handshake to one round trip and removed the weak cipher options, so "enable TLS 1.3 only, TLS 1.2 as the floor" is the current safe default.
Mutual TLS (mTLS) adds the mirror step: the client also presents a certificate, so the server knows which machine is calling before any application code runs. That is how service meshes identify workloads and how many bank APIs identify partner institutions.
Two operational facts. Certificates expire — a large share of "the API is down" incidents at 2 a.m. are expired certificates, and the fix is automation (ACME clients such as cert-manager) plus an alert at 14 days before expiry.
And TLS termination is a design decision: terminate at the load balancer and you can inspect and route on headers but traffic runs in the clear inside your network; terminate at the service and you keep end-to-end encryption at the cost of certificate distribution to every pod. Most platforms terminate at the edge and re-encrypt with mTLS inside.
Now the curl session that makes all of this concrete. It runs against the Spring Boot service built in the next chapter, so the commands below double as its test script.
Step-by-step: what http-walkthrough.sh does, in plain English
- The first call creates an order with
POSTand anIdempotency-Keyheader.-iprints the response headers so you can see the201, theLocation, and theETag. - The second call repeats the exact same POST with the same key. The server recognises the key and returns the original
201response again instead of creating a second order — this is the fix for the double-charge story. - The third call reads the order with
If-None-Matchset to the ETag from step one. The server answers304with no body. - The fourth call asks for the first page of orders with
limit=2. The response carries anext_cursorfield; the fifth call passes that cursor back to get the next page. - The sixth call sends an order with a negative amount. The server rejects it with
422and aapplication/problem+jsonbody — the standard error format from RFC 9457. - The last call asks for a non-existent order, showing the same Problem Details shape for a
404.
#!/usr/bin/env bash
# Requires: the OrdersApplication from the next chapter running on :8080
set -euo pipefail
BASE=http://localhost:8080
echo "--- 1. create an order (POST with an idempotency key)"
curl -s -i -X POST "$BASE/orders" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 7f2c6a0e-1c3b-4d55-9d0a-0d2f4e1b8a11" \
-d '{"customerId":"c-100","amountCents":50000,"currency":"USD"}'
echo; echo "--- 2. same POST, same key: no second order is created"
curl -s -i -X POST "$BASE/orders" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 7f2c6a0e-1c3b-4d55-9d0a-0d2f4e1b8a11" \
-d '{"customerId":"c-100","amountCents":50000,"currency":"USD"}'
echo; echo "--- 3. conditional GET: send the ETag back, expect 304"
ETAG=$(curl -s -i "$BASE/orders/1" | grep -i '^etag:' | awk '{print $2}' | tr -d '\r')
curl -s -i "$BASE/orders/1" -H "If-None-Match: $ETAG"
echo; echo "--- 4. first page (limit=2)"
PAGE=$(curl -s "$BASE/orders?limit=2")
echo "$PAGE"
CURSOR=$(echo "$PAGE" | sed -n 's/.*"nextCursor":"\([^"]*\)".*/\1/p')
echo; echo "--- 5. second page using the cursor"
curl -s "$BASE/orders?limit=2&cursor=$CURSOR"
echo; echo "--- 6. validation failure: expect 422 + application/problem+json"
curl -s -i -X POST "$BASE/orders" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 2b1d9c7a-5e4f-4a3b-8c2d-1e0f9a8b7c6d" \
-d '{"customerId":"c-100","amountCents":-5,"currency":"USD"}'
echo; echo "--- 7. not found: same Problem Details shape"
curl -s -i "$BASE/orders/999999"
Read the output from top to bottom. Call 1 prints HTTP/1.1 201, a Location: /orders/1 header, and an ETag: "1" header — the tag is simply the order's version number in quotes. Call 2 prints the identical 201 and identical body: the key was recognised, and no second order exists — check by listing. Call 3 prints HTTP/1.1 304 and then nothing, because a 304 has no body by definition. Call 4 prints two orders and a nextCursor; call 5 prints the orders after them, and the last page has nextCursor: null. Call 6 prints HTTP/1.1 422, Content-Type: application/problem+json, and a JSON body with type, title, status, detail, instance, plus an errors array naming the offending field. Call 7 prints the same shape with status 404. A client can now handle every failure with one parser instead of one per endpoint.
Before reading on: a mobile client sends DELETE /orders/42, the response is lost, and the client retries. The first call returned 204; the retry returns 404. The mobile team files a bug: "delete is flaky". Is it? What should the client do with the 404, and what would you change on the server, if anything?
Reveal the answer
It is not a bug. DELETE is idempotent in the sense that matters — the state after one call and after two is the same: the order is gone. The response code may legitimately differ, because the second call found nothing to delete.
The client should treat 404 on a retried DELETE as success.
Some teams choose to return 204 for a DELETE of an already-deleted resource to make dumb retry libraries happy; that is a reasonable choice as long as it is documented, but it hides the "was it ever there?" signal.
What you must not do is return 500, which tells retry libraries to keep trying.
Quick reference — HTTP for API designers
- safe / idempotent
- Safe: does not change state (GET, HEAD). Idempotent: doing it twice equals doing it once (GET, PUT, DELETE). POST is neither, which is why it needs idempotency keys.
- The codes worth knowing
201Created +Location·202Accepted (work not done yet) ·204No Content ·304Not Modified ·409Conflict ·412Precondition Failed ·422Unprocessable Content ·429Too Many Requests.- 400 vs 422
400is malformed — the parser failed.422parsed fine but broke a business rule.- 401 vs 403
401: we do not know who you are.403: we do, and you may not.- Concurrency headers
ETagplusIf-Matchgives you optimistic concurrency over HTTP. A mismatch is412.- HTTP/2 and /3
- HTTP/2 multiplexes many streams on one connection. HTTP/3 moves to QUIC over UDP, removing head-of-line blocking at the transport.
03 · The primerREST Done Properly — Resources, Pagination, Errors, Versions, Idempotency
Resources, not verbs. Then the six decisions every real REST API has to make anyway: pagination, filtering, one error format, versioning, retry safety, and how you publish the contract.
A list endpoint at a logistics company served 200 rows per page from a 40-million-row shipments table. Page 1 took 12 milliseconds.
A customer's nightly export walked all 200,000 pages, and page 150,000 took 4.8 seconds — a 400× slowdown for the identical query shape.
The database was healthy, the index was used, and every engineer who looked at it said "the query is fine". It was the pagination design.
This chapter is about the handful of REST decisions — pagination, error shape, versioning, idempotency — that look like taste and behave like architecture.
REST (Representational State Transfer) is a style, not a protocol: expose resources — nouns with stable URLs — and manipulate them with HTTP's fixed set of methods, letting HTTP's own semantics (caching, status codes, idempotency) do the work. You already do most of this. The parts that are usually done badly follow.
Resource modelling and naming
Model nouns, not verbs: /orders, /orders/{id}, /orders/{id}/items.
Plural nouns, lowercase, hyphens in multi-word paths (/shipping-addresses), identifiers that do not leak database internals — a random or time-ordered public id (UUIDv7 is the 2026 default because it sorts by time and does not fragment indexes) rather than an auto-increment integer that lets a customer count your orders.
The exception is actions that are not CRUD: cancelling an order is not a DELETE (the record stays) and not a PATCH of a status field (it triggers side effects). The honest pattern is a sub-resource that is itself a noun: POST /orders/{id}/cancellations creates a cancellation.
When even that reads awkwardly, a clearly named action endpoint — POST /orders/{id}:cancel, Google's convention — beats a lie. Nest at most one level; deeper than /customers/{id}/orders/{oid} and you should flatten with a filter: /orders?customerId=….
Pagination: offset versus cursor, with the arithmetic
Offset pagination is ?page=750&size=200, translated to LIMIT 200 OFFSET 150000. The database cannot jump to row 150,000 in a B-tree; it must walk from the start and discard 150,000 rows to find the 200 you want.
Cost grows linearly with page number — that is the 400× above. It also skips or repeats rows when the underlying data changes between pages: delete one row from page 3 and every later page shifts by one, so the export misses a shipment.
Offset paging is fine for a UI that shows "page 1 of 8" over a few thousand rows, and wrong for anything a program walks end to end.
Cursor pagination (also called keyset or seek pagination) replaces "skip N rows" with "start after this row".
The server sorts by a column set that is unique and indexed — typically (created_at, id) — and returns, with each page, an opaque cursor encoding the last row's sort key.
The next request says ?cursor=…&limit=200, and the server runs WHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESC LIMIT 200. With an index on (created_at, id) the engine seeks straight to the boundary, so page 150,000 costs the same as page 1.
Rows inserted or deleted elsewhere do not shift the window, because the cursor is a position in key space, not a count. The price: no "jump to page 750", and the sort order must be fixed at design time.
Encode the cursor as base64 of the key so clients treat it as opaque and you can change its contents later.
A worked example: the last row on page 1 was created at 2026-08-27T10:15:00Z with id 018f…c3; the cursor is base64 of 2026-08-27T10:15:00Z|018f…c3; the next query seeks to rows strictly before that pair.
Filtering, sorting, and partial responses
Filters are query parameters named after fields: ?status=shipped&createdAfter=2026-08-01. Allow-list which fields may be filtered and sorted, because every sortable column is a column you now must index — a sort on an un-indexed column over 40 million rows is a full scan and a memory sort. Sorting takes a single parameter with a sign or a direction: ?sort=-createdAt,id. Note that cursor pagination and free-form sorting fight each other: the cursor encodes the sort key, so changing the sort invalidates the cursor. Either fix the sort per endpoint or encode the sort inside the cursor. Partial responses (?fields=id,status,total) let mobile clients skip 90% of a payload; they are worth offering on your two or three largest resources and not worth generalising, because at that point you are reinventing GraphQL badly.
One error format: RFC 9457 Problem Details
Every API needs one error shape so clients write one handler. The standard is Problem Details, RFC 9457 (2023, which supersedes RFC 7807 with clarifications, not breaking changes).
The body is JSON with media type application/problem+json and five well-known members: type, a URL that identifies the kind of problem and doubles as documentation; title, a short human summary that does not change per occurrence; status, the HTTP code repeated; detail, a human explanation of this occurrence; and instance, a URL or id for this specific failure that support staff can search logs by.
You may add members — an errors array for field-level validation failures is the common one. Spring Framework 6 and later, so every Spring Boot 3.x and 4.x, has a first-class ProblemDetail class and turns it on for framework errors with spring.mvc.problemdetails.enabled=true.
Versioning: the strategies and their real costs
| Strategy | Looks like | Choose when | Cost |
|---|---|---|---|
| URL path version | /v2/orders | Public APIs with many external consumers; you need the version visible in logs, dashboards, and gateway routes. | A "v2" that changes one resource forces every resource to move; clients hard-code URLs. |
| Header version | API-Version: 2026-08-01 (Stripe style: a date) | You want per-consumer pinning and gradual rollout; the date tells everyone how old their integration is. | Invisible in URLs, harder to test with a browser, needs gateway support to route. |
| Media-type version | Accept: application/vnd.acme.order.v2+json | Purist REST teams versioning one representation at a time. | Almost nobody's tooling does this well; clients forget the header and get v1 silently. |
| No explicit version, additive-only changes | New optional fields only; never rename or remove. | Internal APIs with a small set of consumers you can reach. | Requires discipline and contract tests; a breaking change has nowhere to go. |
The senior point is that the mechanism matters less than the policy: what counts as breaking (removing or renaming a field, changing a type, tightening validation, changing a status code), what does not (adding an optional field, adding an enum value if clients were told to tolerate unknown values), how long old versions live, and how consumers are told. Spring Framework 7 and Spring Boot 4 (GA November 2025) added first-class API versioning support — @RequestMapping(version = "2") with a configurable resolver for path, header, or query strategies — so the mechanics are no longer a reason to delay the policy.
Idempotency keys: the fix for the double charge
The client generates a unique key per logical operation — a UUID created when the user taps "Pay", not per HTTP attempt — and sends it as Idempotency-Key. The server, before doing any work, stores the key with a status of "in progress".
If the same key arrives again, the server returns the stored response of the first attempt instead of doing the work twice. If it arrives while the first is still in progress, the server returns 409 so the client waits.
If the same key arrives with a different body, that is a client bug and the server answers 422. Keys expire after 24 hours or so.
The store must be atomic on insert — a unique index in your database or a Redis SET NX — because two identical requests in the same millisecond must not both win.
This header is being standardised by the IETF HTTP APIs working group as of 2026 and is already the convention at Stripe, Adyen, and most payment providers.
Long-running operations, webhooks, rate limits
Anything over a couple of seconds should not hold the connection. Answer 202 Accepted with a Location: /operations/{id}; the client polls that resource, which reports status: running | succeeded | failed and, on success, links to the result.
A webhook is the push version: the client registers a URL, and you POST an event to it when the operation finishes.
Webhooks are an API you call into someone else's code, so all your reliability rules invert — you retry with backoff, you sign each delivery with an HMAC (a keyed hash the receiver can verify) so the receiver knows it came from you, you include an event id so the receiver can drop duplicates, and you must accept that delivery is at-least-once.
The full design is Q147 in the drill.
Rate limiting is the API telling one client to slow down so the others survive: answer 429 Too Many Requests with Retry-After in seconds, and, increasingly, the IETF draft RateLimit headers that state the remaining quota so well-behaved clients slow down before they hit the wall.
OpenAPI 3.1 as the contract
An OpenAPI document is a YAML or JSON description of every path, parameter, schema, and response.
Version 3.1 (2021) aligned its schema language fully with JSON Schema, which is why it is the version to target; 3.2 was published in September 2025 with additive improvements, and most tooling accepts both as of 2026.
The document is the contract: code generators produce client SDKs from it, contract tests diff it against the running service, gateways validate requests against it, and a diff between two versions of the document is your breaking-change detector.
Write it first for public APIs and generate it from annotations for internal ones — the discipline matters more than the direction.
Step-by-step: what orders-openapi.yaml does, in plain English
- The header declares OpenAPI 3.1.0 and names the API and its version;
serverslists the base URL clients prepend to every path. components/schemasdefines the shared shapes once: anOrder, the request body to create one, a page of orders with a nullable cursor, and the RFC 9457Problemshape.components/responses/Problemis a reusable response that every error status points at, so the error format is defined in one place.components/parametersdefines theIdempotency-Keyheader parameter, thelimit, and thecursoronce.paths./orders.getlists orders with pagination and returns the page shape.paths./orders.postrequires the idempotency header, declares 201 with aLocationheader and anETag, and maps 422 and 409 to the Problem response.paths./orders/{id}.getdeclares the optionalIf-None-Matchheader and the 304 response with no body.
openapi: 3.1.0
info:
title: Orders API
version: "2026-08-01"
description: Reference contract for the OrdersApplication in Chapter E6.
servers:
- url: http://localhost:8080
components:
schemas:
Order:
type: object
required: [id, customerId, amountCents, currency, status, version, createdAt]
properties:
id: { type: integer, format: int64, examples: [1] }
customerId: { type: string, examples: ["c-100"] }
amountCents: { type: integer, format: int64, minimum: 1 }
currency: { type: string, pattern: "^[A-Z]{3}$" }
status: { type: string, enum: [NEW, PAID, SHIPPED, CANCELLED] }
version: { type: integer, description: Used as the ETag. }
createdAt: { type: string, format: date-time }
CreateOrder:
type: object
required: [customerId, amountCents, currency]
properties:
customerId: { type: string, minLength: 1 }
amountCents: { type: integer, format: int64, minimum: 1 }
currency: { type: string, pattern: "^[A-Z]{3}$" }
OrderPage:
type: object
required: [items, nextCursor]
properties:
items: { type: array, items: { $ref: "#/components/schemas/Order" } }
nextCursor: { type: [string, "null"], description: Opaque; pass back as ?cursor= }
Problem:
type: object
description: RFC 9457 Problem Details
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
detail: { type: string }
instance: { type: string }
errors:
type: array
items:
type: object
properties:
field: { type: string }
message: { type: string }
responses:
Problem:
description: Error in RFC 9457 format
content:
application/problem+json:
schema: { $ref: "#/components/schemas/Problem" }
parameters:
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
schema: { type: string, format: uuid }
Limit:
name: limit
in: query
schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
Cursor:
name: cursor
in: query
schema: { type: string }
paths:
/orders:
get:
summary: List orders, newest first, cursor-paginated
parameters:
- $ref: "#/components/parameters/Limit"
- $ref: "#/components/parameters/Cursor"
responses:
"200":
description: One page of orders
content:
application/json:
schema: { $ref: "#/components/schemas/OrderPage" }
"400": { $ref: "#/components/responses/Problem" }
post:
summary: Create an order (idempotent via Idempotency-Key)
parameters:
- $ref: "#/components/parameters/IdempotencyKey"
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/CreateOrder" }
responses:
"201":
description: Created (or replayed for a repeated key)
headers:
Location: { schema: { type: string } }
ETag: { schema: { type: string } }
content:
application/json:
schema: { $ref: "#/components/schemas/Order" }
"409": { $ref: "#/components/responses/Problem" }
"422": { $ref: "#/components/responses/Problem" }
/orders/{id}:
get:
summary: Read one order with ETag support
parameters:
- name: id
in: path
required: true
schema: { type: integer, format: int64 }
- name: If-None-Match
in: header
required: false
schema: { type: string }
responses:
"200":
description: The order
headers:
ETag: { schema: { type: string } }
content:
application/json:
schema: { $ref: "#/components/schemas/Order" }
"304": { description: Not modified — client copy is current }
"404": { $ref: "#/components/responses/Problem" }
Now the service that honours that contract. It is one Java file plus one YAML so you can run it with nothing but a JDK and Gradle or Maven; the in-memory store stands in for the database so the pagination and idempotency logic are the only moving parts. Everything the curl script in the previous chapter exercised lives here.
Step-by-step: what OrdersApplication.java does, in plain English
- The
record Orderis the resource: a numeric id, the fields from the contract, aversionthat becomes the ETag, and acreatedAttimestamp used with the id as the cursor key. record CreateOrderis the request body with Jakarta Bean Validation annotations; Spring rejects an invalid body before the controller runs and raisesMethodArgumentNotValidException.OrderStoreis a thread-safe in-memory table.page()implements keyset pagination in Java: sort newest first, skip to the row strictly after the cursor's(createdAt, id)pair, takelimitrows, and build the next cursor from the last row. In a real service this is one indexed SQL query.Cursor.encodeanddecodeturn the key pair into a base64url string and back, so clients see an opaque token.IdempotencyStoremaps a key to the response already sent.putIfAbsentis the atomic claim; the stored record includes a hash of the request body so a reused key with a different body is detected.OrdersController.listvalidateslimit, decodes the cursor, and returns a page. A bad cursor becomes a 400 Problem.OrdersController.createclaims the key, replays the stored response if the key is known and the body hash matches, answers 422 if the body differs, otherwise creates the order, stores the response, and returns 201 withLocationandETag.OrdersController.getlooks up the order (404 as a Problem if missing), builds the ETag from the version, and callsWebRequest.checkNotModified, which compares againstIf-None-Matchand, on a match, sets the 304 status so the method returns no body.ApiErrorsextends Spring'sResponseEntityExceptionHandler, which already produces Problem Details for framework errors; it overrides the validation case to add anerrorsarray and gives every problem atypeURL.
// Spring Boot 3.5+ or 4.x (as of Aug 2026). Dependencies:
// org.springframework.boot:spring-boot-starter-web
// org.springframework.boot:spring-boot-starter-validation
// Run: ./gradlew bootRun (or mvn spring-boot:run), then run http-walkthrough.sh
package com.example.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@SpringBootApplication
public class OrdersApplication {
public static void main(String[] args) { SpringApplication.run(OrdersApplication.class, args); }
}
// ---------- the resource ----------
record Order(long id, String customerId, long amountCents, String currency,
String status, int version, Instant createdAt) {}
record CreateOrder(@NotBlank String customerId,
@Min(1) long amountCents,
@Pattern(regexp = "^[A-Z]{3}$") String currency) {}
record OrderPage(List<Order> items, String nextCursor) {}
// ---------- cursor = base64url("createdAtEpochMillis|id") ----------
final class Cursor {
static String encode(Order last) {
String raw = last.createdAt().toEpochMilli() + "|" + last.id();
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
/** returns {createdAtMillis, id}; throws IllegalArgumentException on garbage */
static long[] decode(String cursor) {
String raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8);
String[] parts = raw.split("\\|");
if (parts.length != 2) throw new IllegalArgumentException("malformed cursor");
return new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) };
}
}
// ---------- in-memory table standing in for the database ----------
final class OrderStore {
private final Map<Long, Order> rows = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
Order insert(CreateOrder in) {
long id = ids.incrementAndGet();
Order o = new Order(id, in.customerId(), in.amountCents(), in.currency(), "NEW", 1, Instant.now());
rows.put(id, o);
return o;
}
Optional<Order> find(long id) { return Optional.ofNullable(rows.get(id)); }
/** Keyset page: newest first, strictly after the cursor's (createdAt, id). */
OrderPage page(long[] after, int limit) {
Comparator<Order> newestFirst = Comparator.comparing(Order::createdAt).thenComparing(Order::id).reversed();
List<Order> items = rows.values().stream()
.sorted(newestFirst)
.filter(o -> after == null || isBefore(o, after)) // the WHERE (created_at, id) < (:ts, :id)
.limit(limit + 1L) // fetch one extra to know if a next page exists
.toList();
boolean hasMore = items.size() > limit;
List<Order> pageItems = hasMore ? items.subList(0, limit) : items;
String next = hasMore ? Cursor.encode(pageItems.get(pageItems.size() - 1)) : null;
return new OrderPage(pageItems, next);
}
private static boolean isBefore(Order o, long[] key) {
long ts = o.createdAt().toEpochMilli();
return ts < key[0] || (ts == key[0] && o.id() < key[1]);
}
}
// ---------- idempotency: key -> the response we already sent ----------
final class IdempotencyStore {
record Stored(String bodyHash, Order response) {}
private final Map<String, Stored> byKey = new ConcurrentHashMap<>();
/** Atomic claim: returns null if we now own the key, or the prior record. */
Stored claim(String key, String bodyHash) {
return byKey.putIfAbsent(key, new Stored(bodyHash, null));
}
void complete(String key, String bodyHash, Order response) { byKey.put(key, new Stored(bodyHash, response)); }
static String hash(Object body) {
try {
byte[] d = MessageDigest.getInstance("SHA-256").digest(body.toString().getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(d);
} catch (Exception e) { throw new IllegalStateException(e); }
}
}
// ---------- the controller ----------
@RestController
@RequestMapping("/orders")
class OrdersController {
private final OrderStore store = new OrderStore();
private final IdempotencyStore idem = new IdempotencyStore();
@GetMapping
OrderPage list(@RequestParam(defaultValue = "50") int limit,
@RequestParam(required = false) String cursor) {
if (limit < 1 || limit > 200) throw problem(HttpStatus.BAD_REQUEST, "limit must be between 1 and 200");
long[] after = null;
if (cursor != null) {
try { after = Cursor.decode(cursor); }
catch (IllegalArgumentException e) { throw problem(HttpStatus.BAD_REQUEST, "cursor is not valid"); }
}
return store.page(after, limit);
}
@PostMapping
ResponseEntity<Order> create(@RequestHeader("Idempotency-Key") String key,
@Valid @RequestBody CreateOrder in) {
String bodyHash = IdempotencyStore.hash(in);
IdempotencyStore.Stored prior = idem.claim(key, bodyHash);
if (prior != null) {
if (!prior.bodyHash().equals(bodyHash))
throw problem(HttpStatus.UNPROCESSABLE_CONTENT, "Idempotency-Key reused with a different request body");
if (prior.response() == null)
throw problem(HttpStatus.CONFLICT, "a request with this Idempotency-Key is still in progress");
return created(prior.response()); // replay the original response
}
Order o = store.insert(in);
idem.complete(key, bodyHash, o);
return created(o);
}
@GetMapping("/{id}")
ResponseEntity<Order> get(@PathVariable long id, WebRequest request) {
Order o = store.find(id).orElseThrow(() -> problem(HttpStatus.NOT_FOUND, "order " + id + " does not exist"));
String etag = "\"" + o.version() + "\"";
if (request.checkNotModified(etag)) {
return null; // Spring has already set 304; no body is sent
}
return ResponseEntity.ok().eTag(etag).header(HttpHeaders.CACHE_CONTROL, "private, max-age=0").body(o);
}
private static ResponseEntity<Order> created(Order o) {
return ResponseEntity.created(URI.create("/orders/" + o.id()))
.eTag("\"" + o.version() + "\"")
.body(o);
}
private static ErrorResponseException problem(HttpStatus status, String detail) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(status, detail);
pd.setType(URI.create("https://api.example.com/problems/" + status.value()));
return new ErrorResponseException(status, pd, null);
}
}
// ---------- one error shape for everything: RFC 9457 ----------
@RestControllerAdvice
class ApiErrors extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, "request body failed validation");
pd.setType(URI.create("https://api.example.com/problems/validation"));
pd.setTitle("Validation failed");
List<Map<String, String>> errors = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of("field", fe.getField(), "message", String.valueOf(fe.getDefaultMessage())))
.toList();
pd.setProperty("errors", errors);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(pd);
}
}
Step-by-step: what application.yaml does, in plain English
spring.mvc.problemdetails.enabled: trueswitches on Spring's built-in RFC 9457 handling, so errors raised by the framework itself — an unknown path, a wrong method, an unreadable body — come back asapplication/problem+jsonjust like the errors the controller raises.server.port: 8080fixes the port the curl walkthrough expects.
spring:
mvc:
problemdetails:
enabled: true # framework errors (400, 404 on unknown paths, 405, 415) also become application/problem+json
server:
port: 8080
Read the behaviour, not just the code. The second POST with the same key returns the identical 201 because putIfAbsent found the key and the stored response was replayed; two POSTs racing in the same millisecond cannot both create an order because only one putIfAbsent wins. The 304 path works because checkNotModified compares the header value to the tag and sets the response status itself — returning null from the handler is the documented way to send no body. The keyset filter isBefore is exactly the SQL row-value comparison (created_at, id) < (:ts, :id), which both PostgreSQL and MySQL 8 can serve from a composite index; the extra row fetched with limit + 1 is the standard trick for knowing whether a next page exists without a second count query. And every error, whether raised by your code or by Spring's argument binding, leaves the service as application/problem+json with a stable type URL a client can switch on.
There are no dumb questions
- Should I return 200 or 201 when an idempotent POST is replayed?
- Return exactly what the first attempt returned, headers included. The client's retry logic cannot tell the attempts apart, and it should not have to. Stripe replays the original status; the IETF draft for
Idempotency-Keyrecommends the same. Replaying a different code invites a second code path in every client for a case that should be invisible. - Why is PATCH "not idempotent by default" when I only ever send full field values?
- Because the method makes no promise — only your document does. A JSON Merge Patch (RFC 7386) that sets
status: "SHIPPED"is idempotent in effect; a JSON Patch (RFC 6902) with anaddoperation on an array is not, because applying it twice adds twice. Clients and proxies read the method, not your intent, so they will not retry PATCH on your behalf. If you want retry safety on PATCH, add the idempotency key. - Where does the cursor break if two orders share the same
createdAt? - It does not, as long as the tie-breaker column is part of the key and the index. That is why the cursor is
(createdAt, id)and notcreatedAtalone. With a bare timestamp key, two rows created in the same millisecond would straddle a page boundary and one would be skipped or repeated. Every keyset must end in a unique column. - Is an ETag the same as a version column in the database?
- It can be, and that is the simplest correct implementation: the ETag is the row's version in quotes, and
If-Matchon a PUT becomesWHERE id = ? AND version = ?, which is the optimistic locking pattern from Chapter E8. A hash of the body works when there is no version column, but it costs a serialisation on every read and cannot be used as a lock in the database.
Quick reference — REST design decisions
- Offset vs cursor pagination
- Offset is simple and wrong under writes — rows shift between pages. Cursor is stable, needs an index matching the sort, and cannot jump to page 50.
- The cursor index rule
- The index must match the sort exactly, including direction and the tiebreaker column.
- RFC 9457 Problem Details
- One error format:
type,title,status,detail,instance. Use it everywhere rather than inventing a shape per endpoint. - Versioning
- URL path is the honest default. Header-based versioning is cleaner in theory and harder to debug, cache and log in practice.
- Idempotency keys
- The client sends a key; you store the response against it and replay on retry. This is the fix for the double-charge, and it must survive a restart.
- Deprecation
- A public promise with dates: announce, warn in headers and docs, monitor who still calls it, then remove. No date means no removal.
04 · The primergRPC & Protobuf — When It Wins, and the Rules That Keep It Working
A binary contract compiled into both sides. Fast and strictly typed, with two rules about field numbers that you can never break, and one load-balancing surprise.
Two numbers set the scene. A JSON order of 40 fields serialises to about 1.9 KB and takes a Java service roughly 25 microseconds to parse; the same order as a Protobuf message is about 380 bytes and parses in about 3 microseconds.
Multiply by 50,000 calls per second between two internal services and the difference is real CPU and real network.
The second number is the one that bites: a team migrated to gRPC, deployed 12 replicas behind a Kubernetes Service, and watched one pod take 95% of the traffic while eleven sat idle.
Both numbers come from the same fact — gRPC runs on HTTP/2 — and this chapter explains why that one fact gives you the speed and the pitfall together.
The bridge from what you know: gRPC is remote method calls with a schema. Instead of "POST some JSON to a URL and hope", you write an interface file, the .proto, that declares services and their methods with typed request and response messages.
A compiler generates the client stub and server base class in your language. Calling a remote method looks like calling a local one.
That is not new — Java RMI and CORBA did it in the 1990s — but gRPC did it with a compact binary encoding, a streaming-capable transport, and code generation for a dozen languages, and Google, Netflix, and the Kubernetes ecosystem adopted it.
Protobuf: the encoding and the evolution rules
Protocol Buffers encode each field as a tag number plus a value, not a field name plus a value. The tag number is what goes on the wire, so customer_id = 2 costs one byte for the tag regardless of how long the name is. That design gives you the schema-evolution rules, and every rule follows from "the number is the identity":
- Never change a field's number. Renaming a field is free — the name is only in your code. Changing the number makes old writers and new readers disagree about what the bytes mean.
- Never reuse a number. When you remove a field, mark its number
reserved(and its name, so nobody re-adds it by accident). Otherwise a message from an old client puts an old-typed value into a new field. - Adding a field is safe. Old readers skip unknown tags; new readers see the default value (0, empty string, false) when an old writer omitted it. That default rule is why proto3 originally had no way to tell "unset" from "zero" — the
optionalkeyword returned in protobuf 3.15 (2021) to fix this, and you should use it for any field where absence means something. - Changing a type is usually breaking. A few pairs are wire-compatible (
int32andint64,stringandbytes), but treat any type change as a new field. - Enums: put a zero value named
UNSPECIFIEDfirst. Zero is the default, and an old reader that gets an enum value it does not know stores it as unknown; a client must tolerate that.
Protobuf Editions (edition 2023, supported in protoc 26 and later, as of 2026 the recommended replacement for the syntax = "proto3" line) make these behaviours per-feature settings instead of a proto2-versus-proto3 split. Existing proto3 files keep working; new files may declare edition = "2023" and get the same defaults as proto3. The evolution rules above do not change.
The four call shapes, deadlines, and status codes
gRPC supports unary calls (one request, one response — what REST does), server streaming (one request, a stream of responses — perfect for "watch this order for updates" or paging a large result), client streaming (a stream of requests, one response — uploading telemetry), and bidirectional streaming (both at once — a chat or a live pricing feed). Each stream is an HTTP/2 stream on a shared connection, so opening one costs no new handshake.
Every call should carry a deadline: an absolute point in time after which the call is abandoned, sent as a header and propagated to every downstream call the server makes.
This is the single biggest operational difference from typical REST practice, where timeouts are per hop and nobody subtracts the time already spent. With a deadline of 800 milliseconds, a server that has used 500 tells its own downstream "you have 300".
The call fails with DEADLINE_EXCEEDED, one of gRPC's 16 status codes, which replace HTTP status codes at the application level (the HTTP status is always 200, which is why an HTTP-level dashboard sees gRPC errors as successes unless it reads the grpc-status trailer).
The ones to know: OK, INVALID_ARGUMENT (the 400), NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED and UNAUTHENTICATED (403 and 401), RESOURCE_EXHAUSTED (the 429), FAILED_PRECONDITION (the 412 or 409), UNAVAILABLE (retry with backoff — the only code clients should retry blindly), DEADLINE_EXCEEDED, INTERNAL, and UNIMPLEMENTED.
The load-balancing pitfall
Here is the 95%-on-one-pod story. A Kubernetes Service of type ClusterIP balances at layer 4: it picks a pod when a TCP connection is opened. HTTP/1.1 clients open many short connections, so that spreads the load.
A gRPC client opens one HTTP/2 connection and multiplexes every call over it for hours. The Service made one decision at connect time, and every call since has gone to the same pod.
There are three fixes, in increasing order of infrastructure: client-side load balancing, where the client resolves all pod addresses (a headless Service returns them as DNS A records) and round-robins calls across a connection per pod — gRPC's built-in round_robin policy does this; a layer-7 proxy that understands HTTP/2 streams — Envoy, or the Kubernetes Gateway API with an HTTP/2-aware implementation — which balances per call; or a service mesh such as Istio or Linkerd, which is the proxy option installed as a sidecar or ambient layer.
Setting MAX_CONNECTION_AGE on the server so connections are recycled every few minutes is a cheap mitigation, not a fix.
A complete service: the contract, the server, the client
The example is in Python because it needs only pip install and no build plugin, so you can run it in two minutes; the .proto file is identical for Java, where protobuf-gradle-plugin or Maven's protoc-jar generates the same stubs and Spring gRPC (the official Spring project, 1.0 GA alongside Spring Boot 4 as of 2026) wires the server as a bean. The service exposes one unary call and one server-streaming call and demonstrates deadlines, status codes, and reserved fields.
Step-by-step: what orders.proto does, in plain English
syntax = "proto3"selects the proto3 rules (you may writeedition = "2023"with protoc 26+ for the same defaults).package orders.v1namespaces the types and puts the version in the package name — gRPC versioning convention is a new package, not a header.- The
OrderStatusenum starts with a zeroUNSPECIFIEDvalue so an unset field is never mistaken for a real status. Orderis the message. Field 4 isreserved— a previousstring noteswas removed and the number must never be reused. Field 6 isoptionalso "no shipped time" is distinguishable from the zero timestamp.GetOrderRequestandWatchOrderRequestare the input messages; gRPC always wraps inputs in a message so you can add fields later without changing the method signature.- The
OrderServicedeclaresGetOrder(unary) andWatchOrder(server streaming, marked bystreamon the return type).
syntax = "proto3";
package orders.v1;
import "google/protobuf/timestamp.proto";
option java_package = "com.example.orders.v1";
option java_multiple_files = true;
enum OrderStatus {
ORDER_STATUS_UNSPECIFIED = 0; // zero value first: "not set", never a real state
ORDER_STATUS_NEW = 1;
ORDER_STATUS_PAID = 2;
ORDER_STATUS_SHIPPED = 3;
ORDER_STATUS_CANCELLED = 4;
}
message Order {
string id = 1;
string customer_id = 2;
int64 amount_cents = 3;
reserved 4; // was `string notes` — removed; number is retired for ever
reserved "notes";
OrderStatus status = 5;
optional google.protobuf.Timestamp shipped_at = 6; // absent != zero
string currency = 7; // added later: old clients ignore it, old servers send ""
}
message GetOrderRequest {
string id = 1;
}
message WatchOrderRequest {
string id = 1;
}
service OrderService {
// Unary: one request, one response.
rpc GetOrder(GetOrderRequest) returns (Order);
// Server streaming: one request, a stream of status updates until terminal state.
rpc WatchOrder(WatchOrderRequest) returns (stream Order);
}
Step-by-step: what grpc_server.py does, in plain English
- The comment at the top shows the two commands: install
grpcioandgrpcio-tools, then runprotocthrough Python to generateorders_pb2.py(messages) andorders_pb2_grpc.py(service stubs). ORDERSis a tiny in-memory table with two orders.OrderServicesubclasses the generated servicer.GetOrderlooks up the id; if it is missing it callscontext.abortwithNOT_FOUNDand a message — that is how a gRPC server returns an error status.WatchOrderis a generator: it yields the order with each successive status, sleeping half a second between them to simulate real updates. Before each yield it checkscontext.is_active()so a client that hit its deadline or hung up stops the loop instead of wasting work.serve()builds a server with a thread pool, setsgrpc.max_connection_age_msto five minutes so long-lived connections are recycled — the cheap mitigation for the load-balancing pitfall — binds port 50051 without TLS for local use, and blocks until stopped.
# pip install "grpcio>=1.70,<2" "grpcio-tools>=1.70,<2"
# python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. orders.proto
# python3 grpc_server.py
import time
from concurrent import futures
import grpc
from google.protobuf.timestamp_pb2 import Timestamp
import orders_pb2
import orders_pb2_grpc
ORDERS = {
"o-1": orders_pb2.Order(id="o-1", customer_id="c-100", amount_cents=50000,
status=orders_pb2.ORDER_STATUS_NEW, currency="USD"),
"o-2": orders_pb2.Order(id="o-2", customer_id="c-200", amount_cents=1299,
status=orders_pb2.ORDER_STATUS_PAID, currency="EUR"),
}
LIFECYCLE = [orders_pb2.ORDER_STATUS_NEW, orders_pb2.ORDER_STATUS_PAID, orders_pb2.ORDER_STATUS_SHIPPED]
class OrderService(orders_pb2_grpc.OrderServiceServicer):
def GetOrder(self, request, context):
order = ORDERS.get(request.id)
if order is None:
# gRPC errors are a status code + message, not an HTTP status
context.abort(grpc.StatusCode.NOT_FOUND, f"order {request.id} does not exist")
return order
def WatchOrder(self, request, context):
base = ORDERS.get(request.id)
if base is None:
context.abort(grpc.StatusCode.NOT_FOUND, f"order {request.id} does not exist")
for status in LIFECYCLE:
if not context.is_active(): # client cancelled or its deadline passed: stop working
return
update = orders_pb2.Order()
update.CopyFrom(base)
update.status = status
if status == orders_pb2.ORDER_STATUS_SHIPPED:
ts = Timestamp()
ts.GetCurrentTime()
update.shipped_at.CopyFrom(ts) # optional field: present only when shipped
yield update
time.sleep(0.5)
def serve() -> None:
server = grpc.server(
futures.ThreadPoolExecutor(max_workers=8),
options=[
("grpc.max_connection_age_ms", 5 * 60 * 1000), # recycle connections: spreads load over time
("grpc.max_connection_age_grace_ms", 30 * 1000),
],
)
orders_pb2_grpc.add_OrderServiceServicer_to_server(OrderService(), server)
server.add_insecure_port("[::]:50051") # plaintext for local runs; use TLS/mTLS credentials in production
server.start()
print("OrderService listening on :50051")
server.wait_for_termination()
if __name__ == "__main__":
serve()
Step-by-step: what grpc_client.py does, in plain English
- Open one channel to the server. The
grpc.lb_policy_nameoption selects client-sideround_robin; with a single address it has no effect, but against a DNS name resolving to several pods it opens a connection to each and rotates calls. - The first call fetches
o-1with atimeoutof one second. In gRPC,timeoutbecomes an absolute deadline sent with the request. - The second call asks for an id that does not exist. The stub raises
grpc.RpcError; the code readse.code()ande.details()and prints them — this is the client side ofcontext.abort. - The third call watches
o-1with a deadline of 0.8 seconds. The server sends one update per half second, so the client receives one, maybe two, and then getsDEADLINE_EXCEEDED. The loop shows how a streaming call is consumed as an iterator and how the deadline ends it. - The last block repeats the watch with a generous deadline and prints all three updates, showing
HasField("shipped_at")as the way to test an optional field.
# python3 grpc_client.py (server from grpc_server.py must be running)
import grpc
import orders_pb2
import orders_pb2_grpc
def main() -> None:
channel = grpc.insecure_channel(
"localhost:50051",
options=[("grpc.lb_policy_name", "round_robin")], # per-call balancing when DNS returns many pods
)
stub = orders_pb2_grpc.OrderServiceStub(channel)
print("--- 1. unary call with a 1 s deadline")
order = stub.GetOrder(orders_pb2.GetOrderRequest(id="o-1"), timeout=1.0)
print(order.id, order.customer_id, order.amount_cents, orders_pb2.OrderStatus.Name(order.status))
print("--- 2. NOT_FOUND surfaces as an RpcError with code + details")
try:
stub.GetOrder(orders_pb2.GetOrderRequest(id="nope"), timeout=1.0)
except grpc.RpcError as e:
print(e.code().name, "-", e.details())
print("--- 3. server stream cut short by a 0.8 s deadline")
try:
for update in stub.WatchOrder(orders_pb2.WatchOrderRequest(id="o-1"), timeout=0.8):
print("update:", orders_pb2.OrderStatus.Name(update.status))
except grpc.RpcError as e:
print(e.code().name, "- stream ended by the deadline, not by the server")
print("--- 4. same stream with a 5 s deadline: all updates arrive")
for update in stub.WatchOrder(orders_pb2.WatchOrderRequest(id="o-1"), timeout=5.0):
shipped = update.shipped_at.ToDatetime().isoformat() if update.HasField("shipped_at") else "-"
print("update:", orders_pb2.OrderStatus.Name(update.status), "shipped_at:", shipped)
if __name__ == "__main__":
main()
Read the client's output in order. Block 1 prints o-1 c-100 50000 ORDER_STATUS_NEW: one round trip, a typed object back, no JSON parsing in sight. Block 2 prints NOT_FOUND - order nope does not exist, which is the whole gRPC error model in one line — a code from a fixed set plus a message, carried in a trailer, with the HTTP status still 200 underneath. Block 3 prints one or two update: lines and then DEADLINE_EXCEEDED; the server's is_active() check means it stopped generating updates the moment the client's deadline passed, which is what "deadline propagation" buys you and what a REST timeout usually does not. Block 4 prints all three statuses, with a real timestamp only on the shipped one, because shipped_at is optional and absent until then.
When gRPC wins, and when it does not
It wins for internal service-to-service calls where both ends are yours, throughput and latency matter, you want a compiler-enforced contract, or you need streaming. It loses for public APIs consumed from browsers (browsers cannot speak native gRPC; gRPC-Web needs a proxy and drops client streaming), for anything a partner will curl to debug, for teams without the build tooling discipline to keep generated code in sync, and for payloads that are mostly free-text where Protobuf's compactness buys nothing. A common 2026 shape: gRPC inside the cluster, REST with OpenAPI at the edge, sometimes generated from the same proto via a transcoding gateway (Envoy's gRPC-JSON transcoder, or grpc-gateway in Go).
Before reading on: a team renames customer_id to buyer_id in orders.proto, keeps it as field 2, regenerates, and deploys the server. Old clients keep working. A month later someone "cleans up" by moving currency from field 7 to field 4 "to fill the gap". What breaks, for whom, and how would you have caught it in CI?
Reveal the answer
The rename breaks nothing on the wire because only the number is transmitted; every generated class just has a different accessor name — a compile-time change for your own code only.
Moving currency to 4 is the disaster: old clients still send currency as field 7, so the new server reads an empty currency; and field 4 was reserved because an old notes string lived there — any old client that still populates notes now delivers text into the new server's currency.
Worse, if 4 had not been reserved, protoc would not even have complained.
CI catches this with buf breaking (the Buf CLI's compatibility check against the previous commit), which fails on any field-number reuse or type change and turns "someone tidied the proto" into a red build.
Quick reference — gRPC and Protobuf
- The two unbreakable rules
- Never change a field's number. Never reuse a number. Everything about compatibility follows from these.
- What is safe
- Adding a field is safe. Renaming is safe on the wire (the number is the identity). Removing needs
reserved. - The four call shapes
- Unary · server streaming · client streaming · bidirectional.
- deadline
- Set on the client, propagated through the chain. A gRPC call without a deadline is a leak waiting for a slow dependency.
- The load-balancing pitfall
- gRPC holds one long-lived HTTP/2 connection, so a connection-level L4 balancer pins all traffic to one backend. You need per-request (L7) balancing or client-side balancing.
05 · The primerGraphQL — Schema, Resolvers, N+1, and Choosing an API Style
The client asks for exactly the fields it wants. That flexibility is the feature and the problem — it moves query planning to the caller, so the server needs cost limits and batched resolvers.
A mobile team building an order-history screen needed, per order, the customer's name and the first item's thumbnail.
With the REST API that was 1 + N + N calls — one for the list, then one customer and one item fetch per order — 41 round trips for a 20-order page, about 3.2 seconds on a mobile network.
They asked for GraphQL. Six months later a single query with eleven levels of nesting — orders → customer → orders → customer → … — took the GraphQL server down for twenty minutes.
Both stories are true of the same technology, and this chapter explains the mechanism behind each.
The bridge: GraphQL is a query language for your API plus a runtime that executes it. The server publishes a typed schema — object types with fields, and a Query type listing the entry points.
The client sends a query that names exactly the fields it wants, nested as deep as the schema allows, and receives JSON in exactly that shape.
There is one endpoint, usually POST /graphql, and the HTTP status is 200 even for errors, which are reported in an errors array beside data. If REST is "the server decides the shape", GraphQL is "the client decides the shape, within a contract the server wrote".
Resolvers and the N+1 problem
Each field in the schema is served by a resolver — a function that, given the parent object, returns the field's value. Scalar fields resolve trivially from the parent. Relationship fields — Order.customer — call a resolver that loads the customer.
Now run the naive mental model on the mobile query: the orders resolver returns 20 orders; the runtime then calls the customer resolver once per order, and each call runs SELECT … WHERE id = ?.
That is the N+1 problem: one query for the list plus N queries for the relationship, and it compounds at every nesting level. The 41 network calls the mobile team suffered have moved into the server and become 41 database calls — better, but not good.
The fix is a DataLoader: a per-request batching cache. Instead of loading immediately, the customer resolver hands the loader a customer id and gets back a promise.
The runtime finishes resolving every sibling field in the current level, and only then does the loader run one query — SELECT … WHERE id IN (20 ids) — and hand each promise its result.
The loader also remembers what it has fetched within the request, so a customer who placed five orders is loaded once.
The pattern originated at Facebook; every serious GraphQL server has it — java-dataloader under Spring for GraphQL, aiodataloader or Strawberry's built-in loader in Python, the original dataloader package in Node.
Query cost and depth limiting
The nested query that took the server down was legal under the schema, because Customer has an orders field and Order has a customer field, so the graph has a cycle. Every GraphQL server needs three guards before it faces a client you do not control. A depth limit rejects queries nested beyond, say, 8 levels. A cost analysis assigns each field a weight — a list field multiplied by its requested page size — and rejects queries whose estimated cost exceeds a budget, so orders(first: 1000) { customer { orders(first: 1000) … } } is refused before a single resolver runs. And persisted queries — the client registers each query at build time and sends only its hash at run time — mean a public API never executes a query it has not seen before, which also fixes caching, because a GET with a hash is cacheable and an arbitrary POST is not. Also disable introspection (the __schema query that reveals the whole schema) in production for public endpoints, and never return raw exception messages in errors.
A schema and a batched resolver in Spring for GraphQL
Spring for GraphQL (2.0 with Spring Boot 4, 1.3–1.4 with Boot 3.x, as of Aug 2026) sits on the reference Java implementation, GraphQL Java, and turns the DataLoader pattern into one annotation: @BatchMapping. You write a method that takes a list of parents and returns a map from parent to child, and Spring registers a loader, defers the field, and calls your method once per level. The example below is one schema file and one Java file on top of the same web starter as the REST service.
Step-by-step: what schema.graphqls does, in plain English
type Querydeclares two entry points: one order by id, and a page of orders withfirstand an optionalaftercursor — the same keyset idea as the REST chapter.OrderConnectionandPageInfofollow the Relay cursor convention that most GraphQL clients understand: a list of edges, each carrying a node and its cursor, plus whether there is a next page.Orderhas scalar fields and one relationship,customer, which is the field that would cause N+1 without batching.Customerhas the reverse relationship,orders, which creates the cycle that depth limiting must guard.- The
!suffix marks a field as non-null, so clients can rely on it without checks.
type Query {
order(id: ID!): Order
orders(first: Int = 20, after: String): OrderConnection!
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
}
type OrderEdge {
node: Order!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
enum OrderStatus { NEW PAID SHIPPED CANCELLED }
type Order {
id: ID!
amountCents: Int!
currency: String!
status: OrderStatus!
customer: Customer! # relationship: batched by @BatchMapping
}
type Customer {
id: ID!
name: String!
orders: [Order!]! # reverse relationship: this is the cycle to depth-limit
}
Step-by-step: what OrdersGraphQL.java does, in plain English
- Two records,
OrderandCustomer, mirror the schema;Orderholds onlycustomerId, not aCustomerobject, so the relationship must be resolved. Dbis a fake database whosecustomersByIdsmethod logs each call so you can see, in the console, that a page of 20 orders produces one customer query, not 20.@QueryMapping orderresolvesQuery.order; the method name matches the field name.@QueryMapping ordersimplements cursor paging: the cursor is the base64 of the last id, andfirst + 1rows are fetched to computehasNextPage.@BatchMapping customeris the DataLoader. Spring collects everyOrderwhosecustomerfield is requested at this level, calls the method once with the list, and distributes the returned map. The method dedupes ids into a set before querying.@BatchMapping ordersonCustomerbatches the reverse direction the same way.DepthLimitregisters GraphQL Java'sMaxQueryDepthInstrumentationat depth 6 andMaxQueryComplexityInstrumentationat 200 points, so the recursive query is rejected before any resolver runs.
// Spring Boot 3.5+/4.x with:
// org.springframework.boot:spring-boot-starter-web
// org.springframework.boot:spring-boot-starter-graphql
// Then: ./gradlew bootRun and POST queries to http://localhost:8080/graphql
// (set spring.graphql.graphiql.enabled=true in application.yaml for the in-browser IDE)
package com.example.ordersgql;
import graphql.analysis.MaxQueryComplexityInstrumentation;
import graphql.analysis.MaxQueryDepthInstrumentation;
import graphql.execution.instrumentation.ChainedInstrumentation;
import graphql.execution.instrumentation.Instrumentation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.BatchMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
record Order(String id, long amountCents, String currency, String status, String customerId) {}
record Customer(String id, String name) {}
record PageInfo(boolean hasNextPage, String endCursor) {}
record OrderEdge(Order node, String cursor) {}
record OrderConnection(List<OrderEdge> edges, PageInfo pageInfo) {}
// ---------- a fake database that logs every query it runs ----------
@Component
class Db {
private final Map<String, Customer> customers = new LinkedHashMap<>();
private final List<Order> orders = new ArrayList<>();
Db() {
for (int c = 1; c <= 14; c++) customers.put("c-" + c, new Customer("c-" + c, "Customer " + c));
for (int o = 1; o <= 60; o++)
orders.add(new Order("o-" + o, 1000L * o, "USD", "NEW", "c-" + (1 + (o % 14))));
}
Optional<Order> order(String id) {
return orders.stream().filter(o -> o.id().equals(id)).findFirst();
}
/** Keyset page ordered by id; afterId null means "from the start". */
List<Order> ordersAfter(String afterId, int limit) {
System.out.println("SQL: SELECT * FROM orders WHERE id > " + afterId + " ORDER BY id LIMIT " + limit);
return orders.stream()
.filter(o -> afterId == null || o.id().compareTo(afterId) > 0)
.sorted(Comparator.comparing(Order::id))
.limit(limit)
.toList();
}
Map<String, Customer> customersByIds(Set<String> ids) {
System.out.println("SQL: SELECT * FROM customers WHERE id IN (" + ids.size() + " ids)");
return ids.stream().filter(customers::containsKey).collect(Collectors.toMap(Function.identity(), customers::get));
}
Map<String, List<Order>> ordersByCustomerIds(Set<String> ids) {
System.out.println("SQL: SELECT * FROM orders WHERE customer_id IN (" + ids.size() + " ids)");
return orders.stream().filter(o -> ids.contains(o.customerId()))
.collect(Collectors.groupingBy(Order::customerId));
}
}
// ---------- resolvers ----------
@Controller
class OrdersGraphQL {
private final Db db;
OrdersGraphQL(Db db) { this.db = db; }
@QueryMapping
public Order order(@Argument String id) {
return db.order(id).orElse(null); // null + no error = "not found" in GraphQL terms
}
@QueryMapping
public OrderConnection orders(@Argument int first, @Argument String after) {
int limit = Math.min(Math.max(first, 1), 100); // never trust the client's page size
String afterId = after == null ? null : new String(Base64.getUrlDecoder().decode(after), StandardCharsets.UTF_8);
List<Order> rows = db.ordersAfter(afterId, limit + 1);
boolean hasNext = rows.size() > limit;
List<Order> page = hasNext ? rows.subList(0, limit) : rows;
List<OrderEdge> edges = page.stream().map(o -> new OrderEdge(o, cursorOf(o))).toList();
String endCursor = edges.isEmpty() ? null : edges.get(edges.size() - 1).cursor();
return new OrderConnection(edges, new PageInfo(hasNext, endCursor));
}
/** Order.customer — called ONCE per level with every parent Order, not once per Order. */
@BatchMapping
public Map<Order, Customer> customer(List<Order> orders) {
Set<String> ids = orders.stream().map(Order::customerId).collect(Collectors.toSet());
Map<String, Customer> found = db.customersByIds(ids);
Map<Order, Customer> result = new HashMap<>();
for (Order o : orders) result.put(o, found.get(o.customerId()));
return result;
}
/** Customer.orders — the reverse relationship, batched the same way. */
@BatchMapping
public Map<Customer, List<Order>> orders(List<Customer> customers) {
Set<String> ids = customers.stream().map(Customer::id).collect(Collectors.toSet());
Map<String, List<Order>> found = db.ordersByCustomerIds(ids);
Map<Customer, List<Order>> result = new HashMap<>();
for (Customer c : customers) result.put(c, found.getOrDefault(c.id(), List.of()));
return result;
}
private static String cursorOf(Order o) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(o.id().getBytes(StandardCharsets.UTF_8));
}
}
// ---------- guards: reject deep or expensive queries before executing them ----------
@Configuration
class DepthLimit {
@Bean
Instrumentation queryGuards() {
return new ChainedInstrumentation(List.of(
new MaxQueryDepthInstrumentation(6), // orders > customer > orders > customer > … stops here
new MaxQueryComplexityInstrumentation(200) // each requested field costs 1 by default
));
}
}
Read the console, not the JSON. Send { orders(first: 20) { edges { node { id customer { name } } } pageInfo { hasNextPage endCursor } } } and the server logs exactly two SQL lines: one orders query and one customers … IN (14 ids) — 20 orders, but only 14 distinct customers, because the batch method deduped before querying. Without @BatchMapping you would see 21 lines. Now send the recursive query seven levels deep and the response is an errors array saying the maximum query depth was exceeded, with no SQL logged at all — the instrumentation runs during validation, before execution starts. That is the difference between a guard and a timeout.
When NOT to use GraphQL
Do not use it when you have one client you also own, because a REST endpoint shaped for that screen is simpler and cacheable at the CDN. Do not use it for server-to-server calls, where gRPC's typed contract and streaming beat a query language.
Do not use it for file uploads, streaming, or anything where HTTP caching and status codes carry the design — GraphQL flattens all of that into a 200 POST.
Do not use it when your team cannot commit to DataLoader discipline and cost limits, because a GraphQL API without them is a denial-of-service endpoint with documentation.
Use it when many clients with different needs — web, iOS, Android, partners — consume a rich, connected data model and the alternative is a dozen bespoke REST endpoints per screen, or a Backend-for-Frontend (a thin API per client type) that nobody wants to maintain.
Choosing: REST, gRPC, GraphQL, or events
| Choose… | When | Contract | Caching & tooling | Watch out for |
|---|---|---|---|---|
| REST + OpenAPI | Public or partner APIs; browser clients; anything people will curl; resource-shaped data with simple reads and writes. | OpenAPI 3.1 document, generated SDKs. | Best: HTTP caching, CDNs, ETags, every proxy understands it. | Over-fetching and chatty screens; versioning discipline; the 200-with-error anti-pattern. |
| gRPC | Internal service-to-service; high call rates; streaming; polyglot teams needing a compiler-checked contract. | .proto with Buf breaking-change checks. | No HTTP caching; needs HTTP/2-aware load balancing; excellent codegen. | Browser support only via gRPC-Web; debugging needs tooling (grpcurl); L4 balancers pin connections. |
| GraphQL | Many different clients over one rich graph; product teams iterating on screens faster than the backend can add endpoints. | Schema (SDL) with deprecations on fields, no versions. | Persisted queries for caching; DataLoader mandatory; depth and cost limits mandatory. | N+1; unbounded queries; errors hidden in 200s; federation complexity at scale. |
| Async events (Kafka, queues, webhooks) | The caller does not need an answer now; fan-out to many consumers; decoupling availability of producer and consumer. | Schema registry (Avro/Protobuf/JSON Schema) or AsyncAPI document. | Replayable; at-least-once, so consumers must be idempotent. | Eventual consistency; ordering only per partition; debugging "where did my event go" — see the Distributed Systems primer. |
The elevator sentence: "A well-designed API is the cheapest sales channel we own — and a badly versioned one is a liability we cannot see on the balance sheet." Every partner who integrates with our API does a one-time engineering spend to build against it; every breaking change we ship makes them spend it again, and the third time they churn.
A written compatibility policy — additive changes only, 12 months' notice on removals, a machine-readable contract that fails our own build when we break it — turns that churn risk into a number we control.
The idempotency and pagination work in this appendix is not polish: duplicate charges after timeouts are refunds, support tickets, and chargeback fees at roughly $15 to $25 each, and the list endpoint that slows 400× with data growth is a customer's nightly export timing out and a renewal conversation we would rather not have.
Choosing gRPC inside and REST outside is the same reasoning: we spend engineering time where it is cheapest to operate and expose the format our customers can adopt without asking us for help.
Quick reference — GraphQL
- resolver
- One function per field. The default shape produces N+1 automatically, because each parent resolves its children separately.
- DataLoader
- Batches and de-duplicates resolver calls within one tick. This is the answer to GraphQL N+1, not an optimisation.
- Cost controls
- Depth limit, cost analysis, and persisted queries. Without them, one legal nested query can take the server down.
- When not to use it
- Simple CRUD with one consumer. Public APIs where you cannot control query shape. Anywhere caching by URL was doing real work for you.
06 · The primerSecurity & Operations — OAuth2, JWTs, Keys, Gateways, and Not Breaking People
Who is calling, how you know, and what you do about the request they sent. OAuth2 in plain words, the JWT checks people skip, and the injection classes that reach an API.
A fintech's public API validated JSON Web Tokens with a library call that checked the signature and the expiry. It did not check the aud claim — the field that says which API the token was issued for.
A token minted for the company's own internal dashboard, with far broader scopes, was accepted by the public API for eleven months. Nobody exploited it, as far as the audit could tell. The fix was one line.
This chapter is about the handful of one-line decisions in API security and operations that carry most of the risk, explained from the mechanism up so you can defend each one in an interview.
OAuth2 and OpenID Connect in plain words
OAuth 2.0 is a framework for delegated authorisation: letting an application act on a user's behalf against an API without ever seeing the user's password.
Four roles: the resource owner (the user), the client (the app wanting access), the authorisation server (the login and consent service that issues tokens), and the resource server (your API, which accepts tokens).
OpenID Connect (OIDC) is a thin layer on top that adds authentication: an ID token that tells the client who the user is, and a standard /userinfo endpoint and discovery document (/.well-known/openid-configuration) so clients can find the keys and endpoints automatically. The flows you must be able to narrate:
- Authorization Code with PKCE — for anything with a user in a browser or on a phone. The app redirects the user to the authorisation server with a random code verifier's hash (the code challenge); the user logs in and consents; the server redirects back with a short-lived authorisation code; the app exchanges the code plus the original verifier for tokens. PKCE (Proof Key for Code Exchange, RFC 7636) is the hash-then-verifier trick, and it means an attacker who intercepts the code cannot redeem it. As of 2026, OAuth 2.1 (in final draft) makes PKCE mandatory for every client and removes the older Implicit and Password flows entirely.
- Client Credentials — for service-to-service with no user. The client authenticates with its own id and secret (or a private key, or an mTLS certificate) and receives an access token representing itself.
- Refresh tokens — long-lived credentials that fetch a new short-lived access token without the user logging in again. Rotate them on every use so a stolen one is detected when both the thief and the real client try to use it.
- Device Authorization — for TVs and CLIs: the device shows a code, the user enters it on a phone.
JWT validation: the pitfalls, one by one
A JSON Web Token (JWT) is three base64url parts — header, payload, signature — joined by dots. The payload holds claims: iss (who issued it), sub (who it is about), aud (which API may accept it), exp and nbf (valid until and not before), iat (issued at), scope or scp (what it may do), and jti (a unique id). The signature lets your API verify the token without calling the issuer, using the issuer's public key, fetched once from its JWKS endpoint (JSON Web Key Set) and cached. Validation done correctly checks all of the following, and every item in this list corresponds to a real published breach:
- Algorithm allow-list. Reject
alg: noneoutright, and never let the token's header choose the algorithm — an attacker can switchRS256toHS256and sign with your public key as the shared secret. Configure the accepted algorithm on the server side. - Issuer must equal the expected value exactly; audience must contain your API's identifier — this is the fintech's missing line.
- Expiry with a small clock skew allowance (30 to 60 seconds), and not-before if present.
- Key selection by
kidonly from your cached JWKS, refreshed on an unknown key id with a rate limit so an attacker cannot make you hammer the issuer. - Scopes and roles checked per endpoint, not just "a valid token exists".
- Revocation: a JWT cannot be revoked by itself. Keep access tokens short (5 to 15 minutes), rotate refresh tokens, and for high-value operations either do token introspection (ask the issuer if it is still valid) or hold a small deny-list of
jtivalues. - Never log tokens, never put them in URLs, and send them only over TLS. RFC 8725, "JWT Best Current Practices", is the checklist to cite.
Two newer mechanisms worth naming in 2026: DPoP (Demonstrating Proof of Possession, RFC 9449) binds an access token to a key the client holds, so a stolen token cannot be replayed from another machine; and mTLS-bound tokens (RFC 8705) do the same with the client's TLS certificate. Both turn bearer tokens — "whoever holds this can use it" — into sender-constrained tokens.
API keys and mutual TLS
An API key is a long random string that identifies a calling application.
It is authentication without a user, and it is fine for low-risk, server-side integrations if you treat it like a password: store only a hash, show it once at creation, support at least two active keys per client so rotation needs no downtime, scope it (read-only, one environment), rate-limit per key, and send it in a header (Authorization: Bearer or X-API-Key), never in the URL, where it lands in every proxy log.
Prefix keys (sk_live_) so secret scanners can recognise them in leaked repositories — GitHub's secret scanning matches on exactly such prefixes.
For anything moving money or personal data between organisations, prefer mutual TLS: the client presents a certificate, so identity is established before your code runs and cannot be replayed from a log.
The cost is certificate distribution and rotation, which is why it pairs with a service mesh internally and with a small number of high-value partners externally.
Input validation, SSRF, and injection
Validate at the edge with the schema you already have — an API gateway or a library can reject a request that does not match your OpenAPI document before it touches business code — and again in the domain layer for rules the schema cannot express.
The three input attacks specific to APIs: injection in any string that reaches a query or a shell (parameterise every query; there is no other fix); mass assignment, where a client sends "role": "admin" in a body you bind directly to an entity (bind to a request DTO with only the fields a client may set — the CreateOrder record in the REST chapter is exactly that); and SSRF, Server-Side Request Forgery, where a client gives you a URL — a webhook target, an image to fetch, an import source — and you fetch it from inside your network, reaching the cloud metadata endpoint at 169.254.169.254 or an internal admin service.
Defend by resolving the host and refusing private, loopback, and link-local ranges after DNS resolution (an attacker's domain can resolve to 10.0.0.1), disabling redirects or re-checking after each one, and running the fetcher in an egress-restricted network.
The OWASP API Security Top 10 (2023 edition, still current in 2026) lists these with broken object-level authorisation — checking that the caller may see this order, not just an order — at number one.
API gateways and what they should not do
An API gateway is the single door in front of many services.
It terminates TLS, authenticates (validates the JWT once so services do not each fetch JWKS), rate-limits per client, routes by path and version, validates requests against the OpenAPI contract, adds a correlation id, and emits the access log and metrics that make the API observable.
Products as of 2026: Kong, Envoy Gateway and the Kubernetes Gateway API implementations, AWS API Gateway, Apigee, Spring Cloud Gateway for teams that want it in Java. What a gateway should not do is business logic — transforming payloads, orchestrating calls, aggregating responses.
The moment logic lives in the gateway it becomes a service nobody owns, deployed by a team that does not know the domain. If you need aggregation, that is a Backend-for-Frontend service with its own tests and owners.
The resource server, configured correctly
Spring Security's resource-server support does the JWT checks for you, but only the ones you configure. The following configuration is the "correct one-liner" from the opening story made explicit: issuer, audience, algorithm, and scope-per-endpoint, on top of the REST service from chapter 03.
Step-by-step: what SecurityConfig.java does, in plain English
- The dependency comment names
spring-boot-starter-oauth2-resource-server, which brings Spring Security and the Nimbus JWT library. filterChaindeclares the rules: no sessions (tokens are stateless), CSRF off (there is no cookie session to forge),GET /orders/**needs theorders:readscope, writes needorders:write, the health endpoint is open, and everything else requires authentication.oauth2ResourceServer(...jwt(...))turns on bearer-token processing with the decoder built below.jwtDecoderbuilds a decoder from the issuer's discovery document, which finds the JWKS endpoint automatically, and pins the signature algorithm toRS256— the algorithm allow-list.- The validator chain combines the default checks (issuer, expiry with 60 seconds of skew, not-before) with an explicit audience validator that requires
orders-apiinaud. This is the line the fintech was missing. JwtClaimValidatoris Spring's generic validator; it fails with aninvalid_tokenerror, which Spring turns into a 401 with aWWW-Authenticateheader explaining why.- The YAML sets the issuer URI so the decoder knows where to look; the value comes from an environment variable so no environment-specific URL is committed.
// Add to the OrdersApplication project:
// org.springframework.boot:spring-boot-starter-oauth2-resource-server
// Spring Boot 3.5+/4.x, Spring Security 6.5+/7.x (as of Aug 2026)
package com.example.orders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
import java.util.List;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()) // no cookie session, so nothing to forge
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.requestMatchers(HttpMethod.GET, "/orders/**").hasAuthority("SCOPE_orders:read")
.requestMatchers(HttpMethod.POST, "/orders/**").hasAuthority("SCOPE_orders:write")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
JwtDecoder jwtDecoder(@Value("${app.security.issuer}") String issuer,
@Value("${app.security.audience}") String audience) {
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withIssuerLocation(issuer) // reads /.well-known/openid-configuration, caches JWKS
.jwsAlgorithm(SignatureAlgorithm.RS256) // algorithm allow-list: the token header does not choose
.build();
OAuth2TokenValidator<Jwt> defaults = JwtValidators.createDefaultWithIssuer(issuer); // iss, exp, nbf (60 s skew)
OAuth2TokenValidator<Jwt> audienceCheck = new JwtClaimValidator<List<String>>(
JwtClaimNames.AUD, aud -> aud != null && aud.contains(audience)); // the missing line from the story
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(defaults, audienceCheck));
return decoder;
}
}
Step-by-step: what the application.yaml security additions do, in plain English
app.security.issueris the exactissvalue tokens must carry; it is read from theOIDC_ISSUERenvironment variable with a placeholder default so no real URL is committed.app.security.audienceis the identifier this API registers with the authorisation server; a token whoseaudlist does not contain it is rejected by the validator inSecurityConfig.
app:
security:
issuer: ${OIDC_ISSUER:https://auth.example.com/} # must match the token's iss claim byte for byte
audience: ${OIDC_AUDIENCE:orders-api} # must appear in the token's aud claim
Read what happens on a request. A call with no token gets 401 and a WWW-Authenticate: Bearer header. A call with a token from the wrong issuer, or one minted for the internal dashboard with aud: ["dashboard"], gets 401 with error="invalid_token" and a description naming the failed claim — the fintech's bug now fails loudly. A valid token whose scopes contain orders:read but not orders:write can list orders and gets 403 on POST, because Spring maps each scope to an authority prefixed SCOPE_. And none of this calls the authorisation server per request: the JWKS was fetched once at start-up and is refreshed only when a token arrives with an unknown kid.
Observability, compatibility testing, deprecation, and SDKs
Observability for an API means, per route and per client: request rate, error rate split by 4xx and 5xx, and latency as percentiles — p50, p95, p99 — never averages, because an average hides the 2% of requests that take four seconds. Add a correlation id (X-Request-Id, or the W3C traceparent header that OpenTelemetry uses) generated at the gateway and passed to every downstream call and log line, so one customer's failing request can be followed across six services. Alert on the error budget of a written SLO (service-level objective), such as "99.9% of requests under 300 ms over 30 days", rather than on individual spikes.
Backward-compatibility testing is what turns a versioning policy from a wish into a gate. Three layers: diff the OpenAPI document against the last released version in CI and fail on removed fields, changed types, or new required parameters (tools: oasdiff, openapi-diff); run consumer-driven contract tests (Pact is the standard, Spring Cloud Contract for Spring shops) where each consumer records the interactions it depends on and the provider's build replays them; and keep the previous version's integration tests running against the new build. For gRPC, buf breaking is the first layer.
A deprecation policy is a public promise with dates. The shape that works: announce a removal with at least six to twelve months' notice; mark it in the contract (deprecated: true in OpenAPI, @deprecated in GraphQL, a comment and a Deprecation response header, standardised as RFC 9745 in 2025, plus a Sunset header with the date, RFC 8594); measure who still calls it, and contact them directly; brown out the old version for an hour a week in the last month so stragglers notice; then remove. SDK generation from the contract (OpenAPI Generator, Speakeasy, Fern, Stainless; Buf for protos) is what makes deprecation survivable for consumers — a regenerated SDK shows deprecation warnings at compile time, and partners upgrading a library version is a smaller ask than rewriting HTTP calls by hand.
Before reading on: your API accepts JWTs from the company's identity provider. A mobile app stores the access token in device storage, and a token has just leaked through a crash-reporting tool that captured request headers. The token is valid for 60 minutes. What can you do right now, what should have been true already, and which of the mechanisms in this chapter would have made the leaked token worthless?
Reveal the answer
Right now: you cannot revoke a self-contained JWT, so either add its jti to a deny-list every resource server checks, or switch the affected endpoints to token introspection for the next hour, and revoke the user's refresh token at the identity provider so no new access token can be minted. What should have been true already: access tokens of 5 to 15 minutes, refresh-token rotation, and a crash reporter configured to scrub the Authorization header. What would have made the leak worthless: DPoP or mTLS-bound tokens — the thief holds the token but not the key the token is bound to, so every replay fails at the resource server.
Quick reference — Security and operations
- The OAuth2 cast
- Resource owner (the user) · client (the app) · authorisation server (issues tokens) · resource server (your API, validates them).
- Which flow
- Authorization Code with PKCE for anything with a user. Client Credentials for service-to-service. Never the implicit flow.
- JWT: what to actually check
- Signature against JWKS · an algorithm allow-list (never trust the token's own
alg) · issuer · audience · expiry. Skipping the allow-list is howalg: noneattacks work. - SSRF
- A URL the caller influences, fetched by your server. Validate scheme, resolve the host and reject private ranges, and re-check after redirects — each layer alone has a bypass.
- What a gateway should not do
- Business logic, and authorisation decisions your service then trusts blindly. Validate the token at the service too.
07 · DrillHTTP & REST Fundamentals — Q1–Q40
Senior API rounds open with HTTP because it is where a candidate's mental model shows fastest. The questions below look like textbook material, but every one of them has a production follow-up: the retry that duplicated a charge, the 200 that hid an outage from the dashboards, the cache that served one customer's data to another. Say the answer aloud before revealing it, and say the mechanism, not the name.
These questions test whether you can state what each method promises to an intermediary that has never read your documentation — and what breaks when the promise is false.
Q1. "Explain safe versus idempotent HTTP methods, and tell me why the distinction is a correctness issue rather than a style issue."
Reveal answer
The real test Whether you connect the definitions to who is allowed to retry or prefetch without asking you.
Strong answer A safe method is defined by RFC 9110 as read-only: the client is not asking for any state change, so GET, HEAD, and OPTIONS are safe.
An idempotent method is one where one call and many identical calls leave the server in the same final state: PUT and DELETE are idempotent, and every safe method is idempotent too.
POST is neither, and PATCH is only idempotent if the patch document happens to be. The reason this is correctness rather than style is that intermediaries act on the method alone.
A browser or link-prefetcher may issue a GET speculatively; a proxy, retry library, or service mesh may replay an idempotent request after a timeout without telling anyone.
If a GET endpoint creates a record, a prefetcher creates records; if a PUT is secretly non-idempotent, a mesh retry double-applies it. The contract is with software that has never read your docs, so the method is the only promise it can see.
Land it I choose the method by what I am willing to let a retrying proxy do to me, not by what reads nicely in the URL.
- "Name a real intermediary that will retry an idempotent request on its own, and the setting that controls it."
Envoy, which is the proxy inside Istio, has a per-route
retry_policywithretry_onvalues such as5xx,reset, andconnect-failure, and Istio exposes the same thing as aVirtualServiceretriesblock withattemptsandperTryTimeout. By default Istio retries twice on connection resets and 503s.Nginx does it with
proxy_next_upstream, and the important detail there isnon_idempotent, which is off by default, so Nginx will replay a GET or PUT to the next upstream but will not replay a POST unless you opt in.So the mesh is reading the method exactly as I described. If I mark an endpoint PUT but it appends to a list, the mesh has permission to append twice, and nothing in my code is ever told that happened.
- "Is a PATCH ever idempotent, and how would you make one so?"
A PATCH is idempotent when applying the same patch document twice leaves the same state as applying it once. A JSON Merge Patch that sets fields to absolute values, for example
{"status":"CANCELLED"}, is idempotent by construction.A JSON Patch document with an
addto the end of an array, or a patch that says "increment quantity by one", is not.If I need a relative change to be retry-safe, I add a precondition: JSON Patch has a
testoperation that fails the whole patch if the current value is not what the client expected, and HTTP hasIf-Matchwith the ETag.With either guard, a replayed patch fails with 412 or 409 instead of double-applying. So the honest statement is that PATCH is idempotent only when the patch format and the server together make it so, and I document that per endpoint.
- "What about HEAD and OPTIONS — why do they matter for an API author?"
HEAD is GET without the body, so it must return the same headers, including
ETag,Last-Modified, andContent-Length.Clients use it to check whether a large resource has changed before downloading it, and some frameworks synthesise HEAD from GET automatically, so if my GET has a side effect then my HEAD does too.
OPTIONS matters because browsers send it as the CORS preflight before any request that is not simple, and it has to answer quickly with
Access-Control-Allow-Methodsand friends without touching authentication, because the browser sends no credentials on a preflight.If my authentication filter runs before the OPTIONS handler and returns 401, every browser client sees a "CORS error" that is really an auth ordering bug. Both are safe methods, so both must be free of writes.
- "How would you find a GET-with-side-effects bug already lurking in a large codebase?"
I would attack it from three sides. First, static: an ArchUnit rule that any method annotated
@GetMappingmay not call into a class in the repository or service write packages, or more crudely, may not reference methods namedsave,delete, orupdate.Second, dynamic: in the integration test suite, wrap every GET handler test in a transaction with a database trigger or a row-count snapshot and assert that no table changed.
Third, production evidence: correlate GET request logs with write statements from the database's statement log or from a JDBC interceptor, and flag any GET whose trace contains an INSERT, UPDATE, or DELETE. The third one finds the cases the first two miss, such as a GET that updates a "last viewed" timestamp, which is the most common offender and is usually acceptable only if it is done asynchronously.
Q2 · Scenario. "Clients report duplicate charges after timeouts. The payment endpoint is POST /payments, the client retries three times with backoff, and the payment service is healthy. Walk me through it."
Reveal answer
The real test Whether you diagnose the missing idempotency contract rather than blaming the retry.
Strong answer I would go in this order:
- Symptom: one logical payment, multiple charges, correlated with client-side timeouts. The retry is doing its job; the contract lets it do harm.
- Evidence: pull the charges by customer and timestamp and confirm they are spaced by the client's backoff intervals. Check the server logs for the same request body arriving two to four times with different request ids. Confirm the server processed each in under the client timeout, so the response was lost on the way back, not the request.
- Causes ranked: first, no idempotency key, so the server cannot recognise a repeat. Second, a key exists but is generated per HTTP attempt instead of per user action, which is the same as no key. Third, a key exists but the check is not atomic, so two concurrent retries both pass the "not seen" test.
- Fix: require an
Idempotency-Keyheader; claim it atomically with a unique index or RedisSET NXbefore doing work; store the response and replay it on repeats; return 409 while the first attempt is in flight; return 422 if the same key arrives with a different body. Reconcile and refund the historical duplicates. - Prevention: the key becomes mandatory in the OpenAPI document, the SDK generates it at "Pay" tap time, and a contract test sends the same key twice and asserts one charge.
Land it Retries are not the bug; a POST without an idempotency key is a promise to charge twice eventually.
- "You added the idempotency key and duplicates still happen, though far fewer. What next?"
Fewer but non-zero means the key is present but the guarantee has a hole. I would pull the duplicate pairs and check three things. First, are the two requests carrying the same key?
If not, the client is minting a key per attempt, and the fix is on their side and in our SDK. Second, if the keys match, did both requests get past the claim?
That means the claim is not atomic, for example a SELECT followed by an INSERT with no unique index, and two requests within the same few milliseconds both saw "absent". The fix is a unique constraint or
SET NX. Third, did the key expire between attempts?A 24-hour expiry is fine, but a 60-second one is not if the client backs off for minutes. I would also check whether the duplicate exists at the card network rather than in our database, which would mean our downstream call is not keyed either.
- "Why do you return 409 during in-flight rather than blocking until the first attempt finishes?"
Blocking holds a thread and a connection for as long as the first attempt takes, which for a card authorisation can be several seconds, and it turns a retry storm into a pile of parked requests that all wake up at once.
A 409 with a
Retry-After: 1header is cheap and tells the client exactly what to do. It also avoids the deadlock-shaped case where the first attempt is itself stuck waiting on a lock.Stripe's API behaves this way and returns a specific error type for "same key, request in progress". The client SDK can hide the 409 by sleeping and re-sending, so integrators see a slightly slower success rather than an error.
If I did want to block, I would do it in the SDK, not the server, because the SDK owns the caller's time budget.
- "What exactly do you store in the idempotency record, and for how long?"
I store the key, the client id it is scoped to, a SHA-256 hash of the canonical request body plus the path, the state as in-progress, completed, or failed, the response status code and body, and created and updated timestamps.
The body hash is what lets me answer 422 when the same key arrives with a different payload, which usually means a client bug. The stored response is what I replay, headers included where they matter, such as
Location.Retention is 24 hours as a default because that covers any sane retry schedule, and Stripe uses the same window.
For the record itself I also keep the resulting payment id so a reconciliation job can repair a record stuck in in-progress after a crash by looking up whether the payment exists.
- "How do you clean up the historical duplicates without making things worse?"
I would first produce the list, not act on it: query charges grouped by customer, amount, and a time window equal to the client's total retry span, and keep pairs where the request bodies match.
Then I would classify them: duplicates where both charges settled need a refund of all but one; duplicates where one was already refunded or reversed by the customer need nothing.
The refunds go through the normal refund path with their own idempotency keys, from a script that writes what it intends to do to a table first, so it can be re-run safely if it dies halfway.
I would notify affected customers before the refunds land, and I would keep the query as a scheduled report afterwards so the same pattern would be caught within an hour rather than found by support.
Q3. "PUT versus PATCH versus POST for updating an order — when is each right, and what does each promise?"
Reveal answer
Strong answer PUT replaces the whole representation at that URL with the body I send, so the client must send every field and the result is idempotent by construction; it is right when the client owns the full state of the resource, such as a settings document.
PATCH sends a partial change; its semantics depend on the patch format — JSON Merge Patch, RFC 7386, says "set these fields, null means remove", and JSON Patch, RFC 6902, is a list of operations such as add, remove, replace, and test.
PATCH is right when clients update one or two fields of a large resource and I do not want them to race on fields they did not touch.
POST is for anything that is not a replace or a partial update: creating a new resource under a collection, triggering an action such as cancellation, or a computation.
Each promises something different to intermediaries: PUT may be retried, PATCH may not by default, and POST may not without an idempotency key.
One more distinction I would name is that PUT to a client-chosen URL can double as create-or-replace, which is useful for import jobs with stable external ids.
Land it If I cannot say which of the three I would retry safely, I have not finished designing the endpoint.
- "Show me a JSON Merge Patch and a JSON Patch for the same change, and tell me when you would pick each."
To change an order's note and clear its coupon, Merge Patch is
{"note":"Leave at door","coupon":null}, sent asapplication/merge-patch+json; null means remove, so it cannot set a field to a real null. JSON Patch, sent asapplication/json-patch+json, is an array:[{"op":"replace","path":"/note","value":"Leave at door"},{"op":"remove","path":"/coupon"}].I pick Merge Patch for typical forms because it reads like the resource and any client can build it. I pick JSON Patch when I need array element operations, when null is a legitimate value, or when I want the
testoperation as a precondition.In Spring, Merge Patch is trivial with Jackson's
readerForUpdating; JSON Patch needs a library such as json-patch and validation that the paths are allowed.- "A client sends a PUT with only half the fields. What happens, and is that the client's fault?"
By PUT semantics the server replaces the representation with what was sent, so every missing field becomes its default or null, and the client has just wiped data it did not mean to touch.
It is the client's fault by the letter of the standard, but it is my fault as a designer if the API made that easy. I mitigate in three ways. Required fields are validated so a half-body PUT gets 400 with the missing field names.
Fields the client may not set, such as
createdAtorid, are read-only in the OpenAPI schema and ignored or rejected. And if the resource is large, I offer PATCH so clients are not tempted to do read-modify-write on the whole thing.I would also require
If-Matchon PUT so a stale full-body write is caught as 412 rather than silently overwriting a concurrent change.- "When does PUT-to-create beat POST-to-create?"
When the client already owns a stable identifier for the thing.
An import of products from a partner catalogue where each product has the partner's SKU is the classic case:
PUT /partners/acme/products/SKU-123creates on the first call and replaces on the next, returning 201 then 200, and it is retry-safe with no idempotency key because the URL is the key.The same applies to configuration documents, user preferences, and anything keyed by a natural id. POST-to-create is right when the server assigns the id, which is the default for anything with an auto-generated key, and then I need the idempotency header to make it safe.
The trap with PUT-to-create is authorisation: a client that can PUT to any URL can create ids in someone else's namespace, so the path must be scoped to the caller.
Q4. "A colleague says 'DELETE is idempotent, so returning 404 on the second call violates HTTP'. Are they right?"
Reveal answer
Strong answer They are not. Idempotency in RFC 9110 is about the effect on the server's state, not about the response being identical.
After one DELETE and after two, the resource is equally gone, so the requirement is satisfied even though the first call returned 204 and the second returned 404.
What the standard does forbid is a second DELETE causing a different state change, for instance deleting the next item in a list.
That said, there is a pragmatic argument for returning 204 on a delete of an already-absent resource: many retry libraries treat 404 as an error, and a client that retried because the first response was lost will log a failure for a success.
Either choice is defensible; the rule is to document it and keep it consistent across the API. The one thing not to do is return 500, which invites more retries.
Land it Idempotent means same state, not same status — but choose the status your clients' retry logic will understand.
- "Which would you actually choose for a new API, 204 or 404 on the repeat delete, and why?"
For a new API I choose 204 on a delete of something already gone, and I write it in the conventions document. The reasoning is about who sees the response.
A human never does; a retry library, a service mesh, and a Terraform-style reconciler do, and all of them want "the world is now as you asked" to read as success.
Terraform providers, for example, treat a 404 on delete as success internally precisely because so many APIs return it, which tells me the natural expectation is 204.
The one case I would still return 404 is when the id is outside the caller's visible scope, because then I do not want to confirm anything about existence.
That is a permission answer, not an idempotency answer, and it is the same 404 I would return on GET.
- "Is DELETE with a request body legitimate?"
The standard says a body on DELETE has no defined meaning, and in practice many proxies, gateways, and client libraries drop it or refuse it.
Some cloud load balancers strip it silently, which makes for a confusing bug where the endpoint works from curl and fails in production. So I do not depend on it. If a delete needs a reason or options, I have two honest choices.
Put the small ones in query parameters, such as
DELETE /orders/42?reason=customer-request.Or, if it needs a real payload and should leave a record, model it as a POST that creates a cancellation or deletion request resource, which also gives me an audit trail and a place to put the idempotency key.
What I avoid is a DELETE whose behaviour changes depending on a body the network may not deliver.
- "Should a soft delete and a hard delete use the same method?"
Both are DELETE from the client's point of view, because the client asked for the resource to stop existing at that URL; whether the row is flagged or removed is an implementation detail. What matters is the observable contract afterwards.
After a soft delete, a GET returns 404 or 410, not the record with a
deleted: trueflag, unless the API deliberately exposes a trash concept.If it does expose one, I make it explicit:
DELETEmoves to trash,GET /orders/42returns 410 Gone with a link to/trash/orders/42, and aPOST /trash/orders/42:restorebrings it back. A permanent purge is then a DELETE on the trash resource.This keeps each method idempotent and lets the retention policy — say, purge after 30 days — be documented rather than discovered.
Q5 · Scenario. "An analytics dashboard shows a nightly spike of new 'draft reports' created at 2 a.m., all empty, all owned by the same monitoring user. No human is awake. What is happening?"
Reveal answer
Strong answer In order: the symptom is state changes with no human actor at a scheduled time, so the cause is automation touching an endpoint that changes state on read.
The evidence to collect is the access log for that user at 2 a.m., which I expect to show a synthetic monitor or uptime checker issuing GET requests against a URL like /reports/new or /reports?create=true.
The ranked causes: a GET endpoint that creates a draft as a side effect, which is a safe-method violation, so any monitor, prefetcher, or crawler triggers it; or a monitor misconfigured to POST a fixture body.
The fix is to make the creation a POST, return 405 for GET on that path, and delete the junk drafts by owner and time window.
Prevention: an automated check in CI that every GET handler in the codebase is free of write calls, plus a rule that synthetic monitors only hit endpoints marked safe in the OpenAPI document.
Land it A GET with side effects is a bug waiting for the first robot, and every network has robots.
- "You changed the endpoint to POST and the drafts still appear. What next?"
Then the writer is not the endpoint I changed. I would go back to the access log at 02:00 and list every request from that user, not just the one I suspected, and look for any GET that touches a report path.
Common second culprits are a GET on the report detail page that lazily creates a draft when none exists — a "get or create" helper in the service layer — or a GET on the list endpoint that pre-creates a draft for "new report" buttons.
If the log shows no GET writes at all, I check whether the monitor itself now sends POST, because someone may have "fixed" the monitor to match the new method.
Finally I check the database for the writer by adding the request id to the row via a JDBC interceptor, which ties each draft to the exact request that made it.
- "Is a GET that updates a 'last viewed' timestamp also a bug?"
It is a violation of safety in the strict sense, because the response is not the only effect. Whether it matters depends on who can trigger it.
If a monitor or prefetcher can, the timestamps become noise and any feature built on them, such as "recently viewed", is wrong.
The way I keep the feature and the safety is to make the write a side channel: the GET emits an event or an asynchronous fire-and-forget update that is de-duplicated by a short window, and it is skipped for requests that look automated, which I detect by the absence of a user session, a known monitor user agent, or the
Purpose: prefetchandSec-Purposeheaders browsers send on speculative loads.The state the client asked for is unchanged either way, which is the property intermediaries rely on.
- "How should synthetic monitors be configured so they cannot do this?"
Monitors should use a dedicated identity with read-only scopes at the token level, so even if they hit a writing endpoint the authorisation layer refuses.
The monitor's targets should come from the OpenAPI document, restricted to operations tagged safe, and a CI check should fail if a monitor config references an operation that is not a GET or HEAD.
For end-to-end checks that must exercise a write, such as "can we create an order", the monitor runs against a sandbox tenant whose data is purged nightly, and the writes carry a header the service uses to flag them as synthetic so they are excluded from analytics.
That last point is what would have made this dashboard spike impossible to misread: synthetic traffic that is labelled cannot masquerade as customer behaviour.
Q6. "How does an idempotency key store have to behave under concurrency, and where would you keep it?"
Reveal answer
The real test Whether you know the claim must be atomic and the record must outlive the request.
Strong answer The store must support an atomic "insert if absent" so that two identical requests arriving in the same millisecond cannot both believe they are first; in a relational database that is an INSERT into a table with a unique index on the key, and in Redis it is SET key value NX EX 86400.
The record needs three states: in progress, completed with the stored status and body, and failed. On a repeat during in-progress I return 409 so the client waits and retries; on completed I replay the stored response; on failed I let the client try again.
I also store a hash of the request body so a key reused with a different payload is rejected with 422 rather than silently returning the wrong order's response. Keys are scoped per client so two tenants cannot collide, and they expire after about 24 hours.
If the business write and the key store are in the same database, I do the key completion in the same transaction as the write, which is the only way to guarantee there is no window where the order exists but the key says in-progress after a crash.
Land it The key store is a tiny distributed lock with memory, and the transaction boundary is where its correctness lives.
- "Redis or the database for the key store — which do you pick and when?"
If the business write goes to a relational database, I put the key table in that same database, because then the claim and the write share one transaction and there is no crash window to reason about.
The cost is a row insert and update per request, which at thousands of requests per second is fine on a table with a unique index and a nightly purge.
I pick Redis when the write does not go to a transactional store at all — say, the operation calls a third-party payment provider — or when the volume is high enough that the database cannot spare the writes.
With Redis I accept the two-store problem and mitigate it with a short lease, a heartbeat, and a reconciliation loop keyed by the id stored on the business record.
I never use Redis without
appendonlypersistence for this, because losing the key store means every in-flight retry creates a duplicate.- "Walk me through the exact Redis commands for claim, complete, and replay."
Claim is
SET idem:{clientId}:{key} '{"state":"in_progress","hash":"…"}' NX EX 86400; if it returns nil the key exists and I read it.On read, if the state is in-progress I return 409 with
Retry-After: 1; if it is completed I compare the stored body hash to the incoming one, return 422 on mismatch, and otherwise replay the stored status and body.Completion is a single
SETof the same key with the response included, keeping the TTL withKEEPTTL, or better a small Lua script that checks the state is still in-progress before overwriting so a late completion cannot clobber a reconciled record.Failure is either a
DELso the client can retry, or a stored failure state if the failure was deterministic. Every command is a single round trip, and the Lua script is what makes complete-if-in-progress atomic.- "What happens at 10× the volume — a hundred thousand keys per second?"
The unique-index INSERT becomes a hot write on one B-tree, and the purge job becomes a large delete that fights with it.
At that scale I would move to Redis Cluster with the key hashed by client id so each shard sees a slice, keep the value small by storing only status, hash, and the resulting resource id rather than the full response body, and reconstruct the replay from the resource on a repeat.
I would set the TTL lower for low-value operations, and I would partition the database table by day if it stays in the database so the purge is a partition drop rather than a delete.
The other lever is scope: many operations do not need a 24-hour key at all, and a 5-minute window covers every retry schedule an SDK actually uses.
- "Why scope the key by client and not make it globally unique?"
Because a globally unique key means one client can collide with, or deliberately probe, another's.
If keys were global and tenant A happened to reuse the same UUID as tenant B — unlikely, but with client-chosen keys such as "order-1" it is certain — A would get B's stored response, which is a data leak.
Scoping the store by the authenticated client id, taken from the token and never from the request body, makes the key a namespace the client controls.
It also lets me set per-client policies, such as longer retention for a partner with slow retries, and count keys per client for abuse detection.
The practical cost is nothing: the composite of client id and key is the unique index, and the lookup is still a single point read.
Q7 · Design. "Design the retry policy for a client SDK you are publishing for a REST API. Which responses get retried, how, and how do you stop your own SDK from taking the API down?"
Reveal answer
Strong answer Requirements: retries must never duplicate a state change, must not amplify an outage, and must be predictable for the API team.
The design: retry only idempotent requests by default — GET, HEAD, PUT, DELETE — and POST only when the caller supplied an idempotency key, which the SDK generates automatically for create calls.
Retry on connection errors, on 429 and 503 honouring Retry-After when present, and on 502 and 504; never on 4xx other than 429, because the same request will fail again.
Use exponential backoff starting at 200 milliseconds, doubling to a cap of 5 seconds, with full jitter so a thousand clients that failed together do not retry together.
Cap at three attempts and at a total time budget the caller can set, so a 30-second deadline is not blown by retries. Send an X-Retry-Attempt header so the API team can measure retry storms.
Add a client-side circuit breaker: after a burst of failures, stop calling for 30 seconds and fail fast. What I would not do is retry on read timeouts for POST without a key, or implement retries at two layers, SDK and HTTP library, which multiplies attempts.
Land it A retry policy is a promise about load as much as about correctness, and jitter plus a budget is what keeps that promise during an outage.
- "Requirement change: the API is now called from a batch system that runs 10,000 requests a minute. Does the policy change?"
The shape stays but the numbers move.
With that many calls the retry budget matters more than per-request backoff: I would add a token-bucket retry budget in the SDK, the way Google's and Finagle's clients do, where retries may consume at most about 10% of the request rate.
That guarantees that even if every request fails, the SDK sends 1.1 times the normal load, not 4 times.
I would also raise the initial backoff to a second because a batch does not care about a second, honour
Retry-Afterstrictly, and add a shared circuit breaker across worker threads so 50 workers do not each discover the outage independently.And I would push the batch team toward a bulk endpoint, because 10,000 single requests is the thing that makes retries dangerous in the first place.
- "Under time pressure, what would you ship first and what would you cut?"
First: retry only idempotent methods plus keyed POSTs, exponential backoff with full jitter, a cap of three attempts, and honouring
Retry-After. That is a day's work and it removes the two ways an SDK harms an API: duplicated writes and synchronised retry waves.I would cut the client-side circuit breaker, because the backoff and attempt cap already bound the damage and the breaker needs tuning that I would get wrong on day one.
I would also cut the total time budget if the language's HTTP library lacks a clean deadline abstraction, and document that callers should wrap calls in their own timeout.
The
X-Retry-Attemptheader stays because it is one line and it is the thing that lets the API team see the SDK's behaviour in production.- "Why full jitter rather than plain exponential backoff?"
Plain exponential backoff without jitter means every client that failed at the same instant retries at the same instant, so the outage arrives at the server as a series of synchronised waves at 200 milliseconds, 400, 800, and so on.
Each wave is as large as the original burst, and the server's recovery keeps getting knocked over. Full jitter picks the sleep uniformly at random between zero and the exponential ceiling, so the retries spread across the whole window.
The AWS Architecture Blog measured this: full jitter completed the same work with the fewest total calls and the lowest peak load compared with no jitter and with "equal jitter".
The cost is that some individual retries happen sooner than the ceiling, which is fine because the aggregate is what protects the server.
- "How do you test that the SDK's retry behaviour actually matches the policy?"
I test it against a fake server, not a real one. WireMock or a small in-process HTTP stub can be scripted to return 503 twice then 200, to return 429 with
Retry-After: 2, to close the connection mid-response, and to time out.The tests assert the number of attempts, the sequence of sleeps captured through an injected clock rather than real waiting, and that a POST without a key is never retried on a read timeout.
For the aggregate behaviour I run a small load test with a thousand simulated clients against the stub and plot the retry arrival distribution, which is the only way to see whether jitter is doing its job.
In production I confirm the same thing by graphing requests grouped by the
X-Retry-Attemptheader during a real incident.
Q8. "What is the difference between a client timeout, a server timeout, and a deadline, and why does the distinction matter for a chain of three services?"
Reveal answer
Strong answer A client timeout is how long the caller waits before giving up on a response. A server timeout is how long a server will spend on one request before abandoning it.
A deadline is an absolute point in time by which the whole operation must complete, carried with the request and inherited by every downstream call.
The distinction matters in a chain because per-hop timeouts do not add up: if the gateway waits 3 seconds, service A waits 3 seconds on B, and B waits 3 seconds on C, then C can be working on a request the user gave up on six seconds ago, and A can be retrying B after the gateway already returned 504.
With a deadline of 3 seconds propagated as a header, B receives "you have 1.2 seconds left", C receives "you have 0.4", and each abandons work the instant it cannot finish in time.
gRPC carries deadlines natively and cancels the server-side context; in REST I would send an X-Deadline or use the OpenTelemetry baggage header and enforce it in a filter.
Land it Timeouts protect one hop; deadlines protect the user, and they are the only way a chain fails fast instead of failing late.
- "How do you propagate a deadline in a Spring REST service, concretely?"
The gateway stamps an absolute deadline as a Unix millisecond timestamp in a header, say
X-Request-Deadline, computed as now plus the route's budget. A servlet filter in each service reads it, stores it in a request-scoped holder, and immediately answers 504 if it is already past.Every outbound call computes the remaining time as deadline minus now and sets that as the HTTP client's response timeout — with
RestClientthat is a per-requestClientHttpRequestFactorysetting, or with WebClient a.timeout(Duration)on the reactive chain — and forwards the same header unchanged.Database calls get
Statement.setQueryTimeoutfrom the same remaining value. Absolute timestamps require reasonably synchronised clocks; if I cannot rely on that, I propagate a remaining-milliseconds header and subtract the local elapsed time at each hop, which is what gRPC does under the hood.- "What is the right timeout for each hop if the user budget is 3 seconds?"
The wrong answer is 3 seconds at every hop, and the second wrong answer is dividing 3 by the number of hops evenly.
The right approach is to set each hop's timeout from observed latency: roughly the p99.9 of that call plus a margin, so a healthy dependency almost never trips it, and then check that the sum along the critical path fits inside the budget with room for one retry of the cheapest hop.
If the sum does not fit, the design has too many sequential hops or the budget is unrealistic, and no timeout setting fixes that.
In practice, I set the static timeouts as a safety net and let the propagated deadline be the real bound, so a hop that inherited only 400 milliseconds uses 400 rather than its static 1-second value.
- "Once a deadline passes, what does the server actually do with the work in flight?"
Ideally it stops. In gRPC the server context is cancelled and well-written handlers check it between steps.
In a servlet-based Spring service, nothing cancels automatically, so I have to build the checks in: before starting a database query, before an outbound call, and inside long loops, the code asks the deadline holder whether time remains and throws a dedicated exception if not.
Database queries carry a statement timeout so they die on their own.
What I do not do is let the request thread keep running to completion and write a response nobody will read, because that is the "work amplification" that turns a slow period into an overloaded one.
I also log a distinct metric for deadline-exceeded versus other errors, because a rise in that metric is the earliest sign of an upstream slowdown.
- "Does this interact with retries?"
Yes, and it is the interaction that causes retry storms. A retry must fit inside the remaining deadline or it should not happen at all, because a retry that cannot possibly finish in time is pure load.
So the retry logic asks for the remaining budget before each attempt and gives up early with the original error if there is not enough left for at least one full attempt at the p99 latency.
Likewise, the deadline header is forwarded on the retry unchanged, not reset, so the downstream still sees the user's real remaining time.
The failure I have seen is a client library whose timeout restarts on each retry, so a 3-second timeout with three retries becomes 9 seconds of the user waiting, and every service in the chain is still working on the first attempt.
Status codes are the part of your response that every cache, retry library, and alert rule reads without parsing JSON. This group checks that you choose them for those readers, not for humans.
Q9. "401 versus 403 — and why does getting them backwards cause real incidents?"
Reveal answer
Strong answer 401 Unauthorized means "I do not know who you are": no credentials, or credentials I could not validate, and it must carry a WWW-Authenticate header saying what kind of credential is expected.
403 Forbidden means "I know who you are, and you may not do this". The name of 401 is misleading, because it is about authentication.
The incidents come from client logic: SDKs and browsers treat 401 as "refresh the token and try again", so a 401 returned for a permission problem triggers a refresh loop that hammers the identity provider, and a 403 returned for an expired token means the client never refreshes and the user is logged out for no reason.
There is also an information-leak angle: for private resources some APIs return 404 instead of 403 so a caller cannot probe which ids exist, which GitHub does deliberately.
Land it 401 tells the client to fix its credentials; 403 tells it to stop asking — mixing them up turns a policy decision into a retry storm.
- "An expired token — is that 401 or 403?"
401, with
WWW-Authenticate: Bearer error="invalid_token", error_description="expired", which is the format RFC 6750 defines for bearer tokens.The reasoning is that the client's credentials are not currently valid, and the recovery is to obtain new ones, which is exactly what clients do on 401: refresh the access token using the refresh token and retry once.
Returning 403 here strands the user because the client believes it is authenticated and has been refused, so it will not refresh.
The other common mistake is a 401 for an insufficient scope, where the token is perfectly valid but lacks permission; that is 403 with
error="insufficient_scope", again from RFC 6750, so the client can tell the user to grant more rather than looping on refresh.- "How do you stop the refresh loop once it has started?"
On the server, correct the status code, which stops new loops. On the client, an SDK should refresh at most once per request: if the retried request after a refresh returns 401 again, give up and surface the error rather than refreshing forever.
The identity provider side needs rate limiting on the token endpoint per client, so a single bad deployment cannot take down authentication for everyone.
To verify in production, I graph the ratio of token refreshes to API requests; a healthy client refreshes once per token lifetime, so a ratio near one-to-one is a loop.
When I inherited an API with this bug, the tell was that the identity provider's load followed the API's error rate exactly, which is the signature of clients treating an authorisation failure as an authentication failure.
- "When would you deliberately return 404 instead of 403?"
When confirming that a resource exists is itself a leak. Private repositories, other tenants' orders, user accounts by id: an attacker who gets 403 on
/users/1234and 404 on/users/1235has learned that 1234 exists, which feeds enumeration and phishing.GitHub returns 404 for private repositories you cannot see for exactly this reason. The cost is worse debugging for legitimate users who have mistyped a permission, so I pair it with a clear message in the support channel.
I keep 403 for cases where the resource is not secret but the action is, such as a customer trying to refund their own order, because there the existence is already known and a 404 would be a lie that sends the client's code down the wrong path.
Q10 · Scenario. "Your dashboards show 99.99% success for the checkout API while support is flooded with 'checkout failed' tickets. The API is returning HTTP 200 for every request. Diagnose."
Reveal answer
Strong answer The symptom is a disagreement between the transport-level metric and reality, which almost always means errors are hidden inside successful responses.
Evidence: sample response bodies for the affected users and look for a field such as "success": false or "error" inside a 200; check whether the gateway metric is counting HTTP status only.
The ranked causes: first, the service wraps every outcome in 200 with an application-level status, so 5xx alerts, retry logic, and the CDN all see success; second, a resilience layer such as a fallback returns an empty 200 on downstream failure; third, an upstream proxy rewrites errors.
The fix in two steps: immediately, add a metric derived from the body's error field so the dashboard tells the truth; then change the API to return real status codes with RFC 9457 Problem Details, versioned so existing clients that parse the wrapper are not broken.
Prevention: an API linting rule that forbids 200 responses whose schema contains an error field, and an SLO defined on business success, not HTTP status alone.
Land it A 200 with an error inside is an outage that has been told to hide from monitoring.
- "You cannot change the response shape because thousands of clients parse the wrapper. What is your migration path?"
I would fix observability first and the contract second. Day one: the gateway or a servlet filter inspects the body's
successfield and emits a metric and a log field, so dashboards and alerts stop lying even though the wire format has not changed.Week one: the service adds a response header, say
X-Outcome: error, alongside the 200, and the SLO is redefined on that.Then the real change is a new version that returns proper status codes, offered under
/v2or a version header, with the SDKs updated to use it, and the old wrapper version kept alive under the deprecation policy.The one thing I would not do is flip the status codes in place, because clients that check
response.successand never look at the status would suddenly get exceptions from their HTTP library on every failure.- "You fixed the metric, and it shows 4% failures, but support says it is more like 15%. What next?"
Then some failures are not even in the body.
The candidates are a timeout at the client that the server never sees as a failure — the server returns 200 after the user gave up — and failures at a layer in front of the service, such as a CDN or gateway returning its own error page that never reaches the application log.
I would compare the client-side success rate from the mobile and web apps' own telemetry with the server-side rate; the gap is the failures that happen in the network or after the response.
I would also check the gateway's logs separately from the service's, because a 5xx generated by the load balancer for a timed-out upstream is usually logged only there.
And I would look at the checkout funnel: a "failed" ticket may be a user who never received a confirmation email even though the API succeeded.
- "Why is a 200-with-error worse than just a wrong number on a dashboard?"
Because everything that reads status codes without parsing JSON makes the wrong decision. Retry libraries do not retry, so transient failures become permanent for the user.
CDNs and proxies cache the failure body if the response is cacheable, so one failed request can be served to many users. Circuit breakers never open, so a dead downstream keeps receiving traffic. Alerting never fires, which is what happened here.
Load balancers doing health checks see a healthy instance. Even logs sampled by status code miss the failures. Each of those systems is a consumer of the contract that the service silently broke.
The dashboard is the symptom people noticed; the retry and caching behaviour is the damage they did not.
- "How do you write the lint rule that prevents this?"
With Spectral over the OpenAPI document. A custom rule targets every
responses.200schema and fails if it contains a property namederror,errors,success, orstatuswith a string enum that includes an error-like value.A second rule requires that every operation declares at least one 4xx response with the Problem Details schema, which nudges authors toward real codes. The rule runs in CI on the generated document, so code-first teams are caught too.
It is not airtight, since a team could name the field
outcome, so I pair it with a runtime check in staging: a response validator that samples 200s and flags bodies where a known error type registry entry appears.Both together make the wrapper pattern a conscious exception rather than an accident.
Q11. "When do you return 400, 409, 412, and 422, and why do clients care which one they get?"
Reveal answer
Strong answer 400 Bad Request is for input the server cannot parse or that violates the syntax of the contract — malformed JSON, a string where an integer belongs, a missing required parameter.
422 Unprocessable Content is for input that parses fine but fails a business rule — a negative amount, an end date before a start date.
409 Conflict is for a clash with the current state of the resource — a duplicate unique key, trying to ship an order that is already cancelled, an in-progress idempotent request.
412 Precondition Failed is specifically for a failed conditional header — If-Match did not match the current ETag, so someone else changed the resource since the client read it.
Clients care because each implies a different recovery: 400 means fix the code, 422 means show the user a validation message from the errors array, 409 means re-read the resource and decide, 412 means re-read and merge, and none of them should ever be retried as-is.
Land it Four codes, four recoveries — if two of them would make the client do the same thing, I have over-designed; if 500 covers all four, I have under-designed.
- "Where does 404 fit when the id in the body, not the path, refers to something that does not exist?"
404 is about the request target, which is the URL. If
POST /ordersreferences aproductIdthat does not exist, the URL is fine and the body is semantically wrong, so I return 422 with anerrorsentry pointing at/items/0/productIdand a message such as "unknown product".Returning 404 there confuses clients, because their generic handler will conclude that the orders endpoint itself is missing.
The same goes for a foreign reference the caller is not allowed to see: I still say 422 with "unknown product", not 403, so I do not confirm the product exists in another tenant.
The rule I use is that 404 describes the path, 422 describes the body, and 409 describes the state of the thing the path points to.
- "How does this map to exceptions in a Spring application?"
Spring MVC already produces 400 for unreadable JSON via
HttpMessageNotReadableExceptionand for a failed@ValidviaMethodArgumentNotValidException, and withspring.mvc.problemdetails.enabled=trueboth come back as Problem Details. I map the rest myself in a@RestControllerAdvice: a domainValidationExceptionto 422 with the field errors, aStateConflictExceptionto 409, anOptimisticLockingFailureExceptionfrom the JPA version check to 412 if the client sentIf-Matchor 409 if it did not, and aDataIntegrityViolationExceptionfrom a unique index to 409. The important discipline is that the domain layer throws typed exceptions with a machine-readable code, and only the advice layer knows about HTTP, so the same domain can sit behind gRPC with a different mapping.- "Should validation stop at the first error or report all of them?"
Report all of them at the level where it is cheap: syntactic and constraint checks, which run in memory, should collect every failure so a form can show every red field in one round trip.
Business rules that need database lookups — is this product in stock, is this coupon valid — are checked in order and may stop at the first, because each is a query and a body with twenty problems should not cost twenty queries.
In Bean Validation that is the default: all constraints on a payload are evaluated and returned as a set. For the business layer I collect what I can within a single transaction and return them together.
The response shape is identical in both cases, an
errorsarray, so the client does not care which layer produced it.
Q12. "Explain RFC 9457 Problem Details. What goes in each member, and what do you add for validation errors?"
Reveal answer
Strong answer Problem Details is the standard JSON error body, media type application/problem+json, published as RFC 9457 in 2023 as a clarified successor to RFC 7807.
type is a URI that identifies the category of problem and ideally resolves to documentation — I use stable URLs such as https://api.example.com/problems/insufficient-funds, and clients switch on this field, never on the human text.
title is a short summary that is the same for every occurrence of that type. status repeats the HTTP status so a body that is logged or forwarded still carries it. detail is the human explanation of this specific occurrence and may contain values.
instance identifies this occurrence — I put the request id there so support can find the logs. For validation I add an errors array of objects with field, using a JSON Pointer such as /items/2/quantity, and message, and sometimes code for machine matching.
Spring Boot 3 and later produce this natively via ProblemDetail and spring.mvc.problemdetails.enabled.
Land it One error shape means one client-side handler, and a stable type URI is what stops clients from parsing English.
- "Should the type URI actually resolve, and what happens if the domain changes?"
The RFC says the type is an identifier and resolving it is optional, but I make it resolve to a documentation page because that turns every error into a link support can send.
The risk is that the domain changes and the identifier must not, so I use a path under a domain I control for the long term, such as
https://problems.example.com/insufficient-funds, and I treat the string as immutable even if the page moves behind a redirect.Some teams use a tag URI or a relative reference like
/problems/insufficient-funds, which the RFC allows and which is resolved against the request URL; I avoid that because a client logging the body loses the context.The registry of types lives in the OpenAPI document as an enum-like list so SDKs can generate constants from it.
- "How do you keep detail from leaking internals, and what about localisation?"
detailis written by the handler for that error type, never taken from an exception message, so a stack trace or SQL fragment cannot end up in it.My advice class has a default mapping for unexpected exceptions that returns
about:blankas the type, 500, and a detail of "Unexpected error; reference {instance}" with the request id, and logs the real exception server-side.For localisation, I keep
detailin English and treat it as developer-facing. Clients that need to show users a message look up thetypein their own translation table, which is more robust than trusting server text and lets each client phrase things for its audience.If a product truly needs server-side localised text, I add an extension member such as
userMessagechosen byAccept-Language, and declareVaryaccordingly.- "How do you make sure every error path in the service produces this shape and not a framework default?"
Three layers. First, a single
@RestControllerAdvicewith a catch-all forThrowableso nothing reaches the container's default error page.Second, the container's own error handling — Tomcat's error page for a 404 on an unknown route or a 413 for a too-large body — is configured to return a Problem Details body too, in Spring via a custom
ErrorControlleror by enablingspring.mvc.problemdetails.enabledand settingserver.error.whitelabel.enabled=false.Third, the gateway in front is configured with the same shape for the errors it generates itself, such as 401 for a missing token, 429, and 504.
Then a test walks the OpenAPI document and asserts that every non-2xx response schema references the Problem Details component, and an integration test hits an unknown URL, sends malformed JSON, and forces a 500, checking that all three return
application/problem+json.- "What did RFC 9457 change versus 7807?"
Very little on the wire, which is the point; it is a clarification and a registry. The JSON shape and the five standard members are the same, so a 7807 client is a 9457 client.
The main additions are an IANA registry for common problem types so that widely used types can be shared across APIs, guidance that
typedefaults toabout:blankwhen absent, and clearer rules for extension members and for the XML form.It also clarifies that a problem type may define extension members of its own, which is where my
errorsarray sits. So as of Aug 2026, I reference 9457 as the current number, and I do not expect any client to notice the difference.
Q13 · Scenario. "A batch import client sends 5,000 requests a minute and starts getting 429s. The client team says 'your API is broken'. The API team says 'we told you 3,000 per minute'. What do you check, and what should the API have done better?"
Reveal answer
Strong answer Symptom: a client exceeding its documented quota and receiving the correct code.
Evidence: confirm the 429 responses carry Retry-After and the draft RateLimit headers stating limit, remaining, and reset; check whether the client honours them or retries immediately, which would explain why it feels broken — immediate retries on 429 count against the quota and keep it pinned at zero.
Causes ranked: the client ignores Retry-After; the client runs parallel workers with no shared budget; the API's limit is per instance rather than per client, so it varies by which node the request lands on.
The fix on the client side is to read the headers and pace.
What the API should have done better: publish the limit in the OpenAPI document and the SDK, expose the remaining quota on every response, not just the 429, so a well-behaved client slows down before hitting zero, offer a bulk endpoint that accepts 1,000 rows per request so an import is 5 calls not 5,000, and make the limit per client key at the gateway, backed by a shared store, so it is consistent.
Land it A 429 is the API being polite; the design failure is making the client discover the limit by hitting it.
- "The client added Retry-After handling and still sees 429s at 2,900 per minute. What next?"
Below the documented limit and still rejected means the limiter is not counting what they think it counts.
I would check whether the limit is enforced per gateway instance rather than in a shared store, because then each instance has a fraction of the budget and the client's traffic is spread unevenly across them.
I would check the window type: a fixed one-minute window aligned to the clock can reject a burst that is legal on average. I would check whether preflight OPTIONS, retries, or health checks from the same key are counted.
And I would check whether the limit is shared across the client's several API keys or environments, so their staging job is spending the production budget.
The verification is the
RateLimit-Remainingheader on their responses, which should decrement in lockstep with their own counter; where it diverges is where the extra usage is coming from.- "What do the RateLimit headers look like, and are they standard?"
As of Aug 2026 they are an IETF HTTP APIs working group draft,
draft-ietf-httpapi-ratelimit-headers, so they are widely implemented but not yet an RFC number.The current draft form is a structured
RateLimit-Policyheader describing the quota, for example"default";q=3000;w=60for 3,000 per 60 seconds, and aRateLimitheader with the live state, such as"default";r=2400;t=37meaning 2,400 remaining and a reset in 37 seconds.Older deployments use the earlier
X-RateLimit-Limit,X-RateLimit-Remaining, andX-RateLimit-Resettrio, which is what GitHub still sends.Whichever form I choose, the point is to send it on every response, because a client that learns its remaining budget from a 200 can pace itself before it hits zero.
- "How should the client pace 5,000 items if the limit is 3,000 per minute?"
The simple version is a local token bucket set to the published rate, which spreads the calls evenly at fifty per second and finishes in under two minutes with zero 429s.
The better version reads
RateLimit-Remainingand the reset time from each response and adapts, which handles the case where the limit changes or other processes share the key.With parallel workers, the bucket must be shared, in a single process or through a small coordinator, otherwise each worker paces independently and the total exceeds the limit.
And the best version is not to send 5,000 calls: if the API offers a batch endpoint that accepts 1,000 rows, the import becomes five requests. That is why I said the API team owes them a bulk endpoint, not just headers.
- "Should a 429 count against the quota?"
The request was rejected cheaply, so in fairness it should not consume a token, and most token-bucket implementations do not deduct on rejection.
But it is not free: the gateway did work, and a client that retries instantly on 429 can generate thousands of rejections a second.
So I keep the quota untouched by 429s, but I apply a separate, much stricter limit on the rate of rejections per client, and beyond that I slow the responses down or temporarily block the key with a longer
Retry-After.That distinguishes a client that is slightly over its limit, which should be nudged, from one that is hammering, which should be stopped.
I also log 429 rate per client as its own metric, because a client whose rejection rate is high is a client whose engineers need an email.
Q14. "When is 202 Accepted the right answer, and what must the response contain to be usable?"
Reveal answer
Strong answer 202 is right when the work will take longer than a client should hold a connection — anything over a few seconds, such as generating a report, provisioning a resource, or running a bulk import.
It means "I have accepted this and will do it; here is how to follow along". To be usable it must include a Location header pointing at an operation resource, for example /operations/7a3f, and ideally a body with the operation id and an estimated wait.
The operation resource exposes status as queued, running, succeeded, or failed, a progress figure if available, the error in Problem Details form on failure, and a link to the result on success. Polling gets a Retry-After hint so clients do not hammer it.
The operation should also be idempotent to create — the same idempotency key returns the same operation — because clients will retry the initial POST. Webhooks are the push alternative for clients that can receive them.
Land it 202 without a Location is a shrug; with one, it is the long-running-operation pattern that every cloud API converged on.
- "What if the same endpoint is sometimes fast and sometimes slow — do you return 201 or 202?"
I make the contract accept both and document it, the way cloud APIs do: if the work completes within a short synchronous budget, say two seconds, return 201 with the resource and a
Locationto it; otherwise return 202 with aLocationto the operation.The client code handles both branches with the same helper: on 201 it is done, on 202 it polls the operation until it reaches a terminal state and then follows the result link.
The alternative, always returning 202 even when the work is done, is simpler to document and lets the client have a single path, at the cost of an extra round trip on the common case.
For a public API I prefer the always-202 form for that one endpoint, because "sometimes synchronous" is where integrators write the bug that only fires under load.
- "How does the client know when to stop polling if the job never finishes?"
The operation resource must reach a terminal state on its own.
My worker framework has a maximum run time per job type, after which the job is marked failed with a Problem Details error of type
operation-timed-out, and a sweeper marks any operation whose worker heartbeat has stopped as failed too, so a crashed worker does not leave the client polling forever.The client side gets a documented maximum, such as "operations complete or fail within 30 minutes", and the SDK's wait helper has its own deadline that throws rather than looping past it.
The
Retry-Afteron each poll grows with the age of the operation, so a long job is polled every 30 seconds rather than every second. I would also expose the operation'sexpiresAtso the client knows when the record itself will be gone.- "Is 202 cacheable, and what about intermediaries?"
202 is not cacheable by default and I would never make it so, because it is a receipt for a specific request.
The operation resource behind it, though, is a normal GET, so I set
Cache-Control: no-storeon it while it is in progress, and I can allow short caching once it reaches a terminal state because that state will never change.The one intermediary interaction that bites is a proxy timeout: if the initial request itself takes longer than the proxy's timeout while trying to do the work synchronously, the client gets a 504 with no operation to follow.
That is why the decision to go asynchronous must happen before the work starts, based on an estimate, not after the synchronous attempt has already burned the budget.
Q15. "What is the difference between 502, 503, and 504, and which of them should page someone?"
Reveal answer
Strong answer All three are generated by something in front of your service or by the service saying it cannot serve. 502 Bad Gateway means the proxy got an invalid or no response from upstream — usually the process crashed, is not listening, or returned garbage.
503 Service Unavailable means the server is up but cannot take the request right now — overloaded, in maintenance, or a circuit breaker is open — and it should carry Retry-After.
504 Gateway Timeout means upstream did not answer within the proxy's timeout — the service is alive but slow, or a downstream of it is.
For paging: a sustained 502 rate means instances are dying, page immediately; 504s mean latency has crossed the proxy timeout, page if the error budget is burning; 503s are often deliberate load shedding and should alert on rate rather than presence.
All three are retryable from the client's point of view with backoff, which is why load shedding with 503 is a safe way to tell clients to back off.
Land it 502 is dead, 504 is slow, 503 is busy — and the on-call response is different for each.
- "How do you tell whether a 502 came from your load balancer or from your service?"
By where it is logged and by the body.
A 502 generated by the balancer appears in the balancer's access log with an upstream status of nothing or a reset, and never in the application log, and its body is the balancer's default page or a tiny JSON of its own.
A 502 that came through from an upstream proxy inside the service, such as a sidecar, appears in both. In AWS the ALB logs show
target_status_codeas a dash for a target that did not answer, and a metric namedHTTPCode_ELB_502_Countas opposed toHTTPCode_Target_5XX_Count.I also configure the balancer to add a header naming itself on errors it generates, and I make sure my service never returns 502 itself, so the code alone tells me the layer.
- "An instance returns 503 from its health check on purpose during deployment. Is that the same 503?"
It is the same status but a different audience. A health-check 503 is aimed at the balancer, which stops routing to that instance, and no client ever sees it. A request-path 503 is aimed at the client, and it should carry
Retry-After.The point of using 503 on the health endpoint during shutdown is graceful draining: the instance fails its health check first, waits for in-flight requests to finish and for the balancer to notice, then exits.
Spring Boot exposes this as the readiness state; setting
server.shutdown=gracefulplus the actuator readiness probe handles it.The mistake is a single health endpoint used both for liveness and readiness, because then a readiness 503 during startup can make an orchestrator kill a perfectly good instance that was still warming up.
- "Which of the three should a client retry, and how quickly?"
All three are retryable in principle because none means the request was wrong. 503 with
Retry-Afteris the clearest: wait that long, then retry.502 without a hint usually means an instance is down and the balancer will route the retry elsewhere, so a short backoff of a few hundred milliseconds with jitter is fine.
504 is the dangerous one to retry quickly, because the upstream may still be working on the original request, so a retry doubles its load; I use a longer backoff and, for non-idempotent requests, only retry with an idempotency key.
If a client sees a sustained mix of 504s, the right move is to back off hard or open a circuit breaker, because retries at that point are what keep the upstream from recovering.
Q16 · Design. "Design the error contract for a new public API: the shape, the taxonomy of error types, and how it evolves without breaking clients."
Reveal answer
Strong answer Requirements: one parser for all errors, machine-readable causes, human-readable details, support traceability, and additive evolution.
The shape is RFC 9457 Problem Details on every non-2xx response, with type as a stable URI, title, status, detail, instance holding the request id, plus an errors array for field-level validation.
The taxonomy is a registry of type URIs grouped by recovery: client-fixable (validation, malformed), state conflicts (duplicate, stale version, invalid transition), authorisation (unauthenticated, forbidden, scope-missing), quota (rate-limited, plan-limit), and server (internal, dependency-unavailable), each mapped to one status code and documented at the URI. Evolution rules: new types may be added at any time and clients must treat unknown types as their status code's generic case; existing types never change meaning; detail text is never stable and clients must not parse it; new members may be added.
I would not use numeric error codes with no documentation URL, nor a different envelope per endpoint, nor localised messages in detail — localisation is the client's job from the type.
Land it The error contract is the part of the API clients depend on most under stress, so it gets the strictest compatibility rules of all.
- "Requirement change: the API now has to be consumed by an embedded device with 32 KB of RAM. Does the error contract change?"
The shape stays, because Problem Details is already small, but I add rules to keep it bounded. Every error response carries a maximum body size, say 2 KB, with
errorsarrays truncated to the first ten entries and atruncated: trueextension member.The
typeURI is replaced or supplemented by a short numericcodeextension so a device does not have to store long strings for comparison.I would also promise that the five standard members are always in the same order, which is not required by JSON but lets a streaming parser on a tiny device stop early.
And I would offer CBOR as an alternative encoding negotiated by
Accept, which the RFC anticipates. What I would not do is invent a separate error format for the device, because then the SDK has two parsers and the taxonomy splits.- "Under time pressure, what would you cut from this design?"
I would keep the shape and the status mapping, because those are the parts clients build against and the hardest to change later.
I would ship a small initial type registry — perhaps eight types covering validation, not-found, conflict, unauthenticated, forbidden, rate-limited, internal, and dependency-unavailable — and let the rest be added additively, since adding a type is safe by the evolution rules.
I would cut the resolving documentation pages and point every type at a single page with anchors for now. I would cut localisation entirely. The evolution rules themselves are a paragraph and cost nothing, so they stay.
The thing I would refuse to cut is the CI test that every non-2xx response is Problem Details, because a single endpoint that returns a different shape is what forces every client to write two handlers.
- "How do you version the error contract itself if you ever need to?"
I try never to. The rules I set — types are added, never removed or repurposed; members are added, never removed;
detailis never stable — mean the contract only grows, and a growing contract needs no version.If a type genuinely must change meaning, I introduce a new type with a new URI and mark the old one deprecated in the registry, so old clients keep seeing the old type until their major version is retired, and the translation layer per API version chooses which to emit.
The media type parameter
application/problem+jsonstays the same throughout. Changing the envelope, for example dropping Problem Details for something else, would be a major version of the whole API, and I would treat that as the thing my design exists to avoid.- "How do clients discover which error types an endpoint can return?"
Through the OpenAPI document. Each operation lists its possible responses by status, and I make the Problem Details schema for each include an enum-like
x-problem-typesextension listing the type URIs that operation can produce, so the SDK generator can emit typed exceptions or constants.The full registry lives in a components section referenced from every response.
For the long tail, the contract states that any operation may return the generic types for its status class, so a client is never surprised by, say, a 503 on an endpoint that did not list it.
I also publish a changelog entry whenever a type is added, because "additive" does not mean "invisible", and a client author who reads the changelog can add a specific handler before the type starts appearing.
This group tests whether you can make a read endpoint nearly free and a write endpoint safe using headers that already exist — and whether you know the ways a cache can leak data.
Q17. "Walk me through a conditional GET with ETags end to end. What does the server still have to do on a 304?"
Reveal answer
Strong answer On the first GET the server computes an ETag — a short opaque string identifying this exact version, such as the row's version number in quotes or a hash of the body — and sends it in the ETag header with the 200.
The client stores the body and the tag. On the next GET it sends If-None-Match: "v17". The server loads enough state to compute the current tag, compares, and if equal answers 304 Not Modified with no body; the client reuses its copy.
If different, it answers 200 with the new body and tag.
What the server still does on a 304 is the lookup and the comparison — it saves the serialisation, the compression, and the bytes on the wire, but not the database read unless the tag can be computed from a cheaper source such as a cached version number.
A weak ETag, prefixed W/, says "semantically the same" and allows byte differences such as whitespace; a strong one promises byte equality and is required for range requests. Shared caches such as CDNs can also revalidate with the origin using the same header.
Going deeper The cheapest correct ETag is a version column, not a body hash.
If orders.version increments on every write, the tag is "17", and on a conditional GET the server runs SELECT version FROM orders WHERE id = ?, a single indexed point read that never touches the joined data, and returns 304 if it matches.
A body hash forces the full load and serialisation before the comparison, which is why teams that hash see no CPU saving from ETags.
For a collection response the tag can be the maximum version or updated_at across the members plus the count, so a change to any member invalidates the page.
The verification step is a load test with a client that always sends If-None-Match: bytes out should drop to near zero, and database time per request should drop to the cost of the version read; if database time does not move, the tag is computed too late.
Going deeper The cheapest correct ETag is a version column, not a body hash.
If orders.version increments on every write, the tag is "17", and on a conditional GET the server runs SELECT version FROM orders WHERE id = ?, a single indexed point read that never touches the joined data, and returns 304 if it matches.
A body hash forces the full load and serialisation before the comparison, which is why teams that hash see no CPU saving from ETags.
For a collection response the tag can be the maximum version or updated_at across the members plus the count, so a change to any member invalidates the page.
The verification step is a load test with a client that always sends If-None-Match: bytes out should drop to near zero, and database time per request should drop to the cost of the version read; if database time does not move, the tag is computed too late.
Land it ETags cut transfer and CPU, not the lookup — to cut the lookup you cache the tag itself.
- "What headers must accompany a 304, and what goes wrong if you send the wrong ones?"
A 304 must repeat the
ETag, and it should repeatCache-Control,Expires, andVaryif they would have been sent with a 200, because the cache updates its stored entry's metadata from the 304 — that is how a revalidation extends the freshness lifetime.It must not carry a body or a
Content-Lengthfor a body that is not there; some frameworks leak the originalContent-Lengthand confuse HTTP/1.1 clients into waiting for bytes.It also must not send a different
ETagfrom the one that matched, which happens when the tag is computed from something non-deterministic such as map iteration order.The check I run is a curl with
-i -H 'If-None-Match: "17"'and I look at exactly what came back.- "How does this interact with compression? The ETag differs between gzip and identity."
Strictly, a strong ETag identifies the exact bytes of the representation, and gzip bytes differ from identity bytes, so a compliant server sends different strong tags per encoding. Apache does this by appending
-gzip.Where it goes wrong is a CDN that revalidates upstream with the tag from a gzip response while requesting identity, or Nginx, which by default strips the ETag from responses it compresses on the fly unless it is a weak tag.
The practical answer is to generate a weak ETag,
W/"17", when the tag is a version number rather than a byte hash, because a weak tag means "semantically equivalent" and is valid across encodings.The cost is that weak tags cannot be used for byte-range requests, which an API resource never needs.
- "Last-Modified versus ETag — do you send both?"
I send both when I have both cheaply.
Last-Modifiedhas one-second granularity, so two writes within the same second are indistinguishable, and it cannot express "same content, different time".ETaghas neither problem.But some caches and older clients only understand
Last-ModifiedwithIf-Modified-Since, and the RFC says a client should send both preconditions if it has both, withIf-None-Matchtaking precedence on the server. So the server evaluates the tag if present and falls back to the date.The rule that matters is precedence: if the tag matches, it is a 304 regardless of the date, and if the client sends only a date, I compare with seconds truncated, not with the full-precision timestamp from the database, or nothing ever matches.
Q18 · Scenario. "Two users report seeing each other's account balance on the profile page. The API sets no cache headers. What happened and what is the fix?"
Reveal answer
Strong answer Symptom: personalised data served to the wrong person, which is the signature of a shared cache.
Evidence: check for a CDN or reverse proxy in front of the API, look at the response headers for Age or a cache hit header, and confirm the profile URL is the same for every user, for example /me/profile with identity in a cookie or bearer token.
Causes ranked: the proxy applied a default caching policy to a response with no Cache-Control, and because the URL is identical across users it served the first user's body to the second; a second cause is a Vary header missing when the response depends on Authorization.
The immediate fix is Cache-Control: private, no-store on every authenticated response, which forbids shared caches from storing it, and purging the cache.
Prevention: a gateway rule that adds no-store to any response on a path requiring authentication, and a test that fetches the same URL with two tokens and asserts different bodies.
A good default for any API is to set an explicit Cache-Control on every response so no intermediary has to guess.
Land it A missing cache header is not "no caching" — it is "let the proxy decide", and the proxy does not know which responses are personal.
- "You added Cache-Control: private, no-store and one user still reports seeing another's data. What next?"
Then either a cache is ignoring the header, or the cache is not an HTTP cache.
I would first confirm the header is actually reaching the edge with a curl through the public hostname, because a gateway between the service and the CDN can strip or override it.
Then I would look for an application-level cache: a Spring
@Cacheableon the profile service method keyed by nothing but the method name, or a Redis key likeprofile:currentthat omits the user id.Those are the more common cause in my experience and no HTTP header touches them.
I would also look at connection-level state, such as a thread-local holding the previous request's user that was not cleared, which shows up as "the previous request's data" rather than random users.
The evidence is which other user's data is seen: random means shared cache, previous request means thread-local.
- "How do you purge the CDN and know it worked?"
Every CDN has a purge API by URL or by cache tag; I purge the profile path and, because the URL is identical for every user, one purge clears the poisoned entry at every edge.
Then I verify from outside, not from the office network: fetch the URL through the CDN with two different tokens and compare bodies, and read the
Ageand cache-status headers, which should show a miss or a pass.I also count the responses in the CDN log that carried a cache hit for that path after the purge time; it should be zero.
Finally, I keep that two-token test as a permanent synthetic check running every minute, because it costs nothing and it would have caught this incident in sixty seconds rather than through a support ticket.
- "Is there a case where you would want to cache authenticated responses at the CDN?"
Yes, when the response is the same for everyone but the endpoint requires a token, such as a product catalogue behind an API key.
The standard way is
Cache-Control: public, max-age=60together with an explicit statement that the response does not vary by user, and configuring the CDN to ignore theAuthorizationheader in its cache key after validating it.RFC 9111 actually forbids a shared cache from storing a response to a request with
Authorizationunless the response sayspublicor has explicit freshness, so the header must be explicit.For genuinely per-user responses, I would not cache at a shared edge at all; the alternative is to key the cache by user id, which gives a hit rate near zero and just fills the cache with private data.
- "Why did the missing header default to caching rather than not caching?"
Because HTTP allows heuristic freshness. RFC 9111 permits a cache to estimate a freshness lifetime for a response that has no explicit expiry but does have a
Last-Modifiedheader, typically ten percent of the age since modification, and 200 responses to GET are cacheable by default.Many CDNs go further and apply a configured default TTL to anything without
Cache-Control, because their customers usually want caching. So an API that says nothing is relying on every intermediary choosing to be conservative, and at least one will not.The rule I enforce at the gateway is that every response has an explicit
Cache-Control, withno-storeas the default for any route that requires authentication, and I make the linter fail an OpenAPI operation that lacks a documented caching policy.
Q19. "How do you use If-Match for optimistic concurrency on a PUT, and how does it map to the database?"
Reveal answer
Strong answer The client reads the resource and receives ETag: "17".
When it writes back, it sends If-Match: "17" with the PUT. The server compares the current version to the tag; if they differ, someone else wrote in between, and the server answers 412 Precondition Failed without applying anything, so the client re-reads, merges, and retries.
In the database this is the optimistic locking pattern from Chapter E8: UPDATE orders SET …, version = version + 1 WHERE id = ? AND version = 17, and an affected-row count of zero means 412.
It costs no locks and scales well because conflicts are rare in most workloads.
Two refinements: an API can require If-Match on PUT and answer 428 Precondition Required when it is missing, which stops clients from blindly overwriting; and PATCH can use the same header so partial updates are also guarded.
Land it The ETag is the version column wearing an HTTP header, and 412 is the affected-rows-equals-zero check made visible to the client.
- "What if the client sends If-Match with a stale tag but the fields it changed do not overlap with the other writer's?"
With whole-resource PUT the server cannot tell which fields the client intended to change, so 412 is the only honest answer and the client must re-read and merge.
With PATCH the server does know, so I can offer field-level merging: apply the patch if none of the patched fields changed since the client's version, which needs either per-field versions or a diff against the version the client saw.
That is real complexity, so I do it only for resources where concurrent edits by different people on different fields are common, such as a shared document or a ticket. Everywhere else I keep the simple rule: any concurrent write triggers 412 and the client merges.
The client-side merge is usually trivial because the client knows its own intent, and the extra round trip is rare.
- "How does this look in JPA, and what exception do you catch?"
The entity has a field annotated
@Version, which Hibernate includes in every UPDATE's WHERE clause and increments on success.The handler loads the entity, checks that the loaded version equals the tag from
If-Matchand returns 412 immediately if not, applies the changes, and lets the transaction commit.If someone wrote between my load and my commit, Hibernate throws
OptimisticLockException, which Spring translates toObjectOptimisticLockingFailureException, and my advice maps that to 412 as well.The double check matters: the early comparison gives a fast, clear 412 for the common case, and the version column catches the race in the last few milliseconds. The response to the successful PUT carries the new
ETagso the client can chain writes without re-reading.- "Should you require If-Match, and what does 428 do to existing clients?"
For resources where lost updates matter — anything two people edit — I require it and answer 428 Precondition Required with a Problem Details body explaining that a read must precede a write.
Introducing that on an existing API is a breaking change, so I do it per version or per resource with a deprecation window: first a warning header on unguarded PUTs, then a dashboard of which clients send no
If-Match, then enforcement.For resources where the last write is genuinely fine, such as a user's own preference blob, I leave it optional.
The middle ground I use most is "required for PUT, optional for PATCH", because a PUT without a version is a blind overwrite by definition, while a small PATCH is usually intended as an absolute set of a couple of fields.
Q20. "What does Vary do, and what goes wrong when it is missing or too broad?"
Reveal answer
Strong answer Vary tells caches which request headers were used to choose the response, so the cache keys on those headers in addition to the URL. If a response differs by Accept-Language or by Accept-Encoding, the server must say Vary: Accept-Language, Accept-Encoding, otherwise a cache serves the French body to an English client or gzip bytes to a client that cannot decompress.
When it is missing the failure is wrong content served from cache.
When it is too broad — Vary: * or Vary: Cookie on a public page — the failure is the opposite: nearly every request has a different key and the cache hit rate drops to almost zero, so the origin takes all the load anyway.
For authenticated APIs the right move is usually not to vary on Authorization but to mark the response private or no-store, because a shared cache should not hold it at all.
Land it Vary is the cache key extension — too little leaks, too much defeats the cache, and for private data the answer is not to cache.
- "How would you verify in production that Vary is set correctly for a compressed, localised endpoint?"
I would fetch the same URL through the CDN four times with the two encodings and two languages, in a sequence designed to poison a wrong cache: first
Accept-Encoding: gzipwith French, thenidentitywith English.If the second response comes back gzipped, or in French, the cache is keying only on the URL and
Varyis missing or being stripped. I would read theVaryheader on each response and the CDN's cache-status header to see hits versus misses.Then I would look at the CDN's hit ratio for the path over a day: a correct
Vary: Accept-Encoding, Accept-Languagegives a handful of variants and a high hit rate, whereas aVary: Acceptagainst browsers, which send many differentAcceptstrings, fragments the cache and shows as a low hit rate with high origin load.- "Why is Vary: Accept-Encoding often unnecessary at a modern CDN?"
Because most CDNs normalise
Accept-Encodingbefore it reaches the cache key, collapsing the dozens of strings browsers send into gzip, brotli, or identity, and many compress at the edge themselves from a single identity copy at the origin.In that setup the origin's
Vary: Accept-Encodingis harmless but redundant. It still matters for any intermediate cache that does not normalise, such as a corporate proxy or a caching library inside a client, and for correctness when the origin itself compresses.So I still send it, but I make sure the origin does not also add
Varyon headers that vary wildly, likeUser-Agent, which some frameworks do by default and which reduces a CDN to a pass-through.- "How does Vary interact with the ETag and 304 flow?"
The cache stores one entry per combination of URL and the request header values named in
Vary, and each entry has its own ETag.On revalidation, a cache may send several tags in one
If-None-Match: "a", "b"for the variants it holds, and the server answers 304 with the tag that matched so the cache knows which variant is still fresh.If the server changes the
Varyheader between responses, caches treat the stored variants as stale, soVaryshould be stable per endpoint and not depend on the request.A server that returns a 304 without repeating
Varycan cause a cache to merge variants incorrectly on some implementations, which is one more reason to send the same metadata headers on a 304 as on a 200.
These test whether you understand the transport under your API well enough to explain a latency cliff, a certificate outage, or a "CORS error" without hand-waving.
Q21. "What did HTTP/2 change, what did it not change, and what problem did HTTP/3 exist to solve?"
Reveal answer
Strong answer HTTP/2 kept the semantics — the same methods, status codes, headers, and URLs — and changed the wire format: binary framing instead of text, header compression with HPACK, and multiplexing, which means many requests and responses interleave on one TCP connection as independent streams.
That removed the six-connections-per-host workaround and the head-of-line blocking at the HTTP level where one slow response blocked the next on a connection.
What it did not fix is head-of-line blocking at the TCP level: all streams share one TCP byte stream, so a single lost packet stalls every stream until retransmission, and on lossy mobile networks HTTP/2 can be slower than HTTP/1.1 with several connections.
HTTP/3 solves that by running over QUIC, a UDP-based transport where each stream has its own loss recovery, and by merging the TLS 1.3 handshake into the transport handshake, so a resumed connection sends data in the first packet.
It also survives a change of client IP address, which matters for phones moving between Wi-Fi and cellular.
Land it HTTP/2 fixed HTTP's own head-of-line problem and exposed TCP's; HTTP/3 changed the transport to fix the second one.
- "Should an API server speak HTTP/2 or HTTP/3 to clients directly, and how do you turn it on?"
For a public API the edge speaks HTTP/2 and, where the CDN supports it, HTTP/3 to clients, and the service behind it usually speaks HTTP/1.1 or HTTP/2 cleartext to the edge.
Enabling HTTP/2 at a Spring Boot service is
server.http2.enabled=truewith TLS configured, since browsers only do HTTP/2 over TLS; Tomcat, Jetty, and Undertow all support it.HTTP/3 at a Java service is uncommon as of Aug 2026: Netty has a QUIC codec and Jetty has an HTTP/3 module, but the practical route is to let the CDN or a proxy such as Envoy or Nginx with QUIC support terminate HTTP/3 and forward as HTTP/2 or 1.1.
The advertisement to clients is the
Alt-Svc: h3=":443"header, which the edge adds. The service code sees the same request objects either way, which is the whole point of preserving semantics.- "HTTP/2 server push was in the spec — why did it disappear?"
Server push let the server send resources it guessed the client would need before being asked.
It turned out to be hard to use well: the server does not know what the client already has cached, so pushes often wasted bandwidth, and the ordering interacted badly with priorities.
Chrome removed support for HTTP/2 push in 2022, and other browsers followed, so as of Aug 2026 it is effectively dead.
What replaced it are
103 Early Hints, an interim response carryingLink: rel=preloadheaders so the browser starts fetching while the server is still generating the page, and priority hints.For an API rather than a web page, push was never relevant, but the lesson is that protocol features which require the server to guess client state rarely survive.
- "What does HPACK do and why does it matter for an API with large headers?"
HPACK is HTTP/2's header compression.
It keeps a static table of common header names and values and a dynamic table per connection that both sides update, so a header sent once, such as a 2 KB bearer token or a long cookie, is sent as a small index on every later request on that connection.
On HTTP/1.1 the same token is re-sent in full on every request, which for an API where the body is 200 bytes means headers dominate the bytes.
There is also a security angle: header compression is what enabled the CRIME and BREACH attacks on TLS, so HPACK deliberately does not use a general compressor like DEFLATE, and it lets a sender mark a sensitive header as never-indexed. HTTP/3 uses QPACK, the same idea adapted for out-of-order delivery.
- "Concretely, when would HTTP/2 be slower than HTTP/1.1?"
On a lossy network where the client keeps a single connection.
A mobile connection with 2% packet loss stalls the whole HTTP/2 connection on every lost packet until TCP retransmits it, because TCP delivers bytes in order and every stream is multiplexed onto that one byte stream.
With HTTP/1.1 the browser had six connections, so a lost packet stalled one sixth of the requests. Google's measurements before QUIC showed that above a small loss rate, one multiplexed TCP connection loses to several parallel ones.
That is exactly the case HTTP/3 was built for: QUIC's streams have independent loss recovery, so one lost packet stalls only the stream whose data it carried. On a clean data-centre link the effect is negligible and HTTP/2 wins on header overhead and connection count.
Q22 · Scenario. "After switching the edge load balancer from HTTP/1.1 to HTTP/2 towards your Java services, throughput dropped 30% and one instance per deployment is always hot. Explain."
Reveal answer
Strong answer Symptom: uneven load and lower throughput right after an HTTP/2 change, which points at connection-level balancing. Evidence: per-instance request counts, the number of open connections from the load balancer to each instance, and whether the balancer is operating at layer 4 for that listener.
Causes ranked: first, the balancer now opens a few long-lived HTTP/2 connections and multiplexes everything over them, so its per-connection distribution pins most streams to whichever instances got those connections; second, the Java server's HTTP/2 stream concurrency limit is low, so the balancer queues requests instead of spreading them; third, the servlet container's thread pool is sized for HTTP/1.1 connection counts and is now under-provisioned per connection.
The fix is either to balance per request at layer 7 — most cloud balancers do this if configured as HTTP listeners — or to keep HTTP/1.1 to the backends where the balancer terminates HTTP/2 from clients, which is the common arrangement.
Also raise the server's max concurrent streams and set a max connection age so connections rotate. Prevention: load-test any change of protocol between tiers with per-instance metrics, not just aggregate latency.
Land it Multiplexing turns "balance connections" into "balance almost nothing" — the same pitfall gRPC teams hit, dressed as an edge change.
- "You switched the balancer to layer-7 per-request balancing and one instance is still hotter than the others. What next?"
Then it is no longer the connection distribution, so I would look at what is different about that instance.
Is it the one whose connection is used for the balancer's health checks or for a specific client with a long-lived connection that bypasses the balancer's per-request logic?
Are the balancing algorithm and the weights correct, because a "least connections" policy under HTTP/2 counts connections not streams and can look balanced while streams are not?
I would compare request counts per instance from the instances' own metrics, not the balancer's, to check the balancer is telling the truth.
If counts are equal but CPU is not, it is the instance, not the balancer: a noisy neighbour on that host, a different JVM flag from a partial rollout, or a stuck background task.
And I would check the
max_concurrent_streamsthe server advertises, because a low limit on the other instances would push overflow to whichever one accepts more.- "What are the relevant settings on the Java side?"
On Tomcat, the
Http2Protocolupgrade hasmaxConcurrentStreams, default 100 per connection, andmaxConcurrentStreamExecution, default 20, which is the number of streams on one connection that may be executing on container threads at once; the rest queue.With a balancer using only a few connections, 20 executing streams per connection can throttle an instance below its thread pool size, which looks like low throughput with idle threads. Jetty has
maxConcurrentStreamson its HTTP/2 connection factory. The thread pool,server.tomcat.threads.max, still bounds total work.And a max connection age or the balancer's idle timeout lets connections rotate so a newly started instance receives traffic rather than waiting for an existing connection to close.
- "Is this the same problem gRPC teams hit with Kubernetes services?"
Yes, exactly the same. A Kubernetes ClusterIP service balances at layer 4 by connection, and a gRPC client opens one HTTP/2 connection and multiplexes all calls on it, so all traffic from one client pod lands on one server pod until that connection closes.
Scaling the deployment does nothing for existing clients.
The fixes are the same family: a layer-7 proxy or service mesh such as Istio or Linkerd that balances per request; client-side load balancing where the gRPC client resolves the headless service to all pod IPs and round-robins across them; or a server-side
MAX_CONNECTION_AGEso connections are closed periodically and clients reconnect to a fresh pod.I would raise this in the answer because it shows the pattern is about multiplexing, not about the specific edge product.
Q23. "Where should TLS terminate — at the load balancer or at the service — and what changes about your design in each case?"
Reveal answer
Strong answer Terminating at the load balancer or gateway centralises certificates in one place, lets the balancer route on paths and headers, offloads the handshake CPU, and gives one place to enforce TLS versions and ciphers.
The cost is that traffic between the balancer and services is plaintext unless re-encrypted, which fails most compliance regimes and any zero-trust design.
Terminating at the service keeps encryption end to end and lets the service authenticate the caller via mutual TLS, but every instance needs a certificate, rotation becomes a fleet operation, and layer-7 routing at the edge is impossible because the edge cannot read the request.
The common 2026 arrangement is both: terminate public TLS at the edge with an automated certificate from ACME, then re-encrypt with mutual TLS inside the cluster, issued and rotated by a service mesh or cert-manager, so services see an authenticated peer identity and the edge still routes.
The design change is that services must accept forwarded identity headers or mTLS identities, not raw client certificates, and must not trust X-Forwarded-For from anything but the edge.
Land it Terminate at the edge for routing and automate mTLS inside for trust — one without the other is either blind or exposed.
- "What does the service need to change to run behind a terminating proxy correctly?"
It needs to know it is behind a proxy so it generates correct absolute URLs and reads the real client address. In Spring Boot that is
server.forward-headers-strategy=frameworkornative, which makes the container honourX-Forwarded-Proto,X-Forwarded-Host, andX-Forwarded-For, or the newer singleForwardedheader.Without it, a redirect or a
Locationheader on a 201 comes out ashttp://internal-host:8080/…, and rate limiting by client IP sees the proxy's address for everyone.The security half is that those headers must be trusted only from the proxy: Tomcat's
RemoteIpValvehasinternalProxiesfor that, and the proxy itself must overwrite rather than append the headers so a client cannot spoof its ownX-Forwarded-For.Then HSTS and secure-cookie flags are decided by the forwarded scheme, not the local one.
- "What is the performance cost of re-encrypting inside the cluster?"
Smaller than people fear. The TLS 1.3 handshake costs a few hundred microseconds of CPU and one round trip, and connection reuse means it happens once per connection, not per request.
Bulk encryption with AES-GCM on hardware with AES-NI runs at several gigabytes per second per core, so for JSON API traffic it is a low single-digit percentage of CPU. Istio's own published numbers put the sidecar overhead at under a millisecond of added p90 latency per hop with mTLS on.
Where it does hurt is very chatty services that open a new connection per call; the fix there is connection pooling, which they needed anyway.
Ambient-mode meshes as of Aug 2026 move the mTLS into a per-node proxy, which removes the sidecar's memory overhead but not the encryption cost itself.
- "Where do you put the private keys, and how do you rotate them?"
At the edge, the key lives in the balancer's certificate store, such as AWS Certificate Manager or a Kubernetes TLS secret managed by cert-manager, and rotation is automatic through ACME with a renewal about 30 days before expiry and a hot reload that does not drop connections.
Inside the cluster, workload certificates are issued by the mesh's CA or by cert-manager with a private issuer, live only in the pod's memory or a tmpfs mount, and are rotated every 24 hours or less; the workload identity is in the certificate's SAN as a SPIFFE URI such as
spiffe://cluster/ns/payments/sa/api.Nobody copies a private key anywhere, and no long-lived key exists on a disk that a human could read. The CA's own root key is offline, with an intermediate doing the daily issuing.
Q24 · Scenario. "At 09:00 every client of your partner API starts failing with TLS handshake errors. The service is healthy and nothing was deployed. First three checks?"
Reveal answer
Strong answer Symptom: simultaneous TLS failures across all clients with no change on your side, which is the signature of a certificate or trust-chain event.
Check one: certificate expiry — openssl s_client -connect host:443 -servername host and read the notAfter date; a certificate that expired at 09:00 UTC explains everything.
Check two: the chain — an intermediate certificate that expired or was revoked breaks clients that do not fetch intermediates themselves, even when the leaf is fine; the 2021 Let's Encrypt root expiry broke exactly this way for old clients.
Check three: the clients' side — a partner pushed a trust-store update or OS patch that dropped an old root or disabled TLS 1.0 or 1.1 at once, which would present as your API failing. Ranked causes are leaf expiry, chain expiry, then client trust change.
The fix is to renew or re-issue and reload without a restart if the server supports it.
Prevention: automated renewal with ACME, an alert at 14 and 7 days before expiry that checks the served chain from outside, and a monitor that validates the chain the way a strict client would.
Land it "Nothing changed" plus a synchronised failure time is a certificate until proven otherwise.
- "The certificate is valid and the chain is fine, but clients still fail. What next?"
Then the mismatch is in negotiation rather than trust.
I would capture the failing handshake with the client's error message: "handshake failure" from OpenSSL usually means no common cipher suite or protocol version; "unrecognized name" means the SNI hostname did not match a configured virtual host; "certificate unknown" points at a client trust store.
I would check whether an automated hardening change at 09:00 disabled TLS 1.2 or a cipher at the balancer, because "nothing deployed" often excludes security policy pushes. I would test with
openssl s_client -tls1_2and-tls1_3and with the specific ciphers the clients use.If only some clients fail, I would look at what they share, such as an old Java 8 runtime without TLS 1.3 or a corporate proxy doing interception with its own trust store.
- "How does a client end up not fetching the intermediate, and what do you do about it?"
The server is supposed to send the full chain except the root: leaf, then intermediate.
If it sends only the leaf, browsers usually recover by fetching the intermediate from the AIA URL in the certificate, but most non-browser clients — Java, curl on some builds, Go, Python — do not, and they fail with "unable to get local issuer certificate".
The mistake usually happens when someone pastes only the leaf into the balancer's certificate field. I check with
openssl s_client -showcertsand count the certificates, and with an external checker that flags an incomplete chain.Prevention is to have the ACME client install the
fullchain.pemfile, and to have the external monitor validate the chain as a strict client would, without AIA fetching, so an incomplete chain is caught at deploy time and not at 09:00 by partners.- "What does 'reload without a restart' look like, and why not just restart?"
Most proxies support it: Nginx re-reads certificates on
nginx -s reloadby starting new workers and draining old ones, Envoy watches the file through its secret discovery service, and a Java service can use a reloadableSSLContextwith Spring Boot's SSL bundle reload, enabled withspring.ssl.bundle.watch.file.quiet-period, so a new certificate file is picked up in place. The reason not to restart is that a restart of every instance at once is a second outage on top of the first, and a rolling restart is slower than a reload. During an incident I do the reload first and confirm from outside withopenssl s_clientthat the new expiry is being served, since a proxy may reload some workers before others and show a mix for a minute.- "How do you write the alert so this never happens again?"
The alert must check what clients see, not what the file on disk says.
A blackbox probe from outside the network connects to every public hostname, validates the full chain strictly, and exports the days to expiry of the leaf and of every intermediate; alerts fire at 14 days as a ticket and at 7 days as a page.
A second check compares the served certificate's fingerprint with the one the ACME client believes it installed, which catches a renewal that succeeded on disk but was never loaded.
For internal certificates the mesh exposes expiry metrics per workload, and I alert on any certificate under 6 hours from expiry, since those are meant to rotate daily.
The last piece is an inventory: a list of every certificate, its owner, and its renewal method, so "who owns this one" is never a question at 09:00.
Q25. "Explain CORS from the browser's point of view. Why does curl not care, and what does Access-Control-Allow-Origin: * actually protect or expose?"
Reveal answer
Strong answer The browser enforces the same-origin policy: script running on app.example.com may send a request to api.example.com, but the browser will not let the script read the response unless the API opts in.
The opt-in is CORS: the browser adds an Origin header, and the API answers with Access-Control-Allow-Origin naming that origin.
For requests that are not "simple" — any method beyond GET, HEAD, POST with form content, or any custom header such as Authorization — the browser first sends an OPTIONS preflight asking which methods and headers are allowed, and caches the answer for Access-Control-Max-Age seconds.
Curl does not care because CORS is enforced by browsers to protect the user's other sessions from a malicious page; it is not a server-side access control at all.
Allow-Origin: * lets any page read the response, which is fine for public data and forbidden by browsers when combined with credentials, so an API that uses cookies must echo the specific allowed origin and send Access-Control-Allow-Credentials: true.
Preflights also cost a round trip, so a chatty API from a browser benefits from a long max-age.
Land it CORS protects users from pages, not APIs from callers — the API's real protection is the token check that runs after CORS.
- "Does CORS protect against CSRF?"
No, and the confusion causes real vulnerabilities. CORS controls whether a page can read a cross-origin response; it does not stop the browser from sending the request.
A simple request — a POST with
application/x-www-form-urlencodedfrom a form on an attacker's page — is sent with the user's cookies regardless of CORS, and the server acts on it even though the attacker cannot read the reply.That is CSRF. The defences are separate:
SameSite=LaxorStricton the session cookie so it is not sent on cross-site POSTs, a CSRF token for cookie-based sessions, or bearer tokens in theAuthorizationheader, which browsers never attach automatically.For a token-based API, requiring a custom header or
application/jsonbody forces a preflight, which the attacker's page cannot pass, and that is the one way CORS helps indirectly.- "How do you configure CORS in a Spring API, and what is the common mistake?"
Globally through a
CorsConfigurationSourcebean registered with Spring Security viahttp.cors(), listing the allowed origins explicitly, the methods, the headers includingAuthorizationandContent-Type, andsetMaxAge(3600)so preflights are cached for an hour.The common mistake is
allowedOrigins("*")together withallowCredentials(true), which Spring rejects at startup because browsers forbid the combination; people then switch toallowedOriginPatterns("*"), which echoes any origin back and effectively disables the protection for cookie-based sessions.The second mistake is putting CORS on the controller with
@CrossOriginonly, so the security filter chain answers the preflight with 401 before the controller is reached, which is why the preflight must be handled by the security layer.I also set the config at the gateway when several services share an origin so it is consistent.
- "The browser says 'CORS error' but the server logs show a 500. What is really going on?"
The server returned an error page without the CORS headers, and the browser reported the missing header, not the 500, because the missing header is what stopped it from reading the response. This is the single most common false CORS diagnosis.
The cause is an error path that bypasses the CORS filter, for example an exception thrown before the filter runs, or a gateway timeout page from a proxy that does not add the headers.
The fix is to make sure every response, including 4xx and 5xx generated by the container or the proxy, carries the CORS headers, which in Spring means the CORS filter must run before the exception translation, and at the gateway means adding the headers on error responses too.
The way to see the truth is the browser's network tab, which shows the real status even when the console says CORS.
- "What are the exact rules for a 'simple' request?"
A request skips the preflight when its method is GET, HEAD, or POST; its only author-set headers are
Accept,Accept-Language,Content-Language, andContent-Type; and theContent-Typeis one ofapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain.Anything else — a PUT, a
Content-Type: application/json, anAuthorizationheader — triggers an OPTIONS preflight withAccess-Control-Request-MethodandAccess-Control-Request-Headers, which the server answers with the corresponding allow headers.The implication for an API is that a JSON API with bearer tokens always preflights, so
Access-Control-Max-Agematters for latency, and the preflight response must be fast and unauthenticated.The implication for security is that a form POST from any site reaches the server without a preflight, which is why CSRF protection is separate.
Q26. "What is content negotiation, and when would you actually use a vendor media type instead of plain application/json?"
Reveal answer
Strong answer Content negotiation is the client saying what it can accept — Accept: application/json — and what it is sending — Content-Type — and the server choosing a representation and declaring it in its own Content-Type.
The server answers 406 if it cannot produce anything acceptable and 415 if it cannot read what was sent. A vendor media type such as application/vnd.acme.order+json;version=2 puts the representation's identity and version in the header.
I would actually use one in three cases: when the same resource genuinely has multiple representations, such as a full and a summary view or JSON and CSV export; when I am versioning a single representation without moving URLs; and when a gateway routes on the header.
I would not use it for a general public API, because clients forget the header, tooling support is patchy, and browsers cannot set it from a link, so the default representation must be sane anyway.
Most public APIs stay with application/json, negotiate only compression, and put versions elsewhere.
Land it Negotiation is elegant when representations really differ; as a versioning trick it mostly hides the version from the people who need to see it.
- "How does Spring decide which representation to produce, and what do you configure?"
Spring MVC uses a
ContentNegotiationManagerthat, by default, looks only at theAcceptheader, then picks among theHttpMessageConverterinstances that can produce a matching media type — Jackson for JSON, and others if registered.A handler can narrow it with
@GetMapping(produces = "application/vnd.acme.order+json"), and two handlers with differentproducesvalues on the same path are dispatched by theAcceptheader, which is how header-based versioning was done before Spring Framework 7's native support.I configure
spring.mvc.contentnegotiation.favor-parameter=trueonly if I need a?format=csvescape hatch for browser links. Path extensions like.jsonwere removed as a default in Spring 5.3 for security reasons and I would not bring them back.- "A client sends Accept: text/html to your JSON API. What happens?"
Strictly, 406 Not Acceptable, because the server cannot produce what was asked.
Pragmatically, most public APIs return JSON anyway, on the grounds that a client asking for HTML from a JSON API is a browser being pointed at the URL by a curious developer, and JSON is more useful to them than a 406 with an empty body.
RFC 9110 explicitly allows the server to ignore
Acceptand send its default representation.I choose the pragmatic path for the default representation and reserve 406 for cases where the client asked for a specific alternative I do not have, such as
application/xml, because there the client's code genuinely cannot proceed and a clear error is kinder than silently sending JSON it will fail to parse.- "Is application/json with a charset parameter still correct?"
No. RFC 8259 says JSON must be encoded in UTF-8 when exchanged between systems, and the
application/jsonmedia type registration defines nocharsetparameter, soapplication/json;charset=UTF-8is technically an unregistered parameter that everything tolerates.Spring dropped the charset from its default JSON content type in version 5.2 for this reason. It matters in two places: an
Acceptheader matching that compares parameters strictly, and a gateway or WAF rule that matches content types exactly.For a structured-syntax suffix type like
application/problem+jsonorapplication/vnd.acme+jsonthe same rule applies. So I emit plainapplication/json, accept the charset variant on input for old clients, and encode UTF-8 always.
Q27 · Design. "Design the TLS and certificate strategy for an API platform: public edge, 40 internal services, 12 external partners who need strong identity."
Reveal answer
Strong answer Requirements: no expiry outages, encryption everywhere, strong identity for partners, and no manual key handling. Public edge: certificates from a public CA via ACME with automated renewal 30 days before expiry, TLS 1.3 preferred and 1.2 as the floor, HSTS enabled, OCSP stapling on.
Internal: a private CA — a service mesh's built-in one, or cert-manager with a private issuer — issuing short-lived certificates of about 24 hours to every workload, rotated automatically, with mutual TLS enforced between services so each call carries a SPIFFE-style workload identity.
Partners: mutual TLS at a dedicated partner gateway, with client certificates issued by our private CA or pinned from theirs, mapped to a partner id and rate-limit class at the gateway, plus OAuth2 client credentials on top so authorisation stays in tokens and mTLS stays identity.
Operations: an external monitor validates every public chain daily, an alert fires at 14 days, certificate inventory lives in one place. Trade-offs: short-lived internal certs mean the CA is a critical dependency, so it runs highly available with an offline root.
I would not do manual certificate installs on hosts, share one wildcard everywhere, or let services trust X-Forwarded-Client-Cert from anything but the gateway.
Land it Automate every certificate or plan the outage; strong partner identity is mTLS for who, tokens for what.
- "Requirement change: one of the twelve partners cannot do mTLS at all. What do you offer them?"
I keep the identity strength as close as I can without client certificates.
The best alternative is OAuth2 client credentials with a private-key JWT assertion, from RFC 7523, where the partner signs a short-lived JWT with a key they hold and we verify with the public key they registered, so no shared secret ever travels.
On top of that, an IP allow-list at the partner gateway for their egress addresses, and a per-partner rate-limit class.
If they cannot even manage a signing key, a rotated client secret is the floor, and I would document that their calls are limited to lower-risk scopes until they can do better.
What I would not do is weaken the gateway for everyone; they get a separate route with its own policy so the other eleven keep the stronger posture.
- "Under time pressure, what would you ship first and cut?"
First, the public edge with ACME and the external expiry monitor, because that is where the outage risk is public and the work is a day. Second, partner mTLS at the gateway, since strong partner identity was a stated requirement.
I would defer the internal mesh with mTLS to a later phase and, in the meantime, keep the internal network segmented and the balancer-to-service traffic on a private subnet, documenting it as a known gap.
I would cut OCSP stapling tuning and the two-year hardening of cipher lists; TLS 1.3 preferred with a sane 1.2 fallback from a standard profile is enough. I would cut the certificate inventory tool and use a spreadsheet for the twelve partner certificates until it hurts.
What stays regardless is automation for every certificate that exists, because a manual renewal is a scheduled outage.
- "Why are 24-hour internal certificates better than one-year ones?"
Because revocation does not work in practice. Certificate revocation lists and OCSP are slow, often skipped, and inside a cluster nobody checks them, so the only real way to invalidate a compromised long-lived certificate is to rotate everything.
A 24-hour certificate limits the damage of a leaked key to a day and makes rotation a routine that runs constantly, so it is tested every day rather than in a panic.
The cost is that the CA becomes a dependency of every workload every day: if it is down for more than a day, workloads cannot renew and traffic stops.
So the CA runs highly available, its own certificate is longer-lived, and I monitor the fleet's minimum time-to-expiry so a CA problem is visible hours before it becomes an outage.
- "How does the partner's identity get to the service behind the gateway?"
The gateway terminates the partner's mTLS, validates the client certificate against the partner CA, maps the certificate subject or fingerprint to a partner id, and then re-encrypts to the service over the internal mesh. It forwards the identity as a signed token, not as raw headers a caller could forge: either it mints a short-lived internal JWT containing the partner id and scopes, or it forwards the partner's OAuth2 access token and adds the certificate binding, the way RFC 8705 does with a confirmation claim. The service trusts the identity because it arrived over the mesh from the gateway's workload identity, and it checks the token signature, so even a compromised internal workload could not impersonate a partner without the gateway's signing key.
Q28. "Why do people say HTTP is stateless, and what actually holds the state in a real API?"
Reveal answer
Strong answer HTTP is stateless in that each request must carry everything the server needs to handle it; the protocol does not remember previous requests on the connection.
That is what makes horizontal scaling easy — any instance can serve any request — and what lets caches and proxies work, because a response is a function of the request alone.
The state has to live somewhere, though: in the client, as tokens and cursors it sends with each call; in a database or cache shared by all instances; or in a session store keyed by a cookie, which is the traditional web-app approach that APIs mostly avoid because it pins users to a store and complicates caching.
A bearer token is the API version of a session: it carries the identity with each request so the server keeps nothing.
The design consequence is that anything an API "remembers" — a pagination position, a draft, a multi-step workflow — should be a resource with a URL rather than server memory, which is why long-running operations get an operation resource and pagination gets a cursor.
Land it Stateless means the request carries the context; every piece of state you cannot put in the request needs a URL.
- "Does a JWT really keep the server stateless, given you need to revoke tokens?"
Only partly. Validating a JWT is stateless: the server checks the signature against a cached public key and reads the claims, no store involved. Revoking one is not: a signed token is valid until it expires unless the server consults a deny list, which is state.
The usual compromise is short-lived access tokens of five to fifteen minutes plus a refresh token that is stateful and revocable at the identity provider, so the window of a stolen access token is bounded and the server on the hot path stays stateless.
For high-value actions I add a cheap check against a small deny list keyed by token id, which is a Redis lookup and acceptable.
What I do not do is pretend the JWT solved revocation, because a one-hour token that cannot be revoked is a policy decision someone should have made consciously.
- "What about sticky sessions at the load balancer — when are they acceptable?"
They are acceptable as an optimisation, never as a correctness requirement. If a service keeps a warm per-user cache and sticky routing improves hit rate, fine, as long as a request landing on a different instance still works.
The moment correctness depends on stickiness — an upload in progress held in one instance's memory, a multi-step form in a session — a deployment or a scale-down loses the user's work.
WebSockets are the legitimate exception, because the connection itself is stateful and must stay with the instance that holds it, and even then the state that matters, such as a chat room's membership, lives in a shared store so a reconnect anywhere recovers.
My rule is that I should be able to kill any instance at any time with no user-visible effect.
- "How do you handle a multi-step workflow like a checkout without server-side sessions?"
I make the workflow a resource.
POST /checkoutscreates a checkout with an id and a state; each step is a PATCH or a sub-resource POST on that id — set the address, choose shipping, apply a coupon — and the final step isPOST /checkouts/{id}:complete.The state lives in the database, the client carries only the id, and any instance can serve any step.
This gives me things a session never did: the checkout can be resumed from another device, support can look at it by id, abandoned checkouts are rows I can analyse and expire, and the whole flow is testable with plain HTTP calls.
The cost is a database write per step instead of a session write, which is the same cost, and a lifecycle to define, which the session also needed but nobody wrote down.
The last group of this section checks whether you can model a domain as resources without lying about actions, and whether you know what REST buys you that a bunch of endpoints does not.
Q29. "How do you model an action that is not CRUD — cancelling an order, approving a request — in a REST API?"
Reveal answer
Strong answer I have three honest options and one lie.
The first option is a state transition via the resource: PATCH /orders/42 with {"status":"CANCELLED"}, which works when cancellation is just a field change with no extra inputs, but hides side effects and makes validation of allowed transitions awkward.
The second is a sub-resource that is itself a noun: POST /orders/42/cancellations with a body carrying the reason, returning 201 and a cancellation record — this is the most RESTful and gives me an audit trail for free.
The third is a named action endpoint: POST /orders/42:cancel, the convention Google's API design guide uses, which is explicit and easy to document. The lie is GET /orders/42/cancel, which a prefetcher will trigger.
I choose the sub-resource when the action creates something worth reading later, the action endpoint when it does not, and I make the action idempotent — cancelling an already-cancelled order returns the existing cancellation, not 409 — so retries are safe.
Land it Model the action as the record it leaves behind; when there is no record, name the verb honestly rather than hiding it in a PATCH.
- "How do you make POST /orders/42/cancellations idempotent when there is no idempotency key?"
By the natural key: an order can have at most one active cancellation, so the cancellations table has a unique index on the order id, and the handler does insert-if-absent.
On a repeat it finds the existing cancellation and returns 200 with it, rather than 201 or 409. The status code difference tells an honest client what happened, and a retrying client is satisfied either way.
If cancellation has inputs that could differ between the two calls, such as a reason, I return the original and ignore the new reason, which is the same rule as an idempotency key with a mismatched body but more forgiving, because the intent is clearly the same.
Where an action can legitimately happen many times, like adding a note, there is no natural key and I do require the header.
- "What do you return when the action is not allowed in the current state?"
409 Conflict with a Problem Details type such as
invalid-state-transition, a detail saying which state the order is in and which states allow cancellation, and the current state in an extension member so the client does not have to refetch.409 rather than 422 because the request itself is well-formed; it is the resource's state that refuses it, and a client's right move is to re-read and reconsider rather than fix its input. 400 would be wrong because nothing about the request is malformed.
If the action is impossible for a permanent reason, such as cancelling an order that was already delivered and is outside the returns window, I still use 409 but the type is different, so a client can distinguish "wait and retry" from "never".
- "Why not just use PATCH with the status field and validate transitions server-side?"
It works for simple state machines and I have shipped it, but three things push me away as the domain grows.
Cancellation usually needs inputs — a reason, whether to refund, who authorised — and a PATCH body that carries those alongside
statusis a command pretending to be a partial update.Side effects like a refund and a notification do not read as "update a field", so readers of the code and the docs are misled.
And the audit trail: with a sub-resource I get a record with a timestamp and actor for free, whereas with PATCH I have to build a history table separately.
The PATCH form also makes it awkward to express "this transition is allowed but that one is not" in OpenAPI, where a sub-resource is just another operation with its own documented errors.
- "How does the Google colon convention interact with URL encoding and routing?"
The colon is a legal character in a path segment per RFC 3986, so
/orders/42:cancelneeds no encoding, and most routers treat it as part of the segment.In Spring MVC, a mapping of
/orders/{id}:cancelworks with the default path matcher, but the{id}variable must be constrained, for example{id:[^:]+}, so it does not swallow the colon.Some gateways and older proxies normalise or reject unusual characters, so I test the route through the real edge. The alternative spelling
/orders/42/cancelis more portable but blurs the line between a sub-resource and an action, which is why Google chose the colon.Either is fine so long as the conventions document picks one and the linter enforces it.
Q30 · Scenario. "A competitor scraped your entire customer count by iterating /customers/1, /customers/2, and so on. Nothing was authorised that should not have been. What went wrong and what do you change?"
Reveal answer
Strong answer Symptom: business information leaked through the shape of identifiers, not through a permission bypass.
Evidence: the access log shows sequential ids from one client at a steady rate, with 404s and 403s interleaved with 200s — even the errors leak, because the ratio tells them the density of live ids.
Causes ranked: auto-increment primary keys exposed as public ids; distinct 403 and 404 responses that confirm existence; no per-client rate limit on the item endpoint.
The fix: introduce a public identifier that is not guessable — UUIDv7 is the 2026 default since it is time-ordered for index locality yet not enumerable, or a random opaque id — and keep the integer key internal; return 404 for resources the caller may not see, as GitHub does, so existence is not confirmed; rate-limit per client with a lower limit on item lookups that produce 404s.
Migration: add the public id column, backfill, index it, accept both for a deprecation period, and stop emitting integers. Prevention: an API linting rule that path parameters are never database sequences.
Land it A sequential id is a public metric; a UUIDv7 costs nothing and removes the leak at the source.
- "You switched to UUIDs and the same competitor now scrapes via the list endpoint. What next?"
The list endpoint was the bigger hole and the id change did not touch it.
I would check whether the list is scoped to the caller: an authenticated partner should only see the customers they are entitled to, so a global
/customersthat returns everyone under a partner token is a broken object-level authorisation bug, not a scraping problem.If the scope is correct and they are still enumerating a large legitimate set, the levers are a low rate limit on list calls, a cap on page size, and a cursor that is bound to the caller and expires, so a scraper cannot parallelise.
I would also remove counts and totals from the response, and I would look at what metadata leaks: a
createdAton every record reveals growth rate just as well as a sequential id did.- "Why UUIDv7 rather than a random UUIDv4?"
Both are unguessable in the sense that matters here: the random bits are 74 in v7 and 122 in v4, and 74 is far beyond enumeration. The difference is the database.
A v4 key inserts at a random position in the B-tree, so a large table sees page splits, cache misses, and write amplification, whereas v7 puts a millisecond timestamp in the high bits so inserts are append-mostly like an integer sequence.
The trade is that v7 leaks creation time to anyone who decodes it, which is usually fine and sometimes useful, but if creation time is itself sensitive I fall back to v4 for the public id and keep an internal ordered key.
PostgreSQL 18 has a native
uuidv7()function as of Aug 2026, and Java has libraries for it; the JDK's built-in generator still only does v4.- "How do you migrate the public ids without breaking existing integrations?"
Expand and contract. Add a
public_idcolumn, generate a UUIDv7 for every existing row in batches, and add a unique index.Start emitting
idas the new value and, for the deprecation window, keep accepting the old integer on the path by detecting its shape — an all-digit segment is the legacy id — while sending aDeprecationheader on those responses.New records never get an integer id exposed. After the window, integer lookups return 404 with a Problem Details type pointing at the migration guide.
The point that catches people is that the old integers keep leaking if any response still includes them, including in links, webhooks, and exports, so the search for the integer id in serialised output has to be exhaustive before the window closes.
- "Is returning 404 for a forbidden resource really better? It hides bugs from legitimate users."
It does make debugging harder, and I accept that because the alternative is an oracle. The trade-off is decided by what the resource is: for anything whose existence is private — other tenants' customers, private documents — 404 is right and the support channel explains it.
For resources the caller can see but not act on, 403 is right and clearer.
To soften the debugging cost, I make the 404 body a Problem Details with a type of
not-found-or-forbiddenand a detail that says the resource may exist but be outside your access, and I log the real reason server-side with the request id ininstance, so a developer who contacts support can be told precisely what happened without the API telling an attacker.
Q31. "What does HATEOAS mean, and is it worth doing in 2026?"
Reveal answer
Strong answer HATEOAS — hypermedia as the engine of application state — is the part of REST where responses carry links to the next legal actions, so a client discovers what it can do by following links instead of building URLs from documentation.
An order in PAID state would include a cancel link and a SHIPPED one would not. The honest 2026 answer is that full hypermedia clients never became mainstream — most clients are generated from OpenAPI and hard-code the paths — but two pieces are worth keeping.
Links for pagination and related resources, using a simple links object or the Link header, remove URL construction bugs and let the server move things. And state-dependent action links are a cheap way to tell a UI which buttons to show without duplicating the state machine.
Spring HATEOAS and the HAL format exist if a team wants the full model. I would adopt the light form and skip the heavy form unless the API is consumed by a generic client I do not control.
Land it Links are worth it where they carry state the client would otherwise reimplement; the full hypermedia dream is not the bar for a good API.
- "Show me what the light form actually looks like in a response."
An order response would carry a
linksobject alongside the data:"links": {"self": "/orders/42", "customer": "/customers/7", "cancel": "/orders/42/cancellations"}, wherecancelis present only when the order is in a cancellable state. A list response carries"links": {"next": "/orders?cursor=abc"}, withnextabsent on the last page.The
Linkheader form, from RFC 8288, does the same for clients that do not want it in the body:Link: </orders?cursor=abc>; rel="next", which is what GitHub uses.I keep the link relation names stable and documented, and I make the values full paths so a client concatenates nothing.
The client rule that goes with it is "if the link is absent, the action is not available", which removes a whole class of state-checking code on the client side.
- "What does HAL add over a plain links object, and is the extra structure worth it?"
HAL, the Hypertext Application Language, standardises the shape: links go under
_linkswith each relation being an object holdinghref, and related resources can be embedded inline under_embeddedto save round trips.It has its own media type,
application/hal+json, and Spring HATEOAS produces it out of the box, so a Spring Data REST service is HAL by default.The benefit is that generic clients and browsers such as the HAL explorer can walk any HAL API. The cost is that every response has underscore-prefixed wrappers that non-HAL clients find odd, generated SDKs from OpenAPI do not understand link relations, and
_embeddedtends to grow into an ad-hoc field-selection scheme.For an API consumed through generated SDKs, I use the plain links object; for one browsed by people and generic tools, HAL is a reasonable pick.
- "How do links interact with caching and with API versioning?"
Links help with versioning because a client that follows
links.nextnever builds a URL, so the server can change the pagination scheme, move a resource to a new path, or route a client to a different version without the client noticing.Links are part of the response body, so they are cached with it; a state-dependent link such as
cancelis only correct as long as the state is, which is fine because the ETag changes when the state does.The one trap is absolute versus relative URLs: absolute URLs bake the hostname into cached bodies and break behind a different domain or a proxy, while relative URLs need the client to resolve them against the request URL correctly.
I emit absolute paths without the host, which resolves cleanly and stays valid across hostnames.
Q32. "How deep should resource nesting go, and how do you handle a resource that belongs to two parents?"
Reveal answer
Strong answer One level of nesting expresses ownership clearly — /customers/{id}/addresses — and two is the practical maximum; beyond that the URL is repeating context the id already carries, and clients must know three ids to fetch one thing.
The rule I use is that a resource nests under a parent only when it cannot exist without it and is always accessed through it. Anything with its own identity and lifecycle gets a top-level collection and a filter: /orders?customerId=… rather than /customers/{id}/orders/{oid}.
A resource with two parents — an order line that belongs to an order and references a product — lives under the parent that owns its lifecycle, the order, and references the other by id and link.
I would not create two paths to the same resource, because caches, permissions, and documentation now have two of everything.
The nesting decision also interacts with authorisation: a top-level /orders/{id} must check ownership explicitly, which is the broken-object-level-authorisation check at the top of the OWASP API list.
Land it Nest for ownership, filter for association, and give every resource exactly one URL.
- "What exactly is a broken object-level authorisation bug, and how do you test for it?"
It is when the API checks that the caller is authenticated but not that the caller is allowed to touch the specific object the id names, so
GET /orders/42with a valid token for a different customer returns the order.OWASP has ranked it the top API risk since 2019 because it is easy to write and easy to exploit.
The fix is structural: every repository query that loads by id also filters by the caller's tenant or ownership, for example
findByIdAndCustomerId, so there is no code path where the check can be forgotten.The test is mechanical: for every endpoint with an id, the integration suite creates a resource as user A, calls it as user B, and asserts 404.
I automate that from the OpenAPI document so a new endpoint is covered the day it is added, and I run an authorisation-focused scanner in the pipeline as well.
- "Give me a case where you would allow two paths to one resource."
An alias for the current user is the one I accept:
/me/ordersas a convenience that is exactly equivalent to/customers/{myId}/orders.It is not really a second identity for the resource; it is a redirect-like alias, and I can implement it as an internal rewrite so there is one handler, one permission check, and one cache key.
Even then I make the canonical URL appear in
links.selfso a client that stores a reference stores the stable one. A second acceptable case is a permanent redirect after a path change, where the old path answers 308 to the new one during deprecation.What I still refuse is two full, independently implemented paths to the same object, because sooner or later one of them misses a permission check or a validation rule.
- "How do you represent the cross-reference to the second parent in the response?"
By id and by link, never by embedding the whole parent.
An order line under
/orders/42/lines/3carries"productId": "prod_9f3"and"links": {"product": "/products/prod_9f3"}, plus a small denormalised snapshot of the fields a line needs to be readable on its own, such as the product name and unit price at the time of the order.That snapshot is deliberate: it is what the customer bought, and it should not change when the catalogue changes. The client fetches the live product through the link when it needs current data.
This keeps the line's lifecycle tied to the order, keeps the product's own endpoint as the one place that knows about products, and avoids the response-size explosion of embedding parents inside children.
Q33 · Design. "Design the resource model and endpoints for a ticketing system: events, ticket types, orders, tickets, refunds. Show the trade-offs you made."
Reveal answer
Strong answer Assumptions: public API for partners and our own apps, high read traffic on events, contended writes on ticket purchase.
Resources: /events and /events/{id}, with /events/{id}/ticket-types nested because a ticket type cannot exist without its event; /orders top-level, created with POST /orders plus an idempotency key, body listing ticket type ids and quantities, since an order spans one event but is owned by a customer; /orders/{id}/tickets as read-only children generated on payment; /refunds top-level, created via POST /refunds referencing an order or a ticket, because a refund has its own lifecycle and audit requirements.
Purchase is a long-running operation: POST /orders returns 202 with an operation link while inventory is reserved and payment is taken, or 201 if it completes synchronously.
Availability is a read endpoint /events/{id}/availability with a short Cache-Control: max-age=2, because near-real-time is enough and it takes the load off the database.
Trade-offs: tickets under orders rather than top-level makes "all my tickets" a filter across orders, which I accept for the clean ownership; refunds top-level costs a join but keeps finance's view simple.
I would not model purchase as PUT, because it is not idempotent without the key, and I would not expose ticket inventory counts as integers to partners, only tiers such as available, low, sold-out, to stop scraping.
Land it Nest what cannot live alone, give lifecycles their own collection, and make the contended write a keyed, asynchronous operation.
- "Requirement change: tickets must be transferable between customers. How does the model change?"
Tickets stop being purely children of an order, because a ticket can now be owned by someone who never placed the order. I promote tickets to a top-level collection,
/tickets/{id}, withorderIdandownerIdas fields and links to both.The order keeps
/orders/{id}/ticketsas a read-only filtered view. The transfer is an action with a record:POST /tickets/{id}/transferscreating a transfer resource in a pending state, accepted by the recipient viaPOST /transfers/{id}:accept, with the ticket'sownerIdchanging when it completes.Authorisation now has to check ownership of the ticket rather than the order, which is exactly the kind of shift that makes me want the ticket to have one canonical URL. This is the trade-off I mentioned resolving the other way, and the changed requirement flips it.
- "Under time pressure for a launch in four weeks, what would you cut?"
I would cut the asynchronous purchase path and make
POST /orderssynchronous with a 201, holding the reservation and payment inside one request with a strict timeout, because the operation resource and its polling are a week of work and most launches do not hit the load that needs it.I would cut refunds as a self-service API and handle them through an admin endpoint for the first month. I would cut the tiered availability endpoint and return a simple boolean per ticket type.
What I would not cut is the idempotency key on order creation, the state machine on orders, and the one-URL-per-resource rule, because those are the things that are expensive to retrofit and whose absence causes duplicate charges on launch night.
The cuts are all additive later; the keeps are all breaking to add later.
- "How do you handle inventory contention when 50,000 people buy at once?"
The database row for the ticket type is the contention point, and I do not want 50,000 transactions locking it.
The pattern is a reservation step that is cheap and short: a Redis
DECRBYon a per-ticket-type counter, which is atomic and takes microseconds, decides who gets a reservation, and the losers get a fast 409 with asold-outtype.Winners get a reservation with a five-minute expiry and proceed to payment; the database is updated once per successful order, not once per attempt, and expired reservations return their count. For fairness at very high demand, a waiting-room queue in front of the API meters entry.
The verification is a load test at ten times expected demand that asserts no oversell, which means the counter and the database reconcile exactly at the end.
- "Why tiers rather than exact availability counts for partners?"
An exact count is a business metric: a competitor polling it every minute learns sell-through rate for every event, and a scalper's bot uses it to time purchases. Tiers such as
AVAILABLE,LOW, andSOLD_OUTgive partners what they need for their UI without the information.It also lets me cache the availability endpoint aggressively, because a tier changes far less often than a count, so a two-second
max-ageon a tier is almost always a cache hit while the count would invalidate constantly.For our own apps, which are authenticated as first-party, I can expose the exact count on a separate scope. The line I draw is that anything that can be graphed to reveal business performance is not in the partner contract.
Q34. "What is the difference between a collection filter, a search endpoint, and a query resource, and when do you graduate from one to the next?"
Reveal answer
Strong answer A collection filter is query parameters on the list endpoint — /orders?status=PAID&createdAfter=… — with an allow-list of filterable fields, each backed by an index; it covers most needs and stays cacheable.
A search endpoint — /orders/search?q=… or GET /search?type=order — is for free-text or ranked results backed by a search engine, with different semantics: relevance ordering, fuzziness, and no stable cursor without a snapshot.
A query resource is when the query itself is too complex or too long for a URL: the client POSTs a query document to /order-queries, gets a 201 with an id, and reads results from it; this is also the pattern for saved or scheduled reports.
Graduation happens on three signals: URL length or nesting of conditions exceeds what a query string can express cleanly; the query is expensive enough to need asynchronous execution and result caching; or you need to audit or share the query itself.
What I avoid is POST-as-GET for simple filtering, because it throws away caching and idempotency for no gain.
Land it Filter until the URL or the database complains, then make the query a resource with a lifecycle of its own.
- "How long is too long for a URL, and what actually enforces the limit?"
There is no limit in the HTTP standard, but every component has one.
Browsers cope with tens of thousands of characters, but proxies and servers are stricter: Nginx's
large_client_header_buffersdefaults to 8 KB per header line, Tomcat'smaxHttpHeaderSizedefaults to 8 KB for the whole request line and headers, and AWS ALB limits the request line to 16 KB. Beyond the limit the client gets a 414 URI Too Long or a 431 from the proxy, often with no useful body.In practice I treat about 2 KB as the comfortable maximum for a query string, and when a filter expression approaches that, it is a signal to move to a query resource.
CDN cache keys also suffer from long, variably ordered query strings, so I normalise parameter order on the server side.
- "If you must accept a complex filter, what syntax do you use?"
A small, explicit one. For simple cases, named parameters with a fixed operator suffix:
createdAfter,createdBefore,statusas a comma-separated list meaning "any of".If I need combinations, the next step is a structured body posted to a query resource rather than a mini-language in the URL, because a body can be validated against a JSON Schema listing the allowed fields, operators, and nesting depth.
Standardised languages exist — OData's
$filter, RSQL, and the emerging JSON Filter drafts — and they buy tooling at the cost of an unbounded surface: a client can write a filter the database cannot serve.If I adopt one, I wrap it with an allow-list of fields and operators and a cost estimate before execution, which is most of the work anyway.
- "What are the caching consequences of POST-as-search?"
A POST is not cacheable by shared caches, so every search hits the origin, and browsers will not cache it either, so a back button re-submits. For a search endpoint that is usually acceptable because results are personalised or change quickly.
The recent development that helps is the
QUERYmethod, which as of Aug 2026 is an IETF HTTP APIs working group draft: it is a safe, idempotent method with a body, precisely for "a GET that needs a body", and it is defined to be cacheable using the body as part of the key.Support in frameworks and proxies is still patchy, so I would not depend on it in a public API yet, but it is the shape the problem was always waiting for, and I would watch it for internal use.
Q35 · Scenario. "A mobile app breaks after we renamed a field from customer_name to customerName to match a new style guide. The web app was fine. Diagnose and tell me what process was missing."
Reveal answer
Strong answer Symptom: one client class fails after a rename, another survives.
Evidence: the mobile app's parser is strict or maps by exact name and gets null for a required field; the web app ships the same day as the API and was updated together, which is why it was fine.
Causes ranked: a field rename is a breaking change by definition and was treated as cosmetic; no compatibility check ran against the previous contract; mobile clients cannot be redeployed instantly — app-store review and users who never update mean old versions live for months.
The fix: restore customer_name immediately alongside customerName, serving both for at least the mobile support window, mark the old one deprecated in the OpenAPI document with a Sunset date, and measure which app versions still read it.
The missing process: an OpenAPI diff in CI that fails on removed or renamed properties, a written definition of "breaking" that names renames explicitly, consumer-driven contract tests from the mobile team, and a rule that style migrations happen only in a new version or by addition.
For a wholesale naming change the honest route is a new major version with both served in parallel.
Land it There is no such thing as a cosmetic rename in a published API — a name is the contract, and mobile clients remember it for a year.
- "You restored the old field and some mobile users still see the crash. What next?"
Then the old field is not reaching them, or the crash is not the field. I would check the CDN and any response cache, because the broken response without
customer_namemay still be cached for the affected users, and purge it.I would check every path that serves that model: a second endpoint, a webhook, a push notification payload, or a GraphQL type may have been renamed too.
Then I would look at the crash reports by app version and stack trace: if the stack points at a different field, the rename was done as part of a style-guide sweep and other fields changed with it.
And I would confirm that the restored field has the same type and format, not just the same name, since
customer_nameas a string and a restored field that is now an object would crash the same way.- "How do you measure which client versions still read the old field?"
Reads of a response field cannot be observed directly, so I use proxies for it.
Every client sends a
User-Agentor a custom header naming the app and version; the gateway logs it per request, so I can see which app versions are calling at all, and I know from the mobile repository which versions were built against the old contract.That gives me a table of old-contract app versions by traffic share and a decay curve.
The stronger signal is a brownout: omit the old field for five minutes at an announced time and watch crash reports by version; the versions that crash are the ones that depend on it.
For server-side consumers, contract tests in a Pact Broker say exactly who reads what, which is the point of them.
- "How long must the old name live, and who decides?"
As long as the mobile support policy says an app version is supported, which is a product decision I want written down before the first rename, not after.
A typical policy supports the last N versions or anything released in the last twelve months, and forces an update beyond that with a minimum-version check at login.
With that policy, the old field lives until the last supported version that reads it drops out of support, which the version traffic table tells me.
Without a forced-update mechanism, the honest answer is "years", because a fraction of users never update, and that is why I would push for the minimum-version gate as part of the fix.
The
Sunsetheader on the response then carries the actual date so it is visible to every consumer, not just the ones who read email.- "Write the OpenAPI diff rule that would have caught this."
Tools such as oasdiff or openapi-diff compare two documents and classify changes.
In CI I run
oasdiff breaking old.yaml new.yamlagainst the last released document and fail the build on any change in the breaking category, which includes a removed response property, a changed type, and a newly required request property.A rename shows up as a removal plus an addition, so it is caught by the removal.
I extend it with a custom check that any property marked
deprecated: truemust carry anx-sunsetdate, and that a property cannot be removed unless the sunset date has passed.The released document is stored as a build artefact tagged with the release, so the comparison is always against what clients actually generated from, not against the last commit.
Q36. "What does an OpenAPI document give you beyond documentation, and what breaks if it drifts from the running service?"
Reveal answer
Strong answer Beyond documentation it is the contract that machines act on. Client SDKs in six languages are generated from it, so a change to the document is a change to every customer's compile.
Request validation at the gateway rejects anything that does not match the schema before it reaches business code. Contract tests diff the document against the previous release to catch breaking changes, and against live traffic to catch drift.
Mock servers are generated from it so front-end teams work before the backend exists. Security scanners use it to enumerate endpoints and required scopes.
When the document drifts from reality, all of those consumers are wrong at once: the SDK sends a field the server ignores, the gateway rejects valid requests or passes invalid ones, and the mock trains front-end code against a lie.
The defence is to make the document either the source — code generated from it — or generated from code with annotations and verified in CI by replaying its examples against the running service.
Version 3.1 is the target because its schemas are full JSON Schema; 3.2, published September 2025, is a compatible refinement.
Land it OpenAPI is only a contract if something fails when it is wrong — put a test behind it or it is a brochure.
- "How do you test that the document matches the running service?"
Two directions. Request side: a schema validator sits in the integration test suite or at the gateway and rejects any request that does not match the document, so a handler that quietly accepts an undocumented field is exposed when a test uses it.
Response side: every integration test response is validated against the document's response schema for that operation and status; libraries such as swagger-request-validator for Java or the Spring Cloud Contract OpenAPI plugin do this with a filter.
In staging I add a sampling runtime validator that checks one percent of live responses and logs mismatches with the operation id, which catches the data-dependent cases tests never produce, such as a field that is null for legacy rows.
The undocumented endpoint case is covered by comparing the router's registered routes with the document's paths and failing on any difference.
- "What changed in OpenAPI 3.1 that matters, and should we move from 3.0?"
3.1 aligned the schema object with JSON Schema 2020-12, which removed the awkward differences:
nullable: trueis gone in favour oftype: ["string", "null"],exclusiveMinimumis a number rather than a boolean, and you can use full JSON Schema features such as$dynamicRefandunevaluatedProperties.It also added webhooks as a top-level element so a document can describe the callbacks the API sends.
The move is worth it if your tooling supports 3.1, which most major generators and linters did by 2024, but some older generators still produce worse code from 3.1 than from 3.0, so I check the generator matrix before switching.
3.2, published in September 2025, adds things like the
QUERYmethod and tags hierarchy and is backwards compatible with 3.1 documents.- "Where does the document live, and who can change it?"
In the service's repository next to the code, versioned with it, and published as a build artefact on every release to a registry the gateway and SDK pipeline read from.
Changes go through the same pull request review as code, with the diff tool's output posted as a comment so reviewers see "one breaking change" without reading YAML. For design-first teams the document is the first file in a feature branch; for code-first teams it is generated in the build and committed so the diff is visible.
Ownership sits with the team that owns the service, but a platform-level linter with the company conventions runs on every document, and a change flagged as breaking requires an approval from an API reviewer outside the team.
A wiki copy is a lie within a week, so there is no wiki copy.
Q37. "Bulk operations: how do you design POST /orders/batch so partial failure is expressed honestly?"
Reveal answer
Strong answer First decide the atomicity: either all-or-nothing, where the batch is one transaction and any failure rolls back everything with a 422 listing every failing item, or independent, where each item succeeds or fails on its own.
For independent batches the honest response is 207 Multi-Status or, more commonly, a 200 with a results array in the same order as the input, each entry carrying its own status and either the created resource or a Problem Details object.
I include a per-item client reference so callers can correlate without relying on order, cap the batch size at something like 1,000 and reject larger with 413, make the whole batch idempotent with one key and per-item idempotency inside, and if the batch takes long, return 202 with an operation.
I would not return 200 when everything failed, would not stop at the first failure in independent mode, and would not return 500 for one bad item.
Land it A batch endpoint's real contract is its failure shape — decide atomic or independent first, then the status code follows.
- "Show me the response body for an independent batch with one failure."
It would be a 200 with a body like:
{"results": [{"ref": "a1", "status": 201, "order": {…}}, {"ref": "a2", "status": 422, "problem": {"type": "https://problems.example.com/validation", "status": 422, "detail": "quantity must be positive", "errors": [{"field": "/quantity", "message": "must be positive"}]}}, {"ref": "a3", "status": 201, "order": {…}}], "summary": {"succeeded": 2, "failed": 1}}.Each entry mirrors what the single-item endpoint would have returned, including the same Problem Details shape, so a client reuses its existing error handling per item. The
refechoes the client's own reference so it can correlate without relying on order.The summary lets a client decide quickly whether to look at details. The overall status is 200 because the batch itself was processed as requested, even though one member failed.
- "Why not use 207 Multi-Status?"
207 comes from WebDAV, RFC 4918, and its defined body is an XML
multistatuselement, so using it with a JSON body is a borrowed number rather than a standard.Some HTTP libraries and gateways treat 207 as unusual — a few older ones classify it as an error because it is not 200 or 201 — and generated SDKs need a special case for it.
Since the JSON body has to carry per-item statuses anyway, 200 with that body loses nothing and avoids the surprises. I would use 207 only if the API already speaks WebDAV or the consumers explicitly want a status code that says "look inside".
Either way the important part is documented per-item statuses, not the outer number.
- "How do you make per-item idempotency work inside one batch key?"
The batch key covers the whole request: a replay of the same batch returns the same stored results. Inside it, each item needs its own guard so that a batch which crashed halfway can be re-run without re-creating the items that already succeeded.
I use the client's per-item
ref, scoped to the batch key, as the item key: on re-execution, items whose ref already has a result are skipped and their stored result returned.That means the batch processor writes each item's result durably as it goes, which also gives me progress for the asynchronous case.
If the client re-submits with a different batch key but the same items, they are new operations, which is correct: the batch key is the intent, and a new key is a new intent, just as for single requests.
- "When does a batch become an asynchronous job instead?"
When it can exceed the synchronous budget I am willing to promise, which I set at a few seconds. A thousand simple inserts fit; a thousand orders that each call a payment provider do not.
The signal is the p99 of per-item work multiplied by the maximum batch size: if that is above the budget, the endpoint returns 202 with an operation whose result is the same results array, fetched when complete.
I usually make the decision static per endpoint rather than dynamic, so clients know which behaviour to code for.
For genuinely large volumes, hundreds of thousands of rows, the batch endpoint is the wrong tool and I offer a file-based import: upload a file to object storage, submit its reference, and receive a results file with the same per-row shape.
Q38 · Design. "Design the request and response conventions document for a company with 30 teams building REST APIs — the ten rules you would enforce with a linter."
Reveal answer
Strong answer Requirements: consistency across teams, enforceable automatically, and small enough that people read it.
The ten rules: plural lowercase kebab-case paths with no verbs; camelCase JSON properties and ISO 8601 UTC timestamps with a Z suffix; money as integer minor units plus a currency code, never floats; ids as opaque strings, never integers; every non-2xx body is RFC 9457 with a registered type; list endpoints are cursor-paginated with limit capped at 200 and a nextCursor; every POST that creates accepts Idempotency-Key; every response sets an explicit Cache-Control; versioning is a path prefix with a written breaking-change definition; and every API ships an OpenAPI 3.1 document that passes the linter and a diff against the last release in CI. Enforcement: Spectral rules in the repository template and the build, a gateway that refuses to register a route without a passing document, and a review checklist for the judgement calls a linter cannot make.
Trade-off: opinionated conventions frustrate the few APIs that genuinely need a different shape, so there is an exceptions register with an owner. What I would not do is publish a 60-page guide nobody reads or leave the rules unenforced.
Land it Conventions that a linter cannot check are suggestions; ten enforced rules beat sixty documented ones.
- "Requirement change: half the teams are moving to gRPC internally. Does the document survive?"
The document splits into a layer that is protocol-neutral and one that is REST-specific.
Money as integer minor units, opaque string ids, timestamps as UTC, additive-only evolution, a single error taxonomy, cursor pagination with a capped page size, and idempotency on creates all apply to Protobuf messages as much as to JSON; those become the core rules.
The REST-only rules — path naming, Problem Details,
Cache-Control— stay in a REST appendix, and a gRPC appendix adds the equivalents:google.rpc.Statuswith error details, apage_tokenfield per Google's AIP conventions, and Buf lint rules in place of Spectral.The point I would make is that the rules that cost the most to get wrong are the data-shape ones, and they are shared, so the document gets more valuable, not less.
- "Under time pressure, which of the ten rules do you enforce first?"
The ones that are breaking to change later: money as integers, ids as strings, timestamps as UTC ISO 8601, and Problem Details on every error.
Those four are in the data on the wire; a team that ships floats for money or integers for ids will need a major version to fix it. Cursor pagination is fifth, because switching from offset later is a contract change.
Naming conventions,
Cache-Controldefaults, idempotency headers, and the OpenAPI gate are all things that can be added to an existing API without breaking clients, so they can wait a quarter.I would ship those first four as Spectral rules in a shared package in a week, and I would rather have four rules enforced everywhere than ten rules enforced nowhere.
- "How do you handle the team that says their API genuinely needs to break a rule?"
With an exceptions register rather than a fight.
The team writes a one-page request naming the rule, the reason, the consumers affected, and an expiry date; an API reviewer outside the team approves or not; the exception is recorded in the document as a Spectral override with a link to the request, so the linter passes for that path only.
The register is reviewed quarterly and expired exceptions fail the build again. Most requests turn out to be a misunderstanding of the rule or a case the rule already allows, and the conversation is worth having.
Genuine exceptions — a streaming endpoint that cannot use Problem Details, an integration that must mirror a partner's XML — get recorded, which is better than a rule everyone quietly ignores.
- "What would a Spectral rule for one of these actually look like?"
The money rule is a good example.
In the ruleset YAML, a rule named
money-as-minor-unitstargets every schema property whose name matchesamount,price, ortotalwith agivenJSONPath such as$..properties[?(@property.match(/amount|price|total/i))], and athenthat assertstypeequalsintegerand that a siblingcurrencyproperty exists on the parent.Severity is error so the build fails. A second rule,
ids-are-strings, targets$..properties.idand any property ending inIdand assertstype: string. The ruleset is published as an npm package that every repository extends, so a rule change rolls out on the next build everywhere.The rules are unit-tested with fixture documents that should pass and fail, because a linter rule with a wrong JSONPath silently enforces nothing.
Q39. "What are the arguments for and against JSON as the only representation of a public API, and when would you add another?"
Reveal answer
Strong answer For JSON only: every language parses it, it is readable in a browser and in logs, tooling from OpenAPI to gateways assumes it, and one representation means one set of tests.
Against: it has no integer size, so 64-bit ids must be strings to survive JavaScript's number type; it has no binary type, so files are base64 and 33% larger; it has no schema on the wire; and for high-volume numeric data it is verbose and slow to parse compared to Protobuf or CBOR. I would add a second representation in narrow cases: CSV or newline-delimited JSON for bulk export endpoints, because clients stream them into spreadsheets and pipelines; Protobuf or gRPC for internal high-throughput consumers of the same data; multipart or direct object-store upload for files rather than base64.
Each addition is negotiated via Accept and must be documented in the contract. What I would not do is add XML because one partner asked, unless the partner is large enough to fund its lifetime maintenance.
Land it JSON by default, with integers as strings and files out of band — add a representation only when a whole class of clients needs it.
- "What is the actual cost of JSON versus Protobuf for a typical API payload?"
For a typical order object of a few hundred bytes, Protobuf is roughly two to five times smaller before compression and the gap narrows to under two times after gzip, since JSON's repeated field names compress well.
Parsing is where the difference is larger: benchmarks put Protobuf decoding at several times the throughput of Jackson for the same data, because there is no text to tokenise and no field-name lookup.
Whether it matters depends on volume: at a thousand requests a second the JSON cost is a fraction of a core and irrelevant next to the database; at a hundred thousand messages a second on a hot internal path it is the difference between two and eight instances.
So the argument for a second representation is a measured CPU or bandwidth budget, not a general preference.
- "How would you expose CSV and newline-delimited JSON from the same endpoint?"
Via
Acceptand, for browser links, aformatquery parameter as a fallback.The handler produces a stream of rows from the same query and hands it to a writer chosen by media type:
text/csvwith a header row and RFC 4180 quoting, orapplication/x-ndjsonwith one JSON object per line.Both are streamed with chunked encoding so a million rows never sit in memory, which in Spring is a
StreamingResponseBodyor aResponseBodyEmitter.The important discipline is that the row schema is the same in every format, documented once, and that
Vary: Acceptis set so a cache does not serve CSV to a JSON client.Dates and money follow the same conventions as the JSON API, so a data engineer's pipeline does not need format-specific parsing.
- "Why is base64 in JSON so bad for files, given it works?"
It works for small things such as an avatar, and it is wrong for anything else for four reasons.
The size overhead is 33% on the wire and more in memory, since the JSON parser materialises the string before the decoder turns it back into bytes, so a 100 MB file becomes 133 MB of text and then 100 MB of bytes in the same heap.
The request cannot be streamed; the parser needs the whole document. The file's bytes go through the API servers, which is exactly what the upload design avoids.
And the metadata and the bytes are coupled, so a retry of a failed upload re-sends the whole JSON. Multipart requests fix the encoding overhead but not the other three, which is why pre-signed URLs to object storage are the answer beyond a few megabytes.
Q40 · Scenario. "A partner's integration sends 64-bit order ids that arrive at your API off by a few units — 9007199254740993 becomes 9007199254740992. Where is the bug?"
Reveal answer
Strong answer Symptom: large integers rounding to nearby even values, which is the signature of IEEE 754 double precision.
Evidence: the number 2 to the power 53 is 9007199254740992, and every value above it loses precision as a JavaScript number; ask the partner what runtime parses the JSON and I expect Node or a browser.
Causes ranked: our API emits ids as JSON numbers, the partner's JSON parser turns them into doubles, and the id loses its low bits before their code ever sees it; less likely, a spreadsheet or a logging step in between did the same.
The fix on our side is to emit ids as strings in the JSON — Jackson does this with @JsonSerialize(using = ToStringSerializer.class) or a global module — and to declare them as type: string in OpenAPI, delivered additively by adding a string field alongside the numeric one and deprecating the number.
The partner's workaround meanwhile is a parser with BigInt support. Prevention: the conventions rule that ids are opaque strings, and a contract test that round-trips an id above 2 to the 53rd.
Land it JSON numbers are doubles to half the world's parsers; any id that can exceed 2⁵³ goes on the wire as a string.
- "You switched ids to strings and the partner still reports mismatches on a few records. What next?"
Then some path still carries a number. I would grep our serialised outputs — webhooks, exports, error bodies, and the
Locationheader — for numeric ids, because a global Jackson module fixes response bodies but not a hand-built webhook payload or a CSV export.I would ask the partner for the exact records and the source they came from; if they all came through one path, that is the leak.
If the mismatches are historical, the partner's database already holds rounded values from before the fix, and the remedy is a reconciliation where we send them the correct ids for the affected range.
And I would check their side once more, since a JavaScript
parseInton the new string field reproduces the bug perfectly; the SDK they use must keep the id as a string end to end.- "Where exactly does the precision loss happen — in the parser, or later?"
In the parser, at the moment the token becomes a number.
JavaScript's
JSON.parseturns every numeric literal into an IEEE 754 double, which has 53 bits of significand, so any integer above 2 to the 53rd, which is 9,007,199,254,740,992, is rounded to the nearest representable double before any application code runs.The value 9007199254740993 is odd, and doubles at that magnitude can only represent even numbers, so it lands on 9007199254740992. Python, Java, and Go parsers keep arbitrary or 64-bit integers, which is why the bug is partner-specific.
There is no way to recover the low bits after parsing; the only fixes are to not emit a number, or to use a parser such as
JSON.parsewith a reviver plusjson-bigintthat reads the raw token.- "Do you make the same rule for money and timestamps?"
Money as integer minor units is safe up to 2 to the 53rd, which is about 90 trillion in cents, so a number is fine for any real amount and I keep it numeric because clients do arithmetic on it.
Timestamps as epoch milliseconds are around 1.7 trillion, also safe. The rule for those is about semantics, not precision: integers for money because floats cannot represent 0.10 exactly, and ISO 8601 strings for timestamps because a string is unambiguous about timezone and readable in logs.
The general principle is that a JSON number is safe when its magnitude stays under 2 to the 53rd and the value is genuinely something to compute with; an identifier fails the second test and often the first, so it is a string regardless of its size today.
08 · DrillREST Design — Pagination, Versioning, Errors, Idempotency — Q41–Q80
This section is the one interviewers use to separate people who have shipped an endpoint from people who have owned an API for years. Every topic here — pagination, versioning, idempotency, webhooks, rate limits, files — has a naive design that works for the first year and an incident that follows. The design questions expect requirements, a design, trade-offs, and what you would refuse to do.
These questions test whether you can explain why deep pages get slow, how a cursor fixes it, and what you give up — with the SQL and the index named.
Q41 · Scenario. "The p99 of the orders list endpoint grew 40× over a year as the table grew from 1 million to 40 million rows. The query uses an index and returns 100 rows. Nothing else changed. Diagnose."
Reveal answer
The real test Whether you jump to "offset pagination" from the growth pattern and can prove it with the plan.
Strong answer In order:
- Symptom: latency that grows with table size for a fixed-size result, and specifically at p99 rather than p50, which means the slow requests are a subset — deep pages.
- Evidence: log the
pageoroffsetparameter against latency and I expect a straight line; runEXPLAIN ANALYZEon a deep page and see the index scan reporting rows read far above rows returned, for instance 2 million read for 100 returned. - Causes ranked: offset pagination —
LIMIT 100 OFFSET 2000000walks and discards two million index entries; secondarily, aCOUNT(*)for "total pages" on every request, which is a full scan at 40 million rows; thirdly, a sort on a column not covered by the index. - Fix: keyset pagination on
(created_at, id)with a composite index, an opaque cursor, and no total count — offer an approximate count from statistics if the UI insists. The deep page then costs the same as page one. - Prevention: the conventions rule that lists are cursor-paginated, a load test that walks to the last page, and a latency alert per endpoint that includes the p99 so growth is seen before customers see it.
Land it Offset cost is proportional to how far in you are; a cursor makes every page cost the same, at the price of "jump to page N".
- "You moved to keyset pagination and the p99 is better but still 5× what it was a year ago. What next?"
Then a second cost is still scaling with the table. The first suspect is the count query, if it survived the migration in any form, including a "has more than 10,000" check.
The second is the filter: if the endpoint filters by
customer_idand the composite index is(created_at, id)without the filter column leading, the engine walks the index in time order and discards rows from other customers, which scales with the table.EXPLAIN ANALYZEshows it as rows removed by filter. The third is a join or a sub-select per row for something like order line counts, which was cheap on a small table and now misses cache.I would also look at whether the p99 is a different population now — the first page for customers with huge histories — and index for that shape.
- "What does the EXPLAIN output look like for the bad query and the good one?"
For
LIMIT 100 OFFSET 2000000in PostgreSQL, the plan shows a Limit node over an Index Scan, and the important line is on the scan: actual rows 2,000,100 and a large buffers-read figure, with the Limit node reporting rows 100.The offset is applied after reading, and the plan says so. For the keyset query, the Index Scan node shows an index condition of
(created_at, id) < (…), actual rows 101, and buffers in the low tens.If the keyset plan shows a Sort node, the index does not match the ORDER BY direction and the engine is reading a range then sorting, which is still bounded but wasteful.
If it shows a Filter line removing many rows, a filter column is missing from the index. Those two lines are what I look for every time.
- "Why did p50 stay fine while p99 grew?"
Because most clients read the first few pages, and page one costs the same regardless of table size: the index seek finds the newest rows immediately.
The p99 is dominated by the small fraction of requests that ask for deep pages — an integration walking the whole collection nightly, or a UI with a "last page" button — and those requests scale with how deep they go, which grows with the table.
This is why per-endpoint latency percentiles are more useful than averages: an average would have shown a modest rise, and the p99 shows a population of requests whose cost is unbounded.
Once I graph latency against the offset parameter, the correlation is a straight line, and that graph is the artefact I would show the team to justify the migration.
- "How do you migrate clients from offset to cursor without a flag day?"
Serve both for a while. The endpoint keeps accepting
pageandoffsetbut caps the maximum offset at something like 10,000 with a 400 beyond it, and every response — including offset ones — includes anextCursorso a client can switch mid-walk.The SDK's iterator moves to cursors in its next release, which migrates most consumers silently. Deep-offset callers are visible in the logs by their offset values, so I contact them directly, and the
Deprecationheader appears on any response served via offset.After the window, offset parameters return 400 with a Problem Details type pointing at the cursor documentation. The database gets the composite index first, before any client changes, because the index is what makes the cursor path fast and it is invisible to clients.
Q42. "Write the SQL and describe the index for cursor pagination sorted newest first, and explain why the cursor needs two columns."
Reveal answer
Strong answer The query for a page after a cursor is a row-value comparison, which PostgreSQL and MySQL 8 both optimise with a composite index:
SELECT id, created_at, status, total_cents
FROM orders
WHERE (created_at, id) < (:cursor_ts, :cursor_id)
ORDER BY created_at DESC, id DESC
LIMIT 101; -- one extra row tells us whether a next page exists
The index is CREATE INDEX ON orders (created_at DESC, id DESC), matching the sort direction so the engine reads the leaf pages in order without a sort step. The cursor needs two columns because created_at is not unique: two orders in the same millisecond that straddle a page boundary would be skipped or duplicated if the cursor were the timestamp alone. Adding the primary key makes the sort key unique, so "strictly less than this pair" is an exact position. I fetch limit + 1 rows so I know whether to emit a next cursor without a second count query. The cursor sent to the client is base64 of the pair, marked opaque, so I can change its contents later without breaking anyone. For filters, the filter columns go before the sort columns in the index, and the cursor must encode the filter too or the client could reuse a cursor across different filters.
Going deeper Row-value comparison is the clean form, but its index use is engine-specific. PostgreSQL turns (created_at, id) < (:ts, :id) into a single index range condition. MySQL 8 accepts the syntax but, as of Aug 2026, does not always use it as a tight range on a composite index and may scan more than needed; the portable expansion is:
WHERE created_at < :ts
OR (created_at = :ts AND id < :id)
ORDER BY created_at DESC, id DESC
LIMIT 101;
which every planner handles, at the cost of an OR that some engines split into two index ranges. The other detail worth naming is the index direction: an index on (created_at, id) with default ascending order can still serve ORDER BY created_at DESC, id DESC by a backward scan in PostgreSQL, because both columns reverse together; what it cannot serve without a sort is a mixed order such as created_at DESC, id ASC, which needs the index to be declared with matching per-column directions. I check for the absence of a Sort node in EXPLAIN after creating the index, not before.
Going deeper Row-value comparison is the clean form, but its index use is engine-specific. PostgreSQL turns (created_at, id) < (:ts, :id) into a single index range condition. MySQL 8 accepts the syntax but, as of Aug 2026, does not always use it as a tight range on a composite index and may scan more than needed; the portable expansion is:
WHERE created_at < :ts
OR (created_at = :ts AND id < :id)
ORDER BY created_at DESC, id DESC
LIMIT 101;
which every planner handles, at the cost of an OR that some engines split into two index ranges. The other detail worth naming is the index direction: an index on (created_at, id) with default ascending order can still serve ORDER BY created_at DESC, id DESC by a backward scan in PostgreSQL, because both columns reverse together; what it cannot serve without a sort is a mixed order such as created_at DESC, id ASC, which needs the index to be declared with matching per-column directions. I check for the absence of a Sort node in EXPLAIN after creating the index, not before.
Land it Every keyset ends in a unique column and has an index in the same order — miss either and pages overlap or the seek becomes a scan.
- "Show me what the cursor contains and how you protect it."
The cursor is a small JSON such as
{"ts": "2026-08-27T10:15:00.123Z", "id": "ord_9f3", "f": "a1b2c3", "v": 1}, base64url-encoded so it is URL-safe.tsandidare the last row's sort values,fis a hash of the filter and sort parameters so the cursor cannot be reused with different filters, andvis a format version so I can change the contents later.I append an HMAC over the payload using a server-side secret, so a client cannot craft a cursor that points into another tenant's rows or that changes the sort; a tampered cursor gets 400 with a type of
invalid-cursor.The client is told the cursor is opaque and expires, which lets me change the encoding at any time. It carries no secrets itself, just position, so it is safe to log.
- "What happens when the client's filter changes between pages, or a row is inserted with an older timestamp?"
The filter hash in the cursor catches the first case: a cursor issued for
status=PAIDpresented withstatus=SHIPPEDgets a 400, because the position from one ordering is meaningless in another.For the second, keyset pagination promises no duplicates and no gaps for rows that existed and did not move; a row inserted behind the reader's position is simply not seen in this walk, and a row inserted ahead of it will be seen.
For a newest-first feed that is the right behaviour: new rows appear at the top on the next refresh.
If
created_atis set by application clocks that can be skewed, a row can be committed with a timestamp older than rows already read and be missed; the fix for a change feed is a commit-ordered sequence, which is the point of the next question.- "How does this look with Spring Data JPA — does Pageable help?"
PageablewithPageRequest.of(page, size)is offset pagination and issues a count query forPage, so it is exactly what I am trying to avoid.Since Spring Data 3.1 there is
ScrollPosition.keyset()withWindowIterator, which generates the keyset predicate from the sort and the last row's values, and returns aWindowwithhasNext(). It works well for straightforward sorts, and I still verify the generated SQL and the plan.For anything with custom filters I write the query by hand in JPQL or with
JdbcClient, because I want to control the exact predicate and thelimit + 1trick.Returning
Slicerather thanPageis the smaller change if a team is stuck on offset, because it drops the count query while keeping the interface.
Q43. "When is offset pagination the right choice despite its cost?"
Reveal answer
Strong answer When the collection is small and bounded — a few thousand rows per tenant — so even the last page is cheap; when the product genuinely needs random access such as "go to page 37" or a numbered pager in an admin table; when the sort order is user-selectable across many columns and encoding each into a cursor would be unwieldy; and when the results come from a search engine that already computes a ranked window and does not support cursors without a snapshot. In those cases I still cap the maximum offset — say 10,000 rows, which is what Elasticsearch does by default — and return 400 beyond it, and I avoid an exact total count on every page. I would not use offset for anything a program iterates end to end, for any collection that grows without bound, or for feeds where rows are inserted at the front, because the pages shift under the reader.
Land it Offset is a UI convenience for small, stable collections; the moment a machine walks the pages, switch to a cursor.
- "How would you give a numbered pager to a UI on top of a cursor API?"
With a hybrid: the API returns cursors, and the UI keeps a stack of the cursors it has seen, so "previous" and "go to page 3 of the pages I have visited" work without offsets.
For "jump to page 37" from nowhere, there is no honest cursor answer, and I push back on the product requirement, because in practice users use next, previous, first, and last. "Last" is a cursor with the sort reversed.
If the requirement survives, I offer a bounded offset — up to 10,000 rows — for that UI only, on a collection I know is small per tenant, and I measure how often deep jumps actually happen.
In every case I have seen, the numbered pager was a habit from a previous product, and a "load more" or infinite scroll served the users better.
- "Why does Elasticsearch cap at 10,000, and what does it offer instead?"
Because a deep page in a distributed search means each shard must return the top
from + sizehits to the coordinating node, which then merges and discards them; page 1,000 of 10 across 5 shards is 50,000 documents in memory on the coordinator per request.The
index.max_result_windowsetting defaults to 10,000 to bound that. The alternatives aresearch_after, which is keyset pagination on the sort values with a tie-breaker on a unique field, and a point-in-time reader so the walk sees a consistent snapshot despite refreshes.The old scroll API did the same for exports but held resources per scroll and is deprecated in favour of PIT plus
search_after. It is the same lesson as the database: deep offsets are a coordinator's problem, and keyset makes each page constant cost.- "A client insists on offset for an unbounded collection. What guardrails do you put in?"
A hard maximum offset, typically 10,000, returning 400 with a Problem Details type of
offset-too-largeand a detail pointing at the cursor parameter. A maximum page size of 200. No count query unless requested, and a cached one at that.A separate, lower rate limit for offset requests above a threshold, since those are the expensive ones. A latency metric tagged by offset bucket so I can see the cost the client is causing.
And a
nextCursorin every offset response so they can switch with no extra work. Beyond the guardrails, I would look at why they want it: a nightly full walk is an export, a UI wants a pager, and both have better answers than deep offsets. The guardrails buy time; they are not the design.
Q44 · Design. "Design the list endpoint for a transactions API used by both a mobile app and nightly reconciliation exports of up to 50 million rows per customer."
Reveal answer
Strong answer Requirements: interactive paging for the app, complete and consistent iteration for exports, stable ordering, and no load cliffs. Design: one cursor-paginated endpoint GET /transactions?limit=…&cursor=… sorted by (posted_at, id) descending, with filters on account, date range, and type, all indexed with the filter columns leading.
The cursor encodes sort position, filter hash, and a snapshot boundary — the maximum id at the time the first page was requested — so an export sees a consistent set even as new rows arrive.
Limit defaults to 50 for the app and allows up to 1,000 for exports identified by scope.
For the 50-million-row case I add a separate asynchronous export: POST /transaction-exports returns 202 and an operation; the job streams newline-delimited JSON or Parquet to object storage and the client downloads a signed URL, because paging 50,000 times through an API is the wrong tool.
Trade-offs: no total count, and the snapshot boundary means an export excludes rows posted after it began, which reconciliation prefers.
I would not offer offset paging for the app "for convenience", would not let sort be arbitrary, and would not stream 50 million rows through the request path.
Land it Same data, two access patterns: a cursor for people, a file for machines that want everything.
- "Requirement change: reconciliation now needs to see rows posted after the export began. Does the snapshot boundary still work?"
Then the export becomes a change feed rather than a snapshot.
The manifest records the boundary — the maximum commit sequence at the start — and the next night's export asks for everything after that boundary, so nothing is lost between runs; rows that arrived during last night's run are simply in tonight's.
If they need the late rows in the same night, I add an incremental endpoint,
GET /transactions/changes?after=<sequence>, keyed on a commit-ordered sequence rather thanposted_at, which they call at the end of the export to pick up the tail.The key design point is that the boundary must be a value assigned at commit time, because a timestamp assigned before a long transaction commits can be older than rows already exported and would be missed forever.
- "Under time pressure, what would you cut?"
I would cut the separate asynchronous export and the Parquet writer, and instead raise the page size ceiling to 1,000 for the reconciliation scope on the cursor endpoint, with a documented rate limit; 50,000 pages a night is ugly but it works on a read replica, and the snapshot boundary in the cursor gives them consistency.
I would cut the filter hash in the cursor and document that cursors must not be reused across filters.
What I would not cut is the composite index with the filter column leading, the keyset ordering with the id tie-breaker, and the cursor being opaque and signed, because those decide whether the endpoint survives the year.
The export job then becomes the first thing on the next quarter's list, and the cursor endpoint stays for the app either way.
- "How do the mobile app and the export share one endpoint without one hurting the other?"
Through scopes and routing rather than separate code. The token for the app has a scope that caps
limitat 100 and hits the primary or a low-lag replica, because the user wants to see the transaction they just made.The reconciliation token has an export scope that allows
limitup to 1,000 and is routed by the gateway to a dedicated read replica, with its own concurrency cap so a nightly job cannot occupy the connection pool the app uses.Both call the same handler and the same query, so there is one implementation to test. Metrics are tagged by scope, so I can see the export's latency separately and alert on the app's p99 without the export's pages distorting it.
- "What is the snapshot boundary in the cursor, exactly, and what does it cost?"
It is a value captured on the first page — the maximum id, or better a commit sequence number, at that moment — and stored in the cursor.
Every subsequent page adds
AND id <= :boundaryto the query, so rows inserted after the walk began are excluded and the client sees the collection as it was. The cost is one extra predicate that the index already covers, so essentially nothing at query time.The trade-off is staleness: a walk that takes an hour excludes an hour of new rows, which reconciliation wants and an interactive app does not, so the app's cursor omits the boundary and refreshes from the top.
Sequence-based boundaries are safer than id-based when ids are UUIDs, so I keep a monotonically increasing
seqcolumn assigned by the database.
Q45. "How do you expose sorting and filtering safely — what can go wrong if you let clients sort by any field?"
Reveal answer
Strong answer I allow-list both.
Every sortable field is a promise to have an index that supports that order combined with the common filters, so allowing arbitrary sort means arbitrary full scans and in-memory sorts on a 40-million-row table; one client sorting by notes can consume a database core for minutes.
Filters are the same: an un-indexed filter column plus a sort is a scan.
Syntax: ?sort=-createdAt,id with a leading minus for descending, and filters as named parameters with a small operator set such as createdAfter and createdBefore rather than a generic expression language, which is an injection surface and a planner nightmare.
Unknown fields get 400 with a Problem Details body naming the allowed ones. With cursor pagination I fix the tie-breaker as the id and encode the sort into the cursor so it cannot be switched mid-iteration.
If a customer truly needs ad-hoc queries, that is the asynchronous query-resource pattern with its own quota, not the list endpoint.
Land it Every sortable field is an index you are committing to maintain — allow-list, and treat the list as a schema decision.
- "How many indexes does a sort allow-list of five fields and three filters imply?"
Potentially many, and that is the point of the allow-list conversation.
A keyset query needs the filter columns leading in the index and the sort columns following, so each combination of filter set and sort order is a candidate index: five sorts times a few common filter shapes could be fifteen indexes on one table, each costing write amplification and storage.
In practice I look at what clients use and index the three or four combinations that carry real traffic, and I document that the other combinations work but may be slower and are rate-limited.
The database's own statistics —
pg_stat_user_indexesin PostgreSQL — tell me which indexes are used and which are dead weight. An allow-list without this analysis is just a slower way to let clients pick a full scan.- "How do you verify in production that no client is causing a scan?"
With the database's slow query log or
pg_stat_statements, grouped by normalised query text, which shows me the shapes that consume time.A list endpoint's query normalises to one text per sort and filter combination, so a combination that appears with high total time and a high rows-read-to-rows-returned ratio is the one to index or remove.
On the application side, I tag the request metrics with the sort and filter fields used, so I can see which combinations are called and correlate with latency.
A synthetic check runs each allowed combination nightly against a production-sized dataset and fails if any plan contains a sequential scan or a sort node. That last one is the guard that catches a new allowed field added without its index.
- "Why not accept a generic expression language like OData $filter?"
Because the surface is unbounded. An expression language lets a client combine any fields with any operators, including functions such as
containsandtolowerthat defeat indexes entirely, so the database plan is decided by the client.It is also an injection and denial-of-service surface: the parser must be perfect, and a single deeply nested expression can be expensive to plan.
If a product genuinely needs it, I run it through a cost gate: parse into an abstract syntax tree, reject anything outside an allow-list of fields and operators, estimate the cost with
EXPLAINbefore executing, and run it under a statement timeout and its own quota.At that point I have built most of a query resource, so I usually make it one, with asynchronous execution and results stored, and keep the list endpoint simple.
Q46 · Scenario. "A client walking a cursor-paginated feed complains it sees some orders twice and misses others. The cursor is the updated_at timestamp. What is wrong?"
Reveal answer
Strong answer Symptom: duplicates and gaps in a keyset iteration, which means the sort key is not stable or not unique.
Evidence: check whether updated_at changes on rows the client has already passed — an order updated after the client read it moves forward in the sort and appears again — and whether multiple rows share a timestamp at a page boundary.
Causes ranked: the key is mutable, so rows move; the key is not unique, so boundaries are ambiguous; the cursor has no tie-breaker.
The fix is to sort by an immutable, unique key such as (created_at, id) for a listing, or, if the client genuinely wants "changes since", to build a change feed from an append-only, monotonically increasing sequence — a change-log table or a database sequence assigned at commit — and cursor on that.
Prevention: a design rule that keyset columns are immutable and end in a unique column, and a test that mutates rows during iteration and asserts no duplicates or gaps.
Land it A cursor on a mutable column is a moving target; a change feed needs an append-only sequence, not a timestamp.
- "You switched the cursor to (created_at, id) and the client still reports missing rows. What next?"
Then the rows are missing for a different reason.
If the client's goal is "all orders that changed", switching to
created_atmade that impossible: updated orders no longer appear at all, so their report of missing rows is the new design working as intended, and they need the change feed.If the goal was a listing and rows are genuinely missing, I would look at commit-time skew —
created_atset by the application before a long transaction commits, so the row lands behind the reader's position — and at replica lag, since a page read from a replica can miss rows the previous page on the primary implied.I would also test the boundary condition with two rows sharing a timestamp at a page edge, because a comparison of
<=where<was intended would skip exactly one row per page.- "How do you build the change feed sequence, concretely?"
A separate append-only table,
order_changes, with aseqcolumn from a database sequence, the order id, the change type, and the timestamp, written in the same transaction as every order write, or populated by a trigger.The feed endpoint is
GET /orders/changes?after=<seq>&limit=…, ordered byseq, with the cursor being the lastseqseen.The subtlety is that sequence values are assigned when the row is inserted, not when the transaction commits, so a slow transaction can commit a lower sequence after a faster one with a higher sequence has already been read.
The fixes are a small safety margin — only serve changes older than a few seconds — or, in PostgreSQL, ordering by the transaction's commit timestamp with
track_commit_timestamp, or using logical decoding, which is commit-ordered by construction.- "Is a timestamp ever an acceptable cursor?"
Yes, when it is immutable and combined with a unique tie-breaker, which is the
(created_at, id)pattern. The moment either property fails, the cursor lies: a mutable timestamp moves rows, and a non-unique one makes boundaries ambiguous.There is one more condition people forget: the timestamp must be assigned by a single clock, meaning the database's
now()at insert, not each application instance's clock, because skew between instances of even a few hundred milliseconds reorders rows relative to their commit order.When all three hold — immutable, tie-broken, single clock — a timestamp cursor is fine and has the advantage of being human-readable.
When any of them fails, I use a sequence, and I treat "the cursor is
updated_at" in a design review as a bug to be fixed before shipping.
Q47. "How would you offer 'total count' on a paginated endpoint without paying for it on every request?"
Reveal answer
Strong answer First I ask whether the product needs it — most UIs only need "is there more", which the extra fetched row answers for free.
If a count is required, the options in order of cost: an approximate count from planner statistics, which is instant and good enough for "about 1.2 million results"; an exact count only on the first page and only when the client asks with ?includeTotal=true, cached for a minute per filter combination; a materialised counter maintained by the writer for common filters such as per-customer totals; or a separate HEAD or /count endpoint with its own rate limit so a client that wants the number pays for it explicitly.
For search-backed lists the engine gives a bounded count, such as "10,000+".
What I would not do is SELECT COUNT(*) with the full filter on every page, which at 40 million rows is a full scan per click and is usually the second thing wrong with a slow list endpoint after offset.
Land it "Has more" is free; an exact count is a scan — make the client ask for it and cache the answer.
- "How do you get the approximate count, and how approximate is it?"
For an unfiltered table, PostgreSQL's
pg_class.reltuplesgives the planner's row estimate, refreshed by autovacuum's analyse, typically within a few percent for a steadily growing table.For a filtered count, I run
EXPLAIN (FORMAT JSON) SELECT … WHERE …and read the plan's estimated rows, which uses column statistics and is often within a factor of two, sometimes much worse for correlated filters.That is fine for "about 1.2 million" in a UI and not fine for anything a customer reconciles against.
For a bounded exact count,
SELECT COUNT(*) FROM (SELECT 1 FROM orders WHERE … LIMIT 10001) tgives an exact number up to 10,000 and "more than 10,000" above it, at bounded cost, which is the pattern search engines use and the one I reach for most.- "How would you maintain the materialised per-customer counter without it drifting?"
The writer updates the counter in the same transaction as the insert or delete, so it cannot drift under normal operation; the risk is hot-row contention on customers with very high write rates, which I mitigate by sharding the counter into a handful of rows summed on read, or by moving the update to an asynchronous consumer of the change feed with a small lag.
Either way I run a nightly reconciliation job that recomputes counts for a sample of customers and alerts on a mismatch above a threshold, and a full recompute on demand.
For a counter with a lag, the API documents that the total is eventually consistent and includes an
asOftimestamp. The counter table is tiny and indexed by customer, so the read is a point lookup.- "What does the response look like when the count is optional?"
The page body has
items,nextCursor, and ametaobject that always includeshasMoreand includestotalCountonly when requested with?includeTotal=true, withtotalCountIsEstimate: truewhen it came from statistics. The OpenAPI document markstotalCountas optional so generated clients handle its absence.Alternatively, the count is exposed on a
HEADto the collection via a header such asX-Total-Count, which lets a client ask for the number without a page at all, but headers are easy to miss in documentation, so I prefer the body.Either way, the count is cached for a minute per filter combination and the endpoint that computes it has its own rate limit, so the cost of the exact count is visible and bounded.
Q48. "Partial responses and field selection in REST: worth it, and how do you implement them without reinventing GraphQL?"
Reveal answer
Strong answer Worth it on the two or three resources that are large and read from bandwidth-sensitive clients — a product with 80 attributes read by a mobile list screen.
The implementation is a ?fields=id,name,price parameter with an allow-list, applied at serialisation with a Jackson filter or a projection at the query level so the database also reads less.
Nested selection with a small syntax such as fields=id,customer(name) is where I stop, because beyond that I am writing a query language with worse tooling than GraphQL. The fields value must be part of the cache key, which Vary cannot express, so it goes in the URL where caches already key on it.
An alternative that often serves better is a fixed pair of representations — a summary in list responses and the full object on the item endpoint — because two shapes are easier to document, test, and cache than a combinatorial space.
I would not add field selection to every endpoint by default; it doubles the test surface for a benefit most clients never use.
Land it Two fixed shapes beat a field-selection language for most APIs; add selection only where a measured payload problem exists.
- "How do you implement fields= in Spring without leaking or breaking serialisation?"
Jackson's
@JsonFilteron the DTO with aSimpleBeanPropertyFilter.filterOutAllExcept(fields)applied through aMappingJacksonValuewrapper in the controller is the simplest working version. Before applying it, the requested names are validated against an allow-list derived from the DTO, and unknown names return 400 naming the allowed fields.The allow-list must exclude anything sensitive that exists on the DTO but is normally suppressed by a view or role, otherwise a client can select its way to a field it should not see.
For the database side, a projection interface or a constructor expression in the JPQL selects only needed columns when the requested set is small, which is where the real saving is for wide rows.
The response also sets
Varyto nothing extra, because the query string is already in the cache key.- "Does field selection interact badly with ETags and caching?"
It multiplies the cache entries: every distinct
fieldsvalue is a separate URL and therefore a separate cached representation with its own ETag, so ten common field sets means ten cache entries per resource and a lower hit rate per entry.It also makes the ETag computation trickier if the tag is a body hash, though a version-based tag stays the same across projections, which is another argument for version tags.
To keep the cache useful I normalise the parameter — sorted, deduplicated, lowercase — before it becomes the cache key, either in the gateway or by redirecting to the canonical form.
And I publish a handful of named presets, such as
view=summary, so most clients converge on the same few keys instead of inventing their own combinations.- "When would you actually reach for GraphQL instead?"
When the consumer is a set of screens that each need a different slice of a graph of related resources, and the alternative is either many round trips or a bespoke endpoint per screen.
A mobile product page that needs a product, its reviews, the reviewer's name, and stock at the nearest store is the textbook case.
The signal that REST is straining is when I find myself adding
expand=parameters that embed related resources several levels deep, because at that point I am building a query language with worse tooling.The costs to weigh are caching, which goes from free HTTP caching to persisted queries and a client-side cache, and query cost control, which becomes my problem. For an API consumed by many external servers, REST's simplicity and caching usually win.
This group checks whether you have a precise definition of "breaking", a policy with dates, and a mechanism you can defend — and whether you know what Spring gives you now.
Q49. "Define a breaking change for a JSON REST API precisely. Which changes are safe, which are not, and which depend on the client?"
Reveal answer
Strong answer A change is breaking if a client that was correct against the old contract can fail against the new one.
Safe: adding an optional response field; adding an optional request parameter or body field; adding a new endpoint; adding a new error type under an existing status; relaxing validation so previously rejected input is accepted.
Breaking: removing or renaming any field, parameter, or endpoint; changing a field's type or format, including number to string; making an optional request field required; tightening validation so previously accepted input is rejected; changing the status code of an existing outcome; changing the meaning of a field while keeping its name; reordering an array clients treat as positional.
Client-dependent, which I treat as breaking unless the contract says otherwise: adding a new value to an enum, because strict clients reject unknown values; adding a required response field that changes nothing for readers but breaks clients that validate response schemas strictly; and changing default sort order.
The contract should state that clients must ignore unknown fields and tolerate unknown enum values, which moves two of those into the safe column.
Land it Write the definition down and put it in the linter — "we thought it was additive" is how every rename ships.
- "Is changing a field's maximum length or a validation rule breaking?"
It depends on direction. Relaxing an input constraint — allowing longer strings, more items, a wider number range — is safe on the request side, because everything that used to be accepted still is.
Tightening one is breaking, because a client that sent a 300-character note will start getting 422.
On the response side it reverses: a field that was at most 100 characters and may now be 500 is a break for clients that allocated a fixed-width column or a display, which is a client-dependent case I treat as breaking for strings and safe for most.
Enum-like string fields with a documented set of values follow the enum rule. My definition document lists these explicitly per direction, because "relaxing is safe" is only true for inputs.
- "Is changing a response field's value from null to a real value breaking?"
Not under the contract if the field was declared nullable, since the client had to handle both.
It is a behavioural change, though, and behavioural changes can break clients that depended on the old behaviour by accident: a client that used "null means not applicable" for a branch will now take a different branch.
I treat these as compatible but noteworthy — a changelog entry and a lead time — and I distinguish them from schema changes in the diff tool's output, which cannot see them at all.
The same applies to changing the default sort, the default page size, or the precision of a timestamp: schema-compatible, behaviour-changing, and worth a notice. The hard rule is that the schema diff is necessary but not sufficient, and a human reads the behavioural changes.
- "Is adding a required response field really a problem?"
For most clients no, because they ignore what they do not know.
It is a problem for clients that validate responses against the schema they were built with — some generated SDKs do, and some contract tests do — and for clients that echo whole objects back in a PUT, where the new field arrives in a request the server may not have expected on the old version.
It also changes the old document's meaning if it is declared required in a shared schema used for both request and response.
So I add response fields as optional in the document even when the server always sends them, and I promote them to required only in the next major version.
The one-line cost is that SDKs treat the field as nullable, which is a fair price for not breaking strict validators.
- "Who decides, and what happens when the diff tool and a human disagree?"
The written definition decides, and the tool implements the definition. When they disagree, the change is treated as breaking until the disagreement is resolved, because the cost asymmetry is huge: a false alarm costs a conversation, a missed break costs an incident.
The resolution is either a fix to the tool's configuration — oasdiff has flags to treat enum additions as breaking or not, for example — or an amendment to the definition, both by pull request to the conventions repository.
The API reviewer role, held by a small rotating group, makes the call.
Over time the tool covers more and the human less, but there is always a residue of semantic changes that only a person can judge, and the process makes that explicit rather than hoping the linter catches everything.
Q50. "URL versioning versus header versioning versus date-based versioning — argue for one for a public API with hundreds of consumers."
Reveal answer
Strong answer For hundreds of external consumers I argue for a URL major version — /v1, /v2 — combined with additive-only evolution inside a major.
The reasons: the version is visible in every log line, dashboard, gateway route, and support ticket, so "which version are you on" is never a question; routing an old major to a separate deployment is trivial; and clients cannot forget it, whereas a missing header silently selects a default.
The cost is that a major version is a coarse, expensive event, so I make it rare — one every few years — and spend my effort on never needing one.
Date-based versioning, Stripe's model, pins each consumer to the behaviour of the date they signed up and applies transformation layers per date; it is the best consumer experience but requires an engineering investment in version-transform middleware that only very large API companies sustain.
Header versioning fits internal APIs with a gateway. Spring Framework 7 supports all three with @RequestMapping(version = …) and a configured resolver, so the choice is policy, not framework capability.
Land it Put the major in the URL, keep majors rare through additive discipline, and copy Stripe's date scheme only if you can fund its middleware.
- "Show me how Spring Framework 7 API versioning is configured."
As of Aug 2026 with Spring Framework 7 and Boot 4, you register an
ApiVersionConfigurerin aWebMvcConfigurerand choose the resolver:useRequestHeader("API-Version"),useQueryParam("version"),usePathSegment(1)for a/v1/segment, or a media type parameter.Handler methods declare
@GetMapping(value = "/orders", version = "1.0")andversion = "2.0"; a request with a version maps to the highest handler version not greater than it, so a client asking for 1.5 gets the 1.0 handler, and a request with no version can be given a default or rejected with 400 viasetVersionRequired.Boot 4 exposes the same via
spring.mvc.apiversion.*properties. The important thing for the interview is that the mechanism is now standard, so the argument about where the version lives is purely a policy argument about visibility and routing.- "What does Stripe's date-based scheme actually cost to run?"
Every breaking change is written as a versioned transformation — a small class that converts the current response shape to the previous one, and the previous request shape to the current — and the API runs the chain of transforms between the current code and the date the caller is pinned to.
Stripe described this publicly: each change is a module with a description and a transform, and a request from a 2019 account passes through every transform since 2019.
The cost is that every breaking change forever requires such a module, the modules must be tested against each other, and the chain adds latency for old callers. It also requires the domain to be expressible in every historical shape, which constrains what you can change.
For an API with a few breaking changes a year and a dedicated platform team it is sustainable; for a team of six it is not.
- "How do you stop /v1 from becoming a fork of the codebase?"
By the rule that the domain and persistence layers have exactly one version and the API version is a translation at the edge, which the next question covers in detail.
Mechanically, the v1 and v2 controllers live in the same module, share the same service classes, and differ only in DTOs and mappers; a CI test runs v1's contract suite against every build.
The temptation to fork usually comes from a v2 that wants a domain change v1 cannot represent, and the answer there is to make v1 emulate the old behaviour in its mapper rather than keep old domain code alive.
When v1's mappers get too convoluted, that is a signal that v1's sunset date is due, not that it needs its own branch.
Q51 · Design. "Design the versioning and deprecation policy for a platform with 200 external consumers, including how you retire a version."
Reveal answer
Strong answer Requirements: consumers can plan, the platform can evolve, and retirement is measurable, not hopeful.
Policy: URL major versions; within a major only additive changes as defined in a published breaking-change list; at most two majors supported at once; a new major announced with a migration guide and a generated SDK on day one; the previous major supported for 18 months after the new one ships, with security fixes only after month 12.
Signalling: Deprecation and Sunset headers on every response of the old major from the announcement date, the OpenAPI document marked deprecated, and a changelog feed.
Measurement: per-consumer, per-version call counts at the gateway; a dashboard of who is still on the old major and their contract value; direct outreach to the top 20 by traffic at 12, 6, and 3 months.
Retirement: scheduled brownouts — the old major returns 410 Gone for ten minutes at announced times in the final month, which finds the stragglers whose monitoring works; then permanent 410 with a Problem Details body linking the migration guide.
Trade-offs: 18 months of dual running costs engineering, which I accept over churn. I would not sunset silently, would not extend "just for one more customer" without a paid support agreement, and would not ship a new major for anything achievable additively.
Land it A deprecation policy is dates plus headers plus a dashboard — without the dashboard it is a hope, and without brownouts it is a surprise.
- "Requirement change: a regulator requires that partners get 36 months' notice of any removal. How does the policy adapt?"
The 18-month support window becomes 36 for the regulated partners, and the cheapest way to honour that without carrying every old version for everyone is to make support windows a per-consumer attribute at the gateway rather than a global constant.
Regulated consumers are tagged, their calls to a sunset version are allowed until their 36 months elapse, and everyone else is cut at 18.
The engineering consequence is that a major cannot be deleted until the last regulated consumer's window closes, so I make new majors even rarer and lean harder on additive change, and I keep the old major thin — a translation layer, not a fork — so 36 months of carrying it costs mappers and tests rather than a second codebase.
Brownouts are replaced by scheduled written notices for that group, since a surprise 410 would be a compliance breach.
- "Under time pressure, what would you cut?"
The per-consumer dashboard is the thing I would keep at all costs, because without it every other part of the policy is guesswork; even a daily query over gateway logs into a spreadsheet counts.
I would keep the
Sunsetheader, since it is one line at the gateway.I would cut the migration guide to a changelog with before-and-after examples, cut the SDK-on-day-one promise to "SDK within a month", and cut brownouts to a single one two weeks before the end rather than a schedule.
The 18-month window I would not shorten, because it was a promise made when consumers signed, but I would start the clock at announcement rather than at the new major's general availability if the contract allows. Retirement without measurement is the only cut I refuse.
- "What do the Deprecation and Sunset headers look like, and are they standard?"
Sunsetis RFC 8594 and carries an HTTP date after which the resource will be gone:Sunset: Sat, 27 Feb 2027 00:00:00 GMT.Deprecationis RFC 9745, published in 2025, and carries a structured-field date in the@timestamp form,Deprecation: @1756252800, meaning the resource is deprecated as of that instant.Both are meant to be paired with a
Linkheader pointing at the migration guide withrel="deprecation"orrel="sunset".Since both are headers on normal responses, a client sees them on every call without changing anything, and an SDK can log a warning when it sees them, which is the cheapest in-band notice there is.
I set them at the gateway per route and version so no service code changes.
- "How do you run a brownout safely?"
It is a scheduled, announced, short window during which the old version returns 410 Gone with a Problem Details body naming the sunset date and the migration guide.
I announce the schedule a month ahead in the changelog, by email to registered contacts, and via the headers. The first brownout is ten minutes at a low-traffic hour; later ones grow to an hour.
At the gateway it is a route rule flipped by a feature flag, with an instant rollback. During the window I watch per-consumer error rates and support channels; consumers who page us are the ones whose monitoring works, which is the point.
Regulated or contractually protected consumers are excluded from the rule by tag. Afterwards I publish what I saw and contact the consumers who broke, because a brownout is a notice you cannot ignore, not a punishment.
Q52 · Scenario. "You added a new value ON_HOLD to the order status enum. Two hours later three partners' integrations are throwing exceptions. Explain and fix."
Reveal answer
Strong answer Symptom: partner failures immediately after an enum extension, which means strict deserialisation on their side.
Evidence: their errors mention an unknown enum constant; our change log shows the new value; the OpenAPI enum list was updated, and their SDKs were generated from the old one — Java's Jackson fails by default on an unknown enum, and generated clients often validate strictly.
Causes ranked: the contract never told clients to tolerate unknown enum values, so from their side this is breaking; secondarily, we started emitting the value before announcing it.
The immediate fix is to stop emitting ON_HOLD to partners on the old contract — map it to the nearest existing value or omit the affected orders from partner responses — while their SDKs regenerate.
The lasting fix: state in the contract that enums are open and clients must treat unknown values as a documented fallback; generate SDKs with an UNKNOWN catch-all, which OpenAPI Generator supports; and treat new enum values as breaking for consumers who have not opted into open enums.
Prevention: enum additions go through the deprecation-notice channel with a lead time, and a contract test on our side sends an unknown value through each published SDK.
Land it An enum is only open if the contract says so and the SDKs are built for it; until then, adding a value is a rename in disguise.
- "You mapped ON_HOLD to PENDING for the old contract and a partner now reports orders stuck in PENDING for days. What next?"
That is the mapping doing damage: the partner's code treats a long
PENDINGas an anomaly and their reconciliation escalates it. The mitigation was always temporary, and the answer is to move them off it.I would check whether their SDK has regenerated with the
UNKNOWNfallback and, if so, stop mapping for them specifically, via a per-consumer flag at the gateway, so they see the real value.If they cannot regenerate yet, I would give them the real state through a second, additive field —
statusDetail: "ON_HOLD"— that old clients ignore, so their support team can see it while their code stays stable.And I would look at whether an order genuinely on hold for days is a business problem regardless of the API, because the partner's alarm may be right.
- "What does the open-enum contract wording and the SDK generation actually look like?"
The contract says: "Enumerated fields are open. New values may be added at any time. Clients must map unknown values to a documented fallback and must not fail.
" In the OpenAPI document I mark the schema with an extension such as
x-extensible-enumor I list the known values and add a description saying more may appear; OpenAPI Generator's Java client hasenumUnknownDefaultCase=true, which generates anUNKNOWN_DEFAULT_OPEN_APIconstant and maps unrecognised values to it instead of throwing.For Jackson-based clients,
@JsonEnumDefaultValueon a constant plusDeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUEdoes the same. A contract test in our pipeline sends a made-up value through each published SDK's deserialiser and asserts it lands on the fallback.- "Could you have shipped ON_HOLD without any partner seeing it?"
Yes, and that is the version-aware approach: the new value is emitted only to clients that have declared they accept it, by API version or by an explicit opt-in header, and older clients see the mapped value.
Stripe does exactly this with enum expansions tied to an API version date.
It means the state machine's new state is represented to old clients as its nearest old state, with the real state available through an additive field, for as long as the old version lives.
It is more work than announcing and hoping, but it is the only way "additive" is true from the client's point of view.
In a greenfield design, I would ship the open-enum rule and the SDK fallback from day one so this whole class of incident cannot happen.
Q53. "How do you serve two major versions of an API from one codebase without duplicating everything?"
Reveal answer
Strong answer The domain and persistence layers stay single and current; only the representation layer is versioned. Each major has its own request and response DTOs and its own controllers or mappings, and a thin translation maps between the current domain model and each version's DTOs.
In Spring Framework 7 and Boot 4 that is @RequestMapping(version = "1") and version = "2" on separate handler methods with one configured version resolver; on Boot 3 it is separate path prefixes.
Where the old version needs a behaviour the new domain dropped, the translation layer emulates it — Stripe's approach generalised: a chain of transforms from current to each older shape.
Tests run the old version's contract suite against the new build in CI so refactoring the domain cannot silently change v1. What I avoid is copying the service layer per version, which doubles bugs, and branching the repository per version, which guarantees divergence.
The old version should get progressively thinner as its consumers migrate, and its removal should be a delete of DTOs and mappings only.
Land it Version the edges, not the core — old versions are translations of the current model, and a translation is cheap to delete.
- "How do you test that v1 has not changed when the domain is refactored?"
With a frozen contract suite for v1 that is not allowed to change once v1 is frozen.
It is a set of recorded request and response pairs — golden files — for every v1 operation, replayed against each build with a strict comparison of the response body, ignoring only fields declared volatile such as timestamps and ids. Any difference fails the build.
The suite is checked into a directory with a code-owners rule requiring API reviewer approval to modify, so a developer cannot "fix the test" to match a change. On top of that, the v1 OpenAPI document is frozen and diffed on every build.
Together they catch both schema changes and behavioural changes, which is the gap a schema diff alone leaves.
- "What if v2 changes the domain so much that v1 cannot be computed from it?"
Then the mapper needs data that no longer exists, and I have two choices.
Store what v1 needs alongside the new model — a legacy column, an event log I can derive it from — which is a small cost in the schema for as long as v1 lives.
Or accept that v1 becomes read-mostly and degrades gracefully: the field is emitted as a documented best-effort value, and the change is communicated as part of the v1 sunset notice.
What I do not do is keep the old domain code alive to serve v1, because then two implementations of the business rules diverge and the translation-layer promise is gone.
This situation is the signal that v1's sunset date should move earlier, and it is a legitimate reason to accelerate the outreach to remaining v1 consumers.
- "What does the package structure look like in practice?"
One module with
api.v1andapi.v2packages, each containing controllers, request and response records, and a mapper class, plus a shareddomainandpersistence. An ArchUnit test enforces thatapi.v1andapi.v2do not depend on each other and thatdomaindepends on neither.Exception mapping is shared, with the Problem Details types the same across versions. Route registration is by the version resolver in Spring Framework 7 or by path prefix on Boot 3.
Version-specific behaviour that is not a pure shape difference — for example, v1 defaulted the sort differently — lives in the v1 controller, calling the same service with an explicit parameter.
When v1 is removed, the removal is a deletion of one package and one test directory.
Q54. "What are consumer-driven contract tests, and where do they sit relative to an OpenAPI diff?"
Reveal answer
Strong answer A consumer-driven contract test is written by the consumer: it records the exact interactions the consumer depends on — this request, these fields of the response — as a contract file, and the provider's build replays those interactions against the real provider and fails if any expectation breaks.
Pact is the common tool; Spring Cloud Contract is the Spring-native one with the contract on the provider side. An OpenAPI diff, by contrast, compares the provider's full contract between releases and flags every structural break whether or not anyone uses it.
They complement each other: the diff catches breaking changes early and broadly; contract tests tell you which consumers a change actually breaks and, just as usefully, which fields nobody reads, so a removal can proceed with evidence.
Contract tests cost coordination — consumers must write and publish them, and a broker such as Pact Broker tracks which versions are compatible — so I use them for the consumers I cannot afford to break and rely on the diff plus the deprecation policy for the long tail.
Land it The diff says "this could break someone"; contract tests say "this breaks these three" — you want both, and the second is what lets you delete things.
- "Walk me through the Pact flow end to end."
The consumer team writes a test using the Pact consumer library: it describes an interaction — given an order exists, when I GET
/orders/42, I expect status 200 and a body withidandstatusas strings — and runs its own client code against a mock server that Pact spins up.Passing the test produces a pact file, a JSON contract, which is published to the Pact Broker tagged with the consumer's version and branch.
The provider's build fetches every pact for its consumers, starts the real provider with provider-state hooks that set up "an order exists", replays each interaction, and verifies the responses match; results go back to the broker.
Deployment is gated by the broker's
can-i-deploycheck, which says whether this provider version is compatible with every consumer version currently in production. Matching is by type and shape, not exact values, so the contract stays stable across data changes.- "What does the diff miss that contract tests catch, and vice versa?"
The diff misses behavioural changes: a field that is still a string but now contains a different format, a default sort that changed, a status code that the document did not enumerate accurately.
A contract test that asserts on those catches them, because it runs the real provider. The diff also cannot say whether anyone cares about a removal; contract tests can, since only consumed fields are in the pacts.
In the other direction, contract tests miss everything no consumer wrote a test for, which for a public API with hundreds of consumers is nearly everything, and they miss consumers who have not published a pact, such as external partners.
The diff covers the whole surface regardless of who tests it. That asymmetry is why I use contract tests for the few consumers I cannot break and the diff for the rest.
- "How do you get consumer teams to actually write and maintain the tests?"
By making the tests useful to them, not just to me.
A consumer's pact test doubles as their unit test for their client code, because it runs against a mock the pact library provides, so they need no running provider in their build — that is the selling point.
The provider team publishes a template and a working example, and the platform runs the broker so no team has to host it.
I ask only the consumers whose breakage would be an incident, typically five or six, and I make the
can-i-deploygate visible so they see the protection they get.Where a consumer will not participate, I fall back to writing a provider-side contract in Spring Cloud Contract myself, based on what I observe them calling, which is weaker but better than nothing.
Q55 · Scenario. "A field in your API has been documented as 'deprecated' for two years but 40% of traffic still reads it. Your manager wants it gone this quarter. What do you do?"
Reveal answer
Strong answer Symptom: a deprecation with no sunset, which is a documentation change and not a policy.
Evidence: gateway logs by consumer show which clients read the field — usually "read" cannot be observed for a response field, so I check which client versions and SDK versions are calling, and whether the field's replacement is being used.
Causes ranked: no Sunset date was ever set, so nobody prioritised migrating; the replacement field required work the consumers saw no value in; some consumers are unreachable.
The plan: set a sunset date eight to twelve weeks out and announce it in-band with Deprecation and Sunset headers and out of band by email to the owners of the top consumers; ship SDK versions where the field is absent; run brownouts where the field is omitted for an hour at announced times, which flushes out the consumers whose code actually depends on it versus those that merely receive it; then remove.
If the top consumers are commercially critical and cannot move in time, I keep the field for them via a per-consumer flag at the gateway and remove it for everyone else, so the cost is bounded to a named list.
I would not remove it silently on the quarter boundary and I would not extend the deprecation indefinitely.
Land it Deprecated without a date is decoration; a sunset, a brownout, and a named exception list turn it into a removal.
- "You ran the brownout and only 5% of traffic broke, but a top-three customer was in that 5%. What next?"
That is exactly what the brownout was for: it found the dependency before the removal did. The customer goes on the named exception list at the gateway, so their responses keep the field after the removal date, and everyone else loses it on schedule.
Then it becomes an account-management conversation with a date: their exception has an expiry, and their migration is tracked by the account team, ideally with a small engineering contribution from us, such as a pull request against their integration if it is open to us.
The point is that the exception list must be short and dated, otherwise it becomes the new permanent state with extra complexity.
I would also look at why a top customer's integration depended on a two-year-deprecated field, because it usually means our deprecation notices never reached an engineer.
- "How do you make a per-consumer exception at the gateway without touching service code?"
The service stops emitting the field, and the gateway adds it back for tagged consumers using a response transformation, or the reverse: the service keeps emitting it and the gateway strips it for everyone not on the list.
The second is safer because the service's behaviour stays unchanged and the removal is a gateway rule with instant rollback.
In Kong, Apigee, or Envoy that is a response body filter keyed on the consumer's id from the token; the field name and the consumer list live in configuration.
The cost is that the gateway is now doing body rewriting, which has a latency and memory cost for large responses, so I scope the rule to the specific route.
After the exception expires, deleting the rule is the actual removal, and the service change follows whenever convenient.
- "Why does the manager's 'this quarter' matter, and what would you push back on?"
It matters because a deprecation with no forcing date has already failed for two years, and a deadline is the only thing that has worked.
I would push back on the shape of the deadline, not its existence: eight to twelve weeks from the first real notice, with brownouts, is aggressive but honest; removing it on the quarter boundary with no notice would break 40% of traffic and become an incident that costs more than the field.
I would also ask what the field is costing us.
If it is a serialisation line, the cost of keeping it for a named list is near zero and the argument is about hygiene; if it forces us to maintain a join or a legacy table, the removal has a real payoff and the priority is justified.
Either way, the plan has dates and the manager gets a weekly traffic chart.
Q56. "How should a client be written so that it survives the widest range of non-breaking changes?"
Reveal answer
Strong answer The Postel principle applied with limits: be tolerant of what you receive. Ignore unknown JSON fields — FAIL_ON_UNKNOWN_PROPERTIES off in Jackson, which is Spring Boot's default.
Treat unknown enum values as a fallback value rather than an exception, which generated SDKs support with an unknown constant. Never depend on the order of JSON object members or on the absence of a field to mean something unless the contract says so.
Follow links and cursors as opaque strings rather than constructing them. Treat any 2xx as success and any status you do not know as its class — an unknown 4xx as a client error, an unknown 5xx as retryable.
Parse Problem Details by type, never by the text of detail. Send only the fields you mean to set, so a new optional field on the server is not clobbered by a full-object PUT. Pin the API version explicitly rather than relying on a default.
And send a User-Agent that names the SDK and version, which is what lets the provider warn you before they break you.
Land it A tolerant client turns most of the provider's "breaking" list into non-events — and the provider can only be additive if clients let them.
- "Where does tolerance go too far?"
When the client silently accepts things that mean its own assumptions are wrong. Ignoring unknown fields is right; ignoring a missing field it depends on and proceeding with null is wrong, because that is how a payment of zero gets recorded.
Treating an unknown enum value as a fallback is right; treating it as "success" is wrong if the fallback decision has consequences, so the fallback should be a neutral, logged state that a human reviews.
Accepting any 2xx as success is right; accepting a 2xx with an empty body as success when a body was promised is wrong.
The principle I use is that the client tolerates variation in shape and rejects variation in meaning, and it logs every tolerance it exercised so that when the provider changes something, the logs show it before the users do.
- "How do you configure this in a Java client, concretely?"
On the Jackson
ObjectMapper:FAIL_ON_UNKNOWN_PROPERTIESfalse,READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUEtrue with an@JsonEnumDefaultValueconstant on every enum, andACCEPT_SINGLE_VALUE_AS_ARRAYif the provider might change cardinality.Response records have all fields nullable except the ones the client truly requires, and those are validated explicitly after parsing with a clear exception naming the field.
HTTP handling is by status class with specific cases for 401, 403, 409, 412, 422, and 429, and generic retry for 5xx on idempotent calls. The
User-Agentis set toacme-sdk-java/3.4.1.If the SDK is generated with OpenAPI Generator, the same comes from
enumUnknownDefaultCaseand the default lenient mapper, and I check the generated code once rather than trusting the flags.- "Why send only the fields you mean to set — is that not just PATCH?"
It is the PATCH mindset, and the point is what happens when the server adds a field the client does not know.
A client that does GET, modifies one field in its local object, and PUTs the whole object back will send the new field as whatever its parser did with it — usually dropped, because the client's class did not have it — and the PUT silently resets that field on the server.
That is a client that was "correct" and broke on an additive change.
So the client either uses PATCH with just the changed fields, or if it must PUT, it preserves unknown fields through the round trip, which Jackson supports with
@JsonAnySetterand@JsonAnyGetteron a map.The provider's side of the same rule is to reject a PUT missing required fields rather than defaulting them, so the mistake is loud.
Q57 · Design. "Design the migration of an internal API from unversioned to versioned, in a company where 25 services call it and you do not control their release schedules."
Reveal answer
Strong answer Requirements: no flag day, every caller identifiable, and the unversioned surface eventually gone.
Design: freeze the current contract as v1 and serve it at both the old unversioned path and /v1, so callers can move at their own pace with a zero-risk change; add a gateway rule that tags every request as explicit-v1 or implicit-v1 by path and logs the caller identity from mTLS or the service token; publish a dashboard of implicit callers per service.
Build v2 for the actual changes wanted, additive where possible so that most callers never need it. Set a date after which unversioned calls return a Deprecation header, then a later date where they get a one-hour brownout weekly, then a 410.
For teams that cannot prioritise, offer the change as a pull request — it is a path prefix — which usually costs less than the meetings. Trade-offs: months of dual serving; the alternative of a big-bang cutover risks 25 outages at once.
I would not version by header for this, because the implicit callers would be invisible, and I would not build v2 before v1 is pinned, because then there is nothing stable to migrate to.
Land it Pin what exists, make the implicit visible, and make moving cheaper than staying — the policy does the rest.
- "Requirement change: the unversioned path is also called by an external partner you cannot see. How does the plan change?"
The implicit-caller dashboard now has an entry I cannot identify, and I must assume it is production-critical.
I would try to identify it from what I have — source IP ranges, TLS client fingerprint,
User-Agent, call patterns — and from the commercial side, since a partner with API access has a contract and a contact.The brownouts get longer lead times and become the main discovery tool, because a partner whose calls fail for an hour will contact us.
The unversioned path lives longer for that one caller via a gateway exception, and the 410 date for it is set only once I have a name.
The general lesson I would draw is that every caller must be identifiable from day one, so the new versioned path requires an identified client credential even for internal callers, which the mTLS or service-token requirement provides.
- "Under time pressure, what would you cut?"
I would cut v2 entirely from the first phase: the migration to versioning is valuable on its own, and building v2 at the same time doubles the coordination.
Phase one is pin v1, add the tagging and dashboard, and offer the pull requests; that is a week of platform work and a one-line change per caller.
I would cut the brownout schedule to a single announced hour after the dashboard shows the implicit calls under 5%.
I would cut the
Deprecationheader if the gateway cannot add it easily, since the dashboard and direct contact do the same job for 25 known internal callers.I would not cut the identification of callers, because without it the dashboard is a count, not a list, and I cannot send anyone a pull request.
- "Why is a header version wrong here when you argued it fits internal APIs elsewhere?"
The two situations differ in what I need to observe. A header version on a greenfield internal API with a gateway is fine because every caller sends it from the start and the gateway rejects requests without it, so there are no implicit callers.
In a migration from unversioned, the whole problem is the population of callers who send nothing, and a header scheme makes "no header" the default path, which is indistinguishable from "explicitly v1" in logs unless I tag it.
A path version makes the old and new paths different routes with separate metrics for free.
So the argument is not path versus header in the abstract; it is that during a migration, the mechanism must make the unmigrated callers visible, and a path change does that with no extra work.
- "What does the pull request you offer to the calling team look like?"
A one-line change to their configuration — the base URL from
https://orders.internal/tohttps://orders.internal/v1/— plus, if they use a generated client, a regenerated client from the v1 document, and a note in the description linking the migration page and the dashboard entry that will turn green when they deploy.It is deliberately minimal so their review takes five minutes, and it comes with an offer to pair on the deployment. For teams using a shared internal SDK, the change goes into the SDK and their pull request is a version bump.
The reason it works is that the cost of the change is trivial and the cost of scheduling it in a busy team is not; by doing the change, I remove the scheduling problem and leave them only the approval.
Q58. "What is the expand-and-contract pattern, and how does it apply to API changes as well as database changes?"
Reveal answer
Strong answer Expand-and-contract is the way to make a breaking change without a breaking moment: first expand by adding the new thing alongside the old, then migrate every consumer to the new thing while both work, then contract by removing the old.
In databases it is add the new column, dual-write, backfill, switch readers, drop the old column — Chapter E8 covers that sequence.
In APIs it is the same shape: add customerName while still serving customer_name, accept either in requests, announce the sunset, watch the traffic on the old name fall, then remove it.
The pattern's value is that every step is individually safe and reversible, and each step can be verified with metrics before the next. Its cost is the dual period, where the code carries both and tests must cover both.
For a field rename that is trivial; for a change of semantics — a status that now means something different — expansion means a new field with a new name, never a reinterpretation of the old one, because you cannot dual-run two meanings under one key.
Land it Never change a thing in place; add its successor, move the traffic, then delete — for columns and for fields alike.
- "What are the metrics you watch at each step before moving to the next?"
After expanding, I watch that the new field or column is being written and read correctly: for an API, a count of responses carrying the new name, and for a database, a comparison job that reads both columns and reports mismatches.
During migration, I watch the ratio of consumers on the new name to the old, per consumer, and I do not move on until the old name's traffic is either zero or fully accounted for by named exceptions.
Before contracting, I run a brownout or, for a column, switch reads to the new column while still dual-writing, and watch error rates for a full business cycle — a week, or a month-end if there is monthly processing.
The contraction itself is done behind a flag so it can be reversed instantly if a consumer appears that the metrics missed.
- "How long does the dual period typically last, and what does it cost?"
For an internal field rename with a dozen consumers, two to four weeks. For a public API, the deprecation policy's window, which is months.
For a database column with dual writes, as short as a few days once the backfill is verified, because the dual-write code is a source of subtle bugs if it lingers.
The cost is code carrying both paths, tests covering both, and for databases the write amplification of two columns. The hidden cost is cognitive: every developer touching that code has to know which is canonical.
So I mark the old path with a removal ticket and date in a comment and in the tracker, and I treat an expand step without a scheduled contract step as unfinished work, because the codebase full of never-contracted expansions is the one where nobody knows what is live.
- "Give me an example where the semantics change, and show the expansion."
Suppose
statuson an order currently means the fulfilment state, and the business now wants it to mean payment state, with fulfilment tracked separately. Reinterpretingstatusin place would break every client silently.The expansion is two new fields,
paymentStatusandfulfilmentStatus, added alongside the oldstatus, which continues to carry its old meaning computed from the new fields. Clients migrate to the two new fields; the old one is deprecated with a sunset; the contraction removes it.The same applies to units: changing
amountfrom dollars to cents is not a change, it is a new field,amountCents, and the old one lives until sunset. The principle is that a name carries its meaning forever, and a new meaning needs a new name.
The questions here are where money moves. They test whether your design survives a lost response, a crashed worker, and a partner whose server is down for six hours.
Q59 · Design. "Design a public payments API: creating a payment, its lifecycle, failure handling, and the guarantees you give integrators."
Reveal answer
Strong answer Requirements: never charge twice, never lose a charge, integrators can recover from any failure, and every state is observable.
Resources: POST /payments with a mandatory Idempotency-Key, body with amount in minor units, currency, a payment method token, and a client reference; it returns 201 with a payment in state PENDING, SUCCEEDED, FAILED, or REQUIRES_ACTION for 3-D Secure style challenges.
Lifecycle is an explicit state machine documented in the contract, with GET /payments/{id} always readable and a POST /payments/{id}/captures and /refunds as sub-resources with their own keys.
Asynchrony: card networks take seconds to minutes, so the initial response may be PENDING and the final state arrives by signed webhook and is always pollable; integrators must treat the webhook as a hint and the GET as the truth.
Errors: RFC 9457 with a type registry — insufficient-funds, card-declined with a decline code, idempotency-conflict.
Guarantees I state: an idempotency key is honoured for 24 hours and returns the original response; a payment id is stable for ever; webhooks are at-least-once with an event id; amounts never change after creation.
Security: OAuth2 client credentials plus mTLS for high-volume partners, scopes separating read, charge, and refund. Trade-offs: pending states complicate integrators' code but are honest about the network.
I would not accept raw card numbers on this API — tokenise at a separate PCI-scoped endpoint — would not model refunds as a negative payment, and would not make webhooks the only way to learn a final state.
Land it A payments API is an idempotency key, a state machine, and a promise that GET is always the truth — everything else is decoration.
- "Requirement change: the API must support partial captures and multiple refunds per payment. What changes?"
The sub-resources become collections with their own arithmetic.
POST /payments/{id}/capturestakes an amount and creates a capture; the payment tracksamountAuthorized,amountCaptured, andamountCapturable, and a capture exceeding the capturable amount is a 409 with acapture-exceeds-authorizationtype.Refunds likewise carry an amount, and the sum of refunds may not exceed the captured amount. Each capture and refund has its own idempotency key and its own state, because the card network can fail a partial capture independently.
Concurrency now matters within one payment: two captures arriving together must not both pass the check, so the payment row is locked or versioned during the arithmetic.
The state machine grows states such as
PARTIALLY_CAPTURED, and the contract documents the invariants explicitly so integrators can assert them in their own tests.- "Under time pressure, what would you cut?"
I would cut
REQUIRES_ACTIONand 3-D Secure style flows, supporting only payment methods that authorise synchronously, since the challenge flow is the most complex integrator-facing piece. I would cut partial captures and make capture all-or-nothing.I would cut mTLS for partners and ship OAuth2 client credentials only. I would cut webhooks to a single event type, payment reached a terminal state, and rely on polling for the rest.
What stays is the mandatory idempotency key with a 24-hour replay, the explicit state machine with GET as the truth, minor-unit amounts, and the Problem Details type registry for declines, because those are the promises that cannot be added later without breaking integrators, and they are what prevents the double-charge incident on launch week.
- "How do you guarantee never charging twice when the card network itself times out?"
The idempotency key protects against the client retrying us; the network timeout is us retrying the processor, and it needs the same discipline one layer down.
Every call to the processor carries our own idempotency key derived from the payment id and attempt purpose, so a retry after a timeout returns the processor's original result rather than authorising again; every serious processor supports this.
When the processor times out and a retry is not possible, the payment enters
PENDINGwith an unknown outcome, and a reconciliation job queries the processor by our reference until the truth is known, then finalises.The integrator sees
PENDINGand is told to wait for the terminal state, never to create a new payment. That is why the state machine has an honest pending state instead of guessing.- "What does the integrator do if they lose the payment id after a successful create?"
They re-send the same request with the same idempotency key and get the original 201 back, id included, for 24 hours; that is the primary recovery and it is why the key is mandatory.
Beyond 24 hours, or for integrators who lost the key too, they need a lookup by their own reference: the
clientReferencethey supplied is indexed and searchable viaGET /payments?clientReference=…, scoped to their account.I also recommend in the integration guide that they persist the key and reference before calling us, so a crash between the call and the write to their database is recoverable.
The API cannot make that decision for them, but the SDK can, by exposing the key it generated before the request is sent.
Q60. "Where should idempotency keys be generated, and what goes wrong when the server generates them?"
Reveal answer
Strong answer The client generates the key, at the moment the user or the calling system decides to do the operation — when the user taps Pay, when the batch job picks up a row — and reuses the same key for every retry of that decision.
That is the only place that knows "these two HTTP requests are the same intention".
If the server generates the key and returns it, the first request has no key, so the exact failure the key exists for — the lost response to the first attempt — leaves the client with nothing to retry with, and it creates a second operation.
A weaker but useful server-side complement is deriving a natural key from the request, such as the client's own order reference, and rejecting duplicates on it with 409; that catches duplicate intentions even from clients that forget the header, but cannot replay the original response.
For SDKs I generate the key inside the create call automatically and expose it, so integrators get correctness by default.
The key must be unique per client, so it is stored scoped by client id, and it should be a UUID, not a hash of the body, because two legitimately identical orders in a row must remain distinct operations.
Land it The key is the client's statement of intent; a server-generated key arrives one request too late to help.
- "Why a UUID rather than a hash of the request body?"
Because two legitimately identical requests are two intentions.
A customer who orders one coffee, then a minute later orders another identical coffee, has made two orders; a body hash would treat the second as a replay of the first and return the first order, which is a silent lost order.
A UUID minted per intention keeps them distinct. The body hash still has a role, stored alongside the key, to detect the opposite error: the same key reused with a different body, which is a client bug and gets a 422.
Some designs use a natural key such as a cart id as the idempotency key, which works when the domain genuinely has one intention per natural key, but it is a domain decision, not a general rule, and it must be scoped per client to be safe.
- "What happens if a client forgets the header on a create?"
For a payments-grade API, the request is rejected with 400 and a Problem Details type of
idempotency-key-required, because a keyless create is a request to charge twice eventually and the integrator is better served by an error in development than by a duplicate in production.For lower-stakes resources, I accept the request and process it once with no replay protection, and I log a metric per client so I can see who is calling without keys and nudge them.
The SDK makes the question moot by generating the key when the create method is called and exposing it so the caller can persist and reuse it.
A middle path used by Stripe is to make the key optional but strongly recommended; I prefer mandatory for anything that moves money.
- "How does the natural-key defence differ from the idempotency key, and why keep both?"
The idempotency key is the client's declaration that two HTTP requests are the same intention; it lets the server replay the exact original response.
The natural key is the server's knowledge that two intentions cannot both be valid: one active order per cart, one payment per invoice.
It catches duplicates the client created by mistake with different keys, such as a double-click, but it cannot replay a response, so the second request gets a 409 with a link to the existing resource.
Keeping both means the client's retries are correct and the client's bugs are caught. The natural-key constraint is also a database unique index, so it holds even if the idempotency layer is bypassed by an internal caller, which makes it the deeper of the two defences.
Q61 · Scenario. "Idempotency keys are in place, yet a customer still got two orders from one click. The two requests are 40 milliseconds apart with different keys. Explain."
Reveal answer
Strong answer Symptom: duplicates with distinct keys, so the server did its job and the client generated two intentions. Evidence: the two keys and their timestamps; the client code that generates the key; browser or app logs showing two submit events.
Causes ranked: the key is generated inside the request function rather than at the intent — a double-click or a double-tap fires the handler twice and each call mints a fresh key; a front-end framework re-rendering and re-submitting; a retry layer that regenerates the key on each attempt.
The fix is on the client: generate the key when the form is shown or when the button is first pressed, disable the button while a request is in flight, and keep the same key across retries.
On the server I can add a defence in depth: a natural-key check such as one open order per cart id within a short window, returning 409 or the existing order, which catches this even when the client is wrong.
Prevention: SDKs that own key generation at the operation level, and a contract test that simulates a double submit.
Land it An idempotency key protects a retry, not a second click — the key must be minted where the intent is, and the server should recognise duplicate intent by its natural key too.
- "The client fixed the double-click and you still see pairs 40 milliseconds apart. What next?"
Then the second request is not coming from the button.
I would capture the two requests' full headers: if the
User-Agentor a request id header differs, there are two distinct senders, such as a browser and a service worker replaying a queued request, or a retry layer in a proxy.If the headers are identical apart from the key, I would look at the client's HTTP library for automatic retries on connection reset, which some libraries do even for POST, and which regenerate the key if the key is created inside the request builder.
On the web, a form that submits on both the button click and the form's submit event fires twice; on Android, a tap that survives an activity re-creation replays.
The natural-key guard on the server is what makes this class of bug harmless while it is hunted.
- "Where exactly in a front-end should the key be minted?"
At the moment the intention becomes concrete and before anything can retry: when the checkout form is rendered or when the user reaches the confirmation step.
The key is stored in component state or session storage keyed by the cart id, and it is passed into every submission attempt for that cart, including retries after a network error and after a page reload if the storage survives.
It is replaced only when the intention changes — a new cart, or a successful order followed by a new checkout.
The SDK pattern is a
createOrder(request, { idempotencyKey })call where the SDK generates the key if absent and returns it to the caller, so the caller can persist it.The wrong place is inside the function that builds the HTTP request, because that runs once per attempt.
- "Is the server ever wrong to accept both in this case?"
By the letter of the idempotency contract, the server was right: two keys, two operations. By the business, a customer does not want two identical orders forty milliseconds apart, and the server had enough information to suspect it.
That is why I add the natural-key check as a policy: one open order per cart, or a duplicate-suspect rule that flags identical bodies from the same customer within a short window and returns 409 with the existing order's link rather than creating a second.
The window and the rule are domain decisions — a coffee shop might legitimately take two identical orders in a minute, a mortgage application cannot — so I make them configurable per resource and I log the suppressed duplicates so the product team can see how often the guard fires.
Q62. "How do you make the idempotency-key check and the business write atomic, and what happens on a crash between them?"
Reveal answer
Strong answer If the key table and the business tables are in the same database, I do it in one transaction: insert the key row in state in-progress, perform the write, update the key row to completed with the stored response, commit.
A crash before commit rolls back both, so the retry finds no key and proceeds cleanly; a crash after commit means the retry finds the completed key and replays the response.
The dangerous version is a key store in Redis and the write in PostgreSQL: claim the key, write the order, crash before recording completion, and the retry sees in-progress for ever, or after expiry creates a second order.
The mitigations are a short in-progress lease with a heartbeat, a reconciliation job that marks keys completed by looking up the business record by the key stored on it — I always persist the idempotency key on the order row — and returning 409 rather than creating during any ambiguity.
This is the same "two systems, one intent" problem as the outbox pattern in the Distributed Systems primer, and the same answer: put both facts in one transactional store or accept a reconciliation loop.
Land it Same transaction if you can; if the key lives elsewhere, store the key on the business row and reconcile, because the crash window is real.
- "Show me the single-transaction version in SQL."
In one transaction:
INSERT INTO idempotency_keys (client_id, key, request_hash, state) VALUES (?, ?, ?, 'IN_PROGRESS'), which fails on the unique index if the key exists, in which case I roll back and read the existing row.Then the business write:
INSERT INTO orders (…, idempotency_key) VALUES (…). ThenUPDATE idempotency_keys SET state = 'COMPLETED', response_status = 201, response_body = ? WHERE client_id = ? AND key = ?. Then commit.Because it is one transaction, a crash anywhere before the commit leaves neither the key nor the order, so the retry starts clean. A concurrent duplicate blocks on the unique index until the first commits, then sees the completed row.
The insert must happen first, not after the write, so that it is the claim; and the isolation level can be read committed, because the unique index does the serialisation.
- "How does the reconciliation job work for the Redis-plus-database version?"
Every business row stores the idempotency key it was created under, so the job can go from key to outcome.
The job scans Redis keys in
IN_PROGRESSstate older than the lease, say 30 seconds, and for each one queriesSELECT id FROM orders WHERE idempotency_key = ?.If a row exists, the operation succeeded and the job marks the key completed with a response rebuilt from the row. If no row exists and the lease has expired, the operation failed before writing, and the job deletes the key so the client's retry proceeds.
The scan is cheap because in-progress keys are few and I keep them in a separate Redis set. While the key is in-progress and within the lease, requests get 409 with
Retry-After, which is the "ambiguity means wait" rule.- "What if the business write is an external call, like a payment processor, with no transaction at all?"
Then the pattern inverts: the external system's idempotency becomes the source of truth.
I claim the key locally as in-progress, call the processor with a deterministic processor-side idempotency key derived from my key, and on any ambiguous outcome — timeout, connection reset — I do not guess; I mark the key as unknown and a reconciliation job queries the processor by that reference until it gets a definite answer, then completes or clears the key.
The client sees 409 with
Retry-Afterduring the unknown period and the original result afterwards. The processor's own idempotency guarantees that my retry of the same call cannot create a second charge, which is why deriving the processor key from mine matters.It is the two-generals problem, and the answer is a durable intent record plus a query for the truth.
Q63 · Design. "Design a file-upload API for files up to 5 GB, used from browsers and from server-side SDKs, on top of object storage."
Reveal answer
Strong answer Requirements: no 5 GB stream through the API servers, resumable on flaky networks, integrity verified, and the file is a resource with a lifecycle.
Design: the client calls POST /uploads with the file's name, size, content type, and optional checksum, plus an idempotency key; the API creates an upload resource and returns 201 with a plan — for small files a single pre-signed PUT URL to object storage; for large files a multipart plan of, say, 64 MB parts, each with its own pre-signed URL, valid for an hour.
The client uploads parts directly to storage in parallel and can retry any part; GET /uploads/{id} reports which parts are done, which is what makes resumption possible after a browser crash.
When all parts are in, the client calls POST /uploads/{id}:complete; the API asks storage to assemble the multipart object, verifies the ETag or checksum against what the client declared, runs virus scanning asynchronously, and moves the upload to READY or REJECTED, with a webhook or polling.
Incomplete uploads expire after 24 hours via a storage lifecycle rule. Security: pre-signed URLs are short-lived and bound to content length and type; the API never proxies bytes. Trade-offs: two round trips instead of one, and clients must implement multipart, which the SDK hides.
I would not accept the file body on the API, would not base64 it into JSON, and would not trust the client's declared type without checking the bytes.
Land it The API issues permissions and tracks state; the bytes go straight to storage in resumable parts — that is how every cloud upload API works.
- "Requirement change: files must be virus-scanned before anyone can download them. Where does that change the flow?"
The upload flow stays; what changes is that
READYis no longer reached at completion. After the multipart assembly, the upload sits in aSCANNINGstate, the object is stored in a quarantine bucket or prefix with no download permission, and a scanner job processes it.On a clean result the object is copied or re-tagged into the served location and the upload moves to
READY; on a hit it moves toREJECTEDwith a reason and the object is deleted or retained for forensics under a separate policy.Downloads are only ever signed for objects in the served location, so a download request for a scanning file gets 409 with a
not-yet-availabletype.For a 5 GB file the scan takes minutes, which is why the state and the webhook already existed in the design; the change is a new state and a bucket policy, not a new flow.
- "Under time pressure, what would you cut?"
I would cut resumability from the browser SDK and support it only from the server-side SDK, since browser users of 5 GB files are rare and a retry from scratch is tolerable at launch.
I would cut checksum verification against a client-declared value and rely on the object store's part ETags for integrity. I would cut the asynchronous scan and do a synchronous scan for files under 100 MB, rejecting larger files until the scanning job exists.
I would not cut pre-signed direct-to-storage upload, because proxying bytes through the API is the design mistake that is hardest to undo, and I would not cut the upload resource with an expiry and the lifecycle rule that removes abandoned multipart uploads, because without it storage costs grow silently from day one.
- "How do the pre-signed URLs stay safe — what stops someone uploading something else?"
The signature covers the bucket, the key, the method, the expiry, and any headers I choose to bind, so a URL signed for
PUTonuploads/7a3f/part-3cannot be used for a different key or a different method.I bind
Content-LengthandContent-Typewhere the storage service supports it, so a client cannot upload a 50 GB part under a URL issued for 64 MB. The URLs expire in an hour and are issued only to the authenticated owner of the upload.After completion, the API verifies the assembled object's size and, if declared, its checksum, and inspects the first bytes for the magic number of the declared type before marking it ready.
The object key is server-generated and never derived from the client's filename, so path tricks are impossible.
- "Why 64 MB parts, and what are the limits you are working within?"
S3-style multipart allows parts from 5 MB to 5 GB and at most 10,000 parts per object, so a 5 GB file could be 100 parts of 50 MB or 1,000 parts of 5 MB. Larger parts mean fewer round trips and fewer pre-signed URLs to issue, but a failed part costs more to retry, and browser memory for an in-flight part matters.
64 MB is a compromise: a 5 GB file is 80 parts, a retry costs a few seconds on a decent connection, and four parallel parts give good throughput without huge memory. For the server-side SDK I allow larger parts.
The part size is returned in the upload plan rather than hard-coded in clients, so it can change per file size or per client type later without an SDK release.
Q64. "What does a long-running operation resource look like, and how do you keep it from becoming a permanent table of garbage?"
Reveal answer
Strong answer An operation resource is GET /operations/{id} returning an id, the status as one of queued, running, succeeded, failed, or cancelled, timestamps for created and updated, optional progress as a percentage or a count, an error in Problem Details form on failure, and a result link on success.
It is created by the 202 response of the original request and shares that request's idempotency key so retries return the same operation. Polling responses include Retry-After, and the operation may support POST /operations/{id}:cancel.
To keep it from becoming garbage, every operation has a retention period — 24 hours for routine jobs, 30 days for exports — after which it returns 410 Gone and its row is deleted by a scheduled job; the result itself lives as its own resource with its own lifecycle, so deleting the operation record does not delete the export file.
Google's long-running operation design and Azure's async patterns both follow this shape, which is why I would not invent a different one.
Land it An operation is a receipt with an expiry date — the result is the resource, and the receipt is allowed to disappear.
- "Show me the JSON of an operation in each state."
Running:
{"id": "op_7a3f", "status": "RUNNING", "createdAt": "…", "updatedAt": "…", "progress": {"done": 4200, "total": 10000}, "expiresAt": "…", "links": {"self": "/operations/op_7a3f", "cancel": "/operations/op_7a3f:cancel"}}. Succeeded: same shape with"status": "SUCCEEDED",progresscomplete, nocancellink, and"links": {"result": "/exports/exp_91"}.Failed:
"status": "FAILED"and an"error"member that is a Problem Details object with atypesuch asexport-source-unavailable. Cancelled:"status": "CANCELLED"with acancelledAt.The terminal states are documented as final, so a client can stop polling on any of them, and the
resultlink is a separate resource that outlives the operation record.- "How do you handle cancel when the worker is mid-way?"
Cancel is a request, not a guarantee.
POST /operations/{id}:cancelsets a cancel-requested flag on the record and returns 202; the worker checks the flag between units of work — every batch of rows, every file — and stops cleanly, releasing what it holds and moving the operation toCANCELLED.If the worker is inside an uninterruptible step, the cancellation lands after it finishes. If the operation has already succeeded, cancel returns 409 with a
already-completedtype. The client seesCANCELLINGas an intermediate status while the flag is set but the worker has not acknowledged.For operations whose side effects cannot be undone, such as a bulk email send, the contract documents that cancel stops further work but does not roll back completed units, which is honest about what a cancel can mean.
- "How do you make sure a crashed worker's operation reaches a terminal state?"
Each running operation carries a heartbeat timestamp the worker updates every few seconds and a lease.
A sweeper job looks for operations in
RUNNINGwhose heartbeat is older than the lease, say two minutes, and either re-queues them for another worker if the job type is restartable — with the operation id as the idempotency key so a partially completed job does not duplicate its output — or marks themFAILEDwith aworker-losttype if not.The job queue itself, whether SQS with visibility timeouts or a database table with
SELECT … FOR UPDATE SKIP LOCKED, provides the lease.The metric I alert on is the count of operations older than the maximum expected duration for their type, because that catches both crashed workers and a sweeper that has stopped running.
Q65 · Scenario. "A partner's webhook endpoint was down for six hours. When it came back they received 40,000 events in two minutes and fell over again. What was wrong with our design and what should it be?"
Reveal answer
Strong answer Symptom: a burst on recovery that overwhelms the receiver, which means our retry scheduler released a backlog all at once. Evidence: our delivery logs show retries for one endpoint aligned to the same schedule and no per-endpoint concurrency cap.
Causes ranked: retries scheduled by fixed backoff with no jitter so they synchronise; no per-endpoint concurrency limit; no circuit breaker that pauses deliveries to a failing endpoint; and no way for the partner to ask for a slower rate.
The redesign: per-endpoint delivery queues with a concurrency cap of, say, 4 in flight; exponential backoff with jitter from 1 minute to 1 hour over 24 hours; a circuit breaker that stops attempts to an endpoint after N consecutive failures and probes it every few minutes; on recovery, drain at a bounded rate honouring the receiver's 429 and Retry-After; an endpoint-level disabled state after 24 hours of failure with an email to the owner; and a replay API — GET /events?after=… — so a recovered partner can catch up on their own terms instead of receiving a flood.
Prevention: publish a receiver guide that says "return 200 fast, process asynchronously, expect duplicates", and load-test our delivery system with a simulated six-hour outage.
Land it Retries are traffic you generate; without concurrency caps, jitter, and a breaker, a webhook system is a denial-of-service tool pointed at your partners.
- "You added the concurrency cap and the partner still falls over on recovery. What next?"
Then the cap is not the bottleneck on their side, or it is not being honoured.
I would confirm from our delivery logs that in-flight requests to that endpoint never exceeded the cap, since a cap per dispatcher instance is a cap times the number of instances.
If it held, the receiver is failing on something other than concurrency: perhaps each webhook triggers expensive synchronous work and even four at a time is too many, or their database was still recovering.
The next levers are a lower rate for that endpoint, a slow-start ramp after the circuit breaker closes — one in flight for the first minute, then two — and honouring their 429 and
Retry-Afterwith real backoff.And I would offer them the replay API so they pull at their own pace rather than us pushing at ours.
- "How does the circuit breaker decide the endpoint is back?"
After the breaker opens on, say, five consecutive failures, it stops normal deliveries and sends a single probe every few minutes — one real event, not a synthetic ping, because a health endpoint can be up while the handler is broken.
On a 2xx it moves to half-open and lets a small number through, growing the allowed concurrency by one per successful minute up to the cap, which is the slow start.
Any failure during half-open re-opens the breaker with a longer probe interval, capped at fifteen minutes.
The state per endpoint is stored centrally so all dispatcher instances agree, and it is visible in the partner dashboard with the last failure reason, so the partner's engineer can see "we are probing you every five minutes and getting 503" rather than wondering why events are late.
- "What does the replay API look like, and how does it interact with the pushed events?"
GET /events?after=<cursor>&types=order.paid,order.shipped&limit=500, cursor-paginated on the event's commit sequence, returning the same JSON that would have been pushed, including the same event ids. A partner recovering from an outage pauses their webhook endpoint, walks the feed from the last event id they processed, then re-enables the endpoint.Because event ids are the same in both channels, their deduplication table makes overlap harmless. The partner dashboard also offers a "redeliver from time" button that queues deliveries at the throttled rate. The feed is retained for 30 days, which bounds storage and is documented.
Having the pull channel changes the push channel's job from "guarantee delivery" to "deliver promptly", and that is a much easier promise to keep.
Q66 · Design. "Design webhooks with guaranteed delivery for an events platform: signing, ordering, retries, and what 'guaranteed' can honestly mean."
Reveal answer
Strong answer Requirements: no event lost, receivers can verify authenticity, duplicates are detectable, and load is bounded. Honest guarantee: at-least-once delivery, because a lost 200 forces a redelivery, so receivers must be idempotent on the event id; exactly-once is not achievable across the network.
Design: every event is written to an outbox table in the same transaction as the business change, which is the only way "no event lost" is true; a dispatcher reads the outbox and enqueues deliveries per subscription.
Each delivery POSTs a JSON body with id, type, occurredAt, and data, plus headers: a timestamp and an HMAC-SHA256 signature over timestamp and body using a per-subscription secret, so receivers verify origin and reject replays older than five minutes; a Webhook-Id for deduplication.
The receiver must respond 2xx within 10 seconds; anything else is retried with exponential backoff and jitter for up to 3 days, with a per-endpoint concurrency cap and a circuit breaker.
Ordering: guaranteed only per resource, by delivering events for one order sequentially and stamping a per-resource sequence number so the receiver can detect gaps; global ordering is not promised.
Observability: a delivery log per event with attempts and responses visible in the partner dashboard, and a replay endpoint. Secret rotation supports two active secrets. Trade-offs: the outbox adds a write per event; sequential per-resource delivery reduces throughput for hot resources.
I would not sign with a shared global secret, would not deliver before the business transaction commits, and would not promise ordering I cannot keep.
Land it Guaranteed means at-least-once from an outbox, signed, deduplicable, ordered per resource — anything stronger is a promise the network will break.
- "Requirement change: events must be delivered in strict global order for a compliance audit trail. What do you do?"
I would first separate the audit trail from the webhooks. A strictly ordered, complete record is a log, and the right delivery for a log is a pull feed with a commit-ordered sequence, which is strictly ordered by construction, or an export.
Webhooks with retries cannot be globally ordered without serialising every delivery to one endpoint through one queue, which means a single slow response stalls everything and throughput drops to one in flight.
If the requirement truly is push, I offer a per-subscription strictly ordered mode with that cost documented: one in-flight delivery, no skipping, and the subscription paused on any failure until it succeeds.
Most compliance teams, once they hear that, accept the feed with a sequence number and a daily signed export, which also gives them the tamper-evidence they actually wanted.
- "Under time pressure, what would you cut?"
I would cut per-resource ordering and the per-resource sequence numbers, documenting that events may arrive out of order and that receivers should fetch the resource by id for its current state — which they should do anyway for anything that matters.
I would cut the partner dashboard's delivery log to a simple per-endpoint success rate and last error. I would cut dual-secret rotation and require a short cutover instead.
I would not cut the outbox, because without it "no event lost" is false; I would not cut the signature with a timestamp, because unsigned webhooks are a forgery surface; and I would not cut the event id and the at-least-once statement, because they are what makes receivers correct.
Retries with backoff and a concurrency cap are a day's work and stay.
- "Show me the signature scheme and how the receiver verifies it."
Headers:
Webhook-Id: evt_9f3,Webhook-Timestamp: 1756252800,Webhook-Signature: v1,base64(HMAC_SHA256(secret, id + "." + timestamp + "." + rawBody)). Signing over the id and timestamp as well as the body binds the signature to this delivery, so a captured request cannot be replayed with a new id or later.The receiver reads the raw body bytes before any JSON parsing, because re-serialised JSON will not match, recomputes the HMAC with its copy of the secret, compares using a constant-time comparison, and rejects if the timestamp is more than five minutes from its clock.
Multiple signatures may be present, separated by spaces, which is how rotation works: during a rotation both the old and new secret sign each delivery, and the receiver accepts if any matches.
This is the Standard Webhooks convention as of Aug 2026, and Stripe's scheme is essentially the same.
- "Why not just deliver from the business transaction directly, if you are careful?"
Because there is no careful way to make a network call and a database commit atomic. If I call the partner inside the transaction and the commit then fails, they received an event for something that never happened.
If I commit and then call, a crash between the two loses the event with no record it was owed.
The outbox writes the event as a row in the same transaction as the business change, so the two are atomic, and a separate dispatcher reads the outbox and delivers with at-least-once semantics, marking rows sent.
The cost is the extra row per event and a dispatcher process, and the latency of the dispatcher's poll interval, typically under a second. Change data capture on the outbox table, with Debezium or logical replication, removes even the polling.
Q67. "How should a webhook receiver be written, and why is 'process then return 200' the wrong order?"
Reveal answer
Strong answer The receiver verifies the signature with the shared secret and checks the timestamp is within a few minutes, rejecting anything else with 401.
It then stores the raw event by its id in a table with a unique index — insert-if-absent — and returns 200 immediately.
Processing happens afterwards from that table by a worker, with the event id as the idempotency guard so a redelivered event is a no-op.
"Process then return 200" is wrong because processing takes time and can fail: if it exceeds the sender's timeout, the sender marks the delivery failed and retries, and now the receiver processes twice; if it throws, the receiver returns 500 and the sender retries something that may have partly happened.
Storing first makes acknowledgement fast and durable, which is the receiver's only job during the request.
Two more rules: never trust the event's payload as the full truth for money — fetch the resource from the API by id, since a webhook can be stale or reordered — and expose a health endpoint so the sender's circuit breaker can probe you.
Land it A webhook handler is an inbox, not a processor — verify, store, acknowledge, and do the work from the table.
- "What if the receiver's storage insert fails — what status do you return?"
A 5xx, so the sender retries; that is exactly the case retries are for. A 503 with
Retry-Afteris the clearest signal. What I never do is return 200 after a failed store, because then the event is acknowledged and gone.If the insert failed because the event id already exists — the unique index fired — that is a duplicate delivery, and the correct response is 200, because the receiver already has it; a 409 would make the sender retry a delivery it should consider done.
So the handler distinguishes a constraint violation on the id, which is success, from any other failure, which is 5xx.
The same rule applies to signature failures: 401 is a permanent rejection and most senders will not retry it, so it is the right code for a forgery and the wrong one for a transient problem.
- "How do you handle out-of-order events when processing from the inbox?"
By never trusting the event's payload as the current state. When the worker processes an
order.updatedevent, it fetchesGET /orders/{id}from the API and reconciles against that, so an older event arriving after a newer one cannot regress the local copy.If the sender provides a per-resource sequence number, the worker stores the last applied sequence per resource and skips events with a lower one.
For event types that are commands rather than state — "a refund was issued" — ordering matters less, since the worker records the fact by event id.
The worker also processes events for the same resource serially, by partitioning the inbox by resource id, so two workers do not race on one order. The general rule is that the event tells me something happened; the API tells me what is true now.
- "How fast is fast enough for the acknowledgement, and how do you keep it that fast?"
Senders typically time out between five and thirty seconds; Stripe and Standard Webhooks senders use around ten, so I aim for an acknowledgement under a second at p99.
The handler does three things: verify the HMAC, which is microseconds; insert one row into the inbox table, which is a single indexed write; and return. No downstream calls, no parsing beyond reading the id, no locks on business tables.
The inbox insert can be to a queue instead of a table if the database is under pressure.
I measure the handler's latency separately from the worker's and alert on it, because a slow handler causes retries that cause duplicates, which the id guard absorbs but which double the load on the sender's side at exactly the moment they are least able to afford it.
Q68. "Polling versus webhooks versus server-sent events versus WebSockets for delivering updates to API clients — how do you choose?"
Reveal answer
Strong answer Polling is the client asking on a schedule; it is the simplest, works through any firewall, and with ETags and Retry-After is cheap, but latency equals the interval and idle clients waste calls.
Webhooks are the server calling the client; they suit server-side integrators who can expose an endpoint, give low latency, and require the delivery machinery from the previous questions.
Server-sent events are a long-lived HTTP response streaming text events to a browser or client — one direction, automatic reconnection with a last-event id, trivially proxied — ideal for live status pages and progress bars.
WebSockets are a full-duplex connection for chat-like interaction where the client also sends frequently; they need sticky infrastructure and careful scaling.
The decision: partners with servers get webhooks plus a poll-based replay; browsers watching a resource get SSE; interactive bidirectional apps get WebSockets; and everyone gets polling as the fallback that always works.
For internal service updates I would use an event stream on Kafka rather than any of these, as covered in Chapter E7.
Land it Push where the client can receive, stream where it cannot, and keep polling as the truth everyone can fall back to.
- "How do you scale server-sent events across many instances?"
Each SSE connection is held by one instance, so the update that a client needs may originate on another.
The pattern is a fan-out channel: instances subscribe to a topic per resource or per user on Redis pub/sub or a message broker, and when a change is committed, the writer publishes to the topic; every instance holding a connection for that topic writes the event to it.
Connections are cheap on servers with virtual threads or a reactive stack, tens of thousands per instance, but the load balancer needs long idle timeouts and no response buffering, and the proxy must not compress or buffer the stream.
Reconnects arrive with
Last-Event-ID, so the server keeps a short replay buffer per topic to fill the gap. If the buffer cannot cover the gap, the client is told to refetch the resource, which is the polling fallback in action.- "When does polling actually win over all of them?"
When the client population is large and mostly idle, updates are infrequent, and the acceptable latency is measured in minutes.
A million desktop clients checking for a new configuration once an hour is a million cheap conditional GETs returning 304, which any CDN absorbs; a million open SSE connections is a million sockets across a fleet for no benefit.
Polling also wins behind restrictive corporate networks that kill long-lived connections, on battery-sensitive mobile clients where the OS schedules network wakeups, and in any environment where operational simplicity matters more than a few seconds of latency.
The design that makes polling cheap is the same one that makes it correct: ETags,
Cache-Control, aRetry-Afterhint that tells clients how often to ask, and a lightweight "changes since" endpoint so a poll returns only what is new.- "What are the concrete costs of WebSockets that people underestimate?"
Stickiness: the connection lives on one instance, so a deployment or a scale-down disconnects every client on it at once, and clients reconnecting together is a thundering herd, so reconnect logic needs jittered backoff.
Authentication: browsers cannot set headers on a WebSocket handshake, so the token goes in a query string, which leaks into logs, or in the first message, which needs its own protocol.
Load balancers and proxies need explicit support for the upgrade, with long idle timeouts, and some corporate proxies block it entirely. Backpressure: a slow client fills the server's send buffer, and without limits one client can pin memory.
Observability: there are no status codes or request logs per message, so tracing is bespoke. Every one of those is solvable, and none of them exist for SSE, which is why SSE wins whenever the traffic is one-directional.
The last group of this section tests the operational edges of REST design: protecting the service from its clients, moving lots of data, and keeping the contract honest.
Q69. "Token bucket versus sliding window for API rate limiting — what does each let through, and where do you enforce it?"
Reveal answer
Strong answer A token bucket holds up to a burst of B tokens and refills at R per second; each request takes one, and an empty bucket means 429.
It permits short bursts up to B while enforcing the average R, which matches how real clients behave — idle, then a flurry.
A sliding window counts requests in the last N seconds and rejects above a limit; it is stricter about bursts and, in its exact form, needs a log of timestamps per client, so most systems use the approximated sliding window that weights the previous fixed window.
Fixed windows are the naive option and allow double the limit at a boundary.
I enforce at the gateway, keyed by client id from the token, with the counters in a shared Redis so all gateway instances agree, using an atomic Lua script or Redis's built-in rate-limit modules; per-instance limits are inconsistent and drift with scaling.
I also keep a cheap local limit as a backstop if Redis is unreachable — fail open with a conservative local limit rather than fail closed. Responses carry Retry-After and the draft RateLimit headers on every response, not only on 429.
Land it Token bucket for burst-tolerant fairness, enforced once at the gateway with shared counters — and tell clients their remaining budget before they spend it.
- "Show me the Redis token-bucket script."
The bucket is a hash per client with
tokensandts.The Lua script receives the key, the rate, the capacity, the current time, and the cost, then: read tokens and ts; compute elapsed as now minus ts; set tokens to the minimum of capacity and tokens plus elapsed times rate; if tokens is at least cost, subtract cost and set allowed to 1, otherwise allowed is 0; write tokens and now back with an expiry of capacity divided by rate seconds, so idle buckets vanish; return allowed, the remaining tokens, and the seconds until the next token.
Because Redis runs the script atomically, two gateway instances hitting the same bucket cannot both spend the last token. Redis 7's built-in functions or the
redis-cellmodule offer the same in one command, and the return values map directly onto theRateLimitheaders.- "What does the boundary-burst problem with fixed windows look like in numbers?"
With a limit of 1,000 per minute in fixed windows aligned to the clock, a client can send 1,000 requests at 11:59:59 and 1,000 more at 12:00:00, which is 2,000 requests in two seconds while never exceeding the limit in any window.
The approximated sliding window fixes it by weighting the previous window: at 12:00:15, the count is the current window's requests plus 75% of the previous window's, since three quarters of the last 60 seconds fall in the previous window.
That costs two counters per client instead of a timestamp log and is within a few percent of an exact sliding log.
The token bucket takes a different stance: it explicitly permits a burst up to the bucket size, then enforces the refill rate, so the question becomes what burst you want to allow rather than how to forbid one.
- "Why fail open when Redis is down — is that not dangerous?"
It is a trade-off between two failures. Failing closed means a Redis outage becomes a total API outage for every client, including well-behaved ones, which is a worse incident than the rate limiter being lenient for a few minutes.
Failing open with nothing means a hostile client can flood us precisely when a dependency is unhealthy.
So I fail open with a local, per-instance fallback limit set conservatively — the global limit divided by the instance count, roughly — which keeps the worst case bounded while keeping the API up.
The fallback is a separate metric so I know when it is active, and the alert on Redis unavailability pages, because the degraded state must not be allowed to persist. Load shedding based on the service's own health is the backstop beneath both.
Q70 · Scenario. "A single tenant's misbehaving script is consuming 70% of your API capacity, but they are under their per-minute rate limit because they run 50 parallel workers. Other tenants see p99 latency triple. What do you do?"
Reveal answer
Strong answer Symptom: a noisy neighbour within the letter of the limit, degrading others.
Evidence: per-tenant request rate, concurrency, and CPU seconds consumed — the last matters because a rate limit counts requests, not cost, and their requests are probably the expensive kind such as deep list pages.
Causes ranked: the limit is per-minute count only, with no concurrency or cost dimension; expensive endpoints cost the same as cheap ones; no per-tenant capacity isolation.
Immediate action: apply an emergency per-tenant concurrency cap at the gateway, say 8 in flight, which converts their 50 workers into a queue on their side, and contact them.
Lasting fix: add a concurrency limit per tenant alongside the rate limit; weight expensive endpoints so a list page costs 10 tokens and a GET costs 1; add adaptive load shedding that returns 503 to the heaviest tenant first when the service's own latency SLO is at risk; and offer them a bulk export so their job is 5 calls instead of 50,000.
Prevention: define fairness as a share of capacity, not a request count, and dashboard tenant share of CPU time.
Land it A request count is not a capacity share — limit concurrency and cost as well, and shed the heaviest tenant before everyone pays.
- "You applied the concurrency cap and other tenants' p99 is still double. What next?"
Then the damage is happening below the gateway. Eight in-flight requests from that tenant can still saturate a database if each is a deep list page or a heavy report, because the cost is in the database, not the API threads.
I would look at database load by tenant — statement statistics tagged with the tenant id via a comment on the query or a session variable — and at the connection pool: if their eight requests each hold a connection for seconds, the pool is what everyone else is waiting on.
The levers move down a layer: a per-tenant statement timeout, a separate connection pool or a lower pool share for heavy scopes, and a query cost weight so their expensive calls count for more tokens.
And I would check whether their old requests are still in flight, since a cap does not cancel work already running.
- "How do you weight endpoints by cost without guessing?"
By measuring.
Every request already emits its own duration, database time, and rows read, so I compute the median cost per endpoint over a week in CPU-milliseconds and database-milliseconds, normalise the cheapest common endpoint to one token, and round the rest to a small set of weights such as 1, 5, 10, and 50.
The weights are published in the API documentation so clients can predict their spend, and the
RateLimitheaders report the token budget rather than a request count. I re-derive the weights quarterly, since an endpoint that got an index will have become cheaper.For endpoints whose cost depends on parameters — a list with
limit=1000costs more thanlimit=10— the weight is computed from the parameter, which is a small function in the gateway's rate-limit plugin.- "What does adaptive load shedding look like in a Spring service?"
A filter at the front of the chain measures the service's own health signal — usually the number of requests currently in flight versus a limit derived from observed latency, which is what Netflix's concurrency-limits library does with a gradient algorithm — and rejects requests with 503 and
Retry-Afterwhen the limit is exceeded.Priority comes from a header the gateway sets from the tenant's plan and from whether the request is interactive: low-priority requests are shed first, and at the extreme only high-priority traffic is admitted. Resilience4j's bulkhead gives a simpler static version.
The important properties are that the decision is local and instant, since a central decision is too slow during an overload, and that shed requests are cheap, returning in microseconds without touching the database. The metric to watch is shed rate by priority.
- "Should you just bill the tenant for the capacity they use?"
Billing aligns incentives over months, and this incident is happening now, so both are needed.
Usage-based pricing on a cost-weighted basis — tokens rather than requests — makes a script that hammers deep list pages expensive to run, and the customer's own finance team becomes the rate limiter.
But billing does not protect other tenants' latency today, and a tenant willing to pay can still degrade the service unless capacity is genuinely isolated, which means the technical controls remain.
The commercial move I would make immediately is to offer them the bulk export at no extra cost, because it turns their 50,000 calls into a job that runs on a replica and costs us almost nothing, and then price the request-path usage so the export is obviously the better deal.
Q71. "What is the difference between rate limiting, quotas, and load shedding, and which one saves you during an incident?"
Reveal answer
Strong answer Rate limiting is a per-client policy on short windows — 1,000 requests per minute — enforced regardless of how the service feels, to keep clients fair to each other.
A quota is a longer-term entitlement tied to a plan — 1 million requests per month — enforced for commercial reasons and usually reported rather than rejected until exhausted.
Load shedding is the service protecting itself based on its own state: when CPU, queue depth, or latency crosses a threshold, it rejects some fraction of requests with 503 and Retry-After, preferring to drop low-priority or heaviest work first, so the requests it does serve stay within the SLO. During an incident, load shedding is what saves you, because rate limits are tuned for normal capacity — if you lose half your instances, every client can be within its limit and still overwhelm what remains.
Shedding needs a priority signal, such as a header set by the gateway from the client's plan or from whether the call is user-facing, and it needs clients that back off on 503, which is why the retry policy from Q7 matters.
Land it Limits keep clients fair, quotas keep finance happy, shedding keeps the service alive — only the third one reacts to reality.
- "What is the priority signal, and how does it get onto the request?"
It is a small header, for example
X-Request-Priority: 1, set by the gateway and stripped from anything the client sent, so clients cannot promote themselves.The gateway derives it from three things: the tenant's plan from the token, the endpoint's class from the route — a checkout is interactive, an export is batch — and whether the request is a retry, which is deprioritised.
Internal callers propagate the header downstream unchanged so a chain of services sheds consistently; without propagation, a high-priority user request can be shed by the third service because it looks like anything else.
The header is also recorded in traces and logs so that after an incident I can see what was shed and whether the priorities matched what the business would have chosen.
- "How do you verify load shedding works before the incident that needs it?"
With a load test that overshoots capacity deliberately, in staging sized like production or in production during a low-traffic window with a small canary.
I drive traffic to 150% of capacity with a mix of priorities and watch three things: the p99 of admitted requests stays within the SLO, the shed rate rises smoothly rather than in a cliff, and low-priority traffic is shed before high.
Then I kill half the instances mid-test and check that the remainder shed enough to stay healthy rather than collapse.
A game day with the on-call team running it is the most valuable form, because it also tests that the dashboards show shedding clearly and that the runbook says what to do.
Shedding that has never been exercised usually has a misconfigured threshold that either never fires or fires at normal load.
- "Where does each control run — gateway, service, or both?"
Rate limits and quotas run at the gateway, because they are per-client policies that need one consistent view of a client's usage and should stop bad traffic before it consumes a service thread.
Load shedding runs in each service, because it must react to that service's own state in microseconds; the gateway cannot know that the orders service's database is slow.
A coarse form of shedding also runs at the gateway, driven by service health signals, to stop traffic even earlier during a major overload.
The three interact: the gateway's rejections carry
RateLimitheaders and longRetry-Aftervalues, while the service's 503s carry short ones, and clients treat both as back-off signals.If I could have only one during an incident, it is the in-service shedder, because it is the one that works when everything else is already wrong.
Q72 · Design. "Design a bulk export API for a customer's entire dataset — hundreds of millions of rows — that is safe for your database and useful to a data engineer."
Reveal answer
Strong answer Requirements: no impact on the production database's latency, a consistent snapshot, a format pipelines can ingest, and resumable download. Design: POST /exports with the dataset, an optional filter, a format of Parquet or newline-delimited JSON, and an idempotency key returns 202 and an operation.
The job runs against a read replica or a snapshot, streams rows in keyset order to object storage in files of about 256 MB, and writes a manifest listing files, row counts, checksums, and the snapshot timestamp.
When done, GET /exports/{id} returns the manifest with pre-signed download URLs valid for 7 days and a webhook fires. The customer downloads files in parallel and resumes any failed one by range request.
Scheduling: one export per customer at a time, a daily quota, and a concurrency cap across all customers so the replica is never saturated; the job throttles itself against replica lag.
Incremental exports accept a previous export's snapshot timestamp and emit only changed rows via a change-feed sequence, so the nightly job is small. Trade-offs: latency of minutes to hours, which is what "bulk" means; replica lag means the snapshot is slightly behind, which the manifest declares.
I would not paginate this through the request path, would not run it on the primary, and would not stream a single 50 GB file with no manifest.
Land it Bulk export is a job that produces files with a manifest, run on a replica at a throttled pace — the API is the receipt and the download authorisation.
- "Requirement change: the customer needs the export within fifteen minutes of asking, every time. Does the design hold?"
Not for hundreds of millions of rows from a replica on demand; that is hours of streaming.
The design changes from compute-on-request to compute-continuously: a change-data-capture pipeline keeps a per-customer copy of the dataset in object storage as partitioned Parquet, updated every few minutes, and an export request becomes a snapshot of those files — a manifest pointing at the current partitions plus a small delta — which is ready in seconds.
The first full build per customer is still a long job, done once. The trade-offs are storage doubling, a pipeline to operate, and a consistency story that is "as of the last CDC checkpoint" rather than a database snapshot, which the manifest states.
If only a few customers need this, I offer it as a premium tier and keep the batch job for everyone else.
- "Under time pressure, what would you cut?"
I would cut Parquet and ship newline-delimited JSON only, compressed with gzip, because every pipeline can read it and a Parquet writer with correct types is real work. I would cut incremental exports and offer full exports only, with a quota of one per week.
I would cut the webhook and rely on polling the operation. I would cut the manifest's checksums but keep the file list and row counts.
What stays is running on a replica with a concurrency cap, keyset-ordered streaming so memory is flat, files of bounded size rather than one giant object, and pre-signed download URLs with an expiry.
The one thing I would refuse to cut is the throttle against replica lag, because an export that saturates the replica takes down every other read that uses it.
- "How does the job get a consistent snapshot without holding a long transaction?"
A single repeatable-read transaction for hours is a problem: on PostgreSQL it blocks vacuum and bloats the table, on MySQL it holds undo logs.
So I take the snapshot boundary rather than the transaction: record the maximum commit sequence at start, then stream in keyset order with
seq <= boundaryin many short transactions, one per file.Rows updated after the boundary are still read in their current state, so this gives a consistent set of rows but not a consistent point-in-time state for rows that changed.
If true point-in-time consistency is required, I export from a replica paused at that point, from a storage-level snapshot restored to a temporary instance, or with PostgreSQL's exported snapshots,
pg_export_snapshot(), which let several short-lived workers share one snapshot for the duration. The manifest says which guarantee was given.- "What does the data engineer actually want that most export APIs forget?"
A schema they can trust: the manifest includes the column names and types, and the types do not change without a version bump. Stable file naming and partitioning so a loader can be incremental. Row counts and checksums per file to verify completeness.
The snapshot boundary and timestamp so they can reason about what is and is not included. A deterministic sort so re-runs produce diffable output. Deleted rows represented explicitly in incremental exports, since a missing row is otherwise invisible. Null handling and timezone conventions stated once.
And a way to fetch a previous export's manifest, so a failed load can be retried without re-running the job. None of that is hard; it is just the difference between a dump and a dataset.
Q73. "How do you handle very large request bodies and slow clients without letting them exhaust your servers?"
Reveal answer
Strong answer Set a maximum body size at the gateway and in the server — Spring's spring.servlet.multipart.max-request-size and the container's max post size — and return 413 Content Too Large early, before buffering.
Enforce a request read timeout and a minimum transfer rate so a client that trickles bytes, the slowloris pattern, is disconnected rather than holding a thread for minutes; reverse proxies such as Nginx and Envoy have these settings, and they belong at the edge, not in Java.
Prefer streaming parsing for legitimately large payloads rather than reading the whole body into memory. Require Content-Length or bound chunked bodies. Cap concurrent connections per client IP and per client identity.
For anything genuinely large — files, bulk imports — move the bytes out of the request path to object storage as in the upload design, so the API server only ever handles small control messages.
With virtual threads in Java 21 and later, a slow client no longer pins a platform thread, but it still holds memory and a connection, so the limits remain necessary.
Land it Bound the size, bound the time, bound the concurrency — at the edge — and keep large bytes off the API servers entirely.
- "Name the specific Nginx or Envoy settings for slow clients."
In Nginx:
client_max_body_sizefor the size limit,client_body_timeout, which by default is 60 seconds between two successive reads, andclient_header_timeoutfor the headers; there is no direct minimum-rate setting, but a smallclient_body_timeoutapproximates it.In Envoy: the HTTP connection manager's
request_headers_timeout, the route or listenermax_request_bytesvia the buffer filter, and, most relevant,stream_idle_timeout, which fires when no bytes flow in either direction for the period, plusrequest_timeoutfor the whole request.Apache's
mod_reqtimeoutis the one with an explicit minimum rate, such asRequestReadTimeout body=20,MinRate=500. At the Tomcat layer behind them,connectionTimeoutcovers the time waiting for the request line, andserver.tomcat.max-swallow-sizestops it reading a huge rejected body.- "What happens when a request exceeds the body limit — how do you return a clean 413?"
The best behaviour is to reject on the
Content-Lengthheader before reading a byte, which the proxy does when the header is present.For chunked bodies without a length, the server reads until the limit and then aborts; Tomcat throws a
SizeLimitExceededExceptionfor multipart or closes the connection, and Spring mapsMaxUploadSizeExceededExceptionto 413 through the advice.The ugly detail is that the client may still be sending when the 413 goes out, and if the server closes the connection the client sees a reset rather than the response; Tomcat's max-swallow-size controls how much it will read and discard to let the response be delivered.
I set the proxy limit slightly below the application's, so the proxy always answers first with a proper 413 and Problem Details body.
- "How do virtual threads change this picture?"
With platform threads, a slow client holds one of, say, 200 Tomcat threads for the duration of its trickle, and 200 slow clients stop the server from serving anyone; that is the slowloris attack in one sentence.
With virtual threads, enabled in Spring Boot with
spring.threads.virtual.enabled=trueon Java 21 and later, a blocked read parks a cheap virtual thread and the carrier thread serves other requests, so thread exhaustion is off the table.But the connection is still open, its buffers are still allocated, the request's partially read body is still in memory, and the connector still has a maximum connection count, so a large enough number of slow clients exhausts memory or connections instead.
The timeouts and limits stay; virtual threads just move the failure from a few hundred clients to many thousands.
Q74 · Scenario. "Your OpenAPI document says a field is required, but the service has been returning it as null for months and clients cope. A new client generated a strict SDK and now fails. Whose bug is it and what do you do?"
Reveal answer
Strong answer Symptom: contract drift surfaced by the first strict consumer. Evidence: sample responses showing null for the field, the document marking it required and non-nullable, and no CI check that validates live responses against the document.
It is our bug: the contract is the promise, and the service broke it silently; the tolerant clients hid it. The fix depends on which is right.
If null is legitimate, the document is wrong: change the schema to nullable, which is technically a breaking change for strict clients that were never able to work anyway, and note it in the changelog.
If the field should always be present, the service is wrong: fix the data path and backfill, while temporarily declaring it nullable so the new client can proceed. Either way, the new client gets a working SDK within the day.
Prevention: response validation in the integration test suite that checks every response against the OpenAPI schema, a sampled runtime validator in staging that logs mismatches, and treating the document as a build artefact with a diff gate, not a wiki page.
Land it A contract nobody validates against drifts until a strict client finds it — validate responses in CI, and decide which side is lying before you patch.
- "You declared the field nullable and the new client works, but an old client now fails its own schema check. What next?"
That client validates responses against the document version it was generated from, and I changed the document under it; from its point of view the field is still required and non-nullable, and nothing about the wire changed, so the failure must be in how it consumes the new document.
Most likely it regenerated against the updated document and its generated model now has an optional type where code expected a value.
I would check what they actually run and give them the two options: pin to the previous document version, which is why documents are published as versioned artefacts, or update their code for the nullable type, which is the truthful contract.
It is a reminder that a document correction is itself a change that goes through the changelog and the diff gate, with a note explaining that the wire behaviour is unchanged.
- "How do you decide which side is right when the data path is ambiguous?"
By the domain, not the code. I ask the product owner what the field means and whether an entity without it is legitimate.
If the answer is "every order has a customer name", the nulls are data corruption and I trace their source — usually an import path or a migration that skipped validation — fix it, and backfill from wherever the truth lives.
If the answer is "guest checkouts have no name", the nulls are correct and the document was aspirational. Meanwhile I measure: what fraction of rows are null, from which creation paths, over what dates.
A sudden step in that graph points at a specific deployment; a constant fraction points at a legitimate case. That evidence goes into the changelog entry so the decision is recorded, not just made.
- "What does a sampled runtime validator look like, and what does it cost?"
A servlet filter or a gateway plugin that, for one in a hundred responses, loads the OpenAPI operation matching the route, validates the response body against its schema with a library such as openapi4j or the Atlassian swagger-request-validator, and emits a metric and a structured log line on mismatch naming the operation, the JSON pointer, and the violation.
It never changes the response; it only observes. At one percent sampling and a few hundred microseconds per validation the cost is negligible. In staging I run it at 100%.
The output feeds a weekly report of operations with drift, and any new mismatch type opens a ticket. It catches the data-dependent cases — nulls on legacy rows, an enum value nobody documented — that integration tests with fresh fixtures never see.
Q75. "Design-first or code-first for OpenAPI — which do you choose for a public API, an internal API, and why?"
Reveal answer
Strong answer For a public API, design-first: the YAML is written and reviewed before code, because the contract is the product, review happens with the people who will consume it, and generating server stubs and client SDKs from one source guarantees they agree.
It also forces the conversation about naming, errors, and pagination to happen when changing them is free.
For an internal API with a handful of consumers who sit in the same organisation, code-first with annotations — springdoc-openapi on Spring — is pragmatic: the document is always in sync with the code by construction, and the review happens in the pull request.
Either way the document must be a build artefact that a diff gate and a response validator check.
The failure mode of design-first is a document that drifts once the code is written, so the server stub must be generated or validated; the failure mode of code-first is a contract that reflects whatever the code happened to do, including accidental fields, so a linter with conventions runs over the generated document.
Land it Design-first when the contract is the product; code-first when the code is the contract — and a gate in CI either way.
- "In design-first, how do you stop the implementation drifting from the YAML?"
By generating the server interface from the document and making the implementation compile against it.
OpenAPI Generator's Spring server generator emits interfaces with the operation signatures and DTO records; the controller implements the interface, so a path, parameter, or type change in the document is a compile error in the service, and an endpoint added in code without the document has no interface to implement and is caught by a route-versus-document comparison test.
Request validation against the document runs at the gateway or in a filter, and response validation runs in the integration tests. The generated code is not committed; it is produced in the build from the document, which lives in the repository, so there is one source.
The remaining drift risk is behaviour the schema cannot express, which the contract tests cover.
- "In code-first, how do you review a contract change that is buried in a Java diff?"
By making the generated document part of the pull request.
The build generates the OpenAPI document with springdoc and the pipeline diffs it against the document from the main branch, posting the semantic diff — added endpoint, changed type, removed property — as a comment on the pull request. Reviewers read that comment, not the annotations.
A breaking change in the diff requires an approval from an API reviewer, enforced by a status check.
The generated document is also committed alongside the code as a snapshot, so the diff is visible in the pull request's files and the document history is in git.
Without that, code-first reviews see
@Schema(nullable = true)removed in a sea of other changes and nobody registers that it is a contract change.- "What would you do differently in a greenfield public API today?"
Design-first with a twist: the document is written in a repository the consumers can read and comment on before the first line of code, the SDKs are generated from it and published as pre-release packages the day the document is approved, and a mock server from Prism serves the document so the first integrators can build against it in week one.
The service is generated from the same document. The conventions linter runs on every commit to the document, and the diff gate is in place before the first release, not after the first incident.
The thing I would do earlier than most teams is write the breaking-change definition and the deprecation policy into the repository on day one, because the first version is the only time they cost nothing to adopt.
Q76. "What are the arguments against generating client SDKs, and how do you make generated SDKs good enough to publish?"
Reveal answer
Strong answer Against: generated code is generic and often unidiomatic, it exposes every quirk of the contract including ones you would rather hide, a bad generator produces breaking changes in the SDK for non-breaking changes in the API, and each language is a support commitment with its own package registry, versioning, and security patching. For: nobody hand-writes six clients correctly, generated SDKs give consumers types and deprecation warnings at compile time, and they make retries, idempotency keys, pagination, and auth correct by default, which is where hand-written integrations fail. To make them publishable: a curated contract with clean names and consistent conventions, because the SDK is a mirror; a generator that supports customisation — OpenAPI Generator with templates, or commercial ones such as Speakeasy, Fern, or Stainless that produce idiomatic code; a hand-written thin layer for the parts that matter, such as pagination iterators and webhook verification; a test suite that runs each SDK against a mock server built from the same contract; and semantic versioning of the SDK tied to the API's compatibility policy.
Land it Generate from a clean contract, wrap the parts that need taste, and test every SDK against the same mock — or publish nothing, because a bad SDK is worse than curl.
- "How do you stop a non-breaking API change from producing a breaking SDK change?"
The usual culprits are generator behaviours, not API behaviours.
Adding an enum value is additive in the API, but a generator that emits a closed Java enum makes the client throw on the unknown value, so I configure the generator to emit open enums with an
UNKNOWNfallback.Adding an optional field is additive, but a generator that emits a positional constructor reorders parameters, so I require builder or named-argument construction. Renaming an operation id renames the method, so operation ids are frozen once published.
The safeguard is a CI job that regenerates each SDK on every contract change and runs a public-API diff tool against the previous release, such as
japicmpfor Java, and fails the build if a symbol disappeared.As of Aug 2026 the commercial generators do most of this by default, but I still run the diff.
- "What does the hand-written layer actually contain, and how do you keep it from drifting?"
It contains the things a contract cannot express well. Pagination becomes an iterator that follows the cursor for the caller. Webhook verification computes the HMAC over raw bytes with a constant-time compare. Retries carry the idempotency key and honour
Retry-After. Authentication refreshes tokens transparently.Error mapping turns a Problem Details body into a typed exception with the
typeandinstancefields.It stays small, a few hundred lines per language, and it lives in template overrides or a wrapper package that imports the generated core, never in edits to generated files.
Drift is prevented by generating into a clean directory on every build, so any manual edit in generated code is overwritten and the build fails on the diff, and by the mock-server test suite exercising both layers together.
- "Which languages would you publish first, and how do you decide when to add one?"
I would look at the consumer base rather than guess. The gateway's access logs show the
User-Agentof every integration, and that tells me the language mix. For a typical B2B platform that is TypeScript, Python, and Java or Go, and I would start with two.Each language added is a permanent support commitment: a package registry account, signing keys, a release pipeline, security patching of transitive dependencies, and someone who can answer issues idiomatically.
I add a language when a measurable share of consumers, say ten percent of traffic or a named strategic partner, would use it, and only when the mock-server test suite can run for it in CI. I would rather publish two excellent SDKs and a clean OpenAPI document than six mediocre ones.
- "How do you version and release an SDK relative to the API?"
The SDK gets semantic versioning that is independent of the API's major version but tied to its compatibility policy. An additive API change is a minor SDK release. A bug fix in the wrapper is a patch.
An API major version is a new SDK major, and usually a new package name or module path so consumers can run both during migration.
The release is automated: a contract change merged to main triggers regeneration, the diff check, the test suite against the mock, and a publish to the registry with a changelog generated from the contract diff.
I pin the generator version in the repository so a generator upgrade is its own reviewed change, because generator upgrades are where surprise breaking changes come from.
Q77 · Design. "Design the search endpoint for a product catalogue of 20 million items with facets, typo tolerance, and personalised ranking, as part of a REST API."
Reveal answer
Strong answer Requirements: sub-200-millisecond responses, facet counts, fuzzy matching, ranking that can depend on the user, and stable paging.
Design: GET /products/search?q=…&category=…&priceMin=…&sort=relevance&cursor=… backed by a search engine — OpenSearch, Elasticsearch, or a managed service — fed by a change-data-capture pipeline from the catalogue database, so the API's database is not the search index.
The response carries hits with a summary representation, a facets object with counts per value, the total as a bounded number, and a nextCursor that encodes the engine's search-after key and a point-in-time snapshot id so paging is consistent while the index changes.
Personalised ranking is a re-ranking step over the top 200 engine results using user features, done in the API layer with a cache per user and query hash. Typo tolerance and synonyms are engine settings.
Caching: anonymous queries are cacheable at the CDN for 30 seconds keyed by the full URL; personalised ones are private. Rate limits are stricter than for the item endpoint because search is expensive.
Trade-offs: eventual consistency of a few seconds between catalogue and index, which the product accepts; a snapshot-based cursor expires after a few minutes.
I would not run search against the relational database with LIKE, would not expose the engine's query language to clients, and would not personalise inside the engine query, which kills caching and makes results unreproducible.
Land it Search is a separate system behind a REST facade — the API owns the contract and the cursor, the engine owns relevance, and personalisation is a re-rank on top.
- "What if the requirement changed so the index had to reflect a price change within one second, not a few seconds?"
I would separate the fields by volatility rather than speed up the whole pipeline. Text, categories, and attributes change rarely and can keep the change-data-capture path with a few seconds of lag.
Price and stock change constantly and would be served from a fast key-value store at response time: the engine returns the hit ids and ranking, and the API hydrates price and availability from Redis before responding, so the search index never needs to know the current price.
If price must also filter and sort, I would use the engine's partial document update on the price field only, pushed synchronously from the pricing service, with a bounded queue and an alert on lag.
The honest trade-off is that a synchronous update path couples pricing to the search cluster's availability, so it needs a fallback to the asynchronous path.
- "Why re-rank the top 200 in the API layer instead of letting the engine rank with user features?"
Three reasons. Caching: an engine query that includes user features produces a different result per user, so nothing can be cached at any layer; a user-independent engine query is shared across every user and only the cheap re-rank is per user.
Reproducibility: when a merchant asks why their product ranked fifth, I can replay the engine query and get the same answer, and then explain the personal adjustment separately.
Cost: the engine scores millions of candidates and personalised scoring is expensive per candidate; doing it on 200 candidates is trivial.
The limit is recall: if a personally relevant item is not in the top 200 of the generic ranking it will never surface, which I accept and monitor by measuring how often a click lands beyond position 150.
- "How does the cursor work exactly, and what happens when it expires?"
The engine supports
search_after, which continues from the sort values of the last hit, and a point-in-time snapshot with akeep_aliveof a few minutes, so the client pages through a frozen view even while the index is being updated.The cursor I return is an opaque, base64-encoded, signed token containing the point-in-time id, the last hit's sort values, and a hash of the query parameters so a client cannot reuse a cursor with a different query.
When the snapshot expires the engine returns an error, and the API returns 400 with a Problem Details type of
cursor-expiredand a hint to restart from the first page.Signing the token stops clients from fabricating cursors, and encoding the query hash stops them from paging one query with another query's cursor.
- "What would you cut if you had two weeks instead of two months?"
I would ship the engine-backed endpoint with facets, typo tolerance, and cursor paging, because those are engine configuration plus a thin API, and I would cut personalisation entirely for the first release.
Personalised re-ranking needs a feature store, a per-user cache, an evaluation loop, and privacy review, and it is the only part with real product risk.
I would also cut the CDN caching and just use the engine's own request cache, and I would replace the change-data-capture pipeline with a scheduled full reindex every ten minutes if the pipeline is not already there.
What I would not cut is the opaque signed cursor, the capped page size, and the rate limit, because those are the parts that stop the endpoint from taking the cluster down on day one.
- "How do you keep facet counts fast when a filter is applied?"
Facet counts are aggregations, and their cost depends on how many documents match the filter, not on the index size, so the first defence is to make the filters selective and indexed as keyword fields.
The second is to request only the facets the page displays, which the client declares with a
facets=category,brand,colourparameter, capped at a handful.The third is the engine's shard-level request cache, which caches aggregation results for identical filter sets, and is very effective because most users share a small number of popular filter combinations.
For the very hot combinations, such as the category landing pages, I precompute the facets on a schedule and serve them from Redis, marking the count as approximate.
If p99 is still over budget, I reduce facet accuracy with the engine's sampler aggregation on a subset of shards.
Q78. "What does 'API-first' mean in practice for a team, and what is the cost of doing it badly?"
Reveal answer
Strong answer In practice it means the contract is designed and reviewed as a deliverable before implementation, with the consumers in the review; every capability is exposed through the API the same way internal and external clients use it, so there is no privileged back door; the contract is a build artefact with linting, diff gates, and generated SDKs and mocks; and the team owns the API's lifecycle — versioning, deprecation, documentation, and support — as part of the product, not as an afterthought.
Done well it lets front-end and partner work start from the mock while the backend is built, and it stops the "we will fix the naming later" debt that turns into a v2.
Done badly it becomes waterfall in YAML: months of contract design with no running code, contracts that drift because nothing validates them, and generated code nobody maintains. The cost of doing it badly is the worst of both — the ceremony without the guarantees.
The tell of a healthy practice is that the contract changes in the same pull request as the code, and CI fails when they disagree.
Land it API-first is a contract with consequences in the build; without the gates, it is documentation-first, and documentation drifts.
- "How do you keep the contract and the code from disagreeing in practice?"
With a test that runs the service and validates every response against the document.
In a Spring project I run the integration tests through a validating filter, such as the OpenAPI request and response validator from Atlassian, which fails a test when a response has a field not in the schema, a wrong type, or an undocumented status code.
That catches code drifting from the document. For the other direction, document drifting from code, I use the contract diff gate: the document is compared with the last released version on every pull request, and any change is visible in review alongside the code change.
If the team generates the document from annotations, the validator is still needed, because annotations describe intent rather than behaviour. The rule is simple: the pull request that changes the behaviour changes the document, and CI proves they match.
- "What does the review of a contract look like before any code exists, and who attends?"
It is a one-hour session with the producing team, at least one consumer per client type, and someone from the API platform function if there is one.
The input is the OpenAPI document rendered as documentation, plus a mock server generated from it, so consumers can actually make the calls they would make.
We walk through the top three consumer use cases end to end, and ask for each whether the calls, the fields, the errors, and the pagination fit.
We check the conventions linter passed, that naming matches the rest of the platform, and that each error has a registered type. Consumers leave with a mock to build against and the producer leaves with a list of changes.
The point is to make the naming argument happen now, when it costs a document edit, rather than after two clients depend on it.
- "Your team is small and shipping fast. Is API-first worth the ceremony?"
Yes, but scaled down. The minimum is three things: the document is in the repository, the document changes in the same pull request as the code, and one CI check fails when they disagree. That is an afternoon of setup and no ongoing ceremony.
The review can be asynchronous, a comment thread on the pull request with one consumer tagged. What I would skip for a small team is generated SDKs in several languages, a formal design review board, and a catalogue.
The reason it is still worth it is that the cost of a bad contract compounds: every consumer that integrates locks in the naming, and a rename later is a version bump with a sunset.
A small team cannot afford a v2 for cosmetic reasons, so getting v1 reviewed is the cheap option.
- "How would you measure whether API-first is working?"
I would measure outcomes rather than compliance. Breaking changes that reached production versus those caught in CI, which should trend towards zero in production.
Time from a consumer's first request for a capability to their first successful call against a mock, which should shrink because they no longer wait for the implementation. The number of contract-versus-implementation mismatches found by the validator, which should be high at first and then fall.
Support tickets caused by undocumented behaviour. And the count of endpoints whose document was updated after the code shipped, which is the tell of documentation-first creeping back.
If the numbers do not move in six months, the gates are not wired in and the practice is theatre.
Q79 · Scenario. "A client reports that your API 'randomly' returns 503 for about 2% of requests at all hours, and your dashboards show the service healthy. Where do you look?"
Reveal answer
Strong answer Symptom: a steady low error rate invisible to the service's own metrics, which means the errors are generated before the service or by one instance the aggregate hides.
Evidence: the gateway or load balancer access log filtered to 503s with upstream address and reason; the client's request ids for a sample of failures; per-instance rather than aggregate error rates.
Causes ranked: one unhealthy instance out of fifty that the health check passes but that fails 100% of its share — 2% is exactly one in fifty; the load balancer's own connection limits or a full upstream queue producing 503s that never reach the service; a deployment that leaves connections draining incorrectly so a rolling restart yields a trickle of 503s; and a rate limiter or web application firewall at the edge rejecting some pattern in that client's requests.
The fix follows the cause — drain and replace the instance, tune the balancer, fix readiness and graceful shutdown.
Prevention: per-instance error rates with an alert on any instance deviating from the fleet, dashboards built from the gateway's logs rather than only the service's, and a synthetic client that samples the public path continuously.
Land it Two percent at all hours is one bad instance in fifty or a proxy speaking for you — measure from where the client stands, not from inside the service.
- "You replaced the suspicious instance and the 2% is still there. What next?"
Then the errors are not from a service instance, and I move outward.
I take the client's failing request ids and search the gateway access log for them: if the gateway logged a 503 with an upstream address, the failure is between gateway and service, and the reason field tells me whether it was a connection refused, an upstream timeout, or a full queue.
If the gateway has no record at all, the 503 was generated before the gateway, by the load balancer, a web application firewall, or a CDN, and I look at their logs for the same ids.
If the client's ids are absent everywhere, I ask the client for the exact response headers, because a 503 with a
Serverheader from a CDN or from their own corporate proxy is a different investigation.I also check whether the 2% is uniform across routes or clustered on one path or one payload size.
- "Why did your health check pass on a broken instance, and how would you fix the check?"
Because a liveness check answers "is the process running", and a readiness check that only returns 200 from a static endpoint answers the same thing.
An instance can have a full thread pool, an exhausted connection pool, a corrupted local cache, or a broken route to the database and still answer a static health endpoint.
I would make readiness reflect ability to serve: it checks that the connection pool can hand out a connection within a short timeout, that the thread pool has headroom, and that a recent sample of real requests succeeded.
Spring Boot's readiness group can include a custom
HealthIndicatorfor each of those.Beyond the check, the fix is an outlier-detection alert: per-instance error rate compared with the fleet median, so an instance that is 100% failing while the fleet is 2% failing is ejected automatically by the balancer's outlier ejection.
- "How do you build a dashboard that would have shown this?"
The aggregate error rate hid it because 2% looked like noise. I would add three views. First, error rate per instance as a heat map, so one dark row stands out immediately.
Second, error rate from the gateway's perspective by upstream address, which shows errors the service never counted.
Third, a synthetic client hitting the public hostname every 10 seconds from outside the network, whose success rate is the number I alert on, because it measures what customers see.
The alert on the per-instance view fires when any instance exceeds three times the fleet median for five minutes.
I would also add a rule to the load balancer configuration review: any 503 the balancer generates itself must be logged with a reason and counted in the same dashboard.
- "What if the 2% only affected this one client?"
Then the difference is in what that client sends.
I would compare their requests with successful ones on the same route: header size, because some proxies reject headers above 8 kilobytes; a specific header value that a web application firewall rule matches; request bodies at a size boundary; a TLS version or cipher that one balancer node does not support; or a source IP range that a rate limiter groups with another tenant.
Their 50 parallel workers might also hit a per-client concurrency limit at the gateway that returns 503 rather than 429.
I would reproduce with their exact request captured from their side, replayed through each layer in turn, and I would ask whether they use a corporate egress proxy, because a 2% failure at all hours is the signature of one bad node in their pool as often as in mine.
Q80. "When would you NOT build a REST API at all for a new capability?"
Reveal answer
Strong answer When the consumer does not need an answer now and the producer should not depend on the consumer being up — an order placed should not fail because the analytics service is down — the capability is an event published to a stream, not an endpoint.
When the interaction is a high-rate internal call between services I control, gRPC's contract and efficiency beat REST. When the data is large and batch-shaped, files in object storage with a manifest beat any request-response API. When many client types need flexible slices of a rich graph, GraphQL earns its cost.
When the capability is really a library — pure computation with no shared state — a package beats a network call with all its failure modes.
And when the "API" would have one internal consumer that sits in the same deployable, a method call beats a network hop.
The question to ask is who calls it, how often, whether they need an immediate answer, and whether the caller and callee must be independently available — those four answers pick the mechanism, and REST is the right answer for one common combination, not all of them.
Land it REST is the default for synchronous, resource-shaped, externally consumed capabilities — and each of those three words is a reason to choose something else when it does not hold.
- "Give me a concrete case where you chose events over REST and it turned out to be the wrong call."
A common one is an order-validation step.
The team made "validate address" an event so checkout would not depend on the address service, but the checkout screen needed the result to let the user continue, so the front end polled for the validation result, which added latency and a timeout path that was never designed.
The interaction was fundamentally request-response: the caller needed the answer to proceed. We reverted it to a synchronous call with a 300-millisecond deadline and a degraded path where checkout continues with a flag if validation is unavailable.
The lesson I take into interviews is that the test is not "would it be nice to be decoupled" but "can the caller do anything useful without the answer". If the caller blocks anyway, the event just moved the coupling into a poll.
- "What if the capability is both: a synchronous check and a fact others care about?"
Then it is both, and I design both explicitly. The synchronous endpoint returns the answer to the caller. The same transaction writes an outbox row, and a relay publishes the fact to the stream, so interested consumers learn about it without the endpoint calling them.
The important discipline is that the endpoint never fans out synchronously to the interested parties, because that is where the availability coupling comes from, and that the event is written in the same database transaction as the state change, so there is no window where the state changed but the event was lost.
In Spring that is an
@Transactionalservice method writing the entity and the outbox row, and a scheduled or change-data-capture relay reading the outbox. The REST response and the event share one source of truth and one schema for the entity.- "When is a shared library the wrong answer even though the capability is pure computation?"
When the computation must change on a schedule the callers do not control. A tax-rate calculator is pure, but if the rates change monthly and forty services embed the library, every rate change needs forty deployments, and one laggard produces wrong invoices.
The same applies to anything that needs a consistent version across callers at the same instant, such as a fraud-scoring rule or a pricing formula. In those cases a service gives one place to change, with a version in the response for audit.
The other case is when the computation needs data that is large or sensitive, such as a model file or a secret, which should not be shipped inside every caller.
A library is right for stable, small, versionable logic; a service is right when the logic's currency or its data matters more than the network hop.
- "The four questions you named: walk through them for a payment-authorisation capability."
Who calls it: the checkout service and, later, a subscription-billing job.
How often: a few hundred per second at peak, which is well within REST or gRPC. Do they need an immediate answer: checkout does, because the customer is waiting and the answer decides whether the order proceeds; billing does not, it can queue authorisations and read results later.
Must caller and callee be independently available: checkout cannot proceed without payments, so the coupling is inherent, and pretending otherwise with an event would just delay the failure.
So the answer is a synchronous, idempotent
POST /authorizationsfor checkout with a deadline and an idempotency key, plus an asynchronous path for billing: submit a batch, receive 202, and consumeauthorization.completedevents. One capability, two access patterns, chosen per caller.
09 · DrillgRPC, GraphQL, Async & Choosing Between Them — Q81–Q115
The senior round rarely asks "what is gRPC". It asks why the load is on one pod, why the proto change broke a client that was never redeployed, why the GraphQL server fell over, and — the question behind all of them — how you would choose. These thirty-five questions are weighted towards incidents and designs, because the knowledge parts are in the primer and the judgement is what is graded.
These test whether you understand HTTP/2's consequences, Protobuf's evolution rules as mechanisms rather than folklore, and the operational surface of deadlines and status codes.
Q81 · Scenario. "gRPC load is all on one pod: 12 replicas behind a Kubernetes Service, one pod at 90% CPU, eleven idle. Diagnose and fix, with the trade-offs of each fix."
Reveal answer
The real test Whether you can explain connection-level versus call-level balancing and pick a fix appropriate to the infrastructure.
Strong answer In order:
- Symptom: one replica saturated while the rest idle, which is the signature of long-lived connections balanced at layer 4.
- Evidence:
kubectl get endpointsshows all twelve pods ready; the client's connection count to the service is one or a few; per-pod request metrics confirm the skew; the Service is a normal ClusterIP. - Causes ranked: a gRPC client opens one HTTP/2 connection and multiplexes every call over it, and the ClusterIP chose a pod once at connect time; secondarily, a few clients each pinned to the same pod by chance; thirdly, a keepalive so long that connections never rotate.
- Fixes: client-side load balancing — a headless Service so DNS returns every pod IP, and the client configured with the
round_robinpolicy, which opens a sub-connection per pod and rotates calls; the trade-off is that clients must re-resolve on scaling events, which gRPC's DNS resolver does with a refresh interval. Or a layer-7 proxy — a service mesh such as Istio or Linkerd, or Envoy — balancing per call; the trade-off is an extra hop and infrastructure to run. As a stopgap,MAX_CONNECTION_AGEon the server of a few minutes so connections are re-established and spread over time; the trade-off is periodic reconnects and only statistical fairness. - Prevention: a checklist item for any HTTP/2 or gRPC service — "how is this balanced per call?" — and a per-pod load-skew alert.
Going deeper The concrete client configuration matters in the interview. In grpc-java the target must be a DNS target that resolves to every pod, and the policy must be set explicitly, because the default is pick_first:
ManagedChannel ch = ManagedChannelBuilder
.forTarget("dns:///inventory.orders.svc.cluster.local:9090")
.defaultLoadBalancingPolicy("round_robin")
.usePlaintext()
.build();
The Kubernetes Service must be headless, clusterIP: None, so that DNS returns the pod addresses rather than one virtual IP. gRPC's DNS resolver re-resolves when a sub-connection drops and enforces a minimum of 30 seconds between resolutions, so a scale-up is only noticed when a connection breaks or the server rotates it; that is why maxConnectionAge on the server, with a maxConnectionAgeGrace so in-flight calls finish, is the pairing that makes client-side balancing track the fleet. As of Aug 2026 kubectl get endpoints prints a deprecation warning; use kubectl get endpointslices to list the pod addresses behind the Service.
Land it Kubernetes balances connections; gRPC needs something that balances calls — pick client-side round robin or a mesh, and never trust a ClusterIP alone.
- "You switched to a headless Service and round_robin, and the skew is better but two pods still get double the load. Why?"
Round robin balances per client, not per fleet. If there are three client instances and each opens a sub-connection to all twelve pods and rotates, the load is even.
But if one client instance sends ten times the traffic of the others, its round robin is even across pods while the others' are too, so that should still be even.
The usual cause of residual skew is stale resolution: a client resolved before the last scale-up, still has eight sub-connections rather than twelve, and will not re-resolve until a connection drops or the 30-second minimum passes and something triggers it.
The fix is
maxConnectionAgeon the server so connections rotate and resolution refreshes.The other cause is long-lived streaming calls, which pin to a pod for their whole life; those need the stream to be re-established periodically or a mesh that balances new streams away from loaded pods.
- "Which would you pick for a company already running Istio, and what does the mesh change?"
With a mesh already present I would use it and leave the client on the default policy.
The sidecar or ambient proxy terminates the client's single HTTP/2 connection and opens its own connections to every pod, balancing each request individually with the policy set in a
DestinationRule, such asLEAST_REQUEST, which is better than round robin because it avoids sending to a pod that is already slow.The mesh also gives outlier ejection, retries on
UNAVAILABLE, and per-call metrics by gRPC status without touching application code.What it changes is the failure model: the proxy is now in the path and must be sized, its own connection pool limits apply, and a proxy restart during a deploy drops connections unless drain is configured.
It also hides the problem, which is why I still keep the per-pod skew alert.
- "How would you prove the fix worked, and what would the alert be?"
I would look at three numbers before and after. Per-pod request rate, which should be within a few percent of the mean across all twelve pods. Per-pod CPU, which should follow it.
And the client's active sub-connection count from its channel metrics, which should equal the pod count, proving resolution is complete. A quick experiment is to scale the deployment from 12 to 16 and watch whether the new four pods receive traffic within a connection-age period.
The alert I would set is a coefficient of variation on per-pod request rate: if the standard deviation across pods exceeds 25% of the mean for five minutes, page.
That catches the original problem, stale resolution, and a pod that is silently unhealthy but still in DNS.
- "Does the same problem exist for HTTP/1.1 REST services in Kubernetes?"
It exists in a milder form. HTTP/1.1 clients with keep-alive also hold connections to a pod chosen once at connect time, but they open many connections, typically one per concurrent request, and each was balanced independently, so the statistical spread across pods is usually acceptable.
The imbalance appears when a client has a small pool that never rotates, or when a proxy in front pools upstream connections and reuses them for a long time.
The fix on that side is a maximum keep-alive request count or connection lifetime on the server, such as
keepalive_requestsin Nginx, so connections rotate.HTTP/2 makes it worse because one connection carries everything, and gRPC makes it worse still because it holds that one connection for hours by design. The principle is the same: anything that balances at connect time needs a rotation mechanism.
Q82. "Explain the Protobuf wire format well enough to derive the schema-evolution rules from it."
Reveal answer
Strong answer A serialised message is a sequence of key-value pairs where the key is the field number shifted left by three bits plus a wire type — varint, 64-bit, length-delimited, or 32-bit — so the reader knows how many bytes to consume even for fields it does not recognise.
Field names are never on the wire. From that, the rules follow. Renaming is free because names are only in generated code. Changing a number breaks compatibility because the reader looks up meaning by number.
Adding a field is safe because an old reader sees an unknown key, reads its wire type, skips the right number of bytes, and continues, while a new reader of an old message finds the key absent and returns the default.
Reusing a retired number is dangerous because an old writer may still emit it with the old type, and the reader will interpret those bytes as the new field — hence reserved.
Changing a type is safe only between types sharing a wire representation, such as int32 and int64 both being varints, which is why those pairs are listed as compatible.
Defaults are not transmitted, which is why proto3 could not distinguish unset from zero until optional restored explicit presence tracking.
Land it Every evolution rule is a consequence of "the number is the identity and unknown keys are skippable" — know the format and the rules are obvious.
- "Why is a proto3 default not sent on the wire, and what does that break?"
Proto3 defined that a scalar field set to its default value, zero, false, or empty string, is omitted when serialising, which saves bytes and simplifies the model.
What it breaks is presence: the reader cannot tell "the sender set quantity to zero" from "the sender never set quantity".
That matters for partial updates, where absent means keep the current value and zero means set to zero, and for booleans, where absent and false are different business facts.
The fix is the
optionalkeyword, restored in proto3 in 2020, which makes the compiler generate ahasQuantity()method and send the field even when it holds the default.As of Aug 2026 the newer Protobuf Editions model replaces the proto2 and proto3 split with per-field features, and explicit presence is the default there. The rule I apply: any field where "unset" is meaningful is
optional.- "What happens if I change a field from int32 to string?"
They have different wire types. An int32 is a varint, wire type zero, and a string is length-delimited, wire type two.
The key on the wire includes the wire type, so a new reader that expects wire type two and receives a key with wire type zero for that field number treats it as a mismatch.
Depending on the runtime it either stores the bytes as an unknown field, so the string reads as empty, or fails parsing with an invalid wire type error.
Old readers receiving the new writer's string see a length-delimited blob where they expected a varint and do the same. So the change is not compatible in either direction, and
buf breakingreports it as a field type change.The correct move is to add a new field with a new number, populate both during the transition, and reserve the old number afterwards.
- "Why does packed encoding matter for repeated fields, and can you change it safely?"
An unpacked repeated int field writes one key-value pair per element, so a thousand integers cost a thousand keys. Packed encoding writes one key with wire type two followed by a length and all the varints back to back, which is much smaller.
Proto3 packs repeated scalars by default.
It is safe to change between packed and unpacked for numeric types because parsers are required to accept both forms for a repeated scalar field regardless of the declaration, which is one of the few compatibility rules that rests on parser behaviour rather than on the wire format alone.
It does not apply to repeated strings or messages, which are always length-delimited per element. I mention it in interviews because it shows that "unknown keys are skippable" is not the whole story; some rules come from what the parser promises.
- "How would you verify a message actually decodes the way you think, without generated code?"
With the raw decoder in
protoc:protoc --decode_raw < message.binprints every field number, its wire type inferred from the key, and the value, with no schema at all, so I can see exactly which numbers a producer emitted.With a schema,
protoc --decode=orders.v1.Order orders.proto < message.binprints the named fields and shows unknown ones separately.bufhas equivalent commands.That is how I would repair the data in the Q83 scenario: the stored bytes still contain the old field number, and the raw decoder shows it. It is also how I check that a field I marked
optionalis really sent when set to zero.In a test, I compare the byte length of a message with and without a default-valued field to prove presence semantics.
Q83 · Scenario. "A Java service started returning empty currency for 10% of orders after a deploy that only touched the proto file. Nothing in the business logic changed. What happened?"
Reveal answer
Strong answer Symptom: a field silently empty for a subset of traffic after a schema-only change, which means a field-number mismatch between some writers and the new reader.
Evidence: diff the proto — I expect the currency field number changed, or a field was inserted and the numbers behind it shifted because someone renumbered; the 10% matches the share of traffic from clients still on the old proto.
Causes ranked: renumbering; reusing a reserved number; less likely, a change from string to a different wire type.
Because Protobuf does not fail on unknown fields, the old clients' currency arrives under a number the new server does not recognise and is skipped, and the new field reads its default, an empty string.
The fix is to restore the original numbers and redeploy; the data written in between must be repaired from the raw bytes if the unknown fields were preserved — Java's generated classes keep unknown fields, so the original values can be recovered from stored messages.
Prevention: buf breaking in CI against the main branch, which fails on any number change; a rule that numbers are append-only; and code review of proto diffs as seriously as database migrations.
Land it Protobuf never throws on a mismatched number, it just reads a default — silent data loss is the failure mode, and a breaking-change linter is the only guard.
- "You restored the numbers and redeployed, but some orders written during the window still have an empty currency. How do you repair them?"
It depends on what was stored.
If the service persisted the original Protobuf bytes, for example in a Kafka topic or a bytes column, the old field number is still in them as an unknown field, and I can re-parse those bytes with the restored schema and the value comes back.
If the service parsed the message and wrote the fields into relational columns, the currency was lost at write time, and I must recover it from a source of truth upstream, usually the producer's own database or the original event in the topic, joined by order id.
The Java generated classes keep unknown fields in an
UnknownFieldSet, so an entity that stored the message object in a cache also still has it.The repair is a one-off job that reads each affected order, resolves the currency, and writes it with an audit note, and I would verify by counting orders with empty currency before and after.
- "How does buf breaking work and what mode would you run it in?"
It compiles the proto files on the branch and on a reference, usually the main branch or the last tag, and compares the descriptors rule by rule. Its
FILEcategory is the strictest: it fails on any change that breaks generated code, including renames.WIRE_JSONfails only on changes that break the wire or JSON encoding, which allows renames but catches renumbering, type changes, and removed fields without reservation.For an internal service where renames are acceptable and the goal is data safety, I run
WIRE_JSON; for a published contract with generated clients in other teams, I runFILE. The configuration lives inbuf.yamlunderbreaking.use, and CI runsbuf breaking --against '.git#branch=main'.It must be a required check, because a warning is ignored on the day someone is in a hurry.
- "Why did the deploy pass its tests?"
Because the tests serialised and deserialised with the same schema. A unit test that builds an
Order, writes it, and reads it back uses the new numbers on both sides, so it passes.Nothing in the pipeline exercised an old writer against the new reader, which is the only combination that fails.
The fix in the test suite is a compatibility fixture: a directory of serialised messages produced by each released schema version, checked into the repository, that the current reader must decode with every field intact. Every release adds a fixture.
That test would have failed on the renumbering immediately, because the fixture from the previous version carried currency under the old number. It is the Protobuf equivalent of the OpenAPI response validator, and it costs an hour to set up.
- "Could reserved have prevented this, and how do you use it?"
Only for one of the causes.
reservedmarks retired field numbers and names so the compiler refuses to let anyone reuse them, which prevents the "reused a number from a deleted field" variant, where an old writer still emits the old field and the new reader interprets it as the new one.It does not prevent renumbering a live field, because nothing was reserved; that needs the linter. My rule for deleting a field: never delete in the same change that adds.
First stop writing it, deploy all writers, then remove it and add both the number and the name to
reservedin the same commit, with a comment naming the date and the reason. That way a reviewer sees an intentional retirement rather than a mysterious gap.
Q84. "How do gRPC deadlines propagate, and what does a server do with a deadline it cannot meet?"
Reveal answer
Strong answer The client sets a deadline — an absolute time, expressed on the wire as the grpc-timeout header holding the remaining duration — and the server receives it as a cancellable context.
Every outgoing call the server makes with that context inherits the remaining time automatically, so a chain of five services shares one budget without any of them doing arithmetic.
When the deadline passes, the client fails the call with DEADLINE_EXCEEDED and the server's context is cancelled, which in Go and Java stops the handler at its next cancellation check and in Python is observable via context.is_active().
A server that can see it cannot finish — because the remaining time is smaller than its minimum work — should fail fast with DEADLINE_EXCEEDED rather than starting, which is the fail-fast behaviour REST chains rarely have.
The design consequences: deadlines should be set by the outermost caller from the user's tolerance, never defaulted to infinity; retries must fit inside the remaining deadline; and servers should release resources on cancellation, which means checking the context in loops and passing it to database and HTTP clients.
Going deeper The wire representation is a single header, grpc-timeout, whose value is a number and a unit, for example grpc-timeout: 800m for 800 milliseconds or grpc-timeout: 5S for five seconds.
Each hop rewrites it with the time it has left, so the arithmetic is done by the library, not the handler.
In grpc-java the server reads it into Context.current().getDeadline(), and an outgoing stub created inside the handler inherits that context automatically; the handler can inspect Context.current().isCancelled() in a loop and stop work.
A stub call can shorten but never extend the inherited deadline: stub.withDeadlineAfter(200, MILLISECONDS) takes the earlier of the two.
Retries interact with deadlines through the service config: a retryPolicy with maxAttempts: 3 and exponential backoff still fails with DEADLINE_EXCEEDED the moment the overall deadline passes, whatever attempt it is on, which is the behaviour you want.
Land it A deadline is one budget shared by the whole call tree; the win is that work the user gave up on stops everywhere, not just at the edge.
- "A client sets no deadline. What happens, and how do you defend the server?"
With no deadline the call can wait forever: if a downstream hangs, the handler thread or coroutine is held indefinitely, connections pile up, and eventually the server runs out of whatever resource the handler holds.
The defence is a server interceptor that inspects
Context.current().getDeadline()at the start of every call and either rejects calls without one, returningINVALID_ARGUMENTwith a message that says a deadline is required, or, gentler, wraps the handler in a default deadline of, say, five seconds so the server bounds its own exposure.I prefer the reject mode for internal services where I control every client, because it forces callers to think about their budget, and the default mode at a public boundary where I cannot.
Either way the interceptor also emits a metric of calls arriving with no deadline so the offending clients are found.
- "How do you choose the number for the outermost deadline?"
From the user's tolerance and the slowest legitimate path.
For an interactive request the user gives up after about two seconds, so the outer deadline is slightly less than what the front end will wait for, say 1.5 seconds, so the server stops work before the user has already gone.
Inside that, I check that the p99 of the whole chain under normal load fits with margin; if the chain's p99 is 1.8 seconds the deadline will fire on legitimate traffic and I have a performance problem, not a deadline problem.
I set the number in configuration, not code, and I record the deadline-exceeded rate per method so I can see the trade-off. For batch and background calls the deadline is longer but never infinite.
One mistake to avoid: setting the same deadline at every hop, which means the innermost hop has the full budget after the outer ones have used part of it, so it cannot fail fast.
- "What happens to the work already in progress in the database when the deadline fires?"
The gRPC cancellation stops the handler, but it does not stop the database unless the handler propagates it.
With JDBC the query keeps running on the database server until it finishes or its own statement timeout fires, and the connection is returned to the pool only when the handler unwinds.
So I set a JDBC statement timeout close to the remaining deadline, using
Statement.setQueryTimeoutor the driver's socket timeout, and in reactive stacks I pass the cancellation signal to the client, which sends a cancel request to the database.For writes, cancellation mid-transaction is safe because the transaction rolls back when the connection is closed or the handler throws. The design rule is that cancellation must reach every blocking call the handler makes, or the deadline only saves the caller and not the server.
- "How is this different from HTTP timeouts in a REST chain?"
REST has no standard for carrying a budget.
Each client sets its own connect and read timeouts independently, so a chain of five services with two-second read timeouts each can take up to ten seconds at the edge, and none of the inner services knows the user has already left.
Nothing propagates cancellation: when the edge times out, the inner services keep working and keep consuming resources.
Teams reconstruct the gRPC behaviour by hand with a custom header, such as
X-Deadlinecarrying an absolute time, that a filter reads and turns into a per-request timeout, and by wiring cancellation into the HTTP client. It works but every service has to implement it consistently.gRPC's advantage is that this is in the library, and that is one of the reasons I favour it for deep internal call chains.
Q85 · Scenario. "Your HTTP dashboards show 100% success for the gRPC gateway while the mobile app's crash reports are full of UNAVAILABLE. Why do the dashboards lie, and what do you change?"
Reveal answer
Strong answer Symptom: the transport-level metric disagrees with the application-level outcome. Evidence: a sample of failing calls shows HTTP status 200 with grpc-status: 14 in the trailers; the dashboard is built from the load balancer's HTTP status histogram.
Cause: gRPC carries its result in the grpc-status trailer, and the HTTP status is 200 for every completed call regardless, so any metric keyed on HTTP status counts gRPC failures as success.
The UNAVAILABLE itself points at connection-level failures — servers restarting without graceful shutdown, a proxy dropping HTTP/2 streams, or a keepalive misconfiguration causing connections to be closed under the client.
The change: instrument by gRPC status using the server interceptor metrics that OpenTelemetry and the gRPC libraries provide, and configure the proxy or gateway to log the trailer; alert on the rate of non-OK codes per method, treating UNAVAILABLE and DEADLINE_EXCEEDED as availability errors and INVALID_ARGUMENT and NOT_FOUND as client errors.
Then fix the root cause of UNAVAILABLE with graceful shutdown that sends GOAWAY and drains, and keepalive settings that match the proxy's idle timeout.
Land it In gRPC, HTTP 200 means "the call completed", not "it succeeded" — dashboards must read the trailer or they measure nothing.
- "Which gRPC status codes count as errors for an SLO, and why not all of them?"
An SLO measures what the service owes its callers, so it counts failures the service caused and excludes failures the caller caused. I count
UNAVAILABLE,DEADLINE_EXCEEDED,INTERNAL,UNKNOWN,DATA_LOSS, andRESOURCE_EXHAUSTEDwhen it is the server's capacity rather than the caller's quota.I exclude
INVALID_ARGUMENT,NOT_FOUND,ALREADY_EXISTS,PERMISSION_DENIED,UNAUTHENTICATED, andFAILED_PRECONDITION, because those are correct answers to bad requests.CANCELLEDis excluded because the client gave up.The nuance is that a spike in
NOT_FOUNDcan still mean a bug, so those codes are on a dashboard with their own alert on rate of change, just not in the availability SLO. In Prometheus terms that is a recording rule overgrpc_server_handled_totalfiltered on the failure codes divided by the total.- "How exactly do you get gRPC status into the proxy's access log?"
In Envoy the access log format supports
%GRPC_STATUS%and%GRPC_STATUS_NUMBER%, which read thegrpc-statustrailer, or the header when the server sent a trailers-only response. The HTTP filter chain also has a gRPC stats filter that emits per-method counters by status.In Nginx the trailer is available as
$upstream_trailer_grpc_statusfor the log format. In a service mesh the sidecar's metrics already carry thegrpc_response_statuslabel.On the application side, grpc-java's
ServerInterceptorcan wrapServerCall.closeto observe the status, and the OpenTelemetry gRPC instrumentation recordsrpc.grpc.status_codeon every span and metric point.The change I make to the dashboards is to replace every panel keyed on HTTP status with one keyed on gRPC status, and to keep one HTTP panel for the transport errors that never reach a gRPC status at all.
- "The dashboards are fixed and now you see the UNAVAILABLE rate is 3%. What causes that in a healthy-looking fleet?"
UNAVAILABLEis the transport saying "the connection went away", and there are four usual causes. Deploys without graceful shutdown: the server exits with streams open instead of sending GOAWAY and draining, so every in-flight call fails; the timing correlates with rollouts.Idle timeouts in a proxy shorter than the client's keepalive, so the proxy closes an idle connection and the next call on it fails before the client notices. Keepalive misconfiguration as in Q90. And connection limits or overload on a proxy, which resets streams.
I would correlate the
UNAVAILABLEtimestamps with deploy events first, then check the proxy idle timeout against the client keepalive interval, then look at the proxy's reset counters.The mobile app should also retry
UNAVAILABLEonce with a short backoff, because a single reconnect fixes most of these.- "Is HTTP 200 always the status for a gRPC response?"
For a response that the gRPC server produced, yes: the HTTP status is 200 and the result is in
grpc-status. The exception is when something in front of the server answers instead.A proxy that cannot reach an upstream returns HTTP 503, and a gRPC client maps non-200 HTTP statuses to a gRPC code by a defined table: 400 becomes
INTERNAL, 401 becomesUNAUTHENTICATED, 403PERMISSION_DENIED, 404UNIMPLEMENTED, 429, 502, 503, and 504 becomeUNAVAILABLE.So an HTTP dashboard does see the proxy-generated failures, which is why the gateway looked partly healthy. The complete picture needs both: HTTP status for what the proxy did, gRPC status for what the server decided.
Q86 · Design. "Design the internal API for an inventory service consumed by 15 other services at 20,000 calls per second, including streaming stock updates to a few of them."
Reveal answer
Strong answer Requirements: low latency at high rate, strict contract, streaming for a subset, and operability. Choice: gRPC, because both ends are internal, the rate rewards Protobuf's cost, and streaming is native.
Contract: a inventory.v1 package with GetStock, BatchGetStock taking up to 500 SKUs so callers do not fan out, ReserveStock with an idempotency token in the request message, and WatchStock as a server-streaming call filtered by SKU set that emits changes with a sequence number.
Evolution: numbers append-only, buf breaking in CI, a new package for a breaking change.
Operations: deadlines mandatory, enforced by a server interceptor that rejects calls without one; a mesh or client-side round robin for balancing; MAX_CONNECTION_AGE for rotation; per-caller rate limits by mTLS identity in an interceptor; metrics by method and gRPC status.
Streaming clients receive a resumable stream — reconnect with the last sequence number and get the gap — and the server bounds per-stream buffering, dropping slow consumers with RESOURCE_EXHAUSTED rather than growing memory. A REST transcoding layer at the gateway exposes read calls to internal tools.
Trade-offs: gRPC's tooling burden across 15 teams, mitigated by a shared client library; streaming complicates balancing because a stream pins to a pod, which is acceptable for a few consumers.
I would not use GraphQL here, would not expose this directly to browsers, and would not make WatchStock the source of truth — it is a hint, and GetStock is authoritative.
Land it Internal, high-rate, streaming, contract-checked — that is the gRPC sweet spot, provided balancing and deadlines are designed in from day one.
- "How does ReserveStock stay correct when two callers reserve the last unit at the same time?"
With a conditional write in the database, not with application logic.
The reservation is
UPDATE stock SET available = available - :qty WHERE sku = :sku AND available >= :qty, and the service reads the affected row count: one means the reservation succeeded, zero means insufficient stock and the response isFAILED_PRECONDITIONwith anErrorInforeason ofINSUFFICIENT_STOCK.The database serialises the two updates on the row lock, so exactly one wins.
The idempotency token is stored in a reservations table with a unique constraint, inserted in the same transaction, so a retry of the winning call returns the original reservation rather than reserving twice. Reservations carry an expiry, and a sweeper releases expired ones.
Under heavy contention on a few hot SKUs I would shard the available count into buckets, but I would not move the check into memory, because then two pods disagree.
- "What if the requirement changed to 200,000 calls per second?"
Ten times the rate changes where the bottleneck is. The gRPC layer scales horizontally; the database does not, so reads must leave it.
I would add a read-through cache of stock levels keyed by SKU in Redis with a short TTL, invalidated by the same change stream that feeds
WatchStock, soGetStockandBatchGetStockbecome cache hits, and I would mark the response with afreshnesstimestamp so callers know.Writes, meaning reservations, stay on the database but get partitioned by SKU range across several database nodes. I would push the heaviest consumers towards
WatchStockso they hold a local copy and stop polling, which turns 100,000 reads per second into a few thousand change events.And I would introduce per-caller quotas with a cost weight, because at that rate one careless consumer can be half the load.
- "How does a resumable stream work, and what does the server do if a client asks for a sequence it no longer has?"
Every change is assigned a monotonically increasing sequence number per SKU partition when it is committed. The server keeps a ring buffer of recent changes, say the last five minutes or the last 100,000 entries, in memory or in Redis.
A client's
WatchStockrequest carries the last sequence it processed; the server replays everything after that from the buffer, then switches to live changes.If the requested sequence is older than the buffer holds, the server cannot fill the gap, and it replies with
OUT_OF_RANGEand a detail telling the client to take a fresh snapshot viaBatchGetStockand resume from the snapshot's sequence. The client library does that automatically.This is why I say the stream is a hint and
GetStockis authoritative: the design always has a path back to the source of truth.- "What would you cut under time pressure?"
I would ship
GetStock,BatchGetStock, andReserveStockwith deadlines, the idempotency token, and the breaking-change linter, and I would deferWatchStock, telling the few streaming consumers to pollBatchGetStockevery few seconds until the stream lands.Streaming is where the operational surprises live: stream pinning, resumption, slow consumers, and buffer bounds, and doing it badly is worse than not doing it. I would also cut the REST transcoding layer and give internal tools a small
grpcurlcheat sheet.What I would not cut is the mandatory-deadline interceptor, the conditional write for reservations, and the per-method metrics by gRPC status, because each of those prevents an incident rather than adding a feature.
Q87. "Compare gRPC's error model to REST's. What is lost, what is gained, and how do you carry structured error details?"
Reveal answer
Strong answer gRPC has 16 status codes with defined meanings and retry semantics — UNAVAILABLE is the one clients may retry blindly, DEADLINE_EXCEEDED and RESOURCE_EXHAUSTED with care, the rest not — and a free-text message.
That is fewer codes than HTTP but far more consistent, because every language's generated client maps them the same way and the retry policy can be declared in the service config rather than in each client.
What is lost is the HTTP ecosystem's understanding: caches, proxies, and dashboards do not see gRPC errors unless taught.
Structured details are carried in the grpc-status-details-bin trailer as a serialised google.rpc.Status message containing typed detail messages from the standard set — BadRequest with field violations, RetryInfo with a delay, QuotaFailure, ErrorInfo with a reason and domain — which is gRPC's equivalent of Problem Details and just as important to standardise across services.
In Java, io.grpc.protobuf.StatusProto converts between the exception and that message. The discipline I enforce: map every domain error to one code plus one ErrorInfo reason, never encode meaning in the message text, and never return INTERNAL for a client mistake.
Land it gRPC trades HTTP's rich status vocabulary for a small, consistent one with typed details — use the standard detail messages the way you would use RFC 9457.
- "Show me how you would return a validation failure with field details from a Java service."
I build a
google.rpc.Statuswith codeINVALID_ARGUMENT, a short message, and aBadRequestdetail listing each field violation, then convert it withStatusProto.toStatusRuntimeException, which serialises the details into thegrpc-status-details-bintrailer:BadRequest bad = BadRequest.newBuilder() .addFieldViolations(FieldViolation.newBuilder() .setField("quantity").setDescription("must be greater than 0")) .build(); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT.getNumber()) .setMessage("request validation failed") .addDetails(Any.pack(bad)) .build(); throw StatusProto.toStatusRuntimeException(status);On the client,
StatusProto.fromThrowablerecovers the message and I unpack each detail by type. I do this in one exception-mapping interceptor so every service produces the same shape.- "Which codes are safe to retry, and where do you declare the retry policy?"
UNAVAILABLEis safe to retry for any call, because it means the request probably never reached a handler.DEADLINE_EXCEEDEDandRESOURCE_EXHAUSTEDare retryable only for idempotent calls and with backoff, because the work may have happened.ABORTEDmeans a concurrency conflict and is retryable at a higher level, by re-reading and redoing the operation. Everything else is not retryable:INVALID_ARGUMENT,NOT_FOUND,PERMISSION_DENIED, andINTERNALwill fail the same way again.The policy is declared in the service config JSON that the client receives from the resolver or is set with
defaultServiceConfigon the channel: per method,maxAttempts,initialBackoff,maxBackoff,backoffMultiplier, andretryableStatusCodes.The server-side
RetryInfodetail can also tell a client how long to wait, which the client honours instead of its own backoff.- "How does this map back to HTTP when transcoded to REST?"
By the standard table that Google's API design guide and the transcoders use.
INVALID_ARGUMENTandFAILED_PRECONDITIONbecome 400,UNAUTHENTICATED401,PERMISSION_DENIED403,NOT_FOUND404,ALREADY_EXISTSandABORTED409,RESOURCE_EXHAUSTED429,UNIMPLEMENTED501,UNAVAILABLE503,DEADLINE_EXCEEDED504, andINTERNALandUNKNOWN500.The details travel as the JSON form of
google.rpc.Status, with each detail carrying an@typefield.If the public API standardises on RFC 9457 Problem Details, a small filter at the gateway rewrites that JSON: the
ErrorInfo.reasonbecomes thetypeURI, the message becomesdetail, andBadRequest.fieldViolationsbecome theerrorsarray.That keeps one error model internally and one externally without the services knowing about the translation.
- "What is the risk of putting too much in the error message string?"
Two risks. The first is that clients start parsing it, so a wording change becomes a breaking change nobody can detect with a linter; that is why meaning belongs in the code and the
ErrorInfo.reason, which are stable identifiers.The second is leakage: exception messages from databases and libraries carry table names, SQL fragments, internal hostnames, and occasionally data values, and
INTERNALerrors that pass through an exception'sgetMessage()ship all of that to the caller and into every log along the path.My interceptor replaces the message on
INTERNALwith a generic sentence plus a request id and logs the real exception server-side. I keepErrorInfo.metadatafor small, safe key-value context such as the field name or the limit that was exceeded.
Q88 · Scenario. "A gRPC client-streaming upload of sensor data works in tests but in production the server's memory grows until it is killed. The producers send faster than the server writes to the database. Explain and fix."
Reveal answer
Strong answer Symptom: unbounded memory under sustained streaming, which is missing flow control at the application layer. Evidence: heap dumps showing queued messages per stream; HTTP/2 flow-control windows at maximum because the server keeps reading; database write latency lower than message arrival rate.
Causes ranked: the server handler reads messages into a buffer or hands them to an unbounded executor faster than it persists them, so HTTP/2's flow control never pushes back because the application always consumes; the default per-stream inbound message limit is not the issue, since messages are small but many.
The fix is to make reading conditional on capacity: in Java, use the ServerCallStreamObserver's manual flow control — disableAutoRequest() and request(n) after each batch is durably written — so HTTP/2 windows fill and producers block at the transport; in Go, the blocking Recv loop already does this if the handler writes synchronously.
Add batching so each database write takes hundreds of messages, bound the number of concurrent streams per server, and reject new streams with RESOURCE_EXHAUSTED beyond that. Prevention: a load test with producers faster than the sink, and a memory alert per stream count.
Land it HTTP/2 flow control only helps if the application stops reading — backpressure is a handler design, not a transport feature you get for free.
- "You enabled manual flow control and memory is stable, but producers now report timeouts. Is that acceptable?"
It is the correct behaviour showing up somewhere new: backpressure means the producer waits when the sink is slow, and if it waits longer than its deadline, it times out. The question is whether the sink is really at capacity or merely inefficient.
First I check database write throughput; if one round trip per message is the bottleneck, batching 500 messages per insert usually multiplies throughput by ten and the timeouts disappear.
If the database is genuinely saturated, then the producers must buffer locally, which is where the data belongs when the sink is slow, or the fleet must scale.
What I must not do is remove the flow control to make the timeouts go away, because that just moves the buffer back into the server's heap.
I would also make the producer's deadline per batch rather than per stream so a slow spell fails a batch, not a whole upload.
- "Explain how HTTP/2 flow control actually pushes back on the producer."
Every HTTP/2 stream and the connection as a whole have a receive window, by default 65,535 bytes, which the receiver raises with
WINDOW_UPDATEframes as it consumes data. The sender may only transmit as many bytes as the window allows and then must stop.gRPC's transport sends
WINDOW_UPDATEonly when the application has actually taken messages from the transport's buffer. With automatic inbound flow control the library requests the next message as soon as the previous one is delivered, so the buffer drains constantly and the window never closes.With
disableAutoRequest()and explicitrequest(n), the transport stops delivering after n messages, its buffer fills to the window, no update is sent, and the producer's send call blocks at the socket. So the pushback is real and automatic, but only once the application stops consuming.- "What limits would you put on the server to survive a burst of new streams?"
Three explicit limits. A maximum number of concurrent streams per connection,
maxConcurrentCallsPerConnectionin grpc-java, which maps to HTTP/2'sSETTINGS_MAX_CONCURRENT_STREAMS, so one client cannot open thousands.A global concurrent-stream cap in the handler, implemented with a semaphore in an interceptor that fails new streams with
RESOURCE_EXHAUSTEDwhen full, so total buffered memory is bounded by streams times per-stream window.And a maximum inbound message size,
maxInboundMessageSize, default 4 megabytes, so a single oversized message cannot allocate a large buffer.I would set the semaphore from the memory budget: if each stream may hold one window plus one batch, and the heap can spare 500 megabytes, that gives the number.
Then a load test with twice that many producers verifies the server stays up and rejects cleanly.
- "Would a message broker be a better design than a client-streaming RPC here?"
Often yes, and I would say so.
Sensor data is a stream of facts that must not be lost and that arrive faster than they are processed at times, which is precisely what a log-based broker such as Kafka provides: durable buffering, replay, and consumers that go at their own pace.
The RPC design makes the server the buffer, which is the problem we just fixed.
I would keep the client-streaming RPC as the ingestion edge, because devices speak gRPC well and a broker protocol is heavy for them, but the handler's job becomes appending batches to the topic, which is fast and bounded, and the database writer becomes a separate consumer.
That decouples ingestion rate from write rate. The cost is another system to run and at-least-once delivery, so the database writer must be idempotent on a message id.
Q89 · Design. "You need to expose an existing gRPC service to third-party developers who expect REST and JSON. Design the approach and its limits."
Reveal answer
Strong answer Requirements: one source of truth for the contract, REST conventions third parties expect, and no hand-written duplicate.
Design: annotate the proto with google.api.http options mapping each RPC to a method and path — GetOrder to GET /v1/orders/{id}, CreateOrder to POST /v1/orders with the body field named — and run a transcoding layer: Envoy's gRPC-JSON transcoder filter, or grpc-gateway if the stack is Go, or a Spring gateway calling the gRPC stub.
The transcoder maps gRPC status to HTTP status via the standard table, and the google.rpc.Status details can be rendered as a Problem Details body by a small filter. Generate the OpenAPI document from the annotated proto so SDKs and docs come from the same file.
Limits I state up front: only unary and server-streaming calls transcode cleanly — server streams become newline-delimited JSON or SSE; client and bidirectional streaming have no REST equivalent and get a separate design or are excluded; Protobuf's JSON mapping uses camelCase names and string-encoded 64-bit integers, which is fine, but oneof and well-known types need documenting; ETags, conditional requests, and caching headers are not part of gRPC and must be added at the edge by the gateway based on a version field.
Trade-offs: the REST surface inherits gRPC's shape, so it can feel RPC-flavoured; the alternative of a hand-written REST facade gives a nicer API at the cost of two contracts to keep in sync.
I would not expose raw gRPC-Web to third parties or duplicate the model by hand.
Land it Annotate the proto and transcode at the edge — one contract, two protocols — and be honest that client streaming does not survive the translation.
- "What does the Envoy transcoder need to know, and how does it get it?"
It needs a compiled descriptor set of the proto files including the
google.api.httpannotations, because it maps a path such asGET /v1/orders/123to the RPCGetOrderand converts the JSON body to a Protobuf message at runtime.I produce it with
protoc --include_imports --include_source_info --descriptor_set_out=api.pb, orbuf build -o api.pb, and mount it into the Envoy container or load it from the configuration. The filter isenvoy.filters.http.grpc_json_transcoderwithproto_descriptorpointing at the file andserviceslisting the fully qualified service names.On every contract change the descriptor is rebuilt and the proxy configuration is rolled out, so the descriptor build is part of CI. An out-of-date descriptor is the usual cause of "404 on a route that exists", so the version of the descriptor is exposed on the proxy's admin page and checked in a smoke test.
- "How do you add ETags and conditional requests when gRPC has no such concept?"
I make the version a field in the message, for example
string etag = 10onOrder, which Google's API design guide recommends, and let the gateway translate.On a GET, a small filter after the transcoder copies the
etagfield into theETagresponse header and, if the request carriedIf-None-Matchwith the same value, replaces the body with 304.On a PUT or PATCH, the filter copies
If-Matchinto the request message'setagfield, and the service compares it against the stored version inside the transaction, failing withABORTED, which transcodes to 409, if they differ.So the optimistic-concurrency check lives in the service, where it must, and only the header plumbing lives at the edge. Caching headers such as
Cache-Controlare set per route in the gateway's configuration, because the service does not know how the edge caches.- "The third parties are unhappy that the REST API feels like RPC. What would you do about it?"
First I would find out what specifically feels wrong, because most complaints have one of three causes.
Verb-named methods such as
GetOrderleak through as odd paths if the annotation is lazy, and the fix is to write the annotations resource-first:GET /v1/orders/{order_id},POST /v1/orders,PATCH /v1/orders/{order_id}with a body mapped to the message.Google-style field masks and long-running operations are unfamiliar, and the fix is documentation and SDK helpers. Custom actions map poorly, and for those I use the colon convention,
POST /v1/orders/{order_id}:cancel.If after that the shape is still wrong for the audience, I would build a hand-written REST facade for the two or three resources that matter most and keep transcoding for the long tail, accepting that those few resources now have two contracts.
- "How do you handle a server-streaming RPC for a REST client that expects a normal response?"
The transcoder turns a server stream into a JSON array streamed with chunked encoding, so a client that reads the whole body gets a normal array and a client that parses incrementally gets items as they arrive.
That works for bounded streams such as listing large results.
For unbounded streams such as live updates, I expose them as server-sent events at a separate path, with a small adapter that reads the gRPC stream and writes
data:lines with anid:carrying the sequence, so browsers get automatic reconnection withLast-Event-ID.I document which is which. What I do not do is pretend a long-lived stream is a request that eventually returns, because intermediaries buffer, time out at 60 seconds, or cut it, and the third party sees random failures they cannot explain.
Q90 · Scenario. "After enabling gRPC keepalive pings on clients to detect dead connections faster, the server starts closing connections with 'too many pings' and calls fail with UNAVAILABLE. What is happening?"
Reveal answer
Strong answer Symptom: connections closed by the server after a client-side keepalive change. Evidence: server logs containing ENHANCE_YOUR_CALM with too_many_pings, the GOAWAY reason gRPC uses when a client pings more often than the server allows; client keepalive interval below the server's minimum.
Cause: gRPC servers enforce a minimum ping interval — by default five minutes — and permit pings without active calls only if configured to; a client sending keepalives every 10 seconds is treated as abusive and the server sends GOAWAY, which fails in-flight calls with UNAVAILABLE.
The fix is to agree on the policy on both sides: set the server's permitKeepAliveTime to something at or below the client interval and permitKeepAliveWithoutCalls to true if idle connections should be probed, and set clients to a reasonable interval such as 30 to 60 seconds with a timeout of 10 to 20 seconds.
Also make sure any proxy between them tolerates the ping frequency. Prevention: document keepalive settings as part of the service's client configuration bundle, and test connection lifecycle changes against the real server, not a mock.
Land it Keepalive is a two-party agreement — the server's permitted interval must match the client's, or the server punishes the client for being careful.
- "What are the actual parameter names on each side, and what values would you set?"
On a grpc-java client,
keepAliveTimeis the ping interval,keepAliveTimeoutis how long to wait for the ping acknowledgement before declaring the connection dead, andkeepAliveWithoutCallssays whether to ping when idle.On the server,
permitKeepAliveTimeis the minimum interval it tolerates andpermitKeepAliveWithoutCallswhether idle pings are allowed. In grpc-go the equivalents arekeepalive.ClientParameters{Time, Timeout, PermitWithoutStream}andkeepalive.EnforcementPolicy{MinTime, PermitWithoutStream}.Values I use as of Aug 2026: client time 30 seconds, timeout 10 seconds, server minimum 20 seconds so a slightly early ping is tolerated, and idle pings permitted only for clients that hold long streams.
The defaults are the trap: a server minimum of five minutes against a client pinging every 10 seconds.
- "How does the server decide it is 'too many pings' when the client is only slightly over?"
The server counts strikes. Each ping arriving sooner than the permitted interval while no calls are active, or sooner than the minimum while calls are active, is a bad ping.
After two bad pings, the implementation sends GOAWAY with error code
ENHANCE_YOUR_CALMand the debug texttoo_many_pings, and closes the connection. That is why the failure appears intermittent rather than immediate: the first ping is tolerated, the second is tolerated, the third closes the connection.It also explains why calls fail with
UNAVAILABLErather than a clearer error, because GOAWAY is a transport event and every stream on that connection is reset.The client then reconnects, pings again, and the cycle repeats every few intervals, so the symptom looks like periodic connection resets on a healthy network.
- "There is a load balancer between client and server. What does it change?"
The client's keepalive pings terminate at whatever holds the client's TCP connection. If that is a layer-4 balancer, the pings pass through to the server and the analysis is unchanged.
If it is a layer-7 proxy such as Envoy or an application load balancer, the proxy answers the pings itself, and its own idle timeout and its own keepalive to the upstream are separate settings; the client pinging happily proves nothing about the server connection.
Two consequences: the server's
permitKeepAliveTimeis now negotiating with the proxy, not the client, and the proxy's idle timeout, often 60 seconds or 300 seconds, must be longer than the client's ping interval or the proxy closes idle connections between pings.I would configure all three layers from one document and test by leaving a connection idle for twice the longest timeout and then making a call.
- "Why not just set the client's keepalive very low and the server permissive?"
Because pings have a cost and the permissive server is a denial-of-service surface. Each ping is a frame that wakes the server's event loop; with 10,000 clients pinging every second, the server spends measurable CPU acknowledging pings and nothing else.
A permissive setting, such as
permitKeepAliveTimeof one second with idle pings allowed, means any client, including a buggy one, can hold connections open and generate that load indefinitely. The five-minute default exists to protect the server.The right approach is to choose the smallest interval that detects a dead connection within the tolerance the business needs, which is usually tens of seconds, and to set the server's minimum a little below it.
If a specific client genuinely needs sub-second detection, that client should be on its own server pool with its own policy.
Q91. "When would you NOT use gRPC, even for an internal service?"
Reveal answer
Strong answer When the team cannot sustain the tooling: proto compilation in every build, generated code across languages, and a breaking-change linter; without that discipline the schema advantages turn into silent field-number accidents.
When the payloads are mostly free-form or large text where Protobuf's compactness buys little and JSON's debuggability buys a lot. When the consumers include internal browser tools or scripts that need to curl the service, since gRPC-Web needs a proxy and drops streaming.
When the call rate is low enough — hundreds per second — that JSON parsing is not a measurable cost and REST's operational familiarity wins. When the infrastructure balances at layer 4 with no mesh in sight and nobody will own client-side balancing.
And when the interaction is really asynchronous, in which case an event stream is the right tool and gRPC would add a synchronous coupling that does not need to exist.
The honest heuristic is that gRPC pays off when you have at least one of high rate, streaming, or many languages, and you have the platform team to support it.
Land it gRPC is a platform commitment, not a library choice — without rate, streaming, or polyglot needs and a team to own it, REST is the cheaper correct answer.
- "What does 'the tooling burden' actually consist of, in a Java and Kotlin shop?"
Concretely it is a build plugin for every service, the
protobuf-gradle-pluginor the Maven equivalent, pinned to a protoc version that every team must keep aligned.It is a shared repository for proto files with ownership rules, or Buf's schema registry, so consumers do not copy protos around. It is
buf lintandbuf breakingin every pipeline.It is a published client library per service containing the generated stubs, versioned and released on every proto change. It is an interceptor bundle for deadlines, retries, metrics, and tracing that every team must adopt for consistency.
It is the load-balancing configuration from Q81 in every client. And it is debugging tools:
grpcurl, reflection enabled on servers, and a way to read binary logs.Each is small; together they need one person who owns them, and if nobody does, each team reinvents them differently.
- "A service is at 200 calls per second today but the roadmap says 20,000 next year. Do you start with gRPC?"
I would ask how confident the roadmap is and how many consumers exist now.
If there are two internal consumers, both mine, I would start with gRPC, because the migration cost later is a real cost and the tooling is a one-time investment I would need next year anyway.
If there are ten consumers across teams that have never used gRPC, I would start with REST and a clean OpenAPI document, design the resource model so it maps to protos later, and plan the Q92 migration behind transcoding when the rate arrives.
The thing I would avoid is choosing gRPC for a low-rate service purely as an investment while skipping the platform work, because a half-adopted gRPC is worse than either full option: no linter, no balancing, no shared interceptors, and every incident is a first.
- "You said JSON's debuggability. How do you debug a gRPC call in production?"
With four tools. Server reflection enabled on the service, so
grpcurl -plaintext host:9090 listshows the services andgrpcurl -d '{"sku":"A1"}' host:9090 inventory.v1.Inventory/GetStockmakes a call with JSON that the tool converts using the reflected schema.Binary logging, which grpc-java and grpc-go support, writing request and response messages to a file that can be decoded with the schema. OpenTelemetry tracing with the method name and status on every span, plus the request id in metadata.
And the Protobuf text format or JSON printer in a debug endpoint that renders a stored message.
What is genuinely lost compared with REST is the ability to read a packet capture or a proxy log and see the payload, and the ability to reproduce a call with curl from a bash script without the schema at hand.
- "Is there a middle ground between gRPC and REST for internal services?"
Yes, and as of Aug 2026 the one I see adopted most is Connect from Buf.
It uses the same proto files and generated types, but the protocol is plain HTTP with a JSON or binary body and the status in a normal HTTP response, so it works through any proxy, can be called with curl using JSON, and needs no special load balancing because it works over HTTP/1.1 as well as HTTP/2.
Servers implemented with Connect can also speak native gRPC and gRPC-Web on the same port, so a team can start with the friendly protocol and enable gRPC for the few high-rate consumers.
The trade-off is a smaller ecosystem than grpc-java for interceptors and a younger set of libraries. It removes two of my reasons not to use gRPC: the balancing problem and the curl problem, leaving only the schema discipline, which I want anyway.
Q92 · Design. "Design the migration of a busy internal REST API to gRPC without a flag day, for 8 consuming teams."
Reveal answer
Strong answer Requirements: consumers move independently, both protocols share one implementation, and the REST path can be retired with evidence.
Design: write the proto to mirror the current REST model, adding google.api.http annotations so the existing REST paths are transcoded onto the same gRPC handlers; deploy the gRPC server with an Envoy transcoder in front, and switch the REST traffic to that path — consumers notice nothing but now hit the new implementation.
Publish the generated gRPC clients in each team's language with a shared interceptor bundle for deadlines, retries, and metrics. Consumers migrate one at a time behind a flag in their own service, comparing responses in shadow mode first.
Measure REST versus gRPC traffic per consumer at the gateway; when a consumer's REST traffic reaches zero, remove their route allow-list entry. Retire the REST path with the deprecation policy — headers, sunset, brownouts.
Trade-offs: the transcoded REST is slightly slower than native for a while; the proto inherits some REST shapes that are not ideal in gRPC and get cleaned up in a later package version.
I would not run two implementations in parallel, would not require all eight teams to cut over together, and would not skip the shadow comparison, because the JSON-to-proto mapping of numbers and nulls is where subtle differences hide.
Land it Put gRPC underneath the existing REST first, then let consumers move to the native path at their pace — one implementation, two doors, close one door with metrics.
- "What are the JSON-to-proto mapping differences that the shadow comparison is meant to catch?"
The ones I have been burned by. 64-bit integers become strings in Protobuf's JSON mapping, so a REST client that parsed
"total": 1200now sees"total": "1200". Field names become camelCase from snake_case unless the transcoder is told to preserve proto names.A proto3 field at its default value is omitted from JSON output unless the printer is configured to include defaults, so
"quantity": 0disappears.Null in JSON input is accepted for message fields but rejected for scalars, so a client sending
"note": nullgets a 400 that the old service never returned. Enums are emitted as names rather than the integers some clients used.Timestamps become RFC 3339 strings with a
Z, while the old API may have used a different format. Each of these is a breaking change if not caught, and the shadow diff of old versus new responses shows them on real traffic before any consumer notices.- "How exactly do you run the shadow comparison without doubling load on the database?"
The shadow deployment receives a copy of the request from the gateway's mirroring feature, Envoy's
request_mirror_policies, for a sampled percentage, say 5% of GET requests only. Its responses are not returned to the client.To avoid doubling writes, mirroring applies only to safe methods, and the shadow points at a read replica or at the same database with a read-only role.
A small comparison service receives both responses, keyed by the request id that the gateway attaches to both, normalises them, for example sorting keys and treating
0and"0"as a known difference, and records mismatches with the field path.A dashboard shows mismatch rate by route and by field. I run it for a week, work the list to zero, then flip a consumer. For mutations I use a replay of recorded requests against a staging database instead of live mirroring.
- "Three of the eight teams say they have no capacity to migrate this year. What do you do?"
I let them not migrate, because the design makes that fine. The transcoded REST path serves them from the same implementation, so I carry no second codebase for them.
What I would negotiate is a date for the REST path's retirement, twelve months out, communicated with the deprecation headers, and a commitment that new features arrive only on the gRPC path first, which creates a natural incentive without forcing anyone.
I would also lower their cost: publish the generated client with the interceptor bundle so migration for a Java consumer is a dependency change and a handful of call-site edits, and offer a pairing session per team.
If at the retirement date one team still has not moved and has a business reason, the per-consumer allow-list lets me keep the REST route on for them alone while everyone else's is off.
- "What would you do differently if you were designing this service from scratch?"
I would write the proto first and keep the REST annotations from day one, so the REST path exists as a by-product rather than as a migration artefact, and I would model the resources for gRPC rather than mirroring a REST shape: batch methods where callers fan out, field masks for partial reads, and long-running operation messages for slow calls.
I would ship the client library with the interceptor bundle before the first consumer integrated, not after. I would decide on the balancing approach before the first deploy, headless Service and round robin or the mesh, so there is no Q81 incident.
And I would put the linter in the pipeline in the first week.
The migration described in the answer is largely the cost of not having done those things, and the point of the greenfield version is to pay that cost once, up front, when it is cheap.
This group tests whether you can run GraphQL safely — batching, limits, caching, errors — and whether you know when to say no to it.
Q93 · Scenario. "The GraphQL endpoint was taken down by a nested query — orders → customer → orders → customer, eleven levels deep — from an authenticated partner. Diagnose and harden."
Reveal answer
The real test Whether you name the guards that run before execution, not just "add a timeout".
Strong answer In order:
- Symptom: one query consumes the server, which means execution cost is unbounded by the schema's cycle.
- Evidence: the query text from the request log, the resolver count and database query count for that request, and whether it was a single request or a burst.
- Causes ranked: no depth limit, so the cycle recurses; no cost analysis, so each level's list fans out; no DataLoader on one of the relationships, so the fan-out is N+1 at every level; no per-client query timeout or concurrency cap.
- Fix: a depth limit around 8 using the engine's instrumentation, which rejects during validation before any resolver runs; a cost limit that multiplies list fields by their requested page size with a budget per query and per client per minute; mandatory
firstarguments on list fields with a maximum; DataLoader on every relationship; a query timeout that cancels resolvers; and for partners, persisted queries only, so the server never executes text it has not approved. - Prevention: a test that submits the worst legal query against every schema change and asserts rejection, and a dashboard of cost per query hash.
Land it A GraphQL schema with a cycle and no cost limit is an outage waiting for one curious client — the guards run at validation, not at execution.
- "You added a depth limit of 8 and the partner found a query at depth 6 that still takes the server down. What next?"
Depth was never the real bound; fan-out was. A depth-6 query that selects a list of 100 orders, each with 100 line items, each with a product with 50 reviews, is 500,000 resolver calls at depth 6.
The next guard is a cost limit computed before execution: each field costs 1, each list field multiplies its children by the requested page size or by a declared default, and the total must stay under a budget, say 10,000 per query.
In graphql-java that is
MaxQueryComplexityInstrumentationwith a field-complexity calculator that reads thefirstargument, and in Apollo it is a cost directive per field plus a plugin.I would also cap page sizes server-side regardless of what the client asks, and I would apply a per-client budget per minute, so a partner can run expensive queries occasionally but not continuously.
Then I would ask the partner what they actually need and give them a persisted query for it.
- "How do persisted queries work, and what changes for the partner?"
A persisted query is a query the server already knows, identified by a hash. The client sends the hash and the variables instead of the query text, and the server looks up the text from its store, validates it once at registration time, and executes.
In the allow-list mode I want for partners, the server refuses any hash it does not know, so arbitrary query text is impossible.
For the partner, integration changes slightly: they register their queries through a developer portal or a build step, get the hashes, and send
GET /graphql?extensions={"persistedQuery":{"sha256Hash":"..."}}&variables=....Their queries are now reviewed, cost-analysed, and cacheable at the CDN. The cost is that a new query needs a registration step rather than an edit, and I would make that self-service with automatic cost analysis so it does not become a ticket queue.
- "How do you make sure the guards run before execution rather than during?"
By placing them in the validation phase of the engine's pipeline. A GraphQL request goes through parsing, validation against the schema, and then execution.
Depth and cost analysis walk the parsed document and the schema, which is enough to compute both, so they belong in a validation rule or an instrumentation hook that runs before the first resolver. In graphql-java,
MaxQueryDepthInstrumentationandMaxQueryComplexityInstrumentationabort inbeginValidationor before execution.In Apollo Server, a validation rule from the
graphql-depth-limitpackage or a custom rule for cost. The verification I would do is a test that submits the worst legal query and asserts that no resolver was called, using a counter in a test resolver.A timeout that fires during execution is still useful as a last resort, but by then the database has done the work.
- "Why did the schema have this cycle in the first place, and should you remove it?"
Cycles are natural in a graph: an order has a customer, a customer has orders, and both directions are useful to different screens. Removing the cycle would make the schema less useful without making it safe, because fan-out without cycles can still be enormous.
So I keep the cycle and bound the cost.
What I would review is whether every back-reference needs to be a full list; sometimes
customer.orderscan be a connection with a mandatory page size and a maximum of 50, and sometimes it can be a count plus a link to a separate query.I would also check that the resolver for
customer.ordersis batched, because a cycle plus an unbatched resolver is N+1 at every level. The schema review question is not "is there a cycle" but "is every list field bounded and batched".
Q94. "Explain how a DataLoader knows when to fire the batch, and what goes wrong if you share one across requests."
Reveal answer
Strong answer The loader collects keys during one pass of resolution and fires when the execution engine reaches a point where no more keys can arrive for that level — in the original JavaScript implementation that is the next tick of the event loop; in GraphQL Java the engine dispatches loaders explicitly when it finishes resolving a level of the query, which Spring for GraphQL's @BatchMapping relies on.
The batch function receives the deduplicated key list and must return results in the same order, one per key, with null for misses; the loader then caches each key-result pair so a second request for the same key within the request is served from memory.
Sharing a loader across requests breaks two things: the cache leaks data between users, because user A's customer lookups are served to user B without an authorisation check, and the cache goes stale, because a customer updated after the first request is still returned from the loader.
That is why loaders are created per request in a context object and discarded at the end. If you want cross-request caching, that belongs in a proper cache with authorisation and invalidation, behind the batch function.
Land it A DataLoader is a per-request batch-and-memo — share it and you have built a cross-user cache with no invalidation and no permission check.
- "Show me what the batch function contract looks like and what goes wrong if you get the order wrong."
The batch function receives a list of keys and must return a list of results of the same length, in the same order, with a null or an error at each position where the key had no result.
A typical implementation runs one query,
SELECT * FROM customers WHERE id IN (:ids), which returns rows in whatever order the database chooses, then builds a map from id to row and produces the output by iterating the input keys and looking each one up.If the implementation returns the rows in database order instead, the loader assigns customer 7's data to the field that asked for customer 3, and the bug is silent: every field resolves, nothing throws, and the wrong customer appears on the wrong order.
Spring for GraphQL's
@BatchMappingavoids that by letting the method return aMapfrom parent to result, which the framework aligns. The test is a fixture with three parents and shuffled result order.- "How does the Java engine know a level is complete when resolvers are asynchronous?"
graphql-java's execution strategy resolves all fields at one depth of the query, collecting their
CompletableFutureresults, before it descends to the next depth.The DataLoader dispatch instrumentation tracks how many fields at the current level are outstanding; when every field's resolver has either returned a value or registered a load with a loader, and no more fields can be added at that level, it calls
dispatchAll()on the registry, which fires each loader's batch function with its accumulated keys.As results arrive the futures complete and the next level begins. That is why the loader must be registered with the request's
DataLoaderRegistryrather than called ad hoc; a loader outside the registry is never dispatched and the query hangs.In Spring for GraphQL that plumbing is automatic when you use
BatchLoaderRegistryor@BatchMapping.- "What if the batch function needs the current user for authorisation?"
Then the user must be part of the loader's identity, which is another reason loaders are per request.
The loader is created in the request context with the authenticated principal captured, and the batch function applies the authorisation predicate in its query, for example restricting the customers to the caller's tenant, so a key the caller may not see returns null.
Spring for GraphQL exposes the
GraphQLContextand the security context to batch mapping methods. What I avoid is checking authorisation after loading, in the field resolver, because then a loader shared across two users in the same request, such as an admin impersonation case, would leak.If the same key must be cached with different visibility per user, I include the user id in the cache key or disable the loader's cache for that entity.
- "Does the loader's per-request cache make responses inconsistent within one request?"
The opposite: it makes them consistent. Without the cache, a query that references customer 7 in two places could read it twice, and if an update landed between the reads, the two places would disagree.
With the per-request memo, both places get the same object, so the response is a coherent snapshot of the entities it touched. The staleness within a request is at most the request's duration, which is acceptable.
The scenario where it surprises people is a mutation followed by a query in the same request: the mutation updates a customer and a later field reads the customer through the loader and sees the pre-mutation value.
The fix is to call
loader.clear(key)in the mutation resolver after the write, which the DataLoader API provides for exactly this case.
Q95 · Scenario. "GraphQL response times are fine, but the database team reports the query count per second tripled since the GraphQL rollout. Explain how that can be true when latency is fine, and what you check."
Reveal answer
Strong answer Symptom: database load up without user-visible latency, which means many small parallel queries per request — N+1 running concurrently hides its latency but not its cost.
Evidence: queries per GraphQL request from tracing; the most common statements in the database's statistics view, which I expect to be single-row lookups by id; which resolvers are missing a batch mapping.
Causes ranked: relationships resolved per parent with no DataLoader, executed in parallel so latency looks fine; clients over-fetching relationships they do not display, which GraphQL makes easy; a loader present but bypassed by a resolver that calls the repository directly.
The fix is DataLoader on every relationship, verified by a test asserting the query count for a representative query; field-level cost accounting so over-fetching clients hit a budget; and a per-request query counter emitted as a metric with an alert on the p95.
Prevention: a rule that any @SchemaMapping returning a related entity must be a @BatchMapping, enforced by code review or an architecture test.
Land it Parallelism hides N+1 from the latency graph and shows it on the database bill — count queries per request, not just milliseconds.
- "How would you measure queries per GraphQL request in a Spring application?"
With a counter in the database access layer tied to the request. The simplest way is a Hibernate
StatementInspectoror a datasource proxy such as datasource-proxy or p6spy, which increments a counter stored in a request-scoped object or an OpenTelemetry span attribute on every statement.At the end of the GraphQL request an instrumentation hook reads the count and records it as a histogram metric labelled with the operation name, plus a log line when it exceeds a threshold.
I also add the count to the response's
extensionsin non-production environments so developers see it in their tooling. In tests, the same counter lets me assert that a representative query issues at most, say, 4 statements. Hibernate's own statistics,hibernate.generate_statistics, give a coarser fleet-wide count.- "Every relationship has a DataLoader now but the query count is still high. What else?"
Three things to check. First, the loader's batch size: some implementations cap the batch, DataLoader's
maxBatchSize, so 1,000 keys become 10 queries, which is fine, but a misconfigured cap of 10 makes it 100.Second, loaders that are correctly batched per level but where the query shape has many levels, so a deep query still issues one query per level per entity type; that is the expected cost and the fix is the cost limit, not more batching.
Third, lazy loading inside the entity: a resolver returns a JPA entity, and serialisation or a later field touches a lazy collection, which fires a query per entity outside the loader entirely.
The
StatementInspectorlog shows which statements are firing and from which resolver's stack, and that usually names the culprit in minutes.- "The clients are over-fetching relationships they do not display. How do you find and stop that?"
The router or server logs each operation by name and the fields it selected, and I compare that against what the screen renders, which the front-end team can tell me. Apollo Studio and similar tools show field usage per client and per operation.
The common cause is a shared fragment, such as
OrderFields, that grew to include everything any screen ever needed and is reused by every screen. The fix is per-screen fragments, and a rule in front-end review that a fragment lists only what the component renders.On the server side, a cost limit with a budget per client makes over-fetching expensive to the client rather than to me, and field-level metrics, count of selections per field per client, make the conversation with the front-end team concrete: this field is selected 40,000 times a minute and rendered nowhere.
- "Would caching at the resolver have hidden this problem?"
It would have reduced the database count while leaving the design flaw in place, which is why I do not start with caching.
A cache in front of the batch function turns repeated lookups of the same customer into cache hits, so the database sees fewer queries, but the resolver still makes N calls per parent, the cache now takes the load, and the moment a cold cache or a cache outage happens the database is hit with the full N+1.
Caching is the right second step once batching is correct: the batch function reads the keys from cache, queries the database for the misses in one statement, and back-fills the cache.
Then the query count per request is bounded by batching and the cache reduces it further. Order matters: batch first, cache second, and measure the count either way.
Q96. "How do you cache GraphQL responses, given everything is a POST to one URL that returns 200?"
Reveal answer
Strong answer HTTP caching needs a GET with a stable URL and a real status code, so the standard move is persisted queries: the client registers each query at build time, sends GET /graphql?id=<hash>&variables=…, and the CDN caches by URL with Cache-Control set per query — public for anonymous product data, private or no-store for anything personalised.
Apollo's automatic persisted queries do the registration on first use.
Below HTTP, there is entity-level caching in the resolvers — the batch function reads from a cache keyed by id with proper invalidation — which is where most of the benefit lives because it survives any query shape.
Client-side, normalised caches in Apollo Client or Relay dedupe entities across queries.
What I avoid is caching arbitrary POST bodies at a proxy, which breaks on whitespace differences and cannot express per-field privacy, and caching whole responses server-side keyed by query text, which mixes users' data unless the key includes identity.
Land it Cache at the entity in resolvers and at the CDN via persisted GET queries — the arbitrary POST is the one thing you cannot cache.
- "How does the server set Cache-Control per query when the response depends on which fields were selected?"
By computing the cacheability from the schema.
Each type or field carries a cache hint, in Apollo Server the
@cacheControl(maxAge: 60, scope: PUBLIC)directive, and as the query executes the server takes the most restrictive hint across every field that was resolved: the smallestmaxAgeandPRIVATEif any field is private.The result becomes the
Cache-Controlheader on the response. So a persisted query that selects only product names getspublic, max-age=60, and the same query with the user's price tier added getsprivate, max-age=0.If a field has no hint, the default is uncacheable, which is the safe direction. I verify this with a test per persisted query that asserts the expected header, because one unhinted field silently disables caching for the whole response.
- "How do you invalidate the entity cache when data changes?"
The batch function reads entities from Redis keyed by type and id, and the write path invalidates by the same key.
In a Spring service the mutation that updates a product publishes an invalidation, either by deleting the key directly in the same service or, when other services own the data, by consuming their change events and deleting keys.
I always pair invalidation with a TTL, 60 seconds for product data, because an invalidation message can be lost and a TTL bounds the damage.
For lists, I do not cache the list in the entity cache; I cache the id list under a key that includes the filter, with a short TTL, and hydrate the entities from the entity cache, so a single product update does not require finding every list it appears in.
For the CDN, invalidation is a purge by URL or by surrogate key when the data owner publishes the change.
- "What about mutations and subscriptions, can those be cached?"
Mutations must not be cached and must stay POST, because they change state and a cached response would be a wrong answer; the persisted-query GET path is only for operations of type
query, and the server should reject a mutation sent by GET as a CSRF defence. Subscriptions are long-lived streams over WebSocket or server-sent events, so HTTP caching does not apply, but the same entity cache serves them: the subscription resolver receives an event with ids and hydrates through the loader. What I do cache around mutations is the client side: Apollo Client and Relay update their normalised cache from the mutation's response so the UI reflects the change without a refetch, which is why the mutation's return type should include the changed entity with its id and the fields the screens display.- "Automatic persisted queries versus a registered allow-list, when do you pick which?"
Automatic persisted queries, APQ, let any client send a hash first, and if the server does not know it, the client sends the full text once and the server stores it.
That gives caching and smaller requests with zero registration workflow, and it suits first-party clients we control. It gives no security benefit, because a client can still send arbitrary text.
A registered allow-list means the server only executes queries registered at build time, typically extracted from the client bundle by a build plugin and pushed to the server with a version, and it rejects everything else.
That is what I want for public or partner clients and for any app where the query surface should be reviewable. Many teams run both: APQ for internal tools, allow-list for the shipped mobile apps, with the app version in the request selecting the list.
Q97 · Design. "Design a GraphQL API for a mobile and web storefront over six backend services, including how errors, auth, and schema ownership work."
Reveal answer
Strong answer Requirements: one graph for clients, six teams owning their parts, safe under untrusted queries, and observable.
Design: a federated graph — Apollo Federation or the GraphQL Foundation's composite schema spec — where each service publishes a subgraph for its entities and a router composes them; the router resolves cross-service references via entity keys, and each subgraph uses DataLoader internally.
Auth: the router validates the JWT once and forwards identity claims to subgraphs in a signed header; field-level authorisation lives in subgraph resolvers using the claims; schema directives such as @authenticated and @requiresScopes let the router reject unauthorised fields before fan-out.
Errors: a typed error union in the schema for expected business outcomes — PlaceOrderResult = Order | InsufficientStock | PaymentDeclined — so clients handle them as data, with the errors array reserved for unexpected failures with a request id and no stack traces.
Safety: depth and cost limits at the router, persisted queries mandatory for the public apps, introspection disabled in production, query allow-list per client app version.
Ownership: each team owns its subgraph and its part of the schema; composition checks in CI reject breaking changes, and fields are deprecated with @deprecated(reason) and removed by usage metrics from the router.
Trade-offs: a router is a critical component and a new skill set; federation debugging spans teams. I would not build a monolithic GraphQL server that calls six REST APIs — that recreates the N+1 across the network — and I would not expose subgraphs directly.
Land it One composed graph, owned in pieces, guarded at the router, with expected errors in the schema — that is GraphQL at organisational scale.
- "How does the router resolve a product's inventory when products and inventory are in different subgraphs?"
Through entities. The product subgraph declares
type Product @key(fields: "id"), and the inventory subgraph extends the same type withtype Product @key(fields: "id") { stock: Int }and implements a reference resolver that takes a list of product ids and returns stock for each.When a query asks for products with stock, the router plans it: fetch the products from the product subgraph, collect their ids, then call the inventory subgraph's
_entitiesquery with those ids in one batch, and merge the results.So cross-subgraph joins are batched by the router and cost one call per subgraph per level, not one per product.
The design consequence is that every entity needs a stable key, and the inventory team's reference resolver must be a batch lookup, which is the DataLoader discipline again at the subgraph boundary.
- "What if a second requirement arrived: partners get access to the same graph?"
I would not expose the same graph surface unchanged. The partner path gets its own router configuration or a contract: Apollo's contracts feature, or the composite schema equivalent, publishes a filtered schema that includes only fields tagged for partners, so internal fields never appear.
Partners authenticate with client-credentials tokens whose scopes the router checks against
@requiresScopes. They use persisted queries only, from a registered allow-list per partner, with per-partner cost budgets. Rate limits and audit logging are keyed by partner id.Errors returned to partners are the same typed unions but with less internal detail in
extensions. The subgraphs do not change at all, which is the benefit of doing this at the router.What changes organisationally is that a field tagged for partners now has a deprecation policy, because a partner cannot redeploy when I remove it.
- "What would you cut if you had six weeks?"
I would cut federation and start with a single GraphQL server owned by one team that calls the six services through their existing APIs, with DataLoader over each service's batch endpoints, and I would make the schema modular in the code so the subgraph split later is mechanical.
That contradicts my "would not build a monolithic server over six REST APIs" warning, and the difference is time: the monolith is a stepping stone I would commit to replacing, not a destination.
I would keep, non-negotiably, the depth and cost limits, persisted queries for the apps, introspection off in production, and the typed error unions, because those shape client code and are painful to add later.
I would defer field-level auth directives, using resolver-level checks instead, and the usage-based deprecation tooling. What decides whether this was right is whether the batch endpoints exist on the six services; without them the monolith is N+1 over the network and I would not ship it.
- "How do you keep six teams from breaking each other's schema?"
With composition in CI. Every subgraph change runs a composition check against the currently published versions of the other five, using the router's tooling, and the check fails if the composed schema is invalid or if any operation in the operation registry, the persisted queries clients actually use, would break.
That second check is the powerful one: it knows a field is used because it sees the registered operations, so a removal fails the build with the list of clients affected.
Field ownership is explicit: a type's key fields belong to the subgraph that defines it, and another subgraph may add fields but not change existing ones. Deprecations follow
@deprecated(reason: "use x, removed after 2026-12-01"), and a nightly job reports deprecated fields still receiving traffic by client.The rule I enforce is that no subgraph deploys with a schema that has not passed composition, which the deploy pipeline verifies against the registry.
Q98 · Scenario. "Mobile users report that a mutation 'succeeded' but the UI shows an error — the response had HTTP 200, a data object with the new order, and an errors array. What is going on, and how should the API and the client handle it?"
Reveal answer
Strong answer Symptom: a partial success — GraphQL allows data and errors together, meaning the mutation succeeded but some field in the selection failed to resolve, such as a notification preference field throwing after the order was written.
Evidence: the errors entries have a path pointing at the failed field, and the corresponding value in data is null. Cause: a resolver on a non-critical field failed and the client treats any errors array as total failure.
The API side: make expected business outcomes part of the schema as result types so they never appear in errors; make non-critical fields nullable so their failure nulls the field rather than propagating up to the mutation; put a machine-readable code in each error's extensions.
The client side: inspect path and treat errors on optional fields as warnings, and treat a null mutation root as failure.
This is one of GraphQL's sharpest edges — nullability decides how far a failure bubbles — so the schema's nullability is a reliability decision, not a typing nicety.
Land it In GraphQL a success can carry errors — design nullability so failures stop where they belong, and make clients read the error path.
- "Explain null propagation precisely: what decides how far up the null goes?"
When a resolver for a field throws, the engine sets that field to null and records an error with the field's path. If the field's type is nullable, that is where it stops: the parent object is intact with one null field.
If the field is non-null, marked with an exclamation mark in the schema, null is not a legal value for it, so the engine nulls the parent object instead, and then applies the same rule to the parent: if the parent field is nullable it stops, otherwise it continues upward.
In the worst case it reaches the root and
dataitself becomes null even though the mutation ran. In the scenario, the order was written, the notification-preference field was non-null and threw, and the null climbed to the mutation's payload.So the schema rule is: mark a field non-null only if the parent is meaningless without it, because you are also deciding what a failure destroys.
- "What should the mutation's return type look like so clients handle this well?"
A payload type with the successful result and the expected failures modelled as data, and non-critical parts nullable. For example
type PlaceOrderPayload { order: Order, userErrors: [UserError!]! }in the Shopify style, or a unionPlaceOrderResult = PlaceOrderSuccess | InsufficientStock | PaymentDeclined.Inside
Order, fields resolved from other services, such asnotificationPreferenceorestimatedDelivery, are nullable so their failure produces a null and an error entry but leavesorder.idandorder.statusintact.The client's rule becomes simple: if
data.placeOrder.orderis present, the order exists; inspectuserErrorsor the union type for business outcomes; treat entries in the top-levelerrorsarray as warnings if theirpathpoints inside an optional field and as failures only ifdata.placeOrderis null.- "Is there any case where a mutation should return an HTTP status other than 200?"
Yes, for failures that happen before the GraphQL engine executes anything.
A malformed document or a validation failure, such as an unknown field, should return 400 so intermediaries and dashboards see it, and the GraphQL over HTTP specification, which as of Aug 2026 most servers implement, requires 400 for those when the client accepts the
application/graphql-response+jsonmedia type.An unauthenticated request should return 401 from the gateway before execution. Rate limiting returns 429. Server unavailability returns 503. What must stay 200 is any response where execution ran, even partially, because the outcome is in the body.
The practical consequence for observability is that the error rate must be computed from the body's
errorsarray and thedatanull-ness, not from the HTTP status, similar to the gRPC dashboard problem in Q85.- "How do you make sure the mobile client is told about the code in extensions and handles it?"
By making the error codes part of the schema documentation and the client's generated types.
Each error's
extensions.codecomes from a fixed enum on the server, such asNOT_FOUND,FORBIDDEN,DOWNSTREAM_UNAVAILABLE,INTERNAL, and the list is published alongside the schema with the meaning and the recommended client action.The mobile team's GraphQL client has an error link that maps codes to behaviour:
DOWNSTREAM_UNAVAILABLEon an optional path shows the section as unavailable,FORBIDDENon the root triggers re-authentication, unknown codes fall back to a generic message and are logged with the request id.I add a contract test that fires each error code through a test resolver and asserts the shape, so the code list cannot drift from what the server emits. And I include a request id in every error's extensions so support can find it.
These questions ask you to say no — to GraphQL, to synchronous calls, to a protocol chosen by fashion — and to design the asynchronous alternative honestly.
Q99. "When would you refuse GraphQL for a project, even if the product team asks for it?"
Reveal answer
Strong answer When there is one client and we own it, because a REST endpoint per screen is simpler, cacheable at the CDN, and has no query-cost problem.
When the API is public to arbitrary developers and we cannot mandate persisted queries, because an open query language is an attack surface we would need a team to defend. When the workload is server-to-server, where a typed RPC or an event stream fits better.
When the data model is flat — a handful of independent resources with no graph to traverse — so GraphQL's main benefit does not apply.
When the team has no experience with DataLoader and cost limiting and no time to learn before launch, because a naive GraphQL server is the N+1 and outage story waiting to happen.
And when the main motivation is "the front-end wants fewer round trips", which a Backend-for-Frontend or HTTP/2 multiplexing may solve with far less machinery.
I would say yes when multiple client types iterate on screens over a rich, connected model and the alternative is a growing pile of bespoke endpoints.
Land it GraphQL pays for itself when many clients need flexible slices of a graph — with one client or a flat model, it is cost without the benefit.
- "The product team says the front end needs fewer round trips. Show that a BFF or HTTP/2 solves it without GraphQL."
The complaint has two parts: latency from serial calls and the effort of stitching responses.
HTTP/2 multiplexing lets a browser or app make ten requests over one connection in parallel, so ten small REST calls take about as long as the slowest one, not the sum; that removes the latency argument when the calls are independent.
When they are dependent, one call's output feeds another, a BFF endpoint per screen assembles them server-side with a shared deadline and returns one screen-shaped response, which removes both the latency and the stitching.
That is a small service with one endpoint per screen, owned by the front-end team, with no query language to defend.
GraphQL solves the same problem with one endpoint for all screens, and it is worth its cost only if the number of screens and client types grows faster than a BFF can keep up, which I would check by counting them.
- "You accepted GraphQL for a project. What did you require before launch?"
A short list of non-negotiables, each verified by a test. Every relationship resolver batched, verified by a query-count assertion per representative operation. Depth and cost limits at validation, verified by a worst-case query test.
Persisted queries with an allow-list for the shipped apps and introspection disabled outside development. Nullability reviewed field by field with the error-propagation rule in mind. A typed error convention with codes in
extensions. Field-level usage metrics so deprecation is possible.A per-request query counter and cost metric on the dashboard. A schema linter and a breaking-change check in CI. And an owner for the schema who reviews changes.
None of those is exotic; the point is that they exist before the first client, because retrofitting cost limits or nullability after clients depend on the shape is a version change.
- "What about server-to-server use, is GraphQL ever right there?"
Rarely, and the exception is a specific one: an internal data platform where many teams need ad hoc slices of a large, connected model for tooling and reporting, and where the alternative is dozens of bespoke read endpoints.
Even then it is read-only, behind cost limits, and never on the hot path of a transaction.
For the normal case of one service calling another to do work, GraphQL is the wrong tool: the call shape is fixed, so the query language adds parsing and planning cost with no flexibility benefit; the caching, caller identity, and error models are weaker than gRPC's; and a typed RPC contract with a breaking-change linter is the stronger guarantee.
If someone proposes GraphQL between services, my question is which team will use a query they did not write, and if the answer is none, it is REST or gRPC.
- "What is the concrete cost of the 'attack surface' you mentioned for public GraphQL?"
It is the work of making arbitrary query execution safe, and it is ongoing rather than one-off. Every new list field needs a cost weight and a page cap. Every new relationship needs a batch loader. Every schema change needs a worst-case query re-evaluated.
Introspection must be off, but then developers need a schema download endpoint with authentication. Alias abuse, the same field requested a thousand times under different names, needs a separate limit. Batched operations in one HTTP request need a batch cap.
Timeouts must cancel resolvers, not just the response. And each of those needs monitoring, because the failure mode is a partner taking the service down at 3 a.m. with a legal query. For a public API with thousands of unknown developers, that is a person's job.
With persisted queries mandated for all clients, most of it disappears, which is why that is my condition for public GraphQL.
Q100 · Design. "Design a Backend-for-Frontend layer for a mobile app that today calls 14 REST endpoints to render its home screen, and say why you chose it over GraphQL."
Reveal answer
Strong answer Requirements: one round trip for the home screen, mobile-shaped payloads, owned by the mobile team, and no impact on the domain APIs.
Design: a small service, mobile-bff, exposing GET /home that fans out to the domain services in parallel with a shared deadline, assembles a screen-shaped response with only the fields the screen shows, applies ETags so an unchanged home screen is a 304, and degrades gracefully — if recommendations time out, the section is omitted with a flag rather than failing the screen.
It runs per client type, so the web team can have its own or none. Versioning is by app version in a header, and the BFF absorbs domain API changes so the app store lag does not block backend evolution.
Ownership is the mobile team's, because the BFF's shape is their screen.
I chose it over GraphQL because there is one client, one team, and a fixed set of screens; GraphQL would give flexibility nobody asked for and bring cost limiting, persisted queries, and a new runtime.
Trade-offs: another service to run, and the temptation to put business logic in it, which I prevent with a rule that the BFF only composes and reshapes.
I would not put the aggregation in the API gateway and would not let the BFF talk to databases directly.
Land it One client, fixed screens, one team — that is a BFF; GraphQL is what you reach for when that stops being true.
- "What if the web team later wants the same home screen? Does the BFF become GraphQL?"
Not yet.
Two clients with similar screens is still a BFF problem: either the web team runs its own BFF, which is the pure model, or the two teams share one BFF with per-client response variants selected by a client header, which works when the screens are near-identical.
What would change my answer is a third or fourth client type with genuinely different screens over the same data, or screens that change weekly and outpace the BFF team's ability to add endpoints.
At that point the endpoint-per-screen model produces a sprawl of near-duplicate endpoints, and GraphQL's single flexible endpoint becomes cheaper than the sprawl, provided the team accepts the operational list from Q99.
I would monitor the number of BFF endpoints and the rate of "add a field to the home screen" tickets as the signal, rather than guess.
- "How do you keep business logic out of the BFF in practice?"
With a written rule and a review question.
The rule is that the BFF may call domain APIs, combine their responses, rename and reshape fields, apply display formatting such as currency strings, and decide what to omit under failure; it may not decide anything a domain would need to know about, such as eligibility, pricing, or state transitions.
The review question for every BFF change is "would a second client type need this logic too?" If yes, it belongs in a domain service, because the BFF is per client and the logic would be duplicated.
Structurally I keep the BFF free of a database, of a message consumer, and of any write path that is more than forwarding a request, so there is nowhere for state-based logic to live.
When a domain service lacks a capability the screen needs, the BFF team files a request against the domain rather than computing it locally.
- "How does the BFF handle a domain service that is slow, and what does the client see?"
Each fan-out call runs with its own timeout inside a shared deadline of, say, 800 milliseconds for the screen. Sections are classified as critical or optional in the BFF's configuration: the account summary is critical, recommendations are optional.
When an optional call times out or fails, the BFF returns the response without that section and includes a
degraded: ["recommendations"]array so the app can show a placeholder and retry that section later.When a critical call fails, the whole response is a 503 with a Problem Details body and a
Retry-After.A circuit breaker per downstream stops the BFF from waiting the full timeout on a downstream that is known to be down, which keeps the screen's p99 stable during an incident.
The metric I watch is the degraded rate per section, which tells me which domain service is hurting the home screen.
- "How do you version the BFF against app store lag?"
The app sends its version in a header, and the BFF supports the response shape for every app version still in meaningful use, typically the last six to twelve months.
When a domain API changes, the BFF absorbs it: the new domain field is mapped into the old response shape for old app versions and into the new shape for new ones.
Old shapes are removed when the app version's traffic falls below a threshold, which the BFF's metrics by app version show. The domain teams never need to know which app versions exist, which is the point of the layer.
I keep the version handling in one adapter per screen rather than scattered conditionals, and I test each supported app version against a recorded response fixture so removing a domain field cannot silently break a two-year-old app that a few percent of users still run.
Q101. "Request-response versus event-driven APIs — what changes about the contract, the failure modes, and the consumer's obligations?"
Reveal answer
Strong answer In request-response the contract is a method, a path, a schema, and a status; the failure is visible immediately to the caller, who decides to retry, and both sides must be up at the same time.
In an event-driven API the contract is an event schema and a topic, documented in AsyncAPI or a schema registry; the producer does not know who consumes, so it cannot get a status back, and the failure modes move: events are delivered at least once, so consumers must be idempotent on an event id; ordering holds only within a partition key, so anything needing order must share the key; a consumer that is down simply lags rather than causing errors, which is the point, but lag must be monitored; and a bad event poisons every consumer, so schema compatibility rules — backward and forward in the registry — are stricter than for REST because you cannot version by URL. The consumer's obligations are to deduplicate, to tolerate unknown fields, to handle replays from the beginning, and to move poison messages to a dead-letter topic rather than blocking.
Choosing between them is the availability question: if the caller needs the answer to proceed, request-response; if it needs the fact to eventually reach everyone interested, events. the Distributed Systems primer covers delivery semantics in depth.
Land it An event is a fact with no receipt — the contract moves into the schema registry and the obligations move onto the consumer.
- "How does a consumer deduplicate in practice, and what does the store look like?"
Every event carries a unique id assigned by the producer, and the consumer records processed ids in the same transaction as its side effect.
In a relational consumer that is a
processed_eventstable with the event id as primary key, inserted in the same transaction that updates the business tables; if the insert fails with a duplicate key, the whole transaction rolls back and the event is acknowledged as already done.That makes the side effect and the deduplication atomic, which a separate cache cannot. The table is pruned by age, longer than the topic's retention plus replay window, so a replay from the beginning is still deduplicated.
When the side effect is external, an email or a payment, the pattern is the same but the external call goes through an outbox with its own idempotency key, because the transaction cannot include the external system.
- "What happens when a consumer needs strict ordering across two event types?"
Ordering in a partitioned log holds only within one partition, and a partition is chosen by key, so the two event types must be on the same topic with the same key, or the consumer must not depend on cross-topic order.
If
order.createdandpayment.confirmedare on different topics, no broker guarantees their relative order at the consumer, and the consumer must be written to tolerate either order: onpayment.confirmedarriving first, it stores the fact and acts whenorder.createdarrives.The cleaner design is one topic per aggregate,
orders, keyed by order id, with the event type in the payload, so every fact about one order is in sequence. The cost is that the topic carries all event types and consumers filter, which is cheap.The consumer's obligation, either way, is to be state-driven rather than event-driven: act on what the current state is, not on which message arrived.
- "How do you monitor an event-driven contract when there is no status code?"
With three numbers per consumer group. Lag, the difference between the latest offset and the consumer's committed offset, which replaces latency; an alert on lag growing for longer than the tolerance means the consumer is down or slow.
Dead-letter rate, the count of events the consumer could not process and parked, which replaces the 4xx and 5xx split: a schema failure is the producer's fault, a downstream failure is the consumer's.
And end-to-end age, the time between the event's occurrence timestamp and the completion of its side effect, measured by the consumer and reported as a histogram, which is the SLO the business understands. On the producer side, the schema registry's rejection count and the outbox's backlog.
The dashboard is per topic and consumer group, and the on-call runbook names the owner for each.
- "When the producer needs to know the consumer succeeded, what do you do?"
Then either it is not really an event, or I need a reply event.
If the producer's next step depends on the outcome, the interaction is request-response and I would make it a synchronous call with a deadline, possibly with an event published afterwards for everyone else.
If the producer merely wants to track progress, the consumer publishes a result event,
order.fulfilledororder.fulfilment_failed, keyed by the same id, and the producer consumes it and updates its record; that is the choreography model, and its cost is that the workflow is spread across topics with no single place to see it.For multi-step workflows with compensation, a saga orchestrator holds the state and sends commands, which gives one place to see and time out the workflow. The rule: a fact needs no reply, a request needs an answer, and pretending a request is a fact creates polling.
Q102 · Scenario. "An order-created event's schema gained a required field. Two of nine consumers crashed on startup, three silently began dropping events, and four were fine. Explain each group."
Reveal answer
Strong answer Symptom: one schema change, three behaviours, which maps to three deserialisation strategies. Evidence: the registry shows the new version with a required field and no default; consumer logs per group.
The crashed group uses strict deserialisation against the old generated class with a compatibility check at startup — Avro readers with a fixed reader schema, or a Java consumer that validates schema compatibility on connect — and refused to start because the producer's schema is no longer backward compatible with theirs.
The silently dropping group catches deserialisation exceptions per record and skips, so every new-format event goes to the void; this is the worst outcome because it looks healthy.
The fine group either reads with the writer's schema from the registry, ignores unknown fields, and never needed the new field, or already redeployed.
The root cause is that adding a required field without a default breaks backward compatibility, which the registry should have rejected under a BACKWARD compatibility mode — the producer either bypassed the check or the mode was NONE.
The fix: republish the schema with a default for the field, redeploy the producer, replay the affected offset range for the dropping consumers from their dead-letter topic or from the topic itself.
Prevention: enforce BACKWARD_TRANSITIVE in the registry, and forbid swallow-and-skip in consumers — dead-letter with an alert instead.
Land it Required-without-default is the event world's field rename; the registry's compatibility mode is the linter, and silent skipping is the failure that hides.
- "The producer team says they set the registry to BACKWARD. Why did it still let the change through?"
Two likely reasons. First, the compatibility mode is per subject, and a new subject was created by a naming change, for example a different topic name strategy or a renamed record, so the new schema had no predecessor to be checked against.
Second, the producer registered the schema through a path that bypasses the check: auto-registration from a client with
auto.register.schemas=truestill runs the check, but a CI job that registers with the registry's admin credentials and a mode override, or a manual upload with compatibility temporarily set toNONE, does not.I would look at the registry's audit log for the subject's compatibility level history and the registration timestamp.
The prevention is to disable auto-registration in production clients, register only from CI with the check enforced, and set the global default to
BACKWARD_TRANSITIVEso a new subject inherits it.- "Why is a required field without a default backward-incompatible, and how does a default fix it?"
Backward compatibility means a consumer with the new schema can read data written with the old schema. Old data does not contain the new field.
When the reader's schema says the field is required with no default, the reader has no value to put there and fails.
With a default, the reader fills it in and the read succeeds, so the new schema can read old data, which is what
BACKWARDchecks.The reverse direction, forward compatibility, means old readers can read new data; adding a field is forward-compatible in Avro because old readers ignore unknown fields.
In this incident the consumers on the old generated class were reading new data, which is forward compatibility, and Avro's resolution with the writer's schema handles that fine; the ones that failed had a fixed reader schema without the writer's, or a strict JSON deserialiser with
FAIL_ON_UNKNOWN_PROPERTIES, which is a consumer misconfiguration the registry cannot protect against.- "How do you replay the events that the silently dropping consumers missed?"
If they dead-lettered nothing, the events are still in the source topic within its retention.
I find the offset range per partition from the timestamp when the new schema first appeared, using
kafka-consumer-groups --reset-offsets --to-datetimein a dry run to see where that lands, then I reset the fixed consumer group to that offset and let it reprocess.The consumer must be idempotent for this to be safe, because it will also reprocess the events it did handle correctly; that is the deduplication table from Q101.
If retention has already expired, I need the producer's source of truth: a job that re-emits events for the affected orders from the producer's database, marked with a
replayed: trueattribute so consumers can distinguish them.Before any replay I confirm the fix in staging by replaying one partition and comparing side effects.
- "What consumer-side rule would have turned 'silently dropping' into an alert?"
Never catch a deserialisation exception and continue without recording it. The consumer configuration should route failed records to a dead-letter topic with the original bytes, the exception, and the offset in headers, using the framework's error handler, for example Spring Kafka's
DefaultErrorHandlerwith aDeadLetterPublishingRecoverer.A metric counts dead-lettered records per consumer group, and an alert fires on any non-zero rate, because in a healthy system it is zero. The dead-letter topic's own lag is monitored so parked records are not forgotten.
A code review rule forbids a bare
catcharound the deserialiser.And the schema itself is validated at consumer startup against the registry: the consumer fetches the latest schema for its subjects and checks that it can read it, failing fast and loudly, which is what the crashing group did and which, ironically, was the correct behaviour.
Q103 · Design. "Design the notification API for a platform: clients subscribe to events, receive them over the channel that suits them, and never miss one."
Reveal answer
Strong answer Requirements: multiple delivery channels, no loss, replay, and per-subscriber isolation. Design: an event log as the source of truth — every event appended with a global sequence per tenant, retained for 30 days — fed from an outbox in each producing service.
Subscriptions are resources: POST /subscriptions with event types, a filter, and a channel of webhook, server-sent events, or pull. Webhook delivery follows the signed, retried, breaker-protected design from Q66. SSE gives a browser a stream from GET /events/stream?after=<seq> with automatic reconnection carrying the last sequence.
Pull is GET /events?after=<seq>&limit=…, which is also the replay mechanism for every channel: a subscriber that missed anything asks for the range.
Each event carries its sequence, type, occurred time, and a small payload with ids, not full resources, so a consumer fetches the current state if it needs it. Per-subscriber cursors are stored server-side so the dashboard shows lag.
Isolation: per-subscriber queues so one slow webhook does not delay others. Trade-offs: the global sequence per tenant is a serialisation point, so it is assigned by the log writer, not by producers; 30 days of retention bounds replay.
I would not fan out directly from producers to webhooks, would not make the webhook the only path, and would not include full sensitive payloads in events that traverse third-party endpoints.
Land it One sequenced log, many channels, and pull-by-sequence as the universal catch-up — "never miss one" is a replay guarantee, not a delivery guarantee.
- "How is the global sequence per tenant assigned without becoming a bottleneck?"
The sequence is assigned by a single writer per tenant, which is the log's append path, not by producers.
In a relational implementation that is an
eventstable with a composite key of tenant id and sequence, where the sequence comes from a per-tenant counter row updated in the same transaction as the insert, or from a per-tenant Postgres sequence.One tenant's appends serialise on that row, which is fine because a single tenant rarely produces more than a few thousand events per second, and different tenants do not contend. In a Kafka-based implementation, one partition per tenant gives the same property: offsets are the sequence.
At very high tenant counts I shard tenants across partitions and keep the sequence in the payload, assigned by the writer for that partition. What I do not do is let producers pick sequences, because two producers cannot agree without coordination.
- "A subscriber's webhook endpoint is down for three days. What happens to their events?"
Nothing is lost, because the log retains 30 days and the subscriber's cursor is stored server-side. The delivery worker retries with exponential backoff and a circuit breaker per subscriber, so after a few failures it stops hammering the endpoint and checks every few minutes.
Events for that subscriber accumulate as a growing gap between their cursor and the log head, which the dashboard shows as lag with an alert to them and to us. When the endpoint recovers, the worker resumes from the cursor and delivers in order.
If they prefer, they call
GET /events?after=<cursor>to pull the backlog faster than the webhook drip. After 30 days the oldest events expire and the subscription is marked as having a gap, with a notification that they must reconcile from the resources' current state. Per-subscriber queues mean their outage never delays anyone else.- "What would you cut under time pressure?"
I would ship the log, the pull endpoint, and the subscription resource, and cut webhooks and server-sent events from the first release.
Pull-by-sequence is the universal mechanism: every other channel is an optimisation on top of it, and a consumer that polls
GET /events?after=every 10 seconds gets every event, in order, with replay for free.Webhooks bring the whole delivery, retry, signing, and breaker apparatus and the partner-side verification problems from Q133, which is weeks of work.
What I would not cut is the per-tenant sequence, the 30-day retention, the id-only payloads, and the cursor stored server-side, because each of those is a contract promise that is very hard to add later.
I would tell consumers that webhooks are coming and design the subscription resource so a
channelfield can be added without changing anything else.- "Why ids and not full payloads in the events?"
Three reasons. Security: events travel to third-party endpoints and through their logs, and a payload with a customer's address or card details is a data leak waiting for a misconfigured subscriber; an id forces them to fetch through the authenticated API where authorisation and audit apply.
Consistency: a consumer processing a three-day backlog would act on stale payloads, while fetching by id gets the current state; the event says "something changed", the resource says what it is now.
Schema stability: an id-only event has a tiny schema that never needs to change, while a full payload duplicates the resource schema and every field change becomes an event schema change.
The cost is an extra fetch per event, which I mitigate with a small summary in the event, the type and the new status, and with batch fetch endpoints so a backlog is hydrated in a few calls.
Q104 · Scenario. "A synchronous checkout call chain — API to orders to inventory to pricing to payments — has a p99 of 4 seconds and fails whenever any one service deploys. The team proposes 'make it all async'. What do you actually do?"
Reveal answer
Strong answer Symptom: latency and availability that multiply across a deep synchronous chain. Evidence: a trace showing serial calls and which hop dominates; deployment timing correlated with failures, pointing at no graceful shutdown or no retries on UNAVAILABLE.
Causes ranked: serial fan-out where parallel would do; no deadline budget so slow hops accumulate; instances killed mid-request during rollouts; one hop — payments — being genuinely slow and external.
The design: keep the user-facing part synchronous, because the customer needs a yes or no, but shrink it: call inventory and pricing in parallel with one deadline, reserve inventory with an idempotent call, and accept the order in state PENDING_PAYMENT with a 202-style response, then take payment asynchronously and confirm via the order status and a notification.
Fix the deployment failures with readiness gates, graceful shutdown with connection draining, and client retries on connection errors within the deadline.
What I would not do is make everything async — order validation, pricing, and inventory answers are needed to tell the user anything — nor leave the chain as it is and add caching.
The split is "what must the user know now" versus "what can complete after the receipt".
Land it Make the slow, external, or non-answer parts asynchronous and keep the decision synchronous — "all async" trades a slow answer for no answer.
- "You made payment asynchronous, and now customers see 'pending' for a minute and call support. What next?"
A minute means the asynchronous path is slower than the synchronous one was, and that is a queue problem, not a design problem.
I would look at the payment worker's lag and concurrency: a single-threaded consumer or a batch interval is usually the cause, and the fix is more workers and immediate dispatch. The target is a few seconds, which is what a customer tolerates for a payment confirmation.
On the client side, the order page subscribes to status via server-sent events or polls every two seconds with backoff, and the confirmation arrives without a reload.
If the payment provider is itself slow, I show an honest state, "we are confirming your payment", with an email on completion, which is what most large retailers do.
If the business requires a synchronous decline for fraud reasons, I keep only the authorisation step synchronous with a short deadline and move capture asynchronous, which is the usual split.
- "How do you decide which hops to parallelise and which must stay serial?"
From the data dependencies, which the trace makes visible. Inventory and pricing both need only the cart contents, so they are independent and run in parallel. Payment needs the final price, so it must follow pricing. Order creation needs an inventory reservation, so it follows inventory.
I draw the dependency graph and the critical path is the sum of the longest chain, not the sum of all hops; the goal is to make the chain as short as the dependencies allow.
In Java that is a handful of
CompletableFuturecalls joined with a shared deadline, or structured concurrency on newer JDKs.Two cautions: parallel calls multiply load on downstreams, so the fan-out needs bulkheads; and parallelism with retries can create retry storms, so retries are budgeted at the top, not per hop.
- "Why does the chain fail when any one service deploys, and what is the exact fix per service?"
Because each service's rollout drops in-flight requests and the chain has no tolerance for a single dropped hop.
Per service the fix is the Q138 choreography: graceful shutdown so the process finishes in-flight requests before exiting, a
preStopdelay so the load balancer stops routing before the signal, readiness that fails first on shutdown, and a rollout strategy with zero max-unavailable.On the calling side, retries on connection-level failures, meaning connection reset and
UNAVAILABLE, but never on timeouts for non-idempotent calls, and only within the remaining deadline. With both sides fixed, a deploy produces a few retried calls and no failures.The verification is a staging test that runs load through the whole chain while rolling every service in turn and asserts zero failed checkouts; until that test passes, "make it async" is fixing the wrong thing.
- "What is the p99 target after your changes, and how do you get there from 4 seconds?"
The customer-facing part should be under one second at p99, which is achievable when the synchronous chain is inventory and pricing in parallel plus an order write.
From the trace I expect payments to be most of the 4 seconds, since external providers often have a p99 of 2 seconds or more; moving it asynchronous removes that entirely. Parallelising inventory and pricing removes the smaller of their two latencies.
The order write is local and fast. The remainder is usually connection setup and serialisation, which HTTP/2 connection pooling and keeping the payloads small address.
I would also set the outer deadline at 1.5 seconds so the tail is cut rather than waited for, with a clear error that tells the customer to retry.
Then I measure p99 per hop again, because the new bottleneck is whichever hop is now slowest, and iterate.
Q105. "What is AsyncAPI, and how does it relate to OpenAPI and a schema registry?"
Reveal answer
Strong answer AsyncAPI is the OpenAPI equivalent for event-driven interfaces: a YAML document describing channels — topics or queues — the operations of publishing and subscribing, the message schemas, and the servers and protocols, such as Kafka, AMQP, MQTT, or WebSockets.
Version 3 of the specification, current as of 2026, separates channels from operations so one message definition is reused across producers and consumers.
It relates to OpenAPI as a sibling: same idea of a contract as an artefact, same tooling pattern of generators for code, docs, and mocks, and message schemas written in JSON Schema, Avro, or Protobuf.
It relates to a schema registry as documentation relates to enforcement: the registry — Confluent, Apicurio, or the cloud provider's — stores the schema versions and enforces compatibility on registration at runtime, while AsyncAPI describes which schema flows on which channel for humans and generators.
In a mature setup the AsyncAPI document references the registry's schemas rather than copying them, and CI validates that what producers register matches what the document promises.
Land it AsyncAPI is the contract document; the registry is the runtime gate — you want the first for people and the second for producers.
- "What would an AsyncAPI document for the order-created event actually contain?"
A version 3 document has four main parts.
serversnames the broker, its protocol, and the environment, for example a Kafka cluster with SASL.channelsnames the topic,orders.v1, and lists the messages it carries.operationsdescribes what the application does with a channel, asendoperation for the producer andreceivefor consumers, with bindings such as the Kafka partition key.components.messagesdefines each message with headers, a content type, and a payload schema, which can be inline JSON Schema or a reference to the Avro schema in the registry. A short sketch:channels: orders: address: orders.v1 messages: orderCreated: $ref: '#/components/messages/OrderCreated' operations: publishOrderCreated: action: send channel: $ref: '#/channels/orders'The document is owned by the producing team and lives in their repository next to the schema.
- "What tooling actually consumes the document, and is it worth maintaining?"
The AsyncAPI generator produces documentation as an HTML site and can generate producer and consumer skeletons for several languages, though as of Aug 2026 the code generation is less mature than OpenAPI's.
The more valuable consumers are the catalogue, so a developer can search which topic carries which event and who owns it; the linter, Spectral with the AsyncAPI ruleset, which enforces naming and requires every message to have a schema and a description; and the diff tool, which flags removed messages or changed channels between versions.
It is worth maintaining when there are more than a handful of topics and consumers outside the producing team, because that is when "which events exist and what do they mean" becomes a question people ask in chat every day.
For a single team with three topics, a README and the registry are enough.
- "How do you keep the AsyncAPI document and the registry from disagreeing?"
By making one the source and generating or validating the other.
The pattern I use is that the Avro or Protobuf schema files in the producer's repository are the source of truth; CI registers them with the registry under the compatibility check, and the AsyncAPI document references them by file path with a
$refrather than copying the schema inline.A CI step then validates that every message in the document resolves to a schema that is registered, and that every subject the producer registers appears in the document, so an event nobody documented fails the build.
When the document is generated from code annotations, the same check applies to the generated output. The failure mode without this is the OpenAPI drift problem again: a document that says one thing while the wire carries another, and consumers trusting the wrong one.
Q106 · Design. "Design a real-time collaborative feature — several users editing the same document — and justify the protocol choice."
Reveal answer
Strong answer Requirements: sub-second propagation, bidirectional traffic, presence, and convergence under concurrent edits. Protocol: WebSockets, because clients send as often as they receive and latency matters; SSE would cover the server-to-client half but edits would need separate POSTs per keystroke; polling cannot meet the latency.
The connection is authenticated with a short-lived token at handshake and re-authenticated periodically. Messages are small JSON or Protobuf frames carrying operations, not document snapshots.
Convergence uses a CRDT — a data structure where concurrent edits merge deterministically — such as Yjs or Automerge, so the server is a relay and persister rather than a conflict resolver; the alternative, operational transformation, needs a central sequencer.
Scaling: connections are sticky to a node, so nodes share edits for one document via a pub/sub channel — Redis or a message broker — keyed by document id, and presence is a per-document set with expiry. Persistence is periodic snapshots plus an operation log.
Fallback: a REST endpoint for load and save so the document works without the socket. Trade-offs: WebSocket infrastructure — load balancer support, connection limits, graceful drain on deploy — is real work; CRDTs cost memory per document.
I would not use gRPC bidirectional streaming here because browsers cannot speak it natively, and I would not build custom conflict resolution.
Land it Bidirectional and latency-sensitive from a browser is WebSockets; convergence is a CRDT's job, and the server should relay and persist, not referee.
- "Explain in plain terms why a CRDT lets the server avoid resolving conflicts."
A conflict-free replicated data type is a data structure designed so that any two replicas that have seen the same set of operations end up in the same state, no matter in which order they received them.
For text, each character gets a unique identity based on who inserted it and a counter, and its position is defined relative to its neighbours' identities rather than by an index.
So when two users insert at the same place at the same time, both insertions have identities, and every replica orders them by the same deterministic rule, and everyone converges. The server therefore does not decide who wins; it just relays operations and stores them.
The cost is that identities take memory, and deletions are tombstones that must be kept or compacted carefully.
Operational transformation achieves convergence differently, by rewriting operations against each other, which needs a central server to define the order, which is why Google Docs has one and Yjs-based tools do not.
- "What if the requirement changed so that edits must be attributable and reversible for compliance?"
Then the operation log becomes the primary artefact rather than a convenience. Every operation is tagged with the authenticated user id, a server-received timestamp, and a sequence, and the log is append-only and retained for the compliance period. Attribution is then a query over the log.
Reversibility means being able to reconstruct the document at any point in time, which the log plus periodic snapshots supports: load the nearest snapshot and replay operations up to the timestamp.
Undo for a single user's edits is trickier in a CRDT because other users' edits interleave; Yjs provides an undo manager scoped to a user's own operations that handles this.
What changes in the design is that the server must sign or at least authenticate each operation before appending it, so a client cannot forge attribution, and that snapshots must be immutable objects in storage with retention locks.
- "How do you deploy the WebSocket tier without disconnecting everyone at once?"
With a rolling deploy where each node drains gracefully.
When a node receives the termination signal, it stops accepting new connections by failing readiness, then sends each connected client a close frame with a code the client understands as "reconnect now, this is not an error", spread over a drain window of perhaps 30 seconds so 20,000 clients do not all reconnect in the same second.
Clients reconnect with jittered backoff to another node, resume by sending their last known document state vector, and receive any operations they missed from the pub/sub channel or the persisted log.
The Kubernetes settings are the same as Q138:
preStopdelay,terminationGracePeriodSecondslonger than the drain window, and max-unavailable zero.The metric to watch during a deploy is the reconnect rate and the operation-loss count, which should be zero; if it is not, the resume protocol has a gap.
- "What would you cut if you had three weeks?"
I would keep WebSockets, the CRDT library, and the per-document pub/sub relay, because those are the core and the library does the hard part. I would cut presence indicators and cursors, which are nice but separate.
I would cut the operation log and keep only periodic snapshots, accepting that history is not yet available.
I would run a single WebSocket node with sticky sessions rather than a horizontally scaled tier, since a single node handles thousands of documents and horizontal scale can come with the pub/sub layer already designed in.
And I would ship the REST load-and-save fallback first, because it is a day's work and it means the document is usable even if the socket path has a bug.
What I would not cut is authentication at handshake and re-authentication, because a collaborative socket without auth is a data leak on launch day.
Q107 · Scenario. "A team replaced a REST call with a Kafka event to 'decouple' services. Now orders sometimes ship before payment is confirmed. What went wrong in the design?"
Reveal answer
Strong answer Symptom: a business invariant — no shipment without payment — violated after a synchronous check became an asynchronous notification. Evidence: traces showing the shipping service consuming an order-created event and acting immediately; the payment-confirmed event arriving later or on a different partition.
Causes ranked: the decoupling removed a precondition check and replaced it with nothing — shipping now reacts to "order created" rather than "payment confirmed"; events for the same order keyed differently, so ordering across them is not guaranteed; a consumer that does not check current state before acting.
The design fix: shipping consumes the payment-confirmed event, not order-created, or, better, consumes an order-state-changed event with the full state and acts only when state is PAID; all events for an order share the order id as the partition key so they arrive in order; the consumer re-reads the order from the source of truth before an irreversible action, treating events as triggers rather than facts.
Prevention: write down the invariants and, for each, name which event or check enforces it; an async migration review that asks "which precondition did the synchronous call enforce, and where does it live now?"
Land it A synchronous call was also a precondition check — decoupling removes the call, and the check must move somewhere explicit.
- "You changed shipping to consume payment-confirmed, and now some orders never ship. Why?"
Because I replaced one implicit dependency with another.
Orders that were paid before the change have their payment-confirmed event in the past, already consumed or expired, so shipping never sees it for them; and orders where the payment event was published but shipping was not yet subscribed fall in the same gap.
There may also be payment paths, such as invoice or zero-total orders, that never emit payment-confirmed at all.
The fix is to make shipping state-driven: on any order event, and on a periodic sweep, shipping reads the order's current state from the order service and ships if it is
PAIDand not yet shipped.The event becomes a trigger to look, not the fact itself. The sweep also catches missed events. Then I backfill by running the sweep over all orders in
PAIDstate, which ships the stuck ones, with a report so the business knows which ones were delayed.- "What is the review checklist you would apply to any future sync-to-async migration?"
Five questions. Which precondition did the synchronous call enforce, and which check now enforces it? What is the ordering requirement across the events involved, and do they share a partition key?
What does the consumer do if the event arrives twice, late, or never, and is there a state-based sweep to recover? What does the caller do with the result the synchronous call used to return, and if it needed it, why is this being made asynchronous?
And what is the end-to-end latency budget for the fact to be acted on, and is it monitored?
I would also require a written invariant list for the domain, "an order ships only if paid", with the enforcing mechanism named for each, and a test per invariant that publishes events in the wrong order and asserts the invariant holds.
- "Was replacing the REST call with an event even the right decision?"
It could be, for the right reason. The synchronous call coupled shipping's availability to payment's: if payment was down, shipping could not proceed even for orders already paid. An event lets shipping learn about payments without calling payment at the time of shipping.
But the migration kept the trigger wrong and lost the precondition.
A better design keeps both: shipping consumes order-state events to know when to look, and reads the order's state, which the order service owns, before shipping; if the order service is down, shipping waits, which is correct, because shipping an order whose state you cannot read is the bug we started with.
The decoupling gained is that payment can be down without blocking shipments of already-paid orders. What "decouple" should never mean is "act without checking".
- "How would you detect this class of bug before customers did?"
With an invariant monitor: a scheduled query that joins shipments to orders and counts shipments whose order was not in
PAIDstate at shipment time, alerting on any non-zero result. That is cheap, runs every few minutes, and would have fired within minutes of the deploy.For prevention, a contract test in the shipping service that feeds it an
order.createdevent with no payment and asserts that no shipment is created, and a second test with events in reversed order.In staging, an end-to-end scenario that places an order and lets payment fail, asserting no shipment. And the migration review from the checklist above.
Monitoring invariants directly in the data is underused; most teams monitor latency and errors and miss bugs that are fast and successful and wrong.
Q108. "Compare how REST, gRPC, and GraphQL each handle versioning, and which one makes breaking changes hardest to ship by accident."
Reveal answer
Strong answer REST versions by URL, header, or date, with the definition of "breaking" living in policy and enforced, if at all, by an OpenAPI diff; nothing in the protocol stops a rename.
gRPC versions by package name — orders.v1, orders.v2 — and its wire format makes additive change safe by construction, but a renumbering is silent unless buf breaking runs; the compiler catches renames in your own code, not in clients.
GraphQL is designed for version-less evolution: fields are added freely, deprecated with @deprecated, and removed when usage metrics reach zero, and because clients request fields by name the server can see exactly who uses what; the schema's type system makes most breaking changes detectable by tooling, and composition checks in federation reject them in CI. So GraphQL makes accidental breaks hardest, provided usage metrics and schema checks are in place, gRPC is second with a linter, and REST is easiest to break by accident because the contract is a document beside the code rather than the code itself.
In every case the mechanism only works if a check runs in CI and a policy names the dates.
Land it GraphQL sees who uses each field, gRPC's linter sees the numbers, REST's diff sees the document — the safest is whichever one you actually gate in CI.
- "GraphQL is version-less, so how do you ever remove a field?"
Through deprecation with evidence. First mark the field
@deprecated(reason: "Use totalAmount; removed after 2026-12-01"), which generated clients and IDE tooling surface as warnings.Second, watch the field's usage from the server's field-level metrics, broken down by client name and version, which the client sends in headers such as
apollographql-client-name. Third, contact the owners of clients still using it.Fourth, when usage is zero or only from versions below the supported floor, remove the field in a change that the schema check would otherwise flag as breaking, with the usage report attached as justification.
The removal is itself gated: the composition or schema check compares against registered operations, so removing a field still used by a registered persisted query fails until that query is retired.
The whole process is a few months per field, and that is the point: no accidental removals.
- "For REST, what exactly do you diff and what counts as breaking in the tool?"
I diff the OpenAPI document on the pull request against the last released version with
oasdiff breaking, which classifies changes by rules.Breaking: removing a path or operation, removing a response property or making it nullable, changing a property's type or format, adding a required request property, removing an enum value from a response or adding one to a request, tightening a request constraint such as a maximum length, removing a success status, and changing a security requirement.
Non-breaking: adding an optional request property, adding a response property, adding an operation, loosening a request constraint, and adding a response enum value only if consumers have been told to expect unknown values.
The tool's output is attached to the pull request and a breaking result blocks the merge unless the change is under a new major version path. The definition lives in a document that consumers can read, because "breaking" must mean the same thing to both sides.
- "Which of the three would you choose if versioning discipline is the main worry?"
If the consumers are external and the team is small, gRPC with
buf breakinginFILEmode, because the linter is precise, the rule set is small, and the compiler catches most mistakes in generated code; the cost is that external consumers must accept gRPC or a transcoded surface.If the consumers are first-party clients that we can instrument, GraphQL, because knowing exactly who uses each field makes removal safe and additive change trivial.
If the consumers are the general public and the API must be curlable, REST with an OpenAPI diff gate and a written breaking-change policy, accepting that the gate is only as good as the document's accuracy, which the response validator must enforce.
In every case the choice is less important than whether the check is a required status on the pull request; a team that skips the check breaks consumers in any protocol.
- "What is the failure mode of each one's mechanism?"
REST's diff only sees the document, so a service that returns something the document does not describe is invisible to it; response validation in tests closes that gap.
gRPC's linter sees the schema, so a semantic change with the same numbers and types, such as a field that used to hold cents and now holds a decimal string, passes; only review and a comment convention catch that.
GraphQL's usage metrics only see clients that identify themselves and only fields that are requested; a client that sends no client name is invisible, and a field's meaning can change without any schema change at all.
And all three share the failure mode of being bypassed: an emergency override, a new subject, a branch that skips CI. The prevention is the same for all: the gate is required, overrides are logged and reviewed, and semantic changes are treated as breaking by policy even when the tool is silent.
Q109 · Design. "Choose the API style for each of these and defend it in one breath each: a public developer platform, a mobile app's screens, inter-service calls in a trading system, and an audit log consumed by compliance tooling."
Reveal answer
Strong answer Public developer platform: REST with OpenAPI 3.1, generated SDKs, idempotency keys, and a URL major version, because third parties expect it, can curl it, and CDNs and gateways understand it.
Mobile app screens: a Backend-for-Frontend over REST if there is one app team and fixed screens, or GraphQL with persisted queries if web, iOS, and Android iterate independently on a rich graph; either way, never the raw domain APIs.
Inter-service calls in a trading system: gRPC with strict deadlines, client-side balancing, and Protobuf contracts linted for compatibility, because latency and typed contracts dominate and both ends are ours; for market data fan-out, server streaming or a broker.
Audit log for compliance: an append-only event stream with a schema registry and a bulk export to files with a manifest, because consumers need everything, in order, replayable, and provable — not a query API. Each choice follows from who calls, how often, whether they need an answer now, and whether they can be down independently.
Land it Four consumers, four relationships, four styles — the skill is matching the mechanism to the relationship, not picking a favourite.
- "For the trading system, why not a message broker for everything, given latency?"
Because the two traffic types need different things.
An order submission needs an answer, accepted or rejected, within milliseconds, and the caller cannot proceed without it, so a synchronous gRPC call with a deadline is the correct shape; a broker in the path adds a hop, a disk write, and a consumer poll, each of which costs latency and makes the answer asynchronous.
Market data is a fact fanned out to many, with no reply, which is exactly what a broker or a server stream is for.
So I use gRPC for orders and risk checks, and a broker or gRPC server streaming for prices, with the choice between them depending on whether consumers need replay: a broker gives replay and durability; a stream gives lower latency and no persistence.
Latency-critical shops go further and use multicast UDP for market data, which is outside the API-style conversation but worth mentioning.
- "For the public developer platform, what would make you pick GraphQL instead?"
Only if the platform's value is a rich, connected data model that developers explore, such as an analytics or content platform, and if I can require persisted queries or at least enforce strict cost limits with a team to maintain them.
GitHub's GraphQL API is the usual example: a connected model and a sophisticated audience. Even then I would keep a REST surface for the operations that need caching, webhooks, uploads, and simple scripting, because a public platform's audience includes people with curl and a cron job.
For a transactional platform with resources such as payments, orders, and customers, REST wins on every axis that matters to third parties: tooling, SDK generation, caching, idempotency conventions, and the fact that every developer already knows it.
The tell is whether developers ask "give me these three fields across these five types" or "create this, then fetch that".
- "The audit log: why files and a stream rather than a query API?"
Because compliance tooling needs completeness, order, and proof, and a query API gives none of those well. Completeness: the tool must be sure it has every record, which a stream with sequence numbers provides and a paginated query only provides if nothing changes during paging.
Order: the stream is in order by construction.
Proof: files in object storage with a manifest listing each file's hash, and a hash chain across records, let an auditor verify nothing was altered; a query API's response is only as trustworthy as the server at the moment of the query.
Volume: audit logs are large, and a bulk file export is far cheaper for both sides than millions of API calls.
I would still provide a small query endpoint for investigators who need one record by id, but the contract for the compliance system is "consume the stream, or download last month's files and verify the manifest".
- "Change one assumption: the mobile app now has web, iOS, Android, and a partner-embedded widget. Does the answer change?"
Yes, that is exactly the condition where a BFF per client stops scaling and GraphQL earns its place.
Four client types with different screens over the same domain means four BFFs or one shared BFF with a growing number of near-duplicate endpoints, and a partner widget that we do not control needs a stable, self-describing contract.
A federated GraphQL layer with persisted queries for our own three apps and a registered allow-list for the partner widget gives each client its own shape from one graph, with field-level usage metrics that make evolution safe.
The conditions from Q99 apply: batch loaders, cost limits, nullability discipline, and a schema owner. If the team could not meet those, I would rather run four BFFs and accept the duplication than run an unguarded GraphQL endpoint for a partner widget.
Q110 · Scenario. "A partner insists on SOAP with WS-Security for a new integration in 2026. How do you handle it technically and organisationally?"
Reveal answer
Strong answer First, understand why: usually a regulated industry with an existing platform, a compliance rule naming WS-Security, or a vendor product they cannot change; the answer differs if it is habit versus requirement. Technically, I would not build SOAP into the core API.
I would put an adapter at the edge — a small service or a gateway plugin that terminates SOAP, validates the WS-Security signature and timestamp, maps the operations onto our REST or gRPC contract, and returns SOAP faults built from our Problem Details — so one partner's protocol costs one component, not a second API.
Spring Web Services or Apache CXF handle the SOAP side in Java; the adapter has its own contract tests from their WSDL.
Organisationally: agree that the adapter is a paid or scoped deliverable, that it supports exactly the operations they need, and that its life ends with the contract; document that new capabilities land in the primary API first and reach the adapter only if funded.
I would not let the SOAP contract shape the primary API, and I would not refuse outright if the revenue justifies the adapter, because a partner integration is a business decision with a technical cost I can bound.
Land it Isolate the legacy protocol in an adapter with a price tag — the core API stays clean and the partner still gets their SOAP.
- "What does WS-Security validation involve, and where are the traps?"
WS-Security puts a security header in the SOAP envelope containing a timestamp, a token such as a username token or an X.509 binary security token, and an XML signature over selected parts of the message, optionally with XML encryption.
Validating it means verifying the signature against the partner's certificate, checking the certificate chain and revocation, checking the timestamp against a freshness window to stop replay, and confirming the signed parts include the body so an attacker cannot swap the payload while keeping a valid header.
The traps are XML-specific: XML canonicalisation differences that make valid signatures fail, signature wrapping attacks where a second body is inserted and the signature still covers the original, and XML external entity expansion in the parser.
In Java, Apache CXF with WSS4J handles the mechanics; I configure it to require the timestamp and the body in the signed parts and disable external entities.
- "How do you translate SOAP faults to and from your Problem Details errors?"
In the adapter, one mapping in each direction.
Outbound, when our API returns a Problem Details body, the adapter builds a SOAP fault: the
faultcodeisClientfor 4xx andServerfor 5xx, thefaultstringis ourtitle, and adetailelement carries a small XML structure with ourtypeURI,status,detail, andinstance, so the partner's support team can quote our request id.Inbound validation failures of the SOAP envelope itself, a bad signature or an expired timestamp, produce faults defined by WS-Security's own fault codes, such as
wsse:FailedAuthentication.I document the mapping in the adapter's contract so the partner knows which faults are retryable, and I log both the fault and the original Problem Details with the same request id so I can trace a partner complaint to our error.
- "The partner wants the adapter extended with each new capability. How do you push back without losing the deal?"
With the pricing model agreed at the start. The adapter is scoped to the operations in the contract, and every additional operation is a change request with a cost, in money or in a documented delay, because the adapter must be built and tested per operation.
I present the alternative openly: the primary REST API gets the capability the day it ships, with an SDK and a sandbox, and if their platform can call REST for new features while keeping SOAP for the existing ones, they get it immediately.
Many partners in this situation accept a hybrid once they see the timeline difference. What I do not do is let the adapter become a second product with its own roadmap, because the day it does, every API change is designed twice.
If the partner's revenue justifies a dedicated engineer for the adapter, that is a business decision I can support, but it must be made explicitly.
- "How do you test the adapter against the partner's expectations before they connect?"
From their WSDL and sample messages. I generate the adapter's SOAP endpoint from the WSDL they provide, using CXF's
wsdl2java, so the contract is literally theirs.I ask for sample signed requests from their system and use them as test fixtures for the signature validation, which finds canonicalisation problems before go-live.
I run a SoapUI or equivalent test suite with the same fixtures in CI. For the outbound direction, I send our generated responses to a validator against their schema.
Then a connectivity test in the sandbox with their real certificate and a replayed request, and a negative test where I tamper with the body and confirm the adapter rejects it.
Finally I agree a shared test plan with named cases that both sides sign off, which is what the compliance-driven partner usually wants anyway.
Q111. "What is gRPC-Web, and what does it cost you compared to native gRPC or plain REST from a browser?"
Reveal answer
Strong answer Browsers cannot speak native gRPC because JavaScript has no access to HTTP/2 framing or trailers.
gRPC-Web is a variant protocol where the browser sends a request the browser can express — trailers folded into the body, base64 or binary framing over HTTP/1.1 or HTTP/2 — and a proxy, usually Envoy, translates to real gRPC for the backend.
It gives the front end generated typed clients from the same proto, which is the benefit.
The costs: a proxy in the path; only unary and server-streaming calls are supported, with no client or bidirectional streaming; no browser caching of responses; debugging in dev tools shows binary bodies unless the text mode is used; and CORS preflights on every call because of custom headers.
Compared to REST from a browser, you gain the typed contract and lose caching, readability, and the streaming that made gRPC attractive.
Connect, from Buf, is a newer alternative that speaks a simpler HTTP-friendly protocol from the same proto and needs no proxy, which is where many teams landed as of 2026.
I would use gRPC-Web or Connect for internal admin front ends that share protos with services, and REST for anything public.
Land it gRPC-Web gives browsers typed clients at the price of a proxy and half the streaming — for public web, REST; for internal tools sharing protos, Connect or gRPC-Web.
- "Why exactly can a browser not speak native gRPC?"
Native gRPC needs two things the browser's fetch API does not expose.
First, HTTP trailers: gRPC sends the status in trailers after the body, and browsers can receive trailers on the wire but give JavaScript no way to read them, so the client could never learn whether a call succeeded.
Second, control over HTTP/2 framing: gRPC wants to stream request bodies incrementally for client streaming, and browsers only support streaming request bodies in limited cases, with restrictions as of Aug 2026.
gRPC-Web works around the first by encoding the trailers as a final length-prefixed frame inside the response body, which JavaScript can read, and around the second by simply not supporting client streaming. Server streaming works because response bodies can be read incrementally.
That is why the proxy exists: it converts the body-encoded trailers back to real trailers for the gRPC server.
- "How does Connect differ, and why does it need no proxy?"
Connect defines its own protocol over plain HTTP: a unary call is a normal POST with the message as JSON or binary Protobuf in the body, the status in the HTTP status code and a JSON error body, and no trailers at all, so it works over HTTP/1.1, through any proxy, and from any HTTP client including curl.
Streaming uses an enveloped body similar to gRPC-Web. Because a Connect server library also understands the gRPC and gRPC-Web protocols on the same port, one server serves native gRPC clients, browsers, and curl, choosing by the request's content type and headers.
So the browser talks Connect directly to the service and the Envoy translation layer disappears.
The trade-off is adopting Connect's libraries, which as of Aug 2026 exist for Go, Node, Kotlin, Swift, and via connect-es for browsers, with grpc-java on the server able to serve them through a Connect-compatible layer or a thin proxy.
- "What does the CORS cost look like and how do you reduce it?"
A gRPC-Web request carries custom headers such as
x-grpc-webandcontent-type: application/grpc-web+proto, which make it a non-simple request, so the browser sends anOPTIONSpreflight before it, doubling the round trips.The server or proxy must answer the preflight with
Access-Control-Allow-Headerslisting those headers and exposegrpc-statusandgrpc-messageviaAccess-Control-Expose-Headers.The reduction is
Access-Control-Max-Age, which lets the browser cache the preflight result for that origin and method for up to a browser-specific cap, two hours in Chromium, so only the first call pays.The bigger reduction is serving the API from the same origin as the page, through a path on the same hostname, which removes CORS entirely. For an internal admin tool I always do the same-origin approach.
- "Would you use gRPC-Web for a customer-facing web app?"
No, for three reasons beyond the technical costs. Customer-facing pages benefit from CDN caching of reads, and gRPC-Web responses are POSTs with binary bodies that no CDN caches.
Public web apps are debugged by people outside the team, support engineers and partners with browser dev tools, and binary payloads make that slower.
And the front-end ecosystem's tooling, mocking, and error handling conventions assume JSON over REST or GraphQL. The one scenario where I would consider it is a real-time internal dashboard that consumes a server stream of typed events, and there Connect gives the same benefit with fewer costs.
For the customer-facing app I would use REST from a BFF, or GraphQL if the Q99 conditions hold, and keep gRPC where it belongs, between services.
Q112 · Design. "Design a streaming API for delivering live prices to 50,000 concurrent web and mobile clients, where clients subscribe to a few symbols each."
Reveal answer
Strong answer Requirements: high fan-out, low latency, cheap per-connection cost, resumability, and protection of the pricing backend.
Design: a dedicated edge tier of stateless streaming servers that hold the client connections — WebSockets where clients need to change subscriptions frequently, otherwise server-sent events, which are simpler and reconnect automatically — and subscribe once per symbol to an internal price feed on a broker or a gRPC server-stream from the pricing service; the edge multiplexes each symbol's updates to every subscribed connection, so the pricing backend sees 2,000 symbols, not 50,000 clients.
Messages are compact deltas with a sequence per symbol; clients reconnect with the last sequence and the edge serves the gap from a short ring buffer, falling back to a snapshot.
Conflation — sending only the latest price per symbol per 100 milliseconds — bounds bandwidth for hot symbols. Authentication is a short-lived token at connect, re-validated periodically.
Scaling: connection count per node around 20,000 with tuned kernel limits, horizontal nodes behind a layer-4 balancer, since the connection is the unit; graceful drain on deploys with clients reconnecting with jitter. Trade-offs: the edge is a new tier to run; conflation trades fidelity for stability.
I would not connect clients directly to the pricing service, would not use polling, and would not use gRPC streaming to browsers.
Land it Fan out at a stateless edge that subscribes per symbol and serves per client — the backend sees symbols, the clients see sequences, and deploys see jittered reconnects.
- "Why 20,000 connections per node, and what kernel settings does that need?"
The number comes from memory and file descriptors rather than CPU. Each connection costs a file descriptor, kernel socket buffers, and the application's per-connection state; with a non-blocking server such as Netty or Go's runtime, 20,000 idle connections use tens of megabytes of heap and a few hundred megabytes of kernel buffers, which is comfortable on a modest node while leaving headroom for bursts.
Going much higher concentrates blast radius: a node failure disconnects everyone on it at once, and 50,000 clients reconnecting within seconds is a thundering herd.
The settings: the process file-descriptor limit,
ulimit -nor the container'snofile, above the target;net.core.somaxconnand the listener backlog raised for accept bursts; the ephemeral port range if the node also opens many outbound connections; and socket buffer sizes tuned down for small messages.I verify with a load test that opens the target connection count and holds it under message load.
- "How does the client resume without receiving duplicate or missing prices?"
Every message on a symbol carries a per-symbol sequence number assigned by the pricing feed, not by the edge node, so all nodes agree on the numbering. The client keeps the last sequence per subscribed symbol. On reconnect it sends its subscriptions with those sequences.
The new node checks its ring buffer per symbol: if the requested sequence is within the buffer, it replays from the next one, so nothing is missed and nothing is repeated; if the buffer has rolled past it, it sends a snapshot with the current sequence and resumes from there, and the client treats the snapshot as authoritative.
Because the edge nodes all consume the same feed, their buffers agree. The client also discards any message with a sequence at or below the last one it applied, which handles the rare double delivery across a reconnect race.
I test this by killing a node under load and checking clients' sequence continuity.
- "What if the requirement changed to include order submission over the same connection?"
Then the connection becomes bidirectional and stateful in a way price delivery is not, and I would separate concerns rather than overload it. Prices stay on the streaming tier, which is optimised for fan-out and can drop a message under conflation without harm.
Orders go over a request-response call, a POST with an idempotency key and a deadline, because an order must never be conflated, dropped, or duplicated, and it needs an explicit acknowledgement with a status.
If latency requires the order to travel over the existing WebSocket, the protocol gets a request frame with a client-generated id and a response frame echoing it, the edge forwards to the order service synchronously, and the edge never buffers or retries orders on its own.
That keeps the streaming tier stateless for prices while adding a thin, explicit request path. The mistake to avoid is treating an order as just another message on the stream.
- "What would you cut under time pressure?"
I would ship server-sent events instead of WebSockets, because SSE gives reconnection and
Last-Event-IDfor free and needs no special load-balancer support; subscription changes would be a reconnect with a new symbol list, which is acceptable for clients that subscribe to a few symbols.I would cut conflation and instead cap update frequency at the feed, which is cruder but a one-line change. I would cut the ring buffer replay and send a snapshot on every reconnect, accepting a small burst on reconnect. And I would run a single-region tier.
What I would keep is the edge tier itself, because connecting clients directly to the pricing service is the one decision that cannot be undone cheaply, the per-symbol sequence numbers, which the resume protocol needs from day one, and jittered reconnect in the client library, because without it the first deploy is an outage.
Q113 · Scenario. "Mobile users on a poor network report that the GraphQL app 'loads forever' while REST screens in the same app load fine. Both hit the same backend. What is different?"
Reveal answer
Strong answer Symptom: one API style suffers on a bad network where another does not, which points at differences in caching, payload, and failure handling rather than backend speed.
Evidence: response sizes and cacheability — the REST screens use GETs with ETags and a CDN, so on a lossy network they often serve from cache, while the GraphQL calls are POSTs that can never be cached and re-fetch everything; the GraphQL query fetching more fields and deeper relationships than the screen needs; and a client that waits for the single big response to complete rather than rendering partial data.
Causes ranked: no persisted queries, so no GET and no CDN; over-fetching by a shared query; a single query for the whole screen, so one slow field delays everything, versus REST screens that render sections as they arrive; and the GraphQL client's retry policy treating a POST as non-retryable.
Fixes: persisted queries over GET with cache headers; split the screen query into a critical query and deferred ones, using @defer where supported, so the app renders the first part; trim the selection to the screen; and mark persisted queries as safe to retry.
Prevention: a mobile network profile in the test lab and a payload-size budget per screen.
Land it GraphQL's flexibility costs you HTTP's caching and partial rendering unless you deliberately add them back with persisted GET queries and deferred fields.
- "You moved to persisted GET queries and added @defer, and the complaints continue. What next?"
Then the network behaviour of the client itself is the next suspect. I would capture a session on a throttled network and look at four things.
Whether the GraphQL client sets a request timeout at all; many default to none, so a stalled connection waits forever while the REST client's 10-second timeout fails fast and retries.
Whether it retries on network errors; a POST body that failed to send is safe to retry, and with persisted GET queries retries are trivially safe.
Whether the persisted query is actually being sent as GET, because APQ falls back to POST with the full text when the hash is unknown, and a cache miss on a new app version means every user sends the full query once per hash.
And the response size after gzip; a 400-kilobyte response on a 3G connection takes seconds no matter how it is fetched. The fix for the last one is a per-screen payload budget enforced in CI.
- "How does @defer work on the wire and what must the client and intermediaries support?"
With
@deferon a fragment, the server sends the initial response as soon as the non-deferred fields resolve, then sends the deferred fragments as later chunks in a multipart HTTP response, each chunk a JSON object with thepathit belongs to and itsdata, and a final chunk marking completion.The client must understand the multipart format and merge chunks into its cache, which Apollo Client and Relay do.
The intermediaries must not buffer the response: a CDN or proxy that waits for the full body before forwarding defeats the purpose, so the route is configured for streaming, and compression must be per-chunk flushing.
As of Aug 2026
@deferand@streamare still being finalised in the GraphQL specification but are widely implemented. The cost is that a deferred response cannot be CDN-cached as a whole, so I use it for personalised screens and persisted GET queries for cacheable ones.- "What makes the REST screens partial-render while the GraphQL screen waits?"
The REST screens make several independent requests, each rendering its section when it arrives, so the user sees the header at 300 milliseconds and the recommendations at two seconds.
The GraphQL screen made one request for everything, and the response is written only when the slowest resolver finishes, so the whole screen appears at two seconds.
On a good network the difference is invisible; on a poor one the REST version feels alive and the GraphQL version feels dead.
The fix is not to abandon the single request but to shape it: critical fields first without
@defer, everything slow or optional deferred, and an explicit loading state per deferred section in the UI. The screen ends up with the same partial rendering as the REST version but with one connection and one cache entry.This is a UI architecture decision as much as an API one, which is why I want the front-end team in the API review.
- "How do you test for this before release?"
With a network profile in the pipeline.
The mobile test lab or the emulator is configured with a throttled profile, 400 kilobits per second with 300 milliseconds of latency and 2% packet loss, which is a realistic poor connection, and the critical screens are driven through their load with time-to-first-content and time-to-interactive measured.
The budget is per screen, say two seconds to first content on that profile, and the test fails when the budget is exceeded. A second test asserts the payload size per persisted query against a byte budget, which catches the shared-fragment growth from Q95.
A third checks that each persisted query is sent as GET with the expected
Cache-Control. I also run a synthetic client from a mobile network in production, because lab profiles miss carrier-specific behaviours such as connection resets on idle.
Q114. "How do you test an API contract across REST, gRPC, and events so that a breaking change fails a build rather than a customer?"
Reveal answer
Strong answer The principle is the same for all three: the contract is an artefact in the repository, and CI compares it against the last released version with a tool that knows that format's compatibility rules.
For REST that is an OpenAPI diff — oasdiff or openapi-diff — failing on removed or renamed properties, type changes, new required inputs, and status changes, plus response validation of the running service against the document.
For gRPC it is buf breaking against the main branch, failing on number changes, type changes, and removed fields without reservation.
For events it is the schema registry's compatibility check run in CI before deployment, in BACKWARD_TRANSITIVE mode, plus a consumer test that reads the new schema with the old generated class.
On top of all three, consumer-driven contract tests via Pact for the consumers that matter most, and a rule that a change flagged as breaking needs a new major, package, or topic version rather than an override.
What I have seen fail is any of these existing as a manual step; the gate must be a required check on the pull request.
Land it Three formats, one pattern: diff the artefact against the last release with a tool that knows the rules, and make it a required check.
- "How does a Pact consumer-driven contract test work, and when is it worth it?"
The consumer writes a test that describes the request it will make and the minimal response it needs, for example "GET /orders/42 returns 200 with an
idand astatusstring".Running that test produces a pact file, a JSON contract, which is published to a Pact Broker. The provider's CI fetches every consumer's pact and replays the requests against the running provider, verifying each expected response shape, and publishes the result.
The broker's
can-i-deploycheck then tells either side whether a version is safe to deploy given the verified pairs.It is worth it for consumers whose breakage matters and whose usage is narrower than the whole contract, because it tests what they actually use rather than what the document describes.
It is not worth it for hundreds of external consumers, where the OpenAPI diff and the response validator are the scalable gate. Internal teams with a few critical consumers is the sweet spot.
- "How do you make a breaking change on purpose when the gate blocks it?"
The gate blocks accidental breaks; an intentional break goes through a different door. For REST, the change lands on a new major version path,
/v2, with its own document, so the diff against/v1shows nothing removed.For gRPC, a new package,
orders.v2, with the old package untouched, which the linter accepts. For events, a new topic or a new subject with a version suffix, and the old one kept while consumers migrate.In all three the old surface goes through the deprecation process with headers, dates, and usage tracking.
If the team wants an override instead, it needs a written justification, approval from the API owner, and a log entry, and the override is limited to the specific rule, for example
oasdiff's per-check exclusion orbuf'sexceptlist.Silent, blanket overrides are the thing I remove first when I join a team.
- "Where does the response validation of the running service fit, and what does it catch that the diff does not?"
The diff compares two documents; it assumes the document is true.
Response validation checks that assumption by running the service in the integration test suite with a filter that compares each real response against the document: status codes not listed, properties present but undocumented, properties documented as required but absent, wrong types, and formats such as a date-time that is not RFC 3339.
It catches the Q74 case, where the document says required and the service returns null, and the Q130 case, where the document has drifted for months.
In a Spring project it is a servlet filter around the test's
MockMvcor a real server, using the OpenAPI validator library, and it fails the test on the first violation.Together the two form the gate: the validator proves the document matches the code, and the diff proves the document did not break.
- "What about the consumers' side of the events contract, the consumer test you mentioned?"
The producer's CI runs a small test per known consumer language: take the new schema, produce a sample record with it, and deserialise it with the previous schema's generated class, and vice versa.
That catches the case where the registry's compatibility rule passes but a consumer's actual code path fails, for example a strict JSON deserialiser that rejects unknown properties, or an Avro consumer with a fixed reader schema.
The consumers themselves add a startup check that fetches the latest registered schema for the subjects they read and verifies it resolves against their reader schema, failing fast.
And a nightly job in the platform replays a sample of yesterday's real events through every consumer's deserialiser in a test harness, which is the closest thing to a production test without production impact.
It is more machinery than the REST equivalent because there is no single request-response pair to assert on.
Q115 · Design. "A company runs REST, gRPC, GraphQL, and Kafka with no shared conventions. Design the 'API platform' function you would create, and what it would own in its first year."
Reveal answer
Strong answer Requirements: consistency without central bottlenecks, self-service for teams, and measurable improvement. The function is a small platform team that owns paved roads, not approvals.
Year one deliverables: a conventions document per style — the ten-rule REST guide from Q38, a proto style and package guide, a GraphQL schema guide, an event schema guide — each enforced by a linter in a shared CI template; a catalogue where every API's contract is registered and searchable, with owners, consumers, and versions, backed by the gateway's traffic data so "who calls this" is a query; the breaking-change gates from Q114 as required checks; a gateway with JWT validation, rate limiting, and request validation as defaults; SDK generation pipelines for REST and gRPC; an office hours and design review offered, not mandated, for new public APIs; and a deprecation process with the headers, dashboards, and brownout tooling built once.
Metrics: percentage of APIs with a registered contract, breaking changes caught in CI versus in production, time to first successful call for a new consumer.
Trade-offs: paved roads mean some teams' preferences lose; enforcement through templates means teams that fork the template escape it, so the catalogue reports compliance publicly.
I would not make the platform team a gate on every API change, would not pick one protocol for everything, and would not start with a 60-page standard nobody reads.
Land it An API platform owns the paved road, the catalogue, and the gates — it makes the right thing the easy thing and stays out of the approval path.
- "How big is the team, and what happens in the first ninety days?"
Three to five engineers, including one with gateway and infrastructure depth and one who writes well, because half the output is documents and templates. The first ninety days are inventory and quick wins.
Inventory: crawl the gateway and mesh for every route and topic, find owners, and publish a first catalogue even if incomplete, because the catalogue creates the pressure to fill gaps.
Quick wins: a shared CI template with the OpenAPI linter and diff, a proto linter, and a schema registry compatibility check, each opt-in but with a public compliance dashboard; a conventions document of one page per style that captures what the best existing APIs already do rather than inventing new rules; and a design review office hour advertised as help, not approval.
By day ninety I want a number on the dashboard that the organisation looks at, such as the percentage of production APIs with a registered contract and a passing gate.
- "Teams fork your CI template and remove the gates. How do you handle that?"
First by making the paved road easier than the fork: the template is a versioned, reusable workflow that teams reference rather than copy, so updates flow and removal is a visible edit.
Second by measuring rather than policing: the catalogue shows, per API, whether its last deployment passed the gates, and that status is public to engineering leadership.
Third by attaching consequences at the boundary that matters: the gateway's route registration requires a contract and a passing gate for any new public route, because the gateway is where the platform team has a real lever, and internal routes get a grace period.
Fourth by asking why: a team that removed a gate usually hit a false positive or a rule that did not fit, and fixing the rule brings them back.
What I avoid is making the platform team the approver of every change, because that is the bottleneck the function exists to prevent.
- "What would you cut from the first year if headcount is halved?"
I would cut SDK generation pipelines, the deprecation tooling, and the design review office hours, and keep the catalogue, the gates, and the gateway defaults. The catalogue is the foundation; without it nobody knows what exists.
The gates are where breaking changes are stopped, which is the highest-value outcome per hour. The gateway defaults, JWT validation and rate limiting, are security improvements that apply to every route with no per-team work.
SDKs can be generated by the teams that need them from the same contracts once the contracts exist, and deprecation can run manually for the first year because there will be few deprecations before contracts are in place.
Design reviews would happen anyway, informally, if the conventions document is good. The metric I keep is the same: breaking changes caught in CI versus in production.
- "How do you decide the conventions when the four styles already have conflicting habits?"
By writing down what the best existing APIs do and choosing among existing habits rather than inventing.
I pick three APIs per style that consumers say are pleasant, extract their conventions, and resolve conflicts with a preference for what the wider ecosystem does: Google's API design guide for gRPC naming, the GraphQL Foundation's schema conventions, Confluent's subject naming for events, and a REST guide aligned with RFC 9457 and cursor pagination.
Where habits genuinely conflict and both are defensible, such as camelCase versus snake_case in JSON, I pick one for new APIs and grandfather existing ones with a note in the catalogue, because renaming fields in production APIs to satisfy a style guide is a breaking change with no consumer benefit.
Every rule in the document has a linter rule id and a one-sentence reason, and rules without a reason do not go in.
10 · DrillSecurity, Performance & Operations — Scenarios & Design — Q116–Q150
The last section is almost entirely incidents and designs, because that is what the senior round is at this point: the interviewer describes something on fire or something to build and listens for the order in which you think. Diagnose in order — symptom, evidence, ranked causes, fix, prevention — and design with requirements, trade-offs, and refusals.
These questions test whether your token handling would survive an audit, and whether you can explain each OAuth2 decision from the threat it addresses.
Q116 · Scenario. "A security review found that tokens minted for your internal admin dashboard are accepted by the public orders API. Both use the same identity provider. Diagnose and fix without breaking legitimate clients."
Reveal answer
The real test Whether you know the audience claim exists for exactly this and can roll the fix out safely.
Strong answer In order:
- Symptom: a token for one resource server works on another, which means the API validates signature and expiry but not audience.
- Evidence: decode a dashboard token and read its
audclaim; inspect the API's decoder configuration for an audience validator; check whether the identity provider even sets a distinct audience per API. - Causes ranked: no audience validation in the resource server; the provider issuing a shared audience to every client; scopes not checked per endpoint, so any valid token passes.
- Fix: register the orders API as its own resource in the provider with audience
orders-api; make legitimate clients request tokens for that audience; then enable the audience validator — in Spring, aJwtClaimValidatoronaudchained with the defaults — first in log-only mode, watch for rejections from real clients, then enforce. Add scope checks per route so a token with the right audience still cannot exceed its permissions. - Prevention: a security test that presents a token with the wrong audience and expects 401, and a rule that every resource server has its own audience in the provider.
Going deeper As of Aug 2026, Spring Boot 3.1 and later can enforce audience without custom code through spring.security.oauth2.resourceserver.jwt.audiences=orders-api, which adds the audience check to the default validators alongside issuer, expiry, and not-before. The log-only rollout needs custom code, because the built-in validator only rejects. The pattern is a decorator around the default validator that records instead of failing:
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
"aud", aud -> aud != null && aud.contains("orders-api"));
OAuth2TokenValidator<Jwt> observing = jwt -> {
var result = audience.validate(jwt);
if (result.hasErrors()) audienceRejections.increment(); // metric only
return enforce ? result : OAuth2TokenValidatorResult.success();
};
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer(issuer), observing));
The enforce flag flips from configuration once the audienceRejections counter, labelled by the token's azp or client_id claim, has been zero for real clients for a full business cycle.
Land it A signature proves who minted the token; the audience proves who it was minted for — checking only the first accepts every token your provider ever issued.
- "The provider only issues one audience for every client and will not change. What then?"
Then I need a second discriminator that the provider does issue.
Most providers put the client id in an
azporclient_idclaim, so the orders API can maintain an allow-list of client ids permitted to call it, checked in the same validator position as audience would be; the admin dashboard's client id is simply not on the list.Scopes are the other lever: if the provider issues scopes per client, the dashboard client is configured without
orders:readandorders:write, and every orders route requires them.The allow-list is weaker than a real audience because it must be maintained in each API and updated when clients are added, so I would push for the provider change in parallel and treat the allow-list as the interim control, with a ticket and a date.
Either way the test remains: a dashboard token against the orders API returns 401.
- "Why 401 and not 403 for a wrong-audience token?"
Because the token is not valid for this resource server at all, and the semantics of 401 are "the credentials presented are not acceptable here", which invites the client to obtain proper credentials, a token for the right audience.
403 means "I know who you are and you may not do this", which applies when the token is valid for this API but lacks a scope or the object is not theirs.
The distinction matters for clients: a well-written client responds to 401 by re-authenticating or requesting a new token for the correct audience, and to 403 by not retrying.
It also matters for dashboards, because a spike in 401s after a change points at token validation while 403s point at authorisation logic. Spring's resource server returns 401 with a
WWW-Authenticate: Bearer error="invalid_token"header for a failed validator, which is the RFC 6750 behaviour.- "How do you make sure the same mistake is not present in your other forty APIs?"
With a fleet-wide test rather than a fleet-wide code review.
A small tool takes the list of resource servers from the catalogue and, for each, mints a token from the provider with a deliberately wrong audience and a valid signature, calls a known read endpoint, and expects 401. Any API returning 200 is listed.
The same tool checks algorithm pinning with an
alg: nonetoken and issuer validation with a token from a test issuer. It runs nightly and on every gateway change.Structurally, the fix is a shared resource-server starter library that sets audience, issuer, and algorithm validation from three configuration properties and refuses to start if the audience property is missing, so a new API cannot be built without it.
The nightly test remains, because the library can be bypassed and the test cannot.
- "What is the risk during the log-only period, and how long should it last?"
The risk is that the vulnerability remains open for the whole period, so it should be as short as the evidence allows.
I would set an upper bound of two weeks, and shorter if the rejection metric shows only the known dashboard client after a few days.
Compensating controls during the window: alert on any wrong-audience token from a client id that is not the dashboard, because that is an attacker rather than a misconfiguration; and, if the provider supports it, immediately stop issuing dashboard tokens with a broad audience so the exposure narrows from the issuing side while the validating side catches up.
The reason not to enforce on day one is that an unknown legitimate client, perhaps a batch job using the dashboard's credentials by copy-paste, would break in production at 2 a.m. The metric labelled by client id answers that question in days.
Q117 · Design. "Design authentication and authorisation for a public API with three client types: a first-party web app, third-party server integrations, and a mobile app."
Reveal answer
Strong answer Requirements: no passwords at the API, per-client identity, least privilege, revocability, and a good developer experience. Design: one OAuth2 and OpenID Connect authorisation server, with the API as a resource server validating JWTs by issuer, audience, algorithm, expiry, and scope.
First-party web app: Authorization Code with PKCE, tokens held by a thin backend session or in memory, never in local storage, with refresh-token rotation and a 10-minute access token.
Mobile app: the same flow with PKCE via the system browser, tokens in the secure keystore, and DPoP to bind tokens to the device key so a leaked token is useless.
Third-party servers: Client Credentials with a private-key JWT or mTLS for client authentication instead of a shared secret, scoped tokens per integration, and optional API keys only for read-only, low-risk access with hashed storage and rotation.
Authorisation: scopes for coarse permissions, and object-level checks in the service — the caller may see this order — because scopes cannot express ownership.
Operations: JWKS rotation with overlapping keys, token introspection available for high-value endpoints, and audit logs keyed by the token's subject and client id. Trade-offs: running an authorisation server is real work, so a managed one is reasonable.
I would not accept username and password at the API, would not use long-lived bearer tokens, and would not put authorisation logic in the gateway beyond scope checks.
Land it One issuer, three flows chosen by where the client can keep a secret, and ownership checks in the service — scopes say what, the service says which.
- "Why PKCE for a first-party web app that could keep a client secret in its backend?"
Because PKCE protects against a different threat than the client secret does. The secret proves the client's identity at the token endpoint.
PKCE, proof key for code exchange, proves that the party exchanging the authorisation code is the same party that started the login: the client generates a random verifier, sends its SHA-256 hash as the
code_challengewhen redirecting to login, and sends the verifier itself when exchanging the code, so a code stolen from the redirect, through browser history, a referrer leak, or a malicious extension, is useless without the verifier.A confidential client benefits from both, and OAuth 2.1, which as of Aug 2026 is the consolidated best-practice draft, requires PKCE for every authorisation-code client. It costs two lines in the client and nothing at runtime, so there is no reason to omit it.
- "What is private-key JWT client authentication, and why prefer it over a shared secret?"
With a shared secret, the integration's server sends the secret to the token endpoint on every request, so the secret sits in their configuration, their logs if they are careless, and on the wire, and we hold a copy too, which we could leak.
With private-key JWT, defined in RFC 7523, the integration registers a public key with us and authenticates by sending a short-lived JWT signed with its private key, containing its client id as issuer and subject, our token endpoint as audience, a unique
jti, and an expiry of a few minutes.We verify the signature with the registered public key. The private key never leaves their side, we store nothing secret, and a captured assertion expires in minutes and cannot be replayed if we track
jti. Rotation is publishing a new public key.mTLS client authentication, RFC 8705, gives the same property using certificates and additionally binds the issued token to the certificate.
- "What if the requirement changed so third parties act on behalf of our users, not just themselves?"
Then client credentials are the wrong flow, because the token must carry the user's identity and consent.
The third party becomes an OAuth2 client using authorisation code with PKCE: our user is redirected to our authorisation server, sees a consent screen listing the scopes the third party requests, and approves; the third party receives a token whose subject is the user and whose client is them, with only the consented scopes.
The API then enforces object-level authorisation with the user's identity and scope checks with the granted scopes.
Additions: a consent management page where users see and revoke third-party access; refresh tokens with rotation so the integration keeps working without the user present; and audit logs showing both the user and the acting client.
The design choice to avoid is letting the third party collect our users' passwords, which is what happens when this flow does not exist.
- "What would you cut if you had to launch in a month?"
I would use a managed authorisation server rather than run one, which removes weeks.
I would launch the web app and third-party server flows and delay the mobile app's DPoP binding, shipping mobile with PKCE and the secure keystore and adding DPoP in a later app version, since it is additive on the token endpoint.
I would ship scopes at the coarse level of read and write per resource family and refine later.
I would not launch without audience and algorithm pinning, object-level authorisation checks, refresh-token rotation, and JWKS handling with rotation support, because each of those is a security incident rather than a missing feature.
And I would not offer API keys at launch at all; they are a convenience that creates a second credential type to manage, and third parties can use client credentials with a secret on day one and move to private-key JWT later.
Q118 · Scenario. "Your identity provider rotated its signing key at 03:00. From 03:00 to 03:20 roughly a third of requests to your API failed with 401, then it recovered on its own. Explain and prevent."
Reveal answer
Strong answer Symptom: partial 401s exactly after a key rotation, self-healing after a cache interval. Evidence: the failed tokens carry the new kid; the API instances' JWKS cache refresh interval is about 20 minutes; a third of instances had a stale cache.
Causes ranked: the provider began signing with the new key before the API had fetched it, and the decoder rejected tokens with an unknown key id until the scheduled refresh; some libraries refresh on unknown kid, others only on a timer — the failing third were on the timer-only path or were rate-limited from refreshing.
The fix: configure the decoder to refresh JWKS on an unknown kid with a small rate limit so an attacker cannot force fetches, which Spring's Nimbus decoder does by default with a cache but a custom JWK source may not; ask the provider to publish the new key in the JWKS before using it — the standard overlap period is at least the maximum access-token lifetime plus the cache interval.
Prevention: a rotation runbook agreed with the identity team, and a synthetic check that mints a token and calls the API every minute so rotation problems page in seconds, not after customers.
Land it Publish the new key before signing with it, and refresh on unknown key id — rotation should be invisible, and a 20-minute outage means one of those two rules was skipped.
- "What exactly does Spring's default decoder do on an unknown kid, and what did the failing third have?"
Spring Security's
NimbusJwtDecoderbuilt from a JWK set URI uses Nimbus's remote JWK source, which caches the key set and, on a token whosekidis not in the cache, fetches the JWK set again before failing, subject to a rate limit that as of Aug 2026 defaults to allowing a refresh no more often than about every 30 seconds.So the default path recovers on the first token with the new key.
The instances that failed for 20 minutes had something different: a custom
JWKSourcewith a fixed cache and no refresh-on-miss, a JWK set loaded once at startup from a file or a property, a gateway in front doing validation with its own timer-based cache, or a proxy caching the JWKS HTTP response with a longCache-Controlmax-age so the refresh returned stale keys.The investigation is to diff the decoder configuration of a failing instance against a healthy one.
- "What should the identity provider's rotation procedure be, with numbers?"
Three phases with waiting periods sized from the consumers' caches.
First, publish the new key in the JWKS alongside the old one and keep signing with the old; wait at least the longest JWKS cache lifetime among all resource servers, which I would standardise at 10 minutes, plus margin, so wait an hour.
Second, switch signing to the new key; tokens signed with the old key remain valid until they expire, so keep the old key published for at least the maximum access-token lifetime, say another hour if tokens live 15 minutes, and longer if any refresh flow relies on it.
Third, remove the old key. The whole procedure is a runbook with the three timestamps recorded, executed during business hours the first time, and automated afterwards. A 03:00 rotation with immediate signing on the new key skipped phase one, which is what the incident shows.
- "How would the synthetic check have caught this in seconds, and what does it look like?"
A small job runs every minute: it requests a token from the identity provider using the client-credentials flow for a dedicated monitoring client, calls a lightweight authenticated endpoint on each API through the public hostname, and reports success, latency, and the
kidof the token it used.At 03:00 the token would have carried the new
kid, a third of the calls would have returned 401, and the check would have paged within two minutes with a message naming the key id, which points straight at rotation.The check also exports the JWKS the API sees, fetched through the same path, so a proxy caching an old key set is visible as a mismatch.
I keep the monitoring client's token lifetime short and its scope minimal, because it is a credential like any other.
- "What about the gateway validating tokens, does that change the design?"
It moves the same problem to one place, which is better and worse.
Better because one JWKS cache with one refresh policy is easier to configure correctly than forty, and the gateway can forward validated claims to services in a signed header so services do not each fetch keys.
Worse because the gateway's cache behaviour is now the single point of failure for the whole platform; if it refreshes only on a timer, every API fails together.
So the gateway's decoder must refresh on unknown key id with a rate limit, keep serving with a stale key set if the provider is unreachable, and expose the loaded key ids as a metric so a rotation can be watched.
Services behind it still validate the signed header from the gateway, with its own key, which rotates by the same three-phase procedure. Two key rotations to run rather than one, each with the same discipline.
Q119 · Scenario. "A penetration tester forged a valid-looking JWT and your API accepted it. The token's header said alg: HS256. Your API uses RS256. What happened?"
Reveal answer
Strong answer Symptom: a token signed with a symmetric algorithm accepted by an API that expects asymmetric signatures, which is the algorithm-confusion attack. Evidence: the library's verify call takes the algorithm from the token header; the public key is passed as the verification key regardless.
Cause: with RS256 the verifier uses the public key to check a signature made with the private key; with HS256 the verifier uses a shared secret.
If the library lets the token choose the algorithm, an attacker sets HS256 and signs with the public key — which is public — as the HMAC secret, and the verifier, handed the same public key bytes, computes the same HMAC and accepts.
The fix: pin the accepted algorithms on the server side — in Spring, NimbusJwtDecoder…jwsAlgorithm(RS256) — and reject anything else including none; upgrade the library, as modern ones separate key types by algorithm.
Prevention: a test suite of malicious tokens — alg: none, algorithm swap, expired, wrong audience, wrong issuer, tampered payload — run in CI against the resource server, and RFC 8725 as the checklist.
Land it The token must never choose how it is verified — pin the algorithm on the server, or your public key becomes the attacker's secret.
- "Walk me through the exact bytes the attacker signs and why the server's check passes."
The attacker takes a real token or writes their own payload with an admin subject, sets the header to
{"alg":"HS256","typ":"JWT"}, base64url-encodes the header and payload, joins them with a dot, and computes HMAC-SHA256 over that string using, as the HMAC key, the exact bytes of the server's RSA public key in whatever encoding the server loads it, typically the PEM text.They append the base64url of that HMAC as the signature.
On the server, a vulnerable verify function reads
algfrom the header, sees HS256, and calls the HMAC verifier with the key object it was given, which is the public key, converting it to bytes the same way.The two HMACs match because both sides used the same bytes as the secret. The server never used RSA at all.
The fix is that the server decides the algorithm and the key type before looking at the header, so an HS256 header against an RSA key is rejected immediately.
- "Which other token tests would you add to the suite, and what does each prove?"
The suite is a set of malformed tokens presented to a protected endpoint, each expecting 401. An unsigned token with
alg: noneproves the algorithm allow-list. An RS256 token signed by a key not in the JWKS proves signature verification is real.A token with a
kidthat points at an attacker-controlled URL, via thejkuorx5uheader, proves those headers are ignored. An expired token and a token withnbfin the future prove time validation, plus a clock-skew boundary case at 60 seconds.A wrong issuer and a wrong audience prove the claim validators. A valid token with its payload modified after signing proves integrity. A token with an embedded
jwkheader key proves the server ignores keys carried in the token.And a token of 100 kilobytes proves size limits. The suite runs against every resource server in CI and nightly in staging.
- "How do you know your library was vulnerable, and how do you check dependencies for this?"
Modern libraries separate the verifier by key type: Nimbus JOSE, which Spring uses, has
RSASSAVerifierandMACVerifieras different classes, so passing an RSA key to a MAC verifier is a compile-time or immediate runtime error, and the decoder is configured with an allowed algorithm set.The vulnerable pattern is a generic
verify(token, key)that dispatches on the header, which older versions of several libraries across languages had; the well-known advisories from 2015 onward cover them.To check, I look at how the decoder is constructed in each service and grep for any place that reads
algfrom a header, and I run dependency scanning with the advisory database, which flags known-vulnerable versions.The test suite is the real proof, because it does not depend on knowing which library is in use.
- "Is there a variant of this attack that pinning RS256 does not stop?"
Yes, key-source confusion. If the server accepts a
jkuorx5uheader and fetches the key from that URL, the attacker points it at their own key and signs with RS256 legitimately. If the server accepts ajwkheader containing the key inline, the same.If the server matches
kidagainst a file path or a database query without validation, path traversal or injection can select a key the attacker controls, for example a known public key elsewhere on disk.Pinning the algorithm does not help because the algorithm is correct; the key is wrong. The defence is that the server obtains keys only from its configured JWKS URI, uses
kidonly as a lookup into that set, and ignores every key-related header in the token.RFC 8725's checklist covers all of these, which is why I name it in the answer.
Q120 · Design. "Design API key management for a developer platform: creation, storage, rotation, scoping, and detection of leaked keys."
Reveal answer
Strong answer Requirements: keys are never recoverable from our database, rotation needs no downtime, blast radius is bounded, and leaks are detected.
Creation: generate 32 random bytes, encode with a recognisable prefix such as sk_live_ plus a short key id, show the full key once, and store only the key id, a SHA-256 hash of the secret, the owner, scopes, environment, creation date, expiry, and last-used time.
Lookup at the gateway is by key id to a cached record, then a constant-time hash compare. Scoping: read or write per resource family, an environment of test or live, optional IP allow-list, and a per-key rate class.
Rotation: allow two active keys per application so the client adds the new one, switches, then revokes the old; enforce an expiry of 12 months with reminders at 30 and 7 days.
Revocation is immediate through the cache with a short TTL. Leak detection: register the prefix with GitHub's secret scanning partner programme so leaked keys are reported and auto-revoked; alert on a key used from a new country or at an unusual rate; show last-used per key in the dashboard so owners can prune.
Audit every use with key id and request id. Trade-offs: keys are bearer credentials, so for high-value operations require OAuth2 with mTLS instead. I would not store keys encrypted rather than hashed, would not accept keys in query strings, and would not issue keys without expiry.
Land it Hash it, prefix it, scope it, expire it, and register the prefix with the scanners — a key you cannot recover is a key you cannot leak from your own database.
- "Why SHA-256 and not bcrypt for the stored key hash?"
Because the threat model is different from passwords. A password is short and human-chosen, so an attacker with the hash can guess it, and a slow hash such as bcrypt or Argon2 makes guessing expensive.
An API key is 32 random bytes, 256 bits of entropy, which cannot be guessed by any brute force, so a fast hash is enough to make the stored value useless to a database thief.
The fast hash also matters operationally: the gateway hashes on every request at thousands of requests per second, and bcrypt at a sensible cost factor would be tens of milliseconds per request, which is unacceptable.
The only requirement is a constant-time comparison so timing does not leak the hash byte by byte. If keys were ever human-chosen or short, the answer would change to a slow hash, which is a reason never to allow custom keys.
- "How does the GitHub secret scanning partnership actually work?"
We register a regular expression for our key format, which is why the prefix is distinctive, something like
sk_live_[A-Za-z0-9]{32}, and an HTTPS endpoint of ours.GitHub scans public commits, and as of Aug 2026 private repositories that opt in, for matches and posts each match to our endpoint with the token string, the URL where it was found, and a signature we verify with GitHub's public key.
Our endpoint hashes the token, looks it up, and if it is a live key, revokes it immediately, emails the owner with the repository URL, and records the event. We reply with whether the token was valid, which GitHub uses to alert the committer.
The whole path must be fast and reliable because a leaked key is being exploited within minutes of a public commit; scanners other than GitHub's exist, and I register the same pattern with the ones that offer partnership.
- "What if the requirement changed to allow keys to act on behalf of end users, not just the developer's application?"
Then I would not extend API keys; I would move that case to OAuth2. An API key identifies an application and carries no user consent, no per-user scope, and no way for a user to revoke one integration without affecting others.
Acting on behalf of users needs the authorisation-code flow with consent, tokens whose subject is the user, and a consent-management page, which is the third-party design from Q117.
The API key stays for the application-level operations, listing its own resources or reading public data, and the OAuth2 token is required for user-scoped operations, enforced by the scope check per route.
If a developer insists on a key-only integration, I offer a restricted-access token, a long-lived, user-approved token scoped to that user and application, which is functionally an OAuth2 token issued through a simplified consent flow, so all the same controls apply.
- "How do you detect a key being abused when the traffic looks normal?"
With baselines per key. Each key has a profile built over its history: request rate by hour, endpoints used, source networks or countries, and typical response sizes.
A key that suddenly calls an endpoint it never used, appears from a new country, or exports data at ten times its usual volume triggers an alert to the owner and, for high-risk patterns such as bulk reads of personal data, an automatic temporary suspension with a one-click restore for the owner.
Two keys with different owners appearing from the same IP is another signal. I keep the rules simple and explainable rather than opaque scoring, because the owner must understand the alert to act on it.
The dashboard shows last-used and the profile per key so owners can spot drift themselves, and a quarterly report lists keys unused for 90 days for revocation.
Q121 · Scenario. "Users of a single-page app get logged out every 15 minutes since you shortened access tokens. Product wants sessions to last a day. How do you reconcile short tokens with long sessions?"
Reveal answer
Strong answer Symptom: session length tied to access-token lifetime, which means there is no refresh mechanism in the client. Evidence: the app stores the access token and has no refresh-token handling; the authorisation server may not be issuing refresh tokens to the browser client.
Cause: short access tokens are correct — they bound the damage of a leak — but they must be paired with a way to get a new one silently.
The reconciliation: issue refresh tokens with rotation and a 24-hour absolute lifetime, and have the app refresh on 401 or shortly before expiry; for a browser, the safer pattern in 2026 is the backend-for-frontend session — the browser holds an HttpOnly, SameSite cookie to a thin backend that keeps the tokens and refreshes them, so no token is ever in JavaScript-reachable storage.
If the app must be purely static, use the authorisation server's session with silent re-authentication via PKCE and refresh-token rotation with reuse detection. The trade-off is that the BFF adds a component, which I accept for the security gain.
I would not lengthen access tokens to a day and would not store refresh tokens in local storage.
Land it Short access tokens plus rotating refresh tokens give a long session with a small blast radius — and a browser should hold neither, only a cookie to a backend that does.
- "What is refresh-token rotation with reuse detection, and what does it protect against?"
Every time the client uses a refresh token, the authorisation server issues a new access token and a new refresh token and invalidates the one just used, so each refresh token works exactly once.
Reuse detection is what happens when an already-used refresh token is presented again: the server treats it as evidence that the token was stolen, because either the legitimate client or the thief used it first and the other is now replaying it, and it revokes the whole token family, forcing a fresh login.
That turns a stolen refresh token from a long-lived credential into one that is either useless, if the legitimate client refreshed first, or detected within one refresh cycle.
The cost is that the client must store the newest refresh token reliably; a client that loses the new one after a refresh, for example a crash between receiving and saving, is logged out.
Both OAuth 2.1 and the browser-app best-practice document require rotation for public clients.
- "What does the BFF session pattern look like concretely for a single-page app?"
The browser never sees a token. It has a session cookie,
HttpOnly,Secure,SameSite=LaxorStrict, pointing at a session in a thin backend, which in Spring is Spring Security's OAuth2 client support with a server-side session store such as Redis.Login is the authorisation-code flow performed by the backend, which stores the access and refresh tokens in the session.
Every API call from the browser goes to the backend at the same origin, the backend attaches the access token, refreshes it when it is within a minute of expiry, and proxies the call to the API. The session's absolute lifetime is a day and its idle timeout a few hours, which is what product asked for.
The browser cannot leak a token through cross-site scripting because there is none in JavaScript's reach, and CSRF is handled by the cookie's
SameSiteattribute plus a token on state-changing requests.- "Product now wants 'remember me' for 30 days. Does that change anything?"
It changes the risk, so the design adds a step rather than lengthening tokens. The BFF session's absolute lifetime becomes 30 days, but the refresh token behind it keeps its rotation and the authorisation server's session has its own policy.
What I add is step-up: sensitive actions, changing email, viewing payment methods, adding an address, require a recent authentication, checked by the
auth_timeclaim in the ID token being within the last 15 minutes, and prompt for the password or a passkey otherwise.That is how banks give a 30-day login and still protect the dangerous operations. I also add device-bound sessions where the user can see and revoke each device, and I keep the idle timeout short enough that an unattended laptop logs out within hours. Access tokens stay at 10 or 15 minutes throughout.
- "Why is local storage worse than a cookie for tokens, given both are in the browser?"
Because of what JavaScript can read.
Anything in
localStorageis readable by any script running on the page, so a single cross-site-scripting bug, or a compromised third-party script such as an analytics tag, exfiltrates the token to the attacker, who then uses it from anywhere until it expires, or forever with a refresh token.An
HttpOnlycookie is not readable by script at all; the same XSS bug can make requests as the user while the page is open, which is bad, but it cannot steal the credential for later use elsewhere.Cookies bring their own risk, cross-site request forgery, which
SameSiteand anti-forgery tokens address. So the comparison is: local storage plus XSS equals credential theft; cookie plus XSS equals session abuse limited to the page's lifetime; and the second is a smaller blast radius.In-memory storage in the SPA is between the two but is lost on reload, which is what caused the 15-minute logouts.
Q122. "Bearer tokens versus sender-constrained tokens — what threat does DPoP address, and what does it cost?"
Reveal answer
Strong answer A bearer token is usable by whoever holds it, so a token stolen from a log, a crash report, a compromised proxy, or a browser extension works from anywhere until expiry. Sender-constrained tokens bind the token to something only the legitimate client has.
With DPoP, RFC 9449, the client generates a key pair, sends a proof — a short JWT signed with its private key, containing the HTTP method, URL, a timestamp, and a hash of the access token — on every request in a DPoP header; the token itself carries the public key's thumbprint in a cnf claim, and the resource server checks that the proof's key matches and that the proof is fresh and for this request.
A stolen token without the private key is useless. With mTLS-bound tokens, RFC 8705, the binding is to the client's TLS certificate, which suits server-to-server.
The costs: clients must manage a key and sign every request; resource servers must validate proofs and track recent proof ids to prevent replay within the freshness window; proxies must pass the header through; and the gateway's cached token validation gets slightly more expensive.
For public mobile and single-page apps, DPoP is the current best practice; for servers, mTLS.
Going deeper The request shape is worth knowing. The client sends Authorization: DPoP <access-token>, note the scheme is DPoP rather than Bearer, and a second header DPoP: <proof-jwt>.
The proof's header has typ: dpop+jwt, the algorithm, and the public key inline as jwk; its payload has htm for the method, htu for the URL without query or fragment, iat, a unique jti, and ath, the SHA-256 of the access token, so a proof cannot be reused with a different token.
The access token carries cnf: { jkt: "<thumbprint>" }, and the resource server checks that the thumbprint of the proof's jwk equals jkt.
Replay within the freshness window is closed by the server issuing a DPoP-Nonce response header that the client must include as nonce in its next proof; a proof with a stale nonce gets a 401 with error="use_dpop_nonce" and a fresh nonce. That nonce mechanism is what makes the server's replay cache small.
Land it DPoP turns "whoever holds it" into "whoever holds it and the key" — the cost is a signature per request, the benefit is that a leaked token is worthless.
- "Where is the client's private key stored on each platform, and what if it is extracted?"
On iOS the key lives in the Secure Enclave via the Keychain with a non-exportable attribute; on Android in the hardware-backed Keystore with
setIsStrongBoxBackedwhere available; in the browser as a non-extractableCryptoKeyfrom the Web Crypto API stored in IndexedDB, which script can use to sign but cannot read.In each case the key can sign but cannot be copied out by ordinary means.
If the device is fully compromised with root access, the attacker can sign proofs on the device, so DPoP does not protect against malware running as the user on the same device; it protects against the token being used elsewhere.
That is the honest boundary, and it still removes the largest class of token theft, which is leakage through logs, proxies, crash reports, and cross-site scripting exfiltration, none of which can carry the key.
- "How much does proof validation cost the resource server at 10,000 requests per second?"
One signature verification per request, an ES256 verification on a modern CPU taking roughly 50 to 100 microseconds, so 10,000 per second is about one core's worth, which is measurable but affordable.
Add a hash of the access token for
ath, which is negligible, and a nonce orjtilookup in a local cache.The larger cost is that a gateway which cached "this access token is valid" for its lifetime can no longer skip work per request, because the proof changes every time; the gateway caches the token's validation result but must still verify each proof.
In practice the gateway does the proof check once and forwards a signed header to services, so the cost is paid once per request, not per hop.
I would measure it in the load test and expect a few percent of CPU, which is cheap for the property it buys.
- "When would you choose mTLS-bound tokens over DPoP, and can you use both?"
mTLS binding, RFC 8705, suits server-to-server clients that already have certificates and a TLS stack that can present them: the token's
cnfcarries the certificate's thumbprint and the resource server checks it against the TLS connection, with no per-request signature.It fails for browsers and mobile apps, where client certificates are awkward to provision and TLS is terminated at a CDN that does not pass the certificate through.
DPoP works anywhere the client can sign and needs no changes to TLS termination, which is why it is the choice for public clients.
They can coexist on one authorisation server: server integrations get mTLS-bound tokens, apps get DPoP tokens, and the resource server checks whichever
cnfmember is present.What I do not do is accept the same token as both bound and bearer; if
cnfis present, the binding is mandatory.- "What breaks in existing infrastructure when you roll DPoP out?"
Anything that assumed the
Bearerscheme. Gateways and libraries that parseAuthorization: Bearerreject or ignoreAuthorization: DPoP, so the gateway's authentication filter must be updated first. Proxies configured to strip unknown headers drop theDPoPheader, so the allow-list must include it.Any place that caches responses keyed on the
Authorizationheader now sees a different value per request, which is correct but changes cache behaviour.Clients that retry must generate a fresh proof per attempt, because the
jtiis single-use and the URL may differ after a redirect. Token introspection endpoints must return thecnfclaim.The rollout is per client: the authorisation server issues DPoP-bound tokens only to clients that send a
DPoPheader at the token endpoint, so bearer clients keep working while apps migrate, and the resource server accepts both until the last bearer client is gone.
Q123 · Scenario. "Your API allows users to fetch any order by id if they are authenticated. A bug bounty report shows user A fetched user B's order by guessing an id. Where is the bug and how do you find every other instance of it?"
Reveal answer
Strong answer Symptom: broken object-level authorisation, number one on the OWASP API Security Top 10 — the endpoint checks that the caller is someone but not that the object is theirs.
Evidence: the handler loads the order by id with no ownership predicate; the repository method is findById rather than findByIdAndCustomerId.
Fix for this endpoint: load with the caller's identity in the query so a foreign id returns nothing, and return 404 rather than 403 to avoid confirming existence.
Finding every other instance: an inventory of every endpoint taking an object id, generated from the OpenAPI document; a review of each handler for an ownership predicate; an automated test that, for each such endpoint, creates an object as user A and requests it as user B expecting 404; and, structurally, moving to a data-access layer where every query is tenant-scoped by construction — a base repository that injects the caller's tenant id into every query — so forgetting is impossible rather than unlikely.
Prevention: the two-user test becomes part of the endpoint template, and security review of any new id-taking endpoint.
Land it Authentication says who; authorisation must say which — put the owner in the query itself so the check cannot be forgotten.
- "Show what 'the owner in the query' looks like in Spring Data, and what it does not cover."
The repository method becomes
Optional<Order> findByIdAndCustomerId(UUID id, UUID customerId), and the service calls it with the customer id taken from the authenticated principal, never from the request. A foreign id returns empty and the controller maps that to 404.What it does not cover is every access path that is not this method: a
findByIdused somewhere else, a JPQL query written by hand, a relationship navigated from another entity, or a lookup by order number rather than id.That is why the structural version is better: a Hibernate filter,
@FilterDefwith acustomerIdparameter enabled per request, or Postgres row-level security with the caller's id set as a session variable, so every query on the table is scoped whatever method issued it.The test for either approach is the same: create as A, fetch as B through every endpoint, expect 404.
- "Why 404 rather than 403, and are there cases where 403 is right?"
404 avoids telling the caller that the object exists. With 403, an attacker can enumerate ids and learn which ones are real, which is information: order volumes, customer counts, or the existence of a specific record.
With 404, a foreign id and a nonexistent id look identical.
The cases for 403 are when existence is not secret and the distinction helps legitimate users: a shared document where the user has been told the link but not granted access, so a "request access" flow makes sense, or an admin interface where the operator should know the record exists but their role is insufficient.
For a customer-facing orders API, existence is secret and 404 is correct. Whichever is chosen, it must be consistent across every endpoint, because a mix leaks through the inconsistency: 404 from one endpoint and 403 from another for the same id tells the attacker everything.
- "How do you generate the two-user test for every endpoint automatically?"
From the OpenAPI document.
A test generator reads every operation whose path contains an id parameter, groups them by resource, and for each resource uses the create operation to make an instance as user A, then calls each id-taking operation as user B with that id, asserting 404 or 403 per the policy, and finally calls them as user A asserting success.
Resources without a create operation get a fixture. The generated tests run in CI against a real database with two test users.
Operations that legitimately allow cross-user access, such as a shared resource, are annotated in the document with an extension such as
x-access: sharedand excluded with a reason, which makes the exception visible in review.The generator is a few hundred lines and pays for itself the first time a new endpoint ships without the predicate, because the test fails before the bounty report arrives.
- "The bounty also found the same bug via a list endpoint with a filter parameter. Same fix?"
Same principle, different shape. The list endpoint accepted
?customerId=as a filter and returned whatever matched, so user B asked for A's orders by supplying A's id.The fix is that ownership is never a client-supplied filter: the query is always scoped to the caller, and a
customerIdparameter is either removed or, for admins, permitted only with an admin scope and validated against the caller's tenant.The row-level security approach handles this too, because the scoped query returns nothing for another customer's id regardless of the filter.
The list variant is worth calling out in the inventory because it is easy to miss: the operation has no id in the path, so a path-based scan does not find it.
I extend the generator to include any operation with a parameter whose name ends in
IdorIds.
Q124 · Design. "Design service-to-service authentication for 60 microservices in Kubernetes, including how a request's original user identity travels through the chain."
Reveal answer
Strong answer Requirements: every call authenticated at the workload level, no shared secrets in configuration, user context available downstream for authorisation and audit, and no way to forge either.
Design: workload identity via mutual TLS from a service mesh — Istio or Linkerd — or SPIFFE with cert-manager, so each pod has a short-lived certificate encoding its service account, rotated automatically; the mesh enforces allow-lists of which service may call which, which is the coarse authorisation.
User identity travels as the original access token or, better, as a token exchange: the edge validates the user's token and calls the authorisation server's token-exchange endpoint, RFC 8693, to mint a short-lived token with the user's subject, the calling service as actor, and an audience of the next hop; each service can repeat the exchange for its downstream, so tokens are scoped per hop and the chain is auditable.
Where exchange is too heavy, the edge places a signed identity header that services verify with a shared public key, and the mesh guarantees the header can only have come from the edge. Services check object-level authorisation with the user claims.
Trade-offs: a mesh is infrastructure to operate; token exchange adds a call per hop, mitigated by caching.
I would not pass raw user tokens with a broad audience through every service, would not use static API keys between services, and would not trust identity headers without mTLS proving their origin.
Land it mTLS says which workload is calling, a per-hop exchanged token says on whose behalf — two identities, both verifiable, neither forgeable.
- "What does the token-exchange request look like, and what does the exchanged token contain?"
The calling service posts to the authorisation server's token endpoint with
grant_type=urn:ietf:params:oauth:grant-type:token-exchange,subject_tokenset to the user's token it received,subject_token_type=urn:ietf:params:oauth:token-type:access_token,audience=inventory-service, and the requested scopes, authenticating itself with its own client credentials, ideally its workload certificate. The response is a short-lived token, a few minutes, whosesubis still the user, whoseaudis the inventory service, whose scopes are the subset the caller was allowed to delegate, and whoseactclaim names the calling service, with nestedactclaims if there were earlier hops, so the chain is in the token. The inventory service validates it like any token: signature, issuer, audience, expiry, and then usessubfor object-level checks andactfor audit.- "How does SPIFFE differ from a mesh's mTLS, and when would you pick it?"
SPIFFE is the identity standard: a workload identity is a URI such as
spiffe://example.org/ns/orders/sa/orders-api, carried in an X.509 certificate called an SVID, issued by a workload API that attests the pod through Kubernetes and rotates certificates automatically.A mesh such as Istio implements SPIFFE identities inside its sidecars and does the mTLS for you; SPIRE, the reference implementation, gives you the certificates and you do the mTLS in your own stack.
I pick a mesh when I want the transport security, retries, and telemetry without touching application code and the team can operate the mesh.
I pick SPIRE without a mesh when workloads are not all in Kubernetes, for example virtual machines and Kubernetes together, or when the applications already do their own TLS and I only need a trustworthy identity.
Both give the same guarantee: the peer's identity is attested, not configured.
- "Token exchange at every hop is too slow for a 5-hop chain with a 200-millisecond budget. What then?"
Two options that keep the guarantees.
First, cache exchanged tokens per user, caller, and audience for their lifetime, since a user making ten requests in a minute needs one exchange per hop, not ten; with a two-minute token and a local cache the exchange rate drops by an order of magnitude.
Second, exchange once at the edge for a token whose audience is the whole internal trust domain rather than a single service, and let the mesh's per-service allow-lists provide the hop-level authorisation; the user identity travels unchanged, the
actchain is lost, but the mTLS peer identity is still logged at each hop, so audit is reconstructed from logs rather than the token.I would pick the second for latency-critical chains and keep per-hop exchange for the paths that cross a trust boundary, such as into the payments domain, where the narrower audience is worth a few milliseconds.
- "What is the failure mode if the identity header is trusted without mTLS?"
Any workload that can reach a service can claim to be any user. An attacker who compromises one low-value pod, or a developer with a port-forward, sends
X-User-Id: adminand the service believes it, because nothing proves the header came from the edge.mTLS with a mesh policy closes that in two ways: the service only accepts connections from authenticated peers, and the policy says only the gateway's identity may set that header, with the sidecar stripping it from any other source.
Signing the header is the complementary control: the edge signs the claims with a key only it holds, the service verifies the signature, and even a peer allowed to connect cannot forge a user.
Either alone has a gap; signing without mTLS still allows replay from a compromised pod, and mTLS without signing trusts every allowed peer completely. I use both for anything carrying user identity.
Q125 · Scenario. "Your OAuth2 login flow works, but a security audit flags that the redirect URI is matched by prefix and the state parameter is not checked. Explain each finding's actual exploit."
Reveal answer
Strong answer Prefix-matched redirect URIs: the authorisation server registered https://app.example.com/ and accepts anything starting with it.
An attacker crafts an authorisation link whose redirect is https://app.example.com/anything-that-redirects-elsewhere, or exploits an open redirect on the app, so after login the authorisation code is sent to the attacker's page; with PKCE the code alone is not enough to get a token, but without PKCE — or in the older implicit flow, where the token itself is in the redirect — it is a full account takeover.
The fix is exact-string matching of registered redirect URIs, which OAuth 2.1 mandates. Unchecked state: the state parameter is a random value the client generates before redirecting and verifies on return.
Without it, an attacker can start a login as themselves, capture the redirect back with their own code, and trick the victim's browser into completing it, logging the victim into the attacker's account — a login CSRF — after which anything the victim enters, such as a saved card, lands in the attacker's account.
The fix is a per-login random state bound to the user's session, checked on callback; PKCE's verifier gives similar protection for public clients, and doing both is standard.
Land it Exact redirect matching stops code theft; a verified state stops login CSRF — both are one-line fixes with account-takeover consequences.
- "With PKCE in place, is the prefix-matched redirect URI still exploitable?"
Less so, but not safe. With PKCE the stolen authorisation code cannot be exchanged without the verifier, which the attacker does not have, so the classic code theft fails.
What remains: if the attacker can also inject their own login into the victim's browser, they can use their own verifier, which becomes the login CSRF case.
And the open redirect that made the prefix match exploitable is a vulnerability in its own right, usable for phishing with a trusted domain in the link.
There is also the implicit flow and any hybrid flow returning tokens in the fragment, where PKCE does not apply and the token itself leaks. So exact matching is still required; PKCE reduces the impact of one specific exploit but does not remove the finding.
OAuth 2.1 requires both exact redirect matching and PKCE precisely because each closes a gap the other leaves.
- "How exactly should the state parameter be generated, stored, and verified?"
Generated with a cryptographic random source, at least 128 bits, base64url-encoded. Stored server-side in the user's pre-login session, or, for a client without a session, in a signed and encrypted cookie bound to the browser, together with the PKCE verifier and the intended post-login destination.
On the callback, the client looks up the stored value, compares it with the
statequery parameter in constant time, rejects on mismatch or absence, and deletes it so it cannot be reused.The destination is read from the stored record, never from the
statevalue itself, because a state that encodes a destination becomes an open redirect.Spring Security's OAuth2 client does all of this in its authorisation request repository, which is why I would rather configure than hand-write it. The failure that audits find is a client that generates the state but compares it against nothing.
- "Are there other findings in the same family you would look for once these two were found?"
Yes, because the two together suggest a hand-rolled client. I would check whether the ID token's
nonceis verified, which stops replay of ID tokens.Whether the client validates the token's
issagainst the expected issuer, given the mix-up attack where a malicious provider returns codes for another. Whether the authorisation code is single-use at the server and the client does not retry an exchange with the same code.Whether the token endpoint call uses the client secret or a private-key JWT rather than sending the secret in the query. Whether the response type is
codeand nottokenor a hybrid that leaks tokens in the fragment.Whether the redirect URI uses HTTPS with no wildcard. And whether the client follows the OAuth 2.0 Security Best Current Practice, RFC 9700 as of Aug 2026, which is the checklist I would hand the team.
- "The exact-match fix broke a client that uses dynamic ports on localhost. What do you do?"
That is the one sanctioned exception.
Native apps on desktop listen on a loopback address with an ephemeral port because they cannot reserve one, and RFC 8252 permits the authorisation server to match
http://127.0.0.1redirect URIs ignoring the port while still matching the path exactly; OAuth 2.1 carries that exception.So I configure the server to allow the port to vary only for loopback literal addresses, never for
localhostas a hostname, which can be redirected by DNS, and never for any non-loopback host. Everything else stays exact.If the client is a web app that needed the prefix match for environment-specific paths, I register each environment's full redirect URI explicitly. The principle is that any relaxation of matching is a documented exception tied to a specific RFC allowance, not a convenience.
This group tests whether you can defend the edge: what the gateway must do, what it must not, and how the classic API attacks actually work.
Q126 · Scenario. "Your 'import from URL' feature let a user fetch http://169.254.169.254/latest/meta-data/iam/security-credentials/ and obtain cloud credentials. Walk through the attack and the layered fix."
Reveal answer
Strong answer Symptom: server-side request forgery — the server fetched a user-supplied URL from inside the network, where the cloud metadata endpoint hands out the instance's credentials to anything that asks. Evidence: the fetcher's logs show the request; the instance role's permissions define the blast radius.
The fix in layers, because each alone has a bypass: first, validate the URL's scheme to http or https and resolve the hostname, then reject any address in private, loopback, link-local, or metadata ranges — and do the check after resolution and again on each redirect, because attacker.com can resolve to 169.254.169.254 or redirect there; second, pin the resolved address for the actual connection to defeat DNS rebinding between check and fetch; third, run the fetcher in a separate egress-restricted network or service with no route to metadata and no cloud role; fourth, enable the cloud's hardened metadata mode — IMDSv2 on AWS, which requires a session token via PUT that a naive fetch cannot obtain; fifth, scope the instance role to least privilege so what is stolen is worth little.
Also disable following redirects by default, cap response size and time, and log the destination of every fetch. Prevention: an SSRF test with a list of bypass payloads in CI for any feature taking a URL.
Land it Validate after resolution, pin the address, isolate the fetcher, harden the metadata service, and shrink the role — SSRF needs all five because attackers only need one gap.
- "You added the address checks and the tester bypassed them. How?"
The usual bypasses, in order of what I would test.
Alternative encodings of the address:
http://2852039166/is 169.254.169.254 as a decimal integer,0xA9FEA9FEin hex,169.254.169.254.nip.ioresolving to it, and IPv6 forms such as[::ffff:169.254.169.254]; a check that parses the string rather than the resolved address misses these.DNS rebinding: the hostname resolves to a public address at check time and to the metadata address one second later at fetch time, which is why the check must pin the address it validated.
Redirects: the first URL is public and returns 302 to the metadata address, which a client following redirects fetches without re-checking. Other schemes:
file://,gopher://, orftp://if the client library supports them.And URL parser differences, where
http://public.com@169.254.169.254/is parsed by the validator as public.com and by the client as the metadata address.- "How do you pin the resolved address in a Java HTTP client?"
The client must connect to the IP address I validated while still sending the original hostname for the
Hostheader and TLS server name.With Apache HttpClient I install a custom
DnsResolverthat returns only the validated address for that host, and I disable redirects withdisableRedirectHandling(), handling each redirect manually by re-validating the new location.With the JDK
HttpClientthere is no resolver hook, so I resolve first, validate, and then a small proxy or a customSSLParameterswith the hostname plus connecting to the literal address is fragile; in practice I route the fetch through the isolated egress service, which does the resolution and pinning in one place.The check itself uses
InetAddress.isSiteLocalAddress(),isLoopbackAddress(),isLinkLocalAddress(), and an explicit list of metadata ranges, because the built-in methods do not cover all of them.- "What does the isolated fetcher service look like, and what can it still reach?"
It is a small deployment in its own namespace or subnet with a network policy that allows egress only to the public internet, denying RFC 1918 ranges, link-local, and the metadata address at the network layer, so even a bypass in the validation logic cannot reach an internal address.
It runs with no cloud role, or a role with no permissions, so a metadata fetch, if it somehow succeeded, would yield nothing useful.
It has a fixed timeout, a response size cap of a few megabytes, an allow-list of content types, and it strips credentials from the fetched URL. It exposes one internal endpoint,
POST /fetch, taking the URL and returning the body or an error, and it logs every destination.The main application calls it instead of fetching directly.
What it can still reach is the internet, which is the feature, and that means it can still be used to attack third parties, so it has an outbound rate limit and a user agent that identifies us.
- "How does IMDSv2 stop a naive SSRF, and what is the hop limit for?"
IMDSv2 requires a session token obtained with a
PUTrequest to/latest/api/tokencarrying a headerX-aws-ec2-metadata-token-ttl-seconds, and every subsequent metadata request must send that token in a header.A typical SSRF gives the attacker control of a URL only, so they can make a
GETbut cannot make aPUTwith a custom header, and the metadata endpoint refuses.The hop limit,
HttpPutResponseHopLimit, controls how many network hops thePUTresponse may travel; setting it to 1 means the response is only delivered to the instance itself, so a container behind a bridge or a proxy one hop away cannot complete the token handshake.Enforcing v2 is an instance setting,
HttpTokens=required, and an account-level default as of Aug 2026. The other clouds have equivalents: GCP requires aMetadata-Flavor: Googleheader and Azure aMetadata: trueheader, which give a similar protection against header-less SSRF.
Q127 · Design. "Design an API gateway for a company with 80 services and 300 external consumers: what it does, what it refuses to do, and how it fails."
Reveal answer
Strong answer Requirements: one entry point, consistent security, per-consumer control, and no single point of failure.
Responsibilities: TLS termination with automated certificates; JWT validation once with cached JWKS, forwarding verified claims in a signed header; API-key lookup for legacy consumers; rate limiting and concurrency limits per consumer with shared counters; request validation against each service's registered OpenAPI document; routing by path and version to services, including canary weights; a correlation id on every request; access logs and metrics by route, consumer, and status; response header hygiene such as stripping internal headers and adding Cache-Control defaults; and the deprecation headers and brownout switches per route.
Refusals: no business logic, no payload transformation beyond protocol adaptation, no aggregation of multiple services, no database access — any of those become a BFF with its own owners.
Failure: stateless gateway instances behind a layer-4 balancer across zones; rate-limit counters in a Redis cluster with local fallback so Redis loss degrades to approximate limiting rather than outage; JWKS cached with a long stale-while-revalidate so the identity provider being down does not stop traffic; configuration from a versioned store with validation, and a rollback path; health checks that reflect readiness to route, not just process liveness.
Products: Envoy Gateway or Kong for self-managed, a cloud gateway if the team prefers. Trade-offs: a central gateway is a chokepoint for changes, so route configuration is self-service per team with the platform owning the defaults.
I would not put the gateway in the path of internal service-to-service calls — that is the mesh's job.
Land it The gateway does the generic things once, refuses the domain things always, and is built to degrade rather than to stop.
- "What happens to rate limiting when Redis is down, and how do you make the degradation safe?"
Each gateway instance keeps a local token bucket per consumer as a fallback, sized to the consumer's limit divided by the instance count, so with Redis unavailable a consumer gets approximately their limit across the fleet rather than N times it or nothing.
The instance detects Redis failure with a short timeout, a few milliseconds, and a circuit breaker, so it does not add latency to every request while Redis is down. When Redis returns, the shared counters take over.
The degradation is safe because the failure mode is slightly inaccurate limiting, not an outage, and the alternative of failing closed would turn a cache outage into a platform outage.
What I monitor is the time spent in fallback mode and the deviation between local and shared counts, and what I document to consumers is that limits are approximate.
The same fallback thinking applies to JWKS, where a stale key set is better than no validation, and to configuration, where the last known good config is served if the store is unreachable.
- "Why refuse aggregation at the gateway when the products offer it?"
Because aggregation is domain logic with an owner, and a gateway has no owner for domain logic.
When the gateway composes an order with its customer and items, someone must decide what to do when the customer service is slow, which fields to include, and how the shape changes when the order model changes, and that someone is a product team, not the platform team that runs the gateway.
Putting it in the gateway means every such decision becomes a platform ticket and a gateway configuration change, which is the chokepoint I designed to avoid. It also couples the gateway's deployment to domain changes and makes the gateway's failure modes depend on domain services' behaviour.
A BFF gives the same composition with an owning team, its own deploy cadence, and its own tests. The gateway does protocol adaptation, such as gRPC transcoding, because that is generic; composition is never generic.
- "How do 300 external consumers get their own configuration without the platform team in the loop?"
Through a developer portal backed by the same store the gateway reads.
A consumer registers an application, receives credentials, chooses a plan that maps to a rate class, and subscribes to APIs whose owning teams have published them; the portal writes the consumer's record to the configuration store and the gateway picks it up within seconds.
The owning teams manage their routes and plans in their own repositories as versioned configuration, validated in CI against a schema, applied by a pipeline, and rolled back the same way.
The platform team owns the defaults, the schema, and the pipeline, and is paged when the gateway is unhealthy, not when a consumer wants a higher limit.
Exceptions such as a custom limit for a strategic consumer are a pull request against the owning team's route configuration, reviewed by them. The platform team's work is to make that path so smooth that nobody asks them for changes.
- "How do you upgrade the gateway itself without an outage?"
The gateway is stateless and horizontally scaled, so upgrades are a rolling replacement with the same choreography as any service: new instances pass readiness only after loading configuration and warming the JWKS cache, old instances drain by failing readiness and finishing in-flight requests, and long-lived connections are closed gracefully with GOAWAY or connection-close over a drain window.
Before the rollout, the new version runs as a canary receiving a few percent of traffic, compared on error rate, latency, and rejection counts by rule, because a gateway upgrade that tightens a parser or changes a default is exactly how the Q130 incident happens.
Configuration compatibility is tested by loading the production configuration into the new version in CI. And the gateway is deployed across zones so a bad rollout in one zone leaves the others serving. I never upgrade the gateway and change its configuration in the same step.
Q128 · Scenario. "A client sent a JSON body with "role": "ADMIN" to the user-update endpoint and became an admin. The endpoint binds the body to the JPA entity. Explain the class of bug and the structural fix."
Reveal answer
Strong answer Symptom: mass assignment — the request body is bound directly to a persistent object, so every settable property, including ones the client should never touch, becomes writable by anyone who knows the name.
Evidence: the controller takes the entity as @RequestBody; the entity has a role setter.
The structural fix is a request DTO per operation that lists only the fields the client may set — a Java record such as UpdateProfileRequest(String displayName, String locale) — with explicit mapping to the entity in the service, so an unexpected field is ignored by the deserialiser and cannot reach persistence.
Privileged fields change only through dedicated endpoints with their own authorisation, such as POST /users/{id}/roles requiring an admin scope. Retrospectively, audit for other entities bound directly and for properties like ownerId, balance, verified.
Prevention: an architecture test forbidding JPA entities as controller parameters, request validation against the OpenAPI schema at the gateway with additionalProperties: false, and a security test posting unexpected fields to every write endpoint.
Land it Bind to a DTO that names what the client may set — the entity is the wrong shape for input because it names everything.
- "How exactly did Jackson let the role through, and what setting would have blocked it?"
Jackson binds JSON properties to any setter or field on the target class that matches by name, so an entity with
setRoleaccepts"role"from the body, and the persistence layer then writes it.Jackson's default for properties that do not match anything is to fail,
FAIL_ON_UNKNOWN_PROPERTIESis true by default in plain Jackson, though Spring Boot's auto-configured mapper sets it to false, but that is irrelevant here becauserolematched.The annotation
@JsonIgnoreon the setter or@JsonProperty(access = READ_ONLY)on the field would have blocked that one property, and@JsonIgnoreProperties(ignoreUnknown = false)would reject unknown ones.But annotating the entity is the weak fix, because the next privileged field added to the entity is writable until someone remembers the annotation.
The DTO is the strong fix because the deserialiser cannot bind what the DTO does not declare, and the mapping to the entity is explicit code that a reviewer reads.
- "How do you write the architecture test that forbids entities in controllers?"
With ArchUnit in the test suite. A rule states that no method in a class annotated with
@RestControllermay have a parameter annotated with@RequestBodywhose type is annotated with@Entity, and a second rule states that no such method may return a type annotated with@Entity, which prevents the output side of the same problem, leaking fields such as password hashes:ArchRule noEntityInput = noMethods() .that().areDeclaredInClassesThat().areAnnotatedWith(RestController.class) .should().haveRawParameterTypes( DescribedPredicate.anyElementThat(annotatedWith(Entity.class)));The rule runs as a unit test on every build and fails with the offending method's name. I add a third rule that DTO packages may not depend on the persistence package, so the DTO cannot extend or wrap an entity. The rules take an hour to write and remove the class of bug for every future endpoint.
- "Does GraphQL or gRPC have the same bug?"
The same principle, different mechanisms. In GraphQL, an input type is the DTO:
input UpdateProfileInput { displayName: String, locale: String }lists what may be set, and a client cannot send arolefield because the schema rejects unknown input fields at validation.The bug appears if a resolver takes a generic map or binds the input object straight onto an entity by reflection.
In gRPC, the request message is the DTO, and Protobuf ignores unknown fields on the wire, so an attacker cannot add
roleunless the request message declares it; the bug appears when a team reuses the domain message as the request message for convenience, soUpdateUserRequestcontains a fullUserwith arolefield.In every protocol the rule is the same: the input type names what the client may set, and it is not the persistence type.
- "The audit found 30 more endpoints binding entities. How do you fix them without a six-month rewrite?"
Triage by the entity, not the endpoint. For each bound entity I list the properties an ordinary client must never set, typically role, owner, tenant, balance, verified, status, and timestamps. Endpoints whose entity has none of those are lower priority.
For the rest, the quick mitigation is a request-scoped Jackson mixin or a
@JsonIgnorePropertieslisting those properties as ignored on input, applied through a shared configuration, which closes the exploit in a day across all 30.Then the proper DTO fix proceeds per endpoint in priority order, with the architecture test enabled in a mode that only reports until the count reaches zero, at which point it becomes a failing rule.
The security test posting unexpected fields runs from day one to prove the mitigation. That is a week to close the hole and a quarter to remove the pattern, and the interviewer wants to hear both numbers.
Q129 · Design. "Design input validation for a public API so that bad input is rejected early, consistently, and with useful errors — across the gateway, the controller, and the domain."
Reveal answer
Strong answer Requirements: reject cheaply and early, never trust any layer alone, one error format. Three layers with distinct jobs.
The gateway validates shape against the OpenAPI schema — types, required fields, formats, enum membership, string lengths, array sizes, additionalProperties: false — and rejects with 400 in Problem Details before the request costs a thread in the service; it also enforces body size and content type.
The controller validates the request DTO with Jakarta Bean Validation — @NotBlank, @Min, @Pattern, custom constraints for cross-field rules like date ranges — returning 422 with an errors array of field pointers; this is the same rule set as the schema, so the two must be generated from one source or tested against each other.
The domain validates business rules that need state — the SKU exists, the customer may order this, the amount is within limits — raising typed exceptions mapped to 409 or 422 with a registered type. Normalisation happens before validation: trim, Unicode-normalise, canonicalise emails.
Every layer parameterises queries, so injection is not a validation concern. Error messages name the field and the rule, never echo the full input, and never leak internals.
Trade-off: duplicated rules between schema and annotations, which I accept for defence in depth and mitigate with a test that fuzzes the schema against the controller.
Land it Shape at the gateway, constraints at the controller, rules in the domain — each layer rejects what it can see, and none of them trusts the one before.
- "Why 400 at the gateway but 422 at the controller? Consumers will see two codes for 'bad input'."
They see two codes because the two failures are different in kind.
400 means the request could not be understood as a request for this operation: wrong type, missing required field, malformed JSON. 422 means the request was well-formed and understood but violated a rule about its content: a date range where the end precedes the start, a quantity above the allowed maximum for this product type.
RFC 9110 defines 422 as exactly that. The value for consumers is that a 400 always indicates a client bug that a schema check would have caught, while a 422 may be a legitimate user error to show in a form.
What must be identical is the body: both are Problem Details with the same
errorsarray of field pointers and rule names, so the client's error-handling code is one path.If a team wants a single code, I would accept 400 for both over inconsistency, but the two-code convention is documented and usual.
- "How do you keep the schema constraints and the Bean Validation annotations from disagreeing?"
By generating one from the other or testing them against each other. If the OpenAPI document is the source, the DTOs are generated with the OpenAPI Generator's
useBeanValidationoption, which turnsmaxLengthinto@Size,patterninto@Pattern, andminimuminto@Min, so they cannot disagree.If the code is the source, the document is generated from the annotations by springdoc, which reads Bean Validation annotations into the schema.
Where neither generation is in place, a property-based test generates random inputs from the schema with a tool such as Schemathesis and sends them to the controller: anything the schema accepts must not fail Bean Validation with a 422 for a schema-expressible rule, and anything the schema rejects must never reach the domain.
The cross-field rules stay in annotations only and are documented in the schema's description, because JSON Schema cannot express them.
- "Where does normalisation go, and what goes wrong if it runs after validation?"
Normalisation runs in the deserialisation step or a mapper before any validation, and the same normalisation runs at the gateway if the gateway validates the same field.
If it runs after validation, the validated value and the stored value differ, and the stored value may violate the rule: an email validated as unique in its raw form and then lower-cased collides with an existing lower-case one; a string validated at 100 characters becomes 102 after Unicode normalisation to NFC; a path validated as safe becomes traversal after URL-decoding.
The rule is validate what you will store. In Spring that is a custom Jackson deserialiser for the types that need it, or a
@JsonSetterthat trims and normalises, so the DTO's fields are already canonical when Bean Validation sees them.I test it with inputs that only differ by normalisation and assert that both validation and storage treat them identically.
- "What would you cut under time pressure, and what breaks if you cut the wrong layer?"
I would cut the gateway validation first, because it is the layer that duplicates the controller's, and I would keep the controller and domain layers, which are the ones that protect data.
Cutting the controller layer instead leaves the gateway as the only shape check, and the gateway does not know the code's rules, drifts as in Q130, and does not cover internal callers that bypass it.
Cutting the domain layer leaves rules that need state unenforced, and no schema can express "this SKU exists". I would also cut the fuzzing test and rely on generation from a single source.
The one thing I would not cut is the Problem Details error format with field pointers, because clients build their form handling on it and changing it later is a breaking change.
The gateway layer comes back when the platform has request validation rolled out in observe mode, which is a configuration change rather than code.
Q130 · Scenario. "The gateway's request-validation feature was switched on for all routes and 8% of traffic started failing with 400. The services accepted those requests fine before. What happened and how should the rollout have gone?"
Reveal answer
Strong answer Symptom: the contract and the implementation disagreed, and enforcing the contract exposed it.
Evidence: the rejected requests grouped by rule — I expect undocumented query parameters, fields the document marks with a stricter type or pattern than the code enforces, and headers the document omits.
Causes ranked: OpenAPI documents that drifted from services; documents written aspirationally; clients relying on lenient parsing, such as numbers as strings.
The rollout should have been: enable validation in observe mode, logging would-be rejections per route and consumer for two weeks; fix documents or services for each mismatch, in most cases the document; contact the consumers whose requests are genuinely invalid with a date; then enforce route by route, starting with new or low-traffic ones.
The immediate action is to revert to observe mode. Prevention: response and request validation in each service's CI against its own document, so drift is caught before the gateway ever sees it, and the conventions rule that a document is published only if its tests pass.
Land it Turning on enforcement is a discovery of every lie in the contract — observe first, fix the documents, then enforce one route at a time.
- "You reverted to observe mode. Consumers are still failing. Why?"
Because the revert did not reach every gateway instance or every route, or because something else changed with it.
I would check the configuration version on each instance through the admin endpoint, since a rolling configuration push can leave stragglers, and I would check whether the switch to observe mode was per route and some routes were missed.
The other possibility is that enabling validation changed request handling as a side effect that observe mode does not undo: the validator parses bodies, so a body size limit or a content-type requirement became active, or the parser rejects duplicate JSON keys or a UTF-8 byte-order mark that the services tolerated.
The gateway's rejection log grouped by rule tells me which. If it is a parser-level rejection rather than a schema rule, observe mode does not help and the validation feature must be disabled entirely on the affected routes until the parser settings are tuned.
- "How do you decide whether to fix the document or the service for each mismatch?"
By asking what the contract should say, with the consumer in mind. If the service accepts an undocumented parameter that consumers use and it is sensible, the document was wrong and I add the parameter.
If the service accepts a number as a string because of lenient parsing and the document says integer, the document is right in principle but consumers depend on the leniency, so I document the lenient behaviour as accepted, tighten it only in the next major version, and tell the consumers.
If the service accepts something dangerous, such as unknown properties that reach persistence, the service was wrong and the document is right, and I fix the service and treat the consumer's requests as bugs to report.
The rule is that consumers' working requests do not become invalid without notice, and the document ends up describing the actual accepted behaviour, with a dated plan for anything I want to tighten.
- "What does the per-service CI check look like that prevents the drift?"
The service's integration tests run with request and response validation against its own OpenAPI document, so a test that sends a request the document does not permit fails, and a response the document does not describe fails.
Additionally, a contract-coverage report lists operations and response codes in the document that no test exercised, and the build fails below a threshold, because an untested operation is where drift hides.
The document is published to the gateway's registry only from a successful main-branch build, with the build's commit in the metadata, so the gateway never holds a document that was not validated against the code it describes. That gives the gateway's validation a trustworthy input.
A nightly job then replays a sample of production traffic shapes through the validator in observe mode and reports new mismatches, which catches consumers doing something new before enforcement would reject them.
- "The 8% included one large partner whose requests were genuinely invalid. How do you handle them?"
With a per-consumer exemption and a date. The gateway's validation is scoped per route and per consumer, so I keep enforcement on for everyone else and set observe mode for that consumer on the affected routes, which stops the bleeding without weakening the platform.
Then I send them the rejection log for their requests grouped by rule, with examples, which is usually a handful of distinct issues such as a wrong date format or an extra field.
I agree a fix date, typically 30 to 60 days, and I put a brownout in the calendar before it, one hour of enforcement announced in advance, so they discover any remaining issue while support is watching.
The exemption is recorded in the consumer's configuration with an expiry, and the platform dashboard shows exemptions with their dates so they do not become permanent. If they miss the date, the commercial relationship owner decides, with the data.
Q131 · Scenario. "An attacker is enumerating valid email addresses through your password-reset and sign-up endpoints, which return different messages for known and unknown emails. Rate limiting per IP is not stopping them. Fix it."
Reveal answer
Strong answer Symptom: account enumeration through response differences, distributed across IPs to beat per-IP limits. Evidence: the two endpoints return distinct messages or status codes, or distinct latencies, for known versus unknown emails; traffic from many IPs with one pattern.
The fix at the contract: both endpoints return the same 200 and the same message regardless — "if that address exists, we sent an email" — and sign-up with an existing email sends a "you already have an account" email rather than a 409.
Equalise latency by doing the same work on both paths, or by adding a constant delay. Rate limiting: move from per-IP to per-email-address and per-account limits, plus a global limit on these endpoints, and add proof-of-work or a CAPTCHA once a threshold is crossed.
Detection: alert on the ratio of unique emails to requests. Trade-offs: the vaguer messages slightly hurt usability, which is the accepted price for these two endpoints.
I would not rely on IP limits for anything an attacker can distribute, and I would not leave sign-up returning 409, which is the most common enumeration leak.
Land it Make the responses identical in status, message, and time, then limit on the thing the attacker cannot multiply — the target, not the source.
- "You equalised the messages and the attacker still enumerates. How?"
Through timing, most often. Password reset for a known email sends a message, which takes 200 milliseconds through the email provider, while an unknown email returns in 5 milliseconds, and the attacker measures.
The fix is to make both paths do the same amount of work: queue the email asynchronously so the response returns before it is sent, and pad the unknown path with the same queue write.
The second leak is a secondary channel: a different
Set-Cookie, a different response size, a different rate-limit counter that increments only for known emails, or a login endpoint with a lockout that only triggers for existing accounts.The third is a different endpoint entirely, such as a "check availability" call in the sign-up form that the front end uses, or the OAuth provider's own behaviour.
I would run an enumeration test that compares status, headers, body size, and timing distribution for known versus unknown across every endpoint that takes an email.
- "What does the per-email limit look like, and how does it avoid locking real users out?"
A sliding window per normalised email address, for example five reset requests per hour and ten sign-up attempts per day, stored in Redis keyed by a hash of the email, and applied before any lookup so the counter exists for unknown addresses too.
When the limit is hit, the response is identical to the success response, "if that address exists, we sent an email", with no email actually sent, so the attacker learns nothing from being limited.
A real user who requests five resets in an hour is rare, and the email they received on the first request still works, so the impact is minimal.
The global limit on the endpoint is a circuit breaker for distributed attacks: if reset requests fleet-wide exceed ten times the daily baseline, the CAPTCHA or proof-of-work challenge switches on for everyone, which slows the attacker's throughput to human speed without blocking anyone.
- "Why not block the attacker's IP ranges once you have identified them?"
I would block obvious sources as a short-term measure, but it does not solve the problem, because the attacker is already distributed across residential proxies and cloud ranges that legitimate users share; blocking a range blocks customers on the same range and the attacker rotates within minutes.
The structural fix is to make enumeration yield no information, at which point the attacker's traffic is harmless noise rather than a leak, and the limits are about cost rather than blocking.
What I do keep from the IP dimension is reputation signals as an input to the challenge decision: a request from a known proxy network gets the CAPTCHA earlier than one from a residential connection with history.
And I feed the observed source ranges to the web application firewall's managed bot rules so the platform learns, but I never rely on it as the control.
- "How do you prove to the product team that the vaguer messages are acceptable?"
With the conversion numbers, not the security argument alone.
I would run the identical-message version and measure sign-up completion and reset completion rates before and after; in every case I have seen, the change is within noise, because a user who mistyped their email at sign-up gets the "you already have an account" email at the real address and understands, and a user resetting a password checks their inbox either way.
I would also point at what the industry does: the large providers all use the "if that address exists" wording for exactly this reason, so users have seen it.
And I would show the enumeration report: a list of a few thousand confirmed customer emails, obtained in an hour, is a data breach under most privacy regulations, and that framing usually ends the debate.
Product keeps the ability to add a "did you mean to log in?" hint that does not depend on the address's existence.
Q132 · Design. "Design the security testing pipeline for an API: what runs on every pull request, what runs nightly, and what a human still has to do."
Reveal answer
Strong answer Requirements: catch the common classes automatically, keep humans for judgement, and fail builds on regressions.
On every pull request: static analysis for injection and unsafe patterns; dependency and container vulnerability scanning with a severity gate; secret scanning; the OpenAPI linter including security rules such as every operation having a security requirement; the malicious-token suite against the resource server; the two-user object-level authorisation test for every id-taking endpoint; and the unexpected-field test against write endpoints.
Nightly, against a staging deployment: a dynamic scanner such as OWASP ZAP driven by the OpenAPI document; a fuzzing run over request schemas; an SSRF payload suite against URL-taking features; a rate-limit and enumeration probe; and a check that production-like configuration has introspection off, debug endpoints closed, and TLS settings correct.
Humans: threat modelling of new features that touch money, identity, or user-supplied URLs; review of authorisation logic, because tools cannot know who should see what; an annual external penetration test; and triage of the bug bounty. Reporting flows to the owning team with SLAs by severity.
Trade-offs: nightly scans generate noise that needs tuning; the suites need maintenance as the API grows, so they are generated from the contract wherever possible.
Land it Automate the classes of bug that have signatures, and spend the human hours on authorisation and threat models — the tools cannot know who owns which order.
- "How do you keep the nightly dynamic scan from being all noise?"
By driving it from the contract and by baselining. Driving ZAP or an equivalent from the OpenAPI document means it tests the operations that exist with valid-shaped requests, rather than crawling and guessing, which removes most false positives about nonexistent paths.
Baselining means the first run's findings are triaged once, each marked as fixed, accepted with a reason, or false positive with a rule id, and stored as a baseline file; subsequent runs report only new findings, and a new finding at high severity fails the nightly job and opens a ticket for the owning team.
The scanner's own rules are pruned to the relevant set for an API, dropping the browser-oriented checks about HTML forms. And the scan runs against a dedicated staging environment with test data so a finding can be reproduced by a developer.
A scan whose output nobody reads is worse than none, because it creates the illusion of coverage.
- "What is in the threat model session for a new feature, and how long does it take?"
An hour, with the feature's developers, one security-minded engineer, and a whiteboard. We draw the data flow: where input enters, where it is stored, which services touch it, where it leaves.
For each element we ask the STRIDE questions in plain words: can someone pretend to be another user here, change data they should not, deny having done something, read data they should not, break it, or gain extra rights.
Each answer that is "yes, maybe" becomes a line in a table with the control that addresses it and who owns adding it, or an explicit acceptance. The output is that table, checked in next to the design document.
For features touching money, identity, or user-supplied URLs, the session is mandatory before code review; for others it is offered. The point is not completeness but making the developers think as an attacker for an hour before writing the code.
- "What runs on every pull request must be fast. What is the time budget and how do you stay in it?"
The security checks on a pull request must finish in a few minutes, or developers route around them. Static analysis runs incrementally on changed files with a full run nightly. Dependency scanning uses a cached vulnerability database and only re-evaluates when the lock file changed.
Secret scanning is a regex pass over the diff, which takes seconds. The OpenAPI linter runs only if the document changed.
The token suite, the two-user test, and the unexpected-field test are ordinary integration tests that run with the rest of the suite against a containerised database, so they add seconds to a suite that already takes minutes.
Anything that needs a deployed environment, a scanner, or fuzzing moves to nightly. If the pull request checks exceed ten minutes, I look at parallelising them before removing any, because the value of catching an authorisation bug before merge is far higher than the minutes.
- "How does the bug bounty integrate with this, and how do you keep it from becoming a firehose?"
The bounty is a source of findings that the pipeline should have caught and did not, so every valid report ends with the question "which automated check would have found this?" and, if one can be written, it is added.
That is how the two-user test and the unexpected-field test came to exist in most teams that have them.
To keep it manageable, the programme has a clear scope of in-scope hosts and out-of-scope issue types, such as rate limiting on non-sensitive endpoints, a triage rotation with a 48-hour first response, severity definitions tied to the reward table, and a private phase with a small group of researchers before going public.
Reports go into the same tracker as internal findings with the same SLAs. The metric I watch is the ratio of valid reports to total, which tells me whether the scope is well written, and the time from valid report to fix.
Q133 · Scenario. "A partner reports that your webhook signatures fail verification about 1% of the time. Your signing code has not changed. What is different about the 1%?"
Reveal answer
Strong answer Symptom: intermittent signature mismatch, which means the bytes the partner verifies differ from the bytes we signed for a subset of deliveries. Evidence: the failing deliveries' bodies as received versus as sent; the partner's framework; the content encoding on those requests.
Causes ranked: the partner's framework parses and re-serialises the JSON before verification, changing whitespace, key order, or number formatting — 1.0 to 1 — and the 1% are payloads with such values; a proxy or CDN on their side re-encoding or decompressing the body; retries where we regenerated the timestamp and signature but they cache the first; and a secret rotation where 1% of deliveries used the new secret before they added it.
The fix: document that verification must run over the raw request bytes before any parsing, and provide SDK verification code that does so; include the timestamp in the signed payload and in a header, and sign with the exact bytes sent; during rotation, sign with both secrets and send both signatures in the header, which Stripe does, so the receiver can verify with whichever it has.
Prevention: a receiver test kit with tricky payloads — unicode, floats, empty objects — that partners run before going live.
Land it Sign bytes, verify bytes — any parsing before verification turns "sometimes" into an incident, so ship the verifier as code, not prose.
- "What exactly should the signature cover, and how does the receiver check it?"
The signature is an HMAC-SHA256 over a string built from the timestamp, a dot, and the raw request body bytes, using the shared secret, and it is sent in a header such as
Webhook-Signature: t=1724839200,v1=<hex>.The receiver reads the raw body before any framework parsing, reconstructs the same string using the timestamp from the header, computes the HMAC with their copy of the secret, and compares in constant time.
Then they check that the timestamp is within a tolerance, five minutes, to reject replays of captured deliveries. Covering the timestamp inside the signed string is what makes the tolerance check meaningful, because an attacker cannot change the timestamp without invalidating the signature.
In Java the receiver's code reads
request.getInputStream()into bytes first; in Spring, that means the verification runs in a filter or uses a cached-body wrapper, because a@RequestBodyparameter has already consumed and parsed the stream.- "How do you rotate the webhook secret without a single failed delivery?"
With an overlap. The partner generates or receives a new secret through the dashboard, and from that moment we sign every delivery with both the old and the new secret, sending two signatures in the header,
v1=<old>,v1=<new>.The receiver's verification code tries each signature against its configured secret and accepts if any matches, which is what the SDK does.
The partner deploys the new secret at their leisure, then confirms in the dashboard, and we stop signing with the old one after a grace period of, say, 24 hours, or immediately on their confirmation.
If they never confirm, the old secret expires at a documented date and they are emailed. The partner side must support multiple candidate signatures for this to work, which is why the verifier ships as code with that loop built in.
- "The partner insists their code is correct and it is your 1% that is wrong. How do you settle it?"
With evidence from both ends of one failed delivery. I retrieve the exact bytes we sent and the signature from our delivery log, which stores the body hash and the header for every attempt.
I ask them for the exact bytes they received, from their raw request log, and the signature they computed.
If the received bytes differ from the sent bytes, something between us changed them, and comparing the two shows how: re-serialised JSON, a decompressed body, a normalised line ending.
If the bytes match and the signatures differ, they used a different secret or a different string construction, which the SDK test kit will reproduce. If the bytes match and the signatures match but their verification failed, they compared against a re-serialised body.
I keep the tone collaborative; the point of the SDK and the test kit is that this conversation happens once per partner, before go-live.
- "Is HMAC with a shared secret the right design, or should you sign asymmetrically?"
HMAC is simpler and faster and is what most platforms use, but it has two weaknesses: the receiver holds a secret that can also forge deliveries, and each receiver needs its own secret, so the sender manages thousands of secrets.
Asymmetric signing, an Ed25519 signature over the same timestamp-and-body string with our private key and our public key published at a well-known URL, fixes both: receivers hold nothing secret, one key signs for everyone, and rotation is publishing a new key id and signing with both during overlap.
The cost is that the verification code is slightly less familiar to partners and the signature is a few bytes longer.
As of Aug 2026 the Standard Webhooks specification supports both an HMAC scheme and an asymmetric scheme with the same header layout, and for a new platform I would offer both, defaulting to asymmetric, with the SDK hiding the difference.
The final group tests whether you can find a latency cliff from the outside in, keep an API observable enough to debug one customer's request, and run changes without breaking anyone.
Q134 · Scenario. "The p50 of your API is 40 milliseconds, the p99 is 3 seconds, and the average is 90. Product says 'the API is fast'. Support says 'customers complain constantly'. Who is right and what do you do?"
Reveal answer
Strong answer Both are describing the same distribution.
Half of requests are fast, but one in a hundred takes 3 seconds, and a screen that makes 10 API calls has roughly a 10% chance of containing one of them, so a tenth of page loads feel broken — that is the customers' experience.
Evidence to collect: which routes and which consumers dominate the slow tail, from traces grouped by route at p99; whether slow requests correlate with payload size, deep pagination, cold caches, garbage-collection pauses, or a specific downstream.
Ranked causes: a few expensive endpoints — deep list pages or unindexed filters; lock waits or connection-pool queueing under bursts; GC pauses on large heaps; a downstream with its own tail.
Fix by route: keyset pagination and indexes for the lists, pool sizing and timeouts, tuning or moving to a low-pause collector, and deadlines with hedged requests for the downstream.
Then define the SLO on the tail — 99% under 300 milliseconds per route — and alert on burn rate. Prevention: dashboards that show p99 per route and never averages, and a performance budget per endpoint checked in load tests.
Land it The average is a lie and the median is a half-truth — customers live in the tail, so measure, alert, and design for p99 per route.
- "Explain the 10% number, and what it implies for a screen that makes 30 calls."
If each call independently has a 1% chance of landing in the slow tail, the chance that none of 10 calls does is 0.99 to the power of 10, which is about 0.904, so about 9.6% of screens contain at least one 3-second call, and a screen waits for its slowest call.
For 30 calls the same arithmetic gives 0.99 to the power of 30, about 0.74, so a quarter of screen loads include a 3-second call.
That is the mathematical reason the tail matters more the more calls a screen makes, and it is also why a BFF that reduces 30 calls to 1 improves the experience even if every individual call is unchanged.
The independence assumption is optimistic; slow calls often cluster in time, which makes the per-screen effect burstier rather than smaller.
When I set an SLO I ask how many calls a typical screen makes and work backwards to the per-call tail target that gives the screen-level experience product wants.
- "How do you find which requests are in the tail, concretely?"
With the tracing backend's query, not with dashboards. I filter traces to duration above one second for the last hour and group by route, which shows whether the tail is one route or spread.
Within the worst route I look at ten exemplar traces and read the span timeline: the tail is usually one span that dominates, a database query, a downstream call, or a gap between spans that indicates queueing or garbage collection.
I then check whether the slow requests share an attribute: a consumer id, a page offset above 10,000, a payload size, a specific parameter value that misses an index, or a time pattern such as every 15 minutes when a job runs.
Exemplars linked from the latency histogram, which Prometheus and OpenTelemetry support, make this a click from the p99 panel to a representative slow trace.
The output is a ranked list of tail causes with a share of the tail each explains, which decides the order of fixes.
- "What does a hedged request mean, and when is it dangerous?"
A hedged request sends the same call to a second replica if the first has not answered within a threshold, such as the p95 latency, and uses whichever response arrives first, cancelling the other.
It cuts the tail caused by a single slow replica, garbage collection on one node or a noisy neighbour, at the cost of a small amount of extra load, a few percent if the threshold is at p95.
It is dangerous in three cases: when the call is not idempotent, because both copies may execute; when the tail is caused by overload, because hedging adds load to a system that is already slow and makes it worse; and when hedges are not budgeted, because a retry storm under partial outage multiplies traffic.
gRPC supports hedging in its service config with a
hedgingPolicyand a per-channel throttle, and I only enable it for read-only calls with a budget of, say, 5% extra requests.- "Product says the median is what matters because most users are fine. How do you respond?"
I would agree that the median is what most users see on one call, and then show that customers do not experience one call; they experience a session of dozens of calls, and the arithmetic above says a tenth to a quarter of sessions hit the tail.
I would connect it to support: pull the request ids from the last twenty complaints and show that most correspond to tail requests, which turns "customers complain constantly" into data.
Then I would propose the SLO in terms product understands: "99% of screen loads complete within one second", which forces the per-call p99 target. And I would show the cost of the fixes, which is usually modest for the top two tail causes.
The conversation shifts from median versus p99 to how many sessions we are willing to have feel broken, and that is a product decision they can make with numbers.
Q135 · Design. "Design the observability for a public API so that, given one customer's complaint with a timestamp, you can find their request and explain what happened in under five minutes."
Reveal answer
Strong answer Requirements: every request findable, its path through services reconstructable, and its outcome explainable without reading code.
Design: the gateway assigns a request id and starts a trace with the W3C traceparent header; the id is returned to the client in a response header and included in every Problem Details instance, so the customer's complaint can quote it.
Structured JSON logs on every service carry the trace id, span id, consumer id, route, status, and duration; logs are indexed by trace id.
Distributed tracing with OpenTelemetry across gateway, services, database calls, and outbound HTTP, sampled at 100% for errors and slow requests and a few percent otherwise, with tail-based sampling so the interesting traces survive.
Metrics per route and consumer: request rate, error rate by class, latency histograms for percentiles, plus saturation of pools and queues. The gateway's access log is the ground truth for what the customer sent and got, including request validation rejections.
A support tool takes a consumer id and time window and lists their requests with status, duration, and a link to the trace. Privacy: no bodies or tokens in logs, with field-level redaction.
Trade-offs: trace storage cost, managed by sampling; the request id in the response is a small information disclosure that is worth it.
I would not log full request bodies, and I would not rely on service-side logs alone, because a request rejected at the gateway never reaches them.
Land it A request id the customer can quote, a trace that follows it, and logs indexed by it — five minutes is a design goal, not luck.
- "How does tail-based sampling work, and what does it cost compared to head sampling?"
Head sampling decides at the start of a trace, at the edge, whether to keep it, typically a fixed percentage, so the sampled set is random and most slow or failed traces are discarded before anyone knows they are interesting.
Tail-based sampling buffers every span of a trace in a collector until the trace completes or a timeout passes, then decides based on the whole trace: keep everything with an error or a duration above a threshold, keep a percentage of the rest.
The cost is the collector's memory for buffering in-flight traces, a few seconds' worth of all spans, and the requirement that all spans of a trace reach the same collector instance, which is done by routing on trace id with a load-balancing exporter in front of the collector tier.
The OpenTelemetry Collector's tail sampling processor implements this with policies. The benefit is that the traces you need for a complaint are the ones that were kept.
- "The customer only has a timestamp and their account name, no request id. Can you still find it in five minutes?"
Yes, if the gateway's access log is indexed by consumer id and time, which is why those two fields are in every access log line.
The support tool takes the account, resolves it to the consumer id or API key id, and lists requests in a window around the timestamp with route, status, and duration; the customer's description, "I tried to create an order and got an error", narrows it to a POST on the orders route with a non-2xx status.
One click follows the request id to the trace and to the logs. If the customer's clock is wrong, which is common, the window is widened to an hour and filtered by status.
The five-minute goal is realistic only because the access log is the ground truth and is searchable by consumer, not because the customer quotes an id; the id in the response is for the customers who do.
- "How do you keep bodies and tokens out of logs across forty services?"
With a shared logging library and a test, not a policy.
The library provides the structured logger with a redaction layer that masks known field names such as
authorization,password,token,card, and anything matching a credit-card or bearer-token pattern, applied to every log event before it is written.The HTTP logging filter in the library logs metadata only, never bodies, and offers a body-logging mode that works only outside production.
A log-scanning job runs daily over a sample of production logs with the same patterns and alerts on any hit, which catches a service that bypassed the library. And the code review checklist asks whether any new log line includes a request or response object.
What I have seen fail is the exception path: a stack trace whose message includes a request body, which the redaction layer must also process, so it runs on the rendered exception text as well.
- "What would you cut under time pressure, and what do you lose?"
I would cut tracing across services and keep the request id, the structured logs indexed by it, and the gateway access log by consumer, because those three give the "find the request" capability in a day of work.
I would lose the "explain what happened" capability for requests that fan out, since without traces I would be reading logs from several services and correlating by id, which is slower but still possible in five to fifteen minutes.
I would cut tail-based sampling and use head sampling at 100% for errors via a simple rule at the edge, accepting lost slow-but-successful traces. I would cut the support tool and give support a saved query in the log system.
What I would not cut is the request id in the response and in Problem Details, because retrofitting that changes the client contract, and per-route latency histograms, because everything else depends on knowing where to look.
Q136 · Scenario. "Every day at 09:00 the API's error rate spikes to 5% for two minutes, then recovers. Traffic also rises at 09:00 but stays high all day without errors. What is special about the first two minutes?"
Reveal answer
Strong answer Symptom: errors at the start of a load rise, not during sustained load, which is a warm-up or scaling-lag pattern.
Evidence: which errors — 503 from the gateway means no healthy upstream, 504 means slow upstream, 500 from the service means an internal failure like pool exhaustion; instance count over time; JVM metrics on new instances; connection-pool wait times; cache hit rate at 09:00.
Causes ranked: autoscaling reacting after the fact, so for two minutes the overnight instance count serves the morning load; new instances marked ready before the JVM has warmed up and caches are populated, so they are slow and time out; connection pools sized for the small fleet exhausting at the spike; a scheduled job at 09:00 competing for the database.
Fixes: scheduled scaling to pre-warm the fleet at 08:50, since the pattern is predictable; a readiness check that waits for warm-up — cache priming and a few synthetic requests — before the pod joins the pool; CDS or AOT to shorten JVM start on Boot 3.x and 4.x; pool sizes and timeouts revisited with the fleet math from Chapter E3; move the job.
Prevention: an alert on error rate at fine granularity so two-minute spikes are visible, and a load test that ramps rather than steps.
Land it A predictable spike deserves predictive scaling and honest readiness — the error is the fleet being two minutes behind the calendar.
- "You added scheduled scaling at 08:50 and the spike is still there, smaller. What is left?"
Then the remaining cause is per-instance warm-up rather than instance count, and the trace of a 09:01 slow request shows it: the first requests on each new instance are slow because the JVM's just-in-time compiler has not compiled the hot paths, the connection pool is empty and every request pays connection setup, and caches are cold.
The fix is readiness that lies less: the readiness probe returns healthy only after the instance has run a warm-up routine, a few hundred synthetic requests through the real code paths against the real dependencies, and the pool has been pre-filled with
minimumIdleconnections.Spring Boot 3.x and later shorten JIT warm-up with class data sharing archives and, where the team accepts the build changes, ahead-of-time processing. Cache priming loads the hottest keys on start.
Verification is a per-instance latency panel by instance age, which should be flat from the first minute after the change.
- "How do you tell autoscaling lag from warm-up from the scheduled job, from the metrics alone?"
Three signatures. Autoscaling lag shows as a rising ratio of requests per instance and CPU per instance during the two minutes, with the instance count stepping up after the errors have already begun, and the errors are timeouts or 503 from the gateway's queue.
Warm-up shows as errors concentrated on the newest instances, visible when the error panel is broken down by instance start time, and the errors are slow responses rather than refused connections.
A scheduled job shows as database metrics moving before request metrics: active connections and lock waits jump at 09:00 exactly, on the database, regardless of API traffic, and the errors are pool-timeout exceptions from the service.
I would put all three breakdowns on one dashboard row, error rate by instance age, instance count over time, and database wait time, because the incident repeats daily and the panels can be built before tomorrow's spike.
- "Why not just over-provision overnight and avoid the problem?"
It works and it is what I would do first as a mitigation, but it costs money every night for two minutes of benefit, and it does not fix warm-up, because a freshly deployed instance at any time of day still has the same first-minute slowness.
Scheduled scaling gets the same result for a fraction of the cost by starting the scale-up ten minutes early, and readiness with warm-up fixes the slow-first-minute problem for deploys and unplanned scaling too.
The over-provisioning approach also hides the problem, which returns the day traffic grows past the fixed fleet size.
So I would over-provision for a few days while the proper fixes ship, then remove it, and I would keep the fine-grained error alert to prove that the fixes hold. The cost conversation is easy: the scheduled approach costs a few instance-hours a week.
- "What about a load test that ramps rather than steps, what would it have shown?"
A step test goes from idle to peak in seconds and shows the worst case, which is what the 09:00 spike is: it would have shown the fleet failing to absorb the step, the errors during scale-out, and the slow first minute on new instances, all before customers did.
A ramp test increases load gradually and shows the sustained-capacity limit, which is a different question. The teams that only ramp never see the step behaviour, and the teams that only step never learn the capacity curve.
I would run both: a step from overnight load to morning peak with the production autoscaling configuration in place, asserting error rate stays under the SLO, and a ramp to find the point at which p99 breaks.
The step test becomes part of the release pipeline for the gateway and the hot services, run in staging with scaled-down numbers but the same ratios.
Q137 · Design. "Design a caching strategy for a product catalogue API with 10 million items, 50,000 reads per second, and updates that must be visible within 30 seconds."
Reveal answer
Strong answer Requirements: most reads served without the database, bounded staleness of 30 seconds, correctness for personalised fields, and resilience to cache failure.
Layers: at the edge, CDN caching of anonymous item and list responses with Cache-Control: public, max-age=20, stale-while-revalidate=30 and ETags so revalidation is cheap, keyed by URL with a normalised query string; personalised fields such as price for a customer tier are split into a separate small endpoint marked private, so the big payload stays public.
In the service, a distributed cache — Redis — of item representations keyed by id with a 30-second TTL, populated on miss and invalidated on update by the writer publishing the id, which also purges the CDN by URL or surrogate key.
For lists, cache the id list per filter and hydrate items from the item cache, so one item update does not invalidate every list. A small in-process cache with a 2-second TTL absorbs hot keys and protects Redis.
Stampede protection: single-flight per key so one miss triggers one load, and jittered TTLs. Failure: if Redis is down, serve from the database with a circuit breaker and shed low-priority traffic.
Trade-offs: the two-tier invalidation adds complexity; up to 30 seconds of staleness is accepted by the requirement.
I would not cache personalised responses at the CDN, would not cache with no TTL relying only on invalidation, and would not cache full list responses that a single update invalidates.
Land it Public at the edge, private separate, ids in lists and items by key — and every layer has a TTL because invalidation is a hint, not a guarantee.
- "Walk through what happens on a price update, step by step, including the timings."
The catalogue service writes the new price in a transaction along with an outbox row. Within a second the relay publishes an
item.updatedevent with the item id.The cache invalidator consumes it and deletes the Redis key
item:{id}, then issues a CDN purge by surrogate keyitem-{id}, which most CDNs complete within a few seconds.The next request for the item at the CDN misses, hits the service, misses Redis, reads the database, and repopulates both layers. The in-process cache on each instance still holds the old value for up to its 2-second TTL, which is the last piece of staleness.
Worst case end to end is about a second for the outbox plus a few seconds for the purge plus two seconds in-process, well under 30 seconds.
If the purge or the event is lost, the Redis TTL and the CDN
max-agecap the staleness at 30 seconds anyway, which is the requirement.- "What is stampede protection exactly, and what happens without it at 50,000 reads per second?"
A stampede happens when a popular key expires and thousands of concurrent requests miss at the same instant, all go to the database for the same item, and the database sees a burst of identical queries.
At 50,000 reads per second, a hot item expiring could send several hundred simultaneous queries for one row, and if many keys expire together, because they were populated together, the database sees a wave.
Single-flight means the first request for a missed key takes a short lock, in Redis a
SET key:lock NX PX 500, loads the value, populates the cache, and the others wait briefly and read the populated value or serve the stale value if one is kept.Jittered TTLs, 30 seconds plus a random 0 to 5, spread expiries so a wave becomes a trickle. The CDN's
stale-while-revalidatedoes the same thing at the edge: one request revalidates while the rest are served the stale copy.- "What if the requirement changed to five seconds of staleness?"
The CDN layer's TTL would drop to five seconds or the CDN would be removed for the item endpoint, because purges are not reliably faster than that and a 20-second
max-ageno longer fits; I would keep the CDN withmax-age=3and rely on the purge as a bonus.The Redis TTL drops to five seconds and invalidation becomes the primary mechanism rather than a backstop, which means the outbox relay and the invalidator need their own SLO and monitoring, since a two-second lag in the relay now consumes most of the budget.
The in-process cache drops to a few hundred milliseconds or goes away. Hit rates fall, so the database sees more load, and I would need to verify with a load test that it copes; if it does not, a read replica dedicated to cache fills.
The cost of tighter freshness is real and I would say so.
- "What would you cut under time pressure?"
I would ship only the Redis layer with a 30-second TTL and single-flight, and skip the CDN, the in-process cache, and event-driven invalidation entirely, because a 30-second TTL alone satisfies the requirement and Redis at 50,000 reads per second is one modest cluster.
The CDN comes next when egress cost or global latency justifies it, and invalidation comes when product wants staleness lower than the TTL. I would keep the id-list-plus-item-hydration pattern for lists from day one, because switching from cached full lists to hydration later changes the data model of the cache and is painful.
And I would keep the circuit breaker to the database for Redis loss, because a Redis outage on a cache-dependent system without a breaker is a database outage. Those two are architectural; the rest are tuning.
Q138 · Scenario. "A deployment of a backward-compatible change caused 30 seconds of 502s at the load balancer during the rolling restart. Nothing in the change explains it. What in the deployment mechanics does?"
Reveal answer
Strong answer Symptom: errors during rollout independent of the change, which is lifecycle handling — how instances leave and join.
Evidence: 502s timed with pod terminations rather than starts; whether the balancer kept sending to a terminating pod; whether the app closed connections while requests were in flight; the readiness probe's behaviour on new pods.
Causes ranked: no graceful shutdown, so on SIGTERM the server closed listening sockets and dropped in-flight requests while the balancer still routed to it for a few seconds — the endpoint removal in Kubernetes is asynchronous; readiness passing before the app could serve; keepalive connections from the balancer reused against a pod that had stopped.
Fixes: enable graceful shutdown — server.shutdown=graceful with a grace period in Spring Boot — so the server stops accepting, finishes in-flight requests, and exits; add a preStop sleep of a few seconds so endpoint removal propagates before the process is signalled; make readiness reflect real ability to serve and fail it first on shutdown; set terminationGracePeriodSeconds above the app's grace period; and use a rollout with max-unavailable zero.
Prevention: a deployment test in staging that runs load during a rollout and asserts zero non-2xx responses.
Going deeper The timing chain is what the interviewer wants to hear. On pod deletion, Kubernetes does two things in parallel: it removes the pod from the Service's endpoints, and it runs the preStop hook then sends SIGTERM. The endpoint removal takes time to reach every kube-proxy and every ingress controller, typically one to five seconds, and during that window traffic still arrives. So the preStop sleep must be longer than the propagation delay, the application's graceful period must be longer than the longest in-flight request, and terminationGracePeriodSeconds must exceed the sum:
lifecycle:
preStop:
exec: { command: ["sh", "-c", "sleep 8"] }
terminationGracePeriodSeconds: 45 # 8 preStop + 30 graceful + margin
On the Spring Boot side, server.shutdown=graceful with spring.lifecycle.timeout-per-shutdown-phase=30s; as of Aug 2026, Spring Boot 3.4 and later default server.shutdown to graceful, so the remaining work is the Kubernetes side. For keep-alive connections from the ingress, the app must also send Connection: close or close idle connections during shutdown, which Tomcat does once the connector stops accepting; otherwise the ingress reuses a connection to a pod that will vanish and the client sees a reset.
Land it Zero-downtime is a choreography — stop being ready, wait for the balancer to notice, finish what you have, then exit — and each missing step is a burst of 502s.
- "You added graceful shutdown and preStop, and there are still a few 502s. Where now?"
On the joining side rather than the leaving side.
The readiness probe passes before the app can actually serve: a probe on a static endpoint returns 200 while the connection pool is still empty or the JIT is cold, so the first requests time out and the ingress reports 502 or 504.
The fix is the readiness-with-warm-up from Q136.
The second place is the ingress's own behaviour: some ingress controllers keep upstream connections open and retry on a reset only for idempotent methods, so POSTs that hit a vanishing pod fail; enabling retry on connection-level errors for the ingress and the client, scoped to connect failures only, closes that.
The third is HTTP/2 or gRPC connections that the app did not close with GOAWAY, so the client keeps using them. I would look at the 502s' timing relative to pod start versus pod stop; that alone separates the joining and leaving cases.
- "How does the staging deployment test that asserts zero errors actually work?"
A load generator runs a steady mix of real request shapes against the staging environment through the same ingress path as production, at a modest rate, for the duration of a rollout, and records every response.
The pipeline triggers a deployment of the same image with a no-op change while the load is running, waits for the rollout to complete, and then reads the load generator's results: any non-2xx response that is not expected from the request mix fails the pipeline step, with the timestamp and the pod that served it.
It runs on every change to the deployment manifest, the base image, the server configuration, or the shutdown code, and weekly otherwise.
It takes a few minutes and it has caught, in my experience, every regression of this kind, including an ingress upgrade that changed connection reuse.
The one thing it cannot test is the production ingress itself, which is why the first production rollout after such a change is done at low traffic with someone watching.
- "What is the difference between max-unavailable zero and max-surge, and why does it matter here?"
In a rolling update,
maxUnavailableis how many pods may be missing below the desired count during the rollout, andmaxSurgeis how many extra pods may exist above it.With
maxUnavailable: 0andmaxSurge: 1, Kubernetes creates one new pod, waits for it to be ready, then terminates one old pod, so capacity never dips.With the default 25% unavailable, a quarter of the fleet can be terminating at once, and if readiness is optimistic, the remaining pods carry the load plus the failures.
It matters here because the 502s might be partly capacity: at 25% unavailable during peak, the surviving pods queue requests, and the ingress times them out.
The cost of surge is temporary extra capacity, which is cheap; the cost of unavailability is customer-visible, so zero unavailable is my default for any serving workload.
- "Does this apply to consumers of a message broker, or only to HTTP services?"
It applies, with a different failure mode. A Kafka consumer killed mid-batch does not produce 502s; it produces duplicates, because uncommitted offsets are reprocessed by the rebalanced consumer, and it produces a rebalance pause for the whole group while partitions are reassigned.
Graceful shutdown for a consumer means stopping polling, finishing the current batch, committing offsets, and leaving the group cleanly so the rebalance is fast, which Spring Kafka does when the container is stopped within the shutdown phase. Cooperative rebalancing, the
CooperativeStickyAssignor, avoids stopping the whole group.And idempotent processing handles the duplicates that remain. So the same principle, stop taking work, finish what you have, tell the coordinator you are leaving, then exit, gives a clean rollout on both sides, with the metrics being duplicates and rebalance time instead of 502s.
Q139 · Design. "Design the process for shipping an API change to production safely: from pull request to full rollout, for a change that touches a hot endpoint."
Reveal answer
Strong answer Requirements: no undetected breaking change, no big-bang exposure, fast rollback, and evidence at each step. Pull request: contract diff gate, conventions linter, unit and contract tests, a performance test of the touched endpoint against a baseline.
Merge to a staging environment: response validation against the contract, the consumer contract suites, and a load test replaying sampled production traffic shapes.
Production: a canary of 1 to 5% of traffic routed by the gateway with automated comparison of error rate and p99 against the stable set for a defined bake time; for changes to response shape, a shadow deployment that receives copies of traffic and diffs responses without serving them; then progressive rollout by percentage with the same automated checks at each step, and an automatic rollback if the canary's error budget burns.
Feature flags separate deploy from release for behavioural changes, so rollback is a flag flip. Communication: changelog entry, and for anything a consumer could notice, the deprecation channel in advance.
Trade-offs: canaries need enough traffic for statistics, so low-traffic endpoints use a longer bake; shadow traffic doubles load on downstreams, so it targets staging replicas of them.
I would not deploy hot-endpoint changes at peak, would not rely on manual observation of dashboards, and would not ship a shape change without the shadow diff.
Land it Gate the contract, canary the code, flag the behaviour, and let the numbers roll it forward or back — safety is the process, not the reviewer's attention.
- "How does the automated canary comparison decide, and how do you avoid it being fooled by noise?"
The canary and a baseline, a set of stable instances of the same size started at the same time so warm-up is equal, receive the same traffic share.
For a bake period of 10 to 30 minutes, the analysis compares error rate, p50 and p99 latency, and a few business metrics such as orders created per minute, between the two, using a statistical test with a threshold rather than a raw comparison, so a difference of 0.1% on 500 requests is not a failure.
Tools such as Argo Rollouts with an analysis template, or Kayenta, do this with Prometheus queries. The result is a score, and below a threshold the rollout aborts and the canary is removed.
Noise is handled by comparing against a baseline of the same age rather than the whole fleet, by requiring a minimum request count before judging, and by making the bake longer on low-traffic routes.
The rules and thresholds are in the repository next to the deployment, reviewed like code.
- "What if the change alters the response shape? A canary cannot tell you the new shape is right."
Correct, which is why shape changes get a shadow diff before any canary. The shadow instance receives mirrored copies of production requests and its responses are compared field by field with the stable instance's responses for the same request id.
The comparison tool normalises known differences, such as timestamps and request ids, and classifies the rest: fields added, fields removed, values changed.
For a backward-compatible change I expect only additions; any removal or value change is a defect or an undocumented difference, and the report lists examples.
Only when the diff shows exactly the intended changes does the canary begin, and the canary then checks behaviour under real serving. For writes, mirroring is not possible against production data, so the shadow diff runs against replayed traffic in staging with a copied database.
This two-step is what the "would not ship a shape change without the shadow diff" refusal means in practice.
- "What would you cut if the change must ship today?"
If it must ship today, the change is probably a fix, and the risk trade-off is different, but the sequence stays the same with shorter waits. I would keep the contract diff gate and the unit and contract tests, because they take minutes.
I would cut the load test and the shadow diff. I would keep a canary but shorten the bake to five minutes with a manual look at the dashboards, and I would keep the automatic rollback trigger.
I would ship behind a feature flag if the change is behavioural, because the flag is the fastest rollback there is. And I would deploy while someone is watching, not at the end of the day.
What I would not do is skip the canary and roll to 100% at once, because the time saved is a few minutes and the cost of a bad change at 100% on a hot endpoint is an incident that takes hours.
- "How do feature flags interact with the API contract? A flag can change what the API returns."
A flag that changes the response for some callers is a contract change and must be treated as one, which teams forget.
The rule I apply: the contract document describes the union of behaviours, with the new field marked as optional until the flag is fully on, so a consumer that sees the field early is not surprised, and a consumer that does not see it is also within contract.
A flag must never remove a field or change a type for a subset of callers, because then two consumers see two contracts. Flags that select per consumer are also how I do consumer-level rollouts: the new behaviour for one friendly consumer first, then a percentage.
Flags are removed within a sprint of reaching 100%, tracked as technical debt with a date, because a stale flag is an untested code path. And the flag's state is in the trace attributes, so a support investigation can see which behaviour a request received.
Q140 · Scenario. "A large customer's integration makes 40 calls to fetch one order and its lines, items, and prices — 'because that is how your API works'. They want a discount for the traffic. What do you offer instead?"
Reveal answer
Strong answer Symptom: a chatty API forcing clients into N+1 over the network. Evidence: their call pattern in the gateway log — one order, then per-line item and price fetches.
Causes: the order representation exposes lines only by id; no expansion or embedding option; no batch endpoint.
What I offer, in order of leverage: an expand parameter — GET /orders/{id}?expand=lines.item,lines.price, Stripe's pattern — that embeds the related resources in one response, with a documented maximum depth and a cost weight in rate limiting; a batch fetch — GET /items?ids=… with up to 100 ids — for the cases where they already have ids; ETags on the item and price resources so repeated fetches are 304s; and, if their volume justifies it, a nightly bulk export of their catalogue so item and price data is local to them.
Their 40 calls become 1 to 3. Commercially, that is worth more than a discount, and I would present it as a joint fix with a measured before and after.
I would not add GraphQL for one customer and would not simply raise their quota, which leaves the cost with us.
Land it When a customer's traffic is your API's fault, the fix is expansion and batching, not pricing — remove the calls, then talk about the bill.
- "How does expand work internally without becoming N+1 on your side?"
The order handler parses the
expandparameter into a set of paths, validates them against an allow-list of expandable relationships with a maximum depth of two, and then loads in batches per level: all line ids for the order in one query, all items for those lines in oneWHERE id INquery, all prices in one more.That is three queries for any number of lines, and a load test with a 500-line order proves it. In Spring Data that is explicit repository methods taking collections of ids, or JPA entity graphs for the relationships that are always loaded together.
The response nests the expanded objects in place of the id references, using the same representation as the standalone endpoints so the SDK's types are shared.
Each expansion adds a cost weight for rate limiting, say one unit per expanded relationship, so a heavily expanded request counts as three or four rather than one, which is still cheaper than 40.
- "What if the customer's traffic is mostly re-fetching data that did not change?"
Then ETags and conditional requests are the largest lever, and I would quantify it from the log: the share of their GETs on items and prices that returned identical bodies to the previous fetch of the same resource.
If it is high, giving them
ETagheaders and teaching their integration to sendIf-None-Matchturns those into 304 responses with no body, which costs us a cache lookup and them almost nothing.For catalogue data that changes daily, I would also offer a change feed,
GET /items/changes?since=, so they poll once for what changed rather than re-reading everything.Both are additive to the API, benefit every consumer, and let me say honestly to this customer that the traffic will drop by a specific percentage before any discount conversation, with the numbers from their own log.
- "How do you price cost-weighted rate limits so this conversation does not recur?"
By publishing a cost per operation that reflects our actual cost, in a simple table in the documentation: a plain GET is one unit, an expanded GET is one unit per expansion, a search is five, an export is fifty.
The consumer's plan gives a budget of units per minute, and the response headers show units consumed and remaining.
That makes the trade-off visible to the customer's engineers: 40 single calls cost 40 units and one expanded call costs 3, so the efficient pattern is also the cheap one, and nobody needs a commercial escalation to discover that.
The table is derived from measured cost per route, the Q144 metric, and reviewed yearly. It also protects us from the next chatty integration, because the budget bounds the cost before it becomes a discount request.
- "Would GraphQL have prevented this whole problem?"
It would have prevented the client-side N+1, because the customer would request the order with lines, items, and prices in one query.
It would have created the server-side problems from Q93 to Q95 instead: the same query without DataLoaders is N+1 on our database, the cost of an arbitrary query must be bounded, and the customer could write a deeper query tomorrow.
For a public API with one customer asking for nesting,
expandgives the benefit of nested fetching with a fixed, reviewed set of relationships and a fixed maximum depth, which is a small subset of GraphQL's flexibility with none of its operational surface.If many customers asked for many different shapes across a connected model, that would be the signal to reconsider, with persisted queries. The answer to "would GraphQL fix it" is usually "expand is GraphQL's nesting benefit without its query language".
Q141 · Design. "Design multi-tenancy for a SaaS API: how a tenant is identified, isolated, and limited, and how you avoid one tenant's data ever appearing in another's response."
Reveal answer
Strong answer Requirements: tenant identity is unforgeable, every query is tenant-scoped by construction, fair sharing of capacity, and the cross-tenant leak is structurally impossible rather than merely unlikely.
Identification: the tenant id is a claim in the access token issued by the authorisation server, never a header or path parameter the client controls; the gateway copies it into a signed context header for services.
Isolation in data: a tenant_id column on every table with a composite primary key or a leading index column, and row-level security in PostgreSQL or an ORM filter that injects the predicate into every query from the request context — so a developer cannot forget it; for high-isolation customers, a schema or database per tenant behind the same code.
Isolation in cache keys, queues, and object-storage prefixes, all namespaced by tenant. Limits: rate and concurrency limits per tenant at the gateway, queue fairness in workers, and per-tenant cost metrics.
Testing: an automated two-tenant test per endpoint, and a database-level check that no query without a tenant predicate runs, via the query log in CI. Trade-offs: row-level security has a small per-query cost; per-database tenancy costs operations.
I would not derive tenant from a hostname alone without binding it to the token, would not let tenant appear in the request body, and would not rely on developers remembering the predicate.
Land it The tenant comes from the token, goes into every query by construction, and is tested by trying to break it — anything less is a leak on a schedule.
- "Show how Postgres row-level security is wired from the request, and what its failure mode is."
The table has a policy such as
CREATE POLICY tenant_isolation ON orders USING (tenant_id = current_setting('app.tenant_id')::uuid), withALTER TABLE orders ENABLE ROW LEVEL SECURITYandFORCE ROW LEVEL SECURITYso even the table owner is subject to it.At the start of each request's transaction, the service runs
SET LOCAL app.tenant_id = '<id from the token>', in Spring through aTransactionSynchronizationor a datasource wrapper, and every statement in that transaction is filtered by the policy.The application connects as a role that is not the table owner and has no
BYPASSRLS.The failure mode is a request whose setting was not set, which with
current_settingraising an error on a missing setting fails closed, returning no rows, and the other is connection pooling:SET LOCALis transaction-scoped so it cannot leak across pooled connections, while a plainSETwould persist on the connection and leak the next tenant's requests into this tenant's rows.- "What if the requirement changed so some tenants need their data in a specific country?"
Then tenancy gains a residency dimension, and it must be resolved before any data access. The tenant's home region is a property in the tenant registry, replicated globally because it is small and rarely changes.
The gateway reads the tenant from the token, looks up the region, and routes the request to that region's deployment; a request that lands in the wrong region because of DNS is redirected or proxied, never served locally.
Each region has its own database, cache, queues, and object storage, with no cross-region replication of tenant data, so a bug cannot copy it.
Shared services such as the identity provider and the tenant registry are the only global components, and they hold no tenant business data.
Tests add a per-tenant residency check: create data as a tenant homed in one region and prove it exists in no other region's storage. The cost is running the full stack per region and per-region on-call, which the business accepts when regulation requires it.
- "How does the two-tenant test differ from the two-user test in Q123?"
The two-user test checks object-level authorisation within one tenant: user A cannot see user B's order. The two-tenant test checks isolation between tenants across every path, including ones that have no object id: list endpoints, search, aggregations, exports, cache keys, and background jobs.
It creates identical data in tenants X and Y, then, as tenant X, exercises every endpoint and asserts that nothing from Y appears, including counts and totals, which is where leaks show first.
It also exercises the paths that bypass the request context: a scheduled report, a queue consumer, and an admin endpoint, because those run without a token and are the usual source of cross-tenant leaks.
And it inspects the database query log during the run for any statement on a tenant-scoped table without the tenant predicate or the row-level security setting, which catches a leak the assertions might miss because the test data happened not to collide.
- "Noisy-neighbour limits: how do you keep one tenant's batch job from starving another's interactive traffic?"
With separate capacity classes rather than one shared limit. Interactive routes and batch routes are different pools at the gateway, each with its own concurrency limit per tenant, so a tenant's export cannot consume the interactive pool.
In the workers, per-tenant queues with a weighted fair scheduler pull work round-robin across tenants, so a tenant with a million queued jobs gets its share and no more.
In the database, statement timeouts per class, short for interactive and longer for batch, and a separate read replica for heavy reads.
Per-tenant cost metrics show who is consuming what, and a tenant exceeding its plan gets throttled with 429 and a
Retry-Afterrather than slowing everyone. For the largest tenants, dedicated pools or a dedicated deployment, priced accordingly.The verification is a load test where one tenant saturates the batch path and the p99 of another tenant's interactive traffic stays flat.
Q142 · Scenario. "After migrating from a monolith to services, the order endpoint's latency doubled and its error rate tripled, though every service is individually fast and healthy. Explain and fix at the API level."
Reveal answer
Strong answer Symptom: the whole is worse than its parts — latency adds and availability multiplies across serial hops. Evidence: a trace of one order request showing the number of hops and whether they are serial; per-hop timeouts and retries; connection setup per call.
Causes ranked: serial calls where parallel is possible; each hop with its own timeout and retries, so a slow downstream becomes an amplified storm; no deadline propagation; new connections per call with TLS handshakes; chatty fine-grained APIs between services that were method calls before.
Fixes at the API level: define a deadline at the edge and propagate it; parallelise independent calls; replace fine-grained service APIs with coarser ones — a BatchGetItems instead of a loop; cache reference data locally with a short TTL; keep connection pools warm with HTTP/2 or gRPC channels; make retries budgeted and only on idempotent calls; and where availability matters more than freshness, serve a degraded response when a non-critical downstream fails.
Prevention: an availability budget per hop derived from the endpoint's SLO, so a five-hop chain of 99.9% services is understood to give 99.5% before any retries, which Chapter E7 covers in depth.
Land it Decomposition turns method calls into network calls, and network calls need deadlines, batching, and budgets — the API between services is where that latency was created and where it is fixed.
- "Do the availability arithmetic for me: five services at 99.9% in series, and what retries change."
If each hop succeeds independently 99.9% of the time, the chain succeeds 0.999 to the power of five, which is about 0.995, so the endpoint is 99.5% available before anything else, and the error rate is five times a single service's.
That is the "error rate tripled" observation with nothing broken.
A single retry on a failed hop, for idempotent calls and only on connection-level errors, turns each hop's effective failure from 0.1% to roughly 0.1% squared, one in a million, if failures are independent, which brings the chain back to near 99.9%.
But retries only help for transient, independent failures; if a hop is down for a minute, retries within that minute all fail and add load, which is why they are budgeted and paired with a breaker.
And retries add latency, so the p99 rises on the retried fraction. The honest budget is: each hop needs to be better than the endpoint's target, by a factor of the hop count.
- "How do you set timeouts per hop from an end-to-end budget of one second?"
Start from the critical path, the longest serial chain in the trace. If the endpoint does orders then inventory then pricing in series, each hop's timeout must leave room for the ones after it.
With a one-second edge deadline, I propagate it as an absolute deadline and let each hop compute its own remaining time, which is the gRPC model and can be replicated over HTTP with a deadline header.
If I must set static timeouts, I set them from the hop's own p99 plus margin rather than from the budget evenly divided: a hop with a 50-millisecond p99 gets 150 milliseconds, not 333, so a slow hop fails fast and leaves budget for the rest.
The sum of static timeouts on the critical path must be under the edge deadline, or the edge will time out while an inner hop is still waiting.
Retries fit inside the same budget, so a hop that retries once needs its timeout to be under half of what remains.
- "The fix list is long. Which one change would you make first and why?"
Deadline propagation, because it bounds every other problem.
Without it, a slow hop anywhere holds resources everywhere and turns latency into cascading failure; with it, the worst case is a fast, clean failure at the edge, and every other fix, parallelisation, batching, caching, can then be measured against a stable baseline.
It is also cheap: a header from the edge, a filter in each service that reads it into a per-request timeout, and the HTTP client configured to respect it.
The second change is the batch endpoints for the chattiest hop, because the trace shows which one that is and the latency win is usually the largest. Retries and breakers come third, because without deadlines they make things worse.
I would show the p99 and error rate after each change so the team sees which ones mattered, which is also how I would justify stopping when the SLO is met.
- "Should you consider merging some of the services back?"
Yes, and I would say so without embarrassment.
If two services always change together, are owned by the same team, and call each other in a tight loop on the hot path, the network boundary between them is cost without benefit, and merging them removes a hop, a contract, and a failure mode.
The decomposition was probably done by data model rather than by team and change cadence, which is the common mistake. The test I apply per boundary: does this boundary let two teams deploy independently, or scale independently, or fail independently in a way the business wants?
If none of those, it is a candidate to fold. Merging is a migration like any other, with the API of the merged service kept stable for external callers.
The goal is not fewer services or more; it is boundaries that match how the organisation changes the system.
Q143 · Design. "Design the sunset of a legacy public API version with 4,000 registered consumers, 600 of them still active, in a way that the business will approve."
Reveal answer
Strong answer Requirements: measurable migration, minimal revenue risk, and a hard end date. The plan: instrument the old version per consumer with call volume and contract value, and rank the 600 by revenue and traffic.
Announce a 12-month sunset with the date in the changelog, email, dashboard banner, and Deprecation and Sunset headers on every response.
Provide a migration guide, an automated diff of each consumer's usage against the new version — which endpoints and fields they touch and what changes for them — and a generated SDK for the new version.
Offer white-glove help to the top 50 by revenue and self-service to the rest. Report monthly to the business: consumers migrated, traffic on old versus new, and revenue still on the old version.
At 3 months before the date, begin scheduled brownouts — one hour weekly, then daily — announced in advance, which converts silent consumers into support tickets while there is time.
At the date, return 410 with a Problem Details body linking the guide, and keep the ability to re-enable per consumer for a short paid extension for anyone with a signed commitment.
Trade-offs: 12 months of dual running; some revenue at risk from consumers who will not move, which the report makes explicit for a business decision. I would not sunset without per-consumer data, would not skip brownouts, and would not extend for everyone because of a few.
Land it A sunset the business approves is a dated plan with a revenue-ranked list, monthly numbers, and brownouts — not a hope that people read the changelog.
- "What are the exact headers and what does a brownout response look like?"
Every response on the old version carries
Deprecation: @1735689600, the RFC 9745 format with the Unix timestamp of when the version became deprecated,Sunset: Sat, 01 Aug 2026 00:00:00 GMTfrom RFC 8594 with the removal date, and aLink: <https://developer.example.com/migrate/v1-to-v2>; rel="deprecation"pointing at the guide.During a brownout the version returns 410 Gone for the announced window with a Problem Details body:
typeofhttps://developer.example.com/problems/version-sunset, adetailsaying that this version is being retired and this is a scheduled test outage, the sunset date, the guide link, andRetry-Afterset to the end of the window.Generated SDKs surface the
Deprecationheader as a warning log, which is a strong reason to have shipped SDKs. The brownout schedule itself is published on the status page as planned maintenance so nobody mistakes it for an incident.- "The business asks why not just keep v1 running forever. What is the real cost?"
The cost is not the servers; it is everything that must be done twice.
Every security fix, every dependency upgrade, and every data-model change must be built and tested against v1's shape as well as v2's, and the v1 shape constrains what the data model can become. Every incident has two code paths to consider. New engineers must learn both.
Consumers on v1 do not get new capabilities, which caps their spend with us. And v1 is by definition the older security posture, which is where the audit findings accumulate.
I would quantify it: engineering hours per quarter spent on v1-specific work, plus the features delayed because of v1 constraints, plus the revenue on v1 that would be at risk if v1 broke, which it will as its dependencies age.
Against that, the migration cost is the white-glove effort for the top consumers and a year of overlap. Framed as a comparison of two costs, the sunset usually wins.
- "At the sunset date, 40 of the 600 are still active, including two large accounts. What happens?"
What the plan said would happen, because the plan was approved with this scenario in it. The 38 small consumers are cut off; they received twelve months of headers, emails, and brownouts, and their support tickets get the guide and an offer of help.
The two large accounts get the per-consumer extension, because the plan reserved it for consumers with a signed migration commitment and a date, and the account owner has already had that conversation in the monthly report where these two appeared as red for months.
The extension is short, 60 to 90 days, priced or at least invoiced internally so the cost is visible, and the route allow-list keeps v1 alive for exactly those two consumer ids.
What I do not do is quietly extend the whole version, because that teaches every consumer that sunset dates are fiction and makes the next sunset impossible.
- "How do you build the per-consumer usage diff against the new version?"
From the gateway's access logs and the two OpenAPI documents. For each consumer, I aggregate the last 90 days of v1 calls into a set of operations and, where request logging allows, the query parameters and fields they used.
I then map each v1 operation to its v2 equivalent using a mapping table the API team maintains as part of the migration guide, and for each I list what changed: renamed fields, changed types, new required parameters, removed operations.
The output is a personalised report per consumer, "you use these 12 operations; 9 are unchanged except for the path, 2 have renamed fields, 1 is replaced by this new endpoint", delivered through the developer portal and by email.
That report is what turns a generic migration guide into a two-hour task for most consumers, and it is what the white-glove engineers use as the agenda for the large accounts.
Q144 · Scenario. "Your API's costs grew 3× while traffic grew 1.5×. Where do you look, from the API's own design outward?"
Reveal answer
Strong answer Symptom: cost growing faster than traffic, so cost per request rose, which points at heavier requests or more waste per request. Evidence: cost by component — compute, database, egress, cache, logging — and request mix by route and consumer over the period.
Ranked causes from the design outward: a shift in mix towards expensive endpoints such as deep list pages, exports, or search; missing caching so reads that were 304s are now full responses, with egress cost per byte; a new consumer with a chatty pattern; payload growth as fields were added and nobody trimmed; logging or tracing at 100% sampling with bodies; retries or polling by clients with no backoff; and, one layer out, database load from N+1 or unindexed filters introduced by a change.
Fixes follow the cause: cost-weighted rate limits so expensive calls are budgeted; ETags and CDN caching; expansion and batch endpoints to replace chatty patterns; payload trimming and compression; sampling and redaction in observability; and the pagination and index fixes.
Prevention: a cost-per-thousand-requests metric by route on the same dashboard as latency, and a cost budget review with each new consumer onboarding.
Land it Cost per request is an API design metric — measure it by route and consumer, and most of the 3× is a handful of patterns you can name.
- "How do you build a cost-per-thousand-requests metric by route when the bill is per resource, not per route?"
By allocation. Compute cost is split by CPU-seconds per route, which the tracing or profiling data gives per request. Database cost is split by query time attributed to routes through the statement's application-name tag or a comment with the route name, which most drivers support.
Egress cost is split by response bytes per route from the access log. Cache and logging costs by operations and log volume per route.
Each of those is a metric the service already emits or can emit cheaply, and a monthly job multiplies them by the unit prices from the bill to produce cost per route, divided by request count.
It is an approximation, and I say so, but a route that costs ten times another per request is real whatever the rounding.
The dashboard shows cost per thousand requests next to latency and error rate, so an engineer designing an endpoint sees its cost the same way they see its p99.
- "The bulk of the 3× turns out to be logging and tracing. How did that happen and what do you change?"
It happens because observability was configured for debugging and never revisited: 100% trace sampling added during an incident and left on, request and response bodies logged at debug level in a service where debug is enabled in production, and log retention at 90 days for everything.
Traffic growth plus payload growth then multiplies a per-request cost that nobody was watching.
The changes: sampling at a few percent with tail-based retention of errors and slow traces; body logging removed, which is also a privacy fix; log levels enforced by configuration that cannot be overridden in production; retention tiered so that access logs keep 30 days and debug logs 3 days; and a cost metric on the observability pipeline itself, with an alert when log volume per request grows week over week.
The last one prevents recurrence, because the next incident will leave something on again.
- "How would you design the API differently in a greenfield to keep cost per request flat as it grows?"
Four design choices, each with a cost reason. Cursor pagination with a capped page size, so no request can scan a large offset.
ETags and conditional GETs on every resource, so repeated reads are 304s with no body and no database read when the cache holds the version. Batch and expand endpoints from the start, so consumers are never pushed into chatty patterns.
And cost-weighted rate limits published in the documentation, so the expensive operations are budgeted per consumer from day one rather than discovered on the bill.
Operationally, a per-route cost metric on the dashboard from the first release and a cost review as part of onboarding each large consumer. None of those is expensive to build early; all of them are painful to retrofit once consumers depend on the cheap-for-them, expensive-for-us patterns.
- "What if the extra cost is one new consumer doing something legitimate?"
Then the cost is real and the question is whether it is priced.
I would look at what they do and whether the API offers a cheaper way to do it: if they poll for changes every second because there is no change feed or webhook, the fix is to build one and move them, which reduces cost for everyone.
If they genuinely need the volume, an export of their catalogue, then the operation should be on a plan that reflects it, and the conversation with the account owner is about pricing, with the cost per thousand requests for their routes as the input.
What I avoid is silently absorbing the cost or silently throttling them; both end badly.
Cost-weighted limits make this automatic for the future: a consumer who exceeds their plan's budget gets a clear 429 and a link to the plan page, and the commercial conversation happens before the bill arrives.
Q145 · Design. "Design an API for a machine-learning model endpoint — scoring requests at 5,000 per second with a 50-millisecond budget — including batching, versioning of the model, and safe rollout."
Reveal answer
Strong answer Requirements: tight latency, high throughput, reproducibility of which model scored what, and rollout without regressions.
Contract: a POST /v1/scores:batch accepting up to 256 instances per request with a typed feature schema, returning per-instance scores and a response-level modelVersion; single-instance calls go through the same path.
Internally, gRPC between the API and the model servers because of rate and typed tensors, with deadlines of 40 milliseconds and dynamic batching at the model server that groups arriving requests for a few milliseconds to fill a batch.
Model versioning is separate from API versioning: the API contract is stable, and the model version is a header on responses and an optional pin on requests for reproducibility, with the default version controlled by a routing rule.
Rollout: shadow scoring where a candidate model scores a copy of traffic and its outputs are compared offline; then a canary by percentage with automated checks on latency and on score distribution drift; instant rollback by changing the routing rule.
Observability: latency per model version, feature schema validation errors, and score distributions over time. Trade-offs: dynamic batching adds a few milliseconds of latency for throughput; pinning versions means old models must stay loaded.
I would not put feature engineering in the API layer where it can drift from training, would not version the model by changing the API path, and would not roll out a model without a distribution comparison.
Land it Stable API contract, model version as metadata, batching inside the budget, and shadow-then-canary rollout — the model changes weekly, the API should not.
- "Explain dynamic batching and how it fits inside a 50-millisecond budget."
Model inference on a GPU or a vectorised CPU path is far more efficient per item when it processes many items at once, so the model server holds arriving requests for a short window, a few milliseconds, or until a batch size such as 64 is reached, then runs them together and splits the results back to each caller.
The trade-off is that the first request in a batch waits up to the window.
With a 50-millisecond budget, I set the API-to-model deadline at 40 milliseconds, the batching window at 5 milliseconds, and measure the model's latency at the target batch size, which must fit in the remaining 30 with margin.
Servers such as NVIDIA Triton and TorchServe expose the window and maximum batch size as configuration, and the right values come from a load test sweeping both against p99.
At 5,000 requests per second a 5-millisecond window yields batches of about 25, which is usually enough to keep the hardware busy.
- "How do you compare score distributions during rollout, and what does a failure look like?"
The shadow model scores the same inputs as the current model, and for each batch I record both scores.
Offline I compare the distributions with simple statistics: mean and percentiles of the score, the agreement rate at the decision threshold, and a population stability index or a Kolmogorov-Smirnov statistic between the two score histograms.
A healthy candidate shows small, expected shifts consistent with the training change.
A failure looks like a large shift in the mean, a collapse of variance where every score clusters near one value, or a segment where agreement drops, say scores for one country diverge while the rest agree, which usually means a feature pipeline mismatch between training and serving for that segment.
The canary then adds live outcome metrics, conversion or fraud catch rate by model version, with the comparison and rollback rules from Q139. The point is that a model can be fast and available and wrong, and only the distribution check sees wrong.
- "What would you cut under time pressure?"
I would cut the version pin on requests and the multi-version serving that supports it, and ship one active model version with the version reported in responses, because keeping old models loaded and routing by pin is real operational complexity.
I would cut the shadow-scoring infrastructure and do the distribution comparison offline on a replay of logged requests, which gives most of the value for a fraction of the build. I would keep the batch endpoint and dynamic batching, because the throughput target needs them.
I would keep the stable API contract with the feature schema validated at the edge and the model version as a response header, because both are contract decisions consumers will build on.
And I would keep an instant rollback by routing rule, because a model that turns out wrong in production must be gone in seconds, not after a redeploy.
- "Why not put feature engineering in the API layer for convenience?"
Because training-serving skew is the most common cause of a model that scores well offline and badly in production.
If the API computes features, such as normalising a timestamp into hour-of-week or bucketing an amount, in Java, while training computed them in Python from a different code path, any divergence, a time zone, a rounding rule, a null handling, produces features the model never saw, and the scores silently degrade.
The fix is one implementation: features are computed by the same library or the same feature store lookup in both training and serving, and the API passes raw inputs plus a schema version.
The API's job is validation, batching, versioning, and observability, and it reports the feature schema version so a mismatch is detectable.
When someone argues convenience, I ask them how they will prove that the Java and Python feature code agree next month, and there is rarely an answer.
Q146 · Scenario. "A consumer's client library sends Expect: 100-continue on large POSTs and reports 1-second delays before every upload. Small requests are fine. What is happening?"
Reveal answer
Strong answer Symptom: a fixed delay on large bodies with a specific header, which is the 100-continue handshake timing out.
Evidence: the client library — older .NET and some Java clients send Expect: 100-continue by default above a size threshold; the delay is exactly the client's continue timeout, typically one second.
Mechanism: the client sends headers and waits for the server to reply 100 Continue before sending the body, so a rejected request does not waste the upload; if the server or a proxy in between never sends the interim response, the client waits for its timeout and then sends the body anyway.
Causes ranked: a proxy or gateway that does not forward or generate 100 Continue; a server framework that ignores the header; HTTP/2 in the path, where the mechanism differs.
Fix: configure the gateway to handle the expectation — most modern proxies do — or advise the consumer to disable the header in their client, and document it in the SDK guide.
Prevention: include a large-POST test through the full production path in the API's synthetic checks.
Land it A one-second delay on large bodies is the continue handshake waiting for a proxy that never answers — fix the proxy, or turn the header off in the client.
- "Which layer should answer 100 Continue, and how do you find which one is dropping it?"
The first hop that terminates the HTTP connection from the client should answer, or transparently forward the expectation to the upstream and relay its answer.
Most modern proxies do: Nginx answers 100 Continue itself when it will proxy the body, Envoy has a
proxy_100_continuesetting to forward it, and cloud load balancers generally handle it.To find the culprit, I reproduce with curl:
curl -v -H "Expect: 100-continue" --data-binary @large.json https://api.example.com/uploadand watch whether theHTTP/1.1 100 Continueline arrives immediately or the body is sent after a delay.Then I repeat against each layer directly, bypassing the CDN, then the load balancer, then hitting the service pod, and the layer where the interim response disappears is the one to configure.
The service itself must also support it: Tomcat and Netty send 100 Continue when the framework reads the body, but a filter that rejects the request early must send a final status instead so the client does not wait.
- "Is Expect: 100-continue worth keeping at all, or should you tell every client to disable it?"
It is worth keeping for large uploads, because it saves the client from sending a multi-megabyte body that the server would have rejected for authentication or size reasons, and that saving is the difference between a fast 401 and a 30-second wasted upload on mobile.
The problem is only that some layer is not honouring it. So my preference is to fix the path so that the expectation is answered within milliseconds, then leave clients alone.
I document the behaviour in the API guide: the server honours
Expect: 100-continueand responds within 100 milliseconds, and clients that disable it are fine too.What I advise against is a global "disable it in your client" note, because it hides the misconfiguration for the next client that sends it, and because the client libraries that send it by default, older .NET and some Java HTTP clients, do so for a reason.
- "Does this happen with HTTP/2 as well?"
In HTTP/2 the mechanism exists formally, the
expectheader is allowed and the server may send an informational 100 response as a HEADERS frame, but in practice it matters less because HTTP/2 flow control already limits how much body a client can send before the server consumes it, so a server that rejects early simply resets the stream and the client has sent at most a window's worth.Most HTTP/2 clients do not send
Expectat all. The case where it reappears is a proxy that terminates HTTP/2 from the client and speaks HTTP/1.1 to the upstream: the proxy must either answer 100 itself or translate, and some do not.So the same reproduction applies, with
curl --http2against each layer, and the diagnostic question is which layer downgrades to HTTP/1.1 towards the service.- "How would a synthetic check have caught this, given it does not hurt small requests?"
Only if the check includes a large body through the production path with the header set, which is why the answer names it as a prevention.
The synthetic client runs, every few minutes, a POST of one megabyte with
Expect: 100-continueagainst a test endpoint that accepts and discards uploads, measures time to the 100 response and time to the final response separately, and alerts if the first exceeds 200 milliseconds.Small-request checks would never see the delay, and neither would server-side latency metrics, because the server's timer starts when the body arrives, after the client's one-second wait.
That gap, client-perceived time versus server-measured time, is the general lesson: the synthetic check measures from where the client stands, which is also why Q79's steady 2% was invisible from inside.
Q147 · Design. "Design a sandbox environment for your public API that lets developers integrate safely, with realistic behaviour, and without touching production data or money."
Reveal answer
Strong answer Requirements: the same contract as production, deterministic test scenarios, isolation, and no real side effects.
Design: a separate deployment of the same API code at a sandbox hostname, backed by its own databases and by simulated versions of external dependencies — a fake payment processor that responds according to magic values, such as a card number that always declines or an amount that triggers a timeout, so developers can test every error path on demand.
Credentials are separate test keys with a sk_test_ prefix, so a test key can never reach production. Data is per developer account, resettable via an endpoint, and seeded with fixtures.
Webhooks fire from the sandbox to developer-registered endpoints with a dashboard that shows deliveries and lets them replay. Rate limits are looser but present, so clients still implement backoff.
Behaviour parity is enforced by running the production contract tests against the sandbox in CI, and the sandbox is deployed from the same build before production, which doubles as a pre-production check.
Trade-offs: the simulators must be maintained alongside real integrations; deterministic magic values are documented behaviour that must not change.
I would not share a database between sandbox and production with a flag, would not stub the API with a mock server that diverges, and would not let sandbox call real third parties.
Land it Same code, separate world, scripted failures — a sandbox is production with the money and the third parties replaced by actors you control.
- "How do you keep the fake payment processor faithful to the real one as the real one changes?"
By treating the simulator as a client of the real processor's contract.
The real integration has contract tests against the processor's own sandbox, and the simulator is tested against the same recorded fixtures: every request and response pair captured from the processor's sandbox, with secrets removed, becomes a test that the simulator must reproduce.
When the processor changes its API, the recorded fixtures update, the contract test fails, the integration is updated, and the simulator's tests fail until it is updated too, all in the same pull request.
The magic values, a card number that declines, are documented behaviours with tests. The simulator's code lives next to the integration code and is owned by the same team.
What I have seen fail is a simulator built once by another team and forgotten; the ownership rule and the shared fixtures are what stop that.
- "A developer says the sandbox does not behave like production for rate limits and timing. Are they right and does it matter?"
They are partly right, and it matters for some things.
Rate limits are deliberately looser so developers are not blocked, but present so backoff code is exercised; I would make the sandbox offer a "strict mode" per account that applies production limits and realistic latency, including simulated slow responses and occasional 503s, which a developer switches on for their final testing.
Timing of asynchronous events, such as a payment settling a day later, is compressed in the sandbox with an endpoint to advance the clock for a test account, which is documented as a sandbox-only feature.
What the sandbox must match exactly is the contract: status codes, error shapes, field names, validation rules, and webhook formats, which the shared contract tests enforce.
The line I draw is "same behaviour, different scale and speed", and the strict mode narrows even that gap for the developers who ask.
- "How do you prevent a test key from ever hitting production, and vice versa?"
Three independent controls. The key prefix,
sk_test_versussk_live_, is checked at the gateway of each environment, and a test key at the production hostname is rejected with a clear error before any lookup, and the reverse too.The key stores are separate databases in separate environments, so even if the prefix check failed, a test key's hash does not exist in production's store.
And the hostnames differ,
sandbox.api.example.comversusapi.example.com, with the SDK selecting the hostname from the key's prefix automatically, so a developer cannot point a test key at production by accident.The error message for a mismatch is specific, "this is a test key; use sandbox.api.example.com", because the most common support ticket for a new integration is exactly that mistake. A test in the pipeline sends each key type to each environment and asserts the rejection.
- "What would you cut under time pressure?"
I would cut the webhook delivery dashboard with replay and the per-account reset endpoint, giving developers a manual reset through support for the first months. I would cut the strict mode and the clock-advance feature.
I would keep the separate deployment of the same code, the separate key prefix and store, the fake payment processor with a small set of magic values, and the contract tests running against the sandbox in CI, because those are what make it a sandbox rather than a mock.
If I had to cut further, I would keep the sandbox as a separate deployment with the real code and a fixed set of seeded fixtures per account, and defer the payment simulator by pointing the sandbox at the processor's own sandbox environment, which most processors offer, accepting that its magic values are theirs rather than mine.
Q148 · Scenario. "A team enabled HTTP response compression on the API and a security scanner immediately flagged it. What is the concern, and when is compression safe?"
Reveal answer
Strong answer Symptom: a scanner flagging compression over TLS, which is the BREACH class of attack.
Mechanism: if a response mixes a secret — a CSRF token, a session id, an API key echoed back — with content an attacker can influence, such as a reflected query parameter, then the compressed size leaks whether the attacker's guess shares bytes with the secret; by varying the guess and measuring size, the secret is recovered byte by byte.
The condition needs all three: compression, a secret in the body, and attacker-controlled content in the same response. For a JSON API that never reflects input into responses containing secrets, compression is safe and worthwhile — payloads shrink 5 to 10 times.
Making it safe by design: never include tokens or secrets in response bodies alongside reflected input; randomise or mask per-response secrets such as CSRF tokens; disable compression on the few endpoints that must echo input and carry secrets; and compress only above a size threshold.
Prevention: the scanner finding becomes a checklist item in the API review for any endpoint that reflects input.
Land it Compression leaks secrets only when a secret and attacker-controlled text share a response — keep them apart and take the bandwidth win.
- "Walk me through the actual attack. How does the attacker measure the compressed size if the response is encrypted?"
TLS encrypts the bytes but does not hide how many there are, so an attacker who can watch the network sees the exact length of every response.
The attacker also needs a way to make the victim's browser send requests with attacker-chosen input, usually a page that fires image loads or fetches at the API with a query parameter set to a guess.
Say the response contains a CSRF token that starts with
3f9aand also reflects the query parameter. If the guess is3f9b, the compressor finds a three-byte match and the response is one byte shorter than for a guess of3f9z.The attacker tries all sixteen hex characters for the next position, keeps the shortest response, and moves on. With about two to five requests per character, a 32-character token falls in a few hundred requests.
That is why the scanner cares: it is cheap and it works through the browser without ever breaking the encryption.
- "You said compression is safe for a JSON API that does not reflect input. How would you verify that claim rather than assert it?"
I would test it rather than reason about it.
First, a static pass over the response shapes: for every endpoint, list the fields that ever carry a token, session id, or key, and separately list fields that echo request input, such as a search echo, a validation error that quotes the bad value, or a name the caller supplied.
Any endpoint on both lists is a candidate.
Second, a dynamic check: for each candidate, send the same request twice with the reflected input set to a prefix of the real secret and to a random string of the same length, then compare the
Content-Lengthof the compressed responses.If they differ consistently, the leak is real.
I would put that check into the API test suite so it runs on every change, because the dangerous case usually arrives later, when someone adds a helpful error message that quotes the input on an endpoint that already returns a token.
- "What if the endpoint genuinely has to reflect input and return a secret, say a form endpoint returning a CSRF token plus a validation error quoting the field?"
Then I break one leg of the three-legged condition, and the cheapest leg to break is usually the secret's stability. Mask the CSRF token per response: generate a random 16-byte pad, XOR the real token with it, and send pad plus masked value.
The server unmasks on receipt. Because the bytes on the wire change every response, the attacker's guess never gets a repeatable match, and the compression side channel gives noise instead of signal. Django and Rails both do this by default now.
If masking is not possible, for example a bearer token that must round-trip unchanged, I disable compression for that route only, with
Content-Encoding: identityforced at the gateway by a route rule, and keep it on everywhere else.The third option, padding the response to a random length, is weaker, because it only slows the attack by forcing more samples per guess.
- "Does TLS 1.3 or HTTP/2 change any of this? The team says modern protocols fixed it."
They fixed a different attack. CRIME attacked TLS-level compression, and that was removed from TLS entirely, so TLS 1.3 has no compression to abuse.
HTTP/2 introduced HPACK for header compression, and HPACK was designed with this exact side channel in mind, using a static table and per-connection rules so that header values from different origins do not compress against each other.
But BREACH is about the response body, which is compressed by the application or gateway with gzip or Brotli before TLS touches it, and neither TLS 1.3 nor HTTP/2 nor HTTP/3 change body compression at all.
So the honest answer to the team is that the protocol upgrades closed the header and transport variants, and the body variant is still entirely our responsibility.
As of Aug 2026 there is no protocol-level fix planned, because the server is the only party that knows which bytes are secret.
- "What does compression cost, and where would you enable it, the service or the gateway?"
Compression costs CPU on the sender and buffering on both sides.
With gzip at level 5 or 6, a 100-kilobyte JSON body takes roughly one to two milliseconds and shrinks about eight times, so for an API doing 5,000 responses a second that is a few cores of work and a large bandwidth saving, which is usually a good trade.
Brotli at quality 4 gives a bit better ratio at similar cost, and levels above 6 are for static assets, not dynamic responses.
I would enable it at the gateway or the ingress rather than in each service, because that gives one place for the route-level exclusions, one
min_lengththreshold, say 1 kilobyte, since small bodies get bigger when compressed, and one place to honourAccept-Encodingcorrectly with aVary: Accept-Encodingheader so caches store one copy per encoding.Services then keep sending plain bodies, and the compression policy is auditable in one configuration file.
Q149 · Design. "Design the on-call runbook entry for 'the API is slow' — the first ten minutes, in order."
Reveal answer
Strong answer Requirements: narrow the blast radius fast, avoid guessing, and know when to escalate.
Minute one: confirm from the outside — the synthetic check and the gateway's p99 by route — and check whether it is all routes, one route, or one consumer, and whether error rate moved with latency.
Minutes two to three: check for a change — deployments, feature flags, configuration, certificate or key rotations, traffic spikes by consumer — in the last hour; roll back the most recent change if the timing matches, before understanding why.
Minutes four to six: if no change, look at saturation in order — connection pool wait time and queue depth, thread pool or event loop saturation, CPU and GC pauses, then the database's active queries and locks from Chapter E8's checklist, then downstream latency from traces.
Minutes seven to eight: mitigate — shed load for the heaviest consumer or route, raise the rate limit's strictness, scale out if CPU-bound, kill a runaway query, fail over a downstream to its fallback.
Minutes nine to ten: communicate — status page update with impact and next update time, and escalate to the owning team of whichever layer showed saturation. Throughout, write down timestamps and what was checked for the postmortem.
What the runbook says not to do: restart everything at once, change several things simultaneously, or debug code before checking for a change.
Land it Outside in, change first, saturation second, mitigate before understanding — and write it down, because the postmortem is where the next ten minutes get shorter.
- "You rolled back the most recent deploy at minute three and latency did not improve. What do you do next?"
First I confirm the rollback actually took effect, because that is where a lot of incidents lose ten minutes: check the running version label on the instances and confirm traffic is hitting the old build.
If it really is rolled back and nothing changed, the deploy was a coincidence and I move to the saturation ladder without regret; a two-minute rollback that rules something out is cheap.
I then widen the change window, because the cause may be a change that is not a deploy: a scheduled job that started at the top of the hour, a partner who launched a campaign, a certificate rotation that made every client re-handshake, a database autovacuum or a migration adding an index.
The gateway's traffic-by-consumer graph and the database's active-session count are the two views that separate "we got slower" from "we got busier". If neither moved, the next suspect is a downstream, and the trace waterfall for a slow request tells me which span grew.
- "How do you decide whether to shed load, and what exactly do you shed?"
I shed when the system is saturated, meaning queue depth or pool wait time is growing rather than steady, because in that state adding capacity takes minutes and doing nothing makes every request slow instead of some requests failing fast.
What I shed, in order: the heaviest single consumer if one is out of proportion, using a per-client concurrency cap at the gateway; then the non-critical routes, such as exports, reports, and analytics reads, which get a 503 with
Retry-After; then reads before writes, because a write lost is a support ticket and a read delayed is a refresh.I would never shed uniformly at random first, because that degrades everyone equally including the checkout path.
The mechanism is a priority tag on each route, set in the gateway configuration in advance, so during the incident the action is flipping one setting, not editing rules under pressure. Afterwards the shed count goes into the postmortem as an impact number.
- "What would you add to this runbook if the API were fronted by a CDN and served ten times the traffic?"
At that scale the first minute changes: I would check whether the CDN's cache hit ratio dropped, because a cache-key change, a new
Varyheader, or a purge can send ten times the normal origin traffic in seconds and looks exactly like "the API is slow".So minute one gains three numbers: edge hit ratio, origin request rate, and the CDN's own error and latency view, which separates edge problems from origin problems.
I would also add regional views, because at ten times the traffic a single-region degradation shows up as a blended p99 that hides the fact that one region is on fire.
The mitigation list gains two items: raise TTLs or enable stale-while-revalidate at the edge to shield the origin, and enable the CDN's origin request coalescing so a thousand identical misses become one origin call.
And the escalation includes the CDN vendor's status and support path, with the account id written in the runbook.
- "What would you cut from this runbook under time pressure, and what would you never cut?"
Under pressure I would cut the detailed saturation ladder down to three checks: pool wait time, database active sessions, and the slowest downstream span in a trace, because those three catch most causes and the rest can wait for the postmortem.
I would also cut the status page update from a written paragraph to a template with two fields, impact and next update time.
What I would never cut is the change check, because it is the single highest-yield question and it takes one minute; the rule of one change at a time, because two simultaneous mitigations mean nobody knows which one worked; and the timestamped notes, because without them the postmortem is guesswork and the next incident is no shorter.
The honest version of this answer is that the runbook is already the cut-down version; the full playbook lives in the wiki, and the runbook entry is the ten lines that fit on one screen.
- "How do you verify in production that the runbook works before an incident forces you to?"
I would run it as a drill.
Pick a low-traffic window, inject a controlled slowdown — a 200-millisecond artificial delay on a downstream call using the mesh's fault-injection or a feature flag — and have the on-call engineer follow the runbook cold, timed, with an observer writing down every place they hesitated or opened a dashboard that was not linked from the runbook.
That drill checks the things you cannot check by reading: that the dashboard links still resolve, that the rollback command works under the current deploy tool, that the load-shedding flag actually sheds, and that the person on call has the permissions to do all of it.
I would do this quarterly and after every major platform change. The output is a diff to the runbook, not a report. A runbook nobody has executed in six months should be assumed broken, in the same way a backup nobody has restored should be.
Q150 · Design. "You have one week to review a partner team's new public API before launch. What do you check, in what order, and what would make you block the launch?"
Reveal answer
Strong answer Day one, the contract: an OpenAPI document exists, passes the conventions linter, and matches the running service under response validation; the breaking-change definition and version strategy are written down; errors are RFC 9457 with a type registry.
Day two, correctness under failure: every create has an idempotency key, every list is cursor-paginated with a capped limit and indexed sort, long operations return 202 with an operation resource, and timeouts and deadlines exist.
Day three, security: OAuth2 with audience and algorithm pinned, scopes per endpoint, the two-user object-level test on every id endpoint, DTOs not entities on writes, SSRF controls on any URL input, rate limits per consumer, no secrets in URLs or logs.
Day four, operations: request ids in responses and errors, tracing across the chain, p99 per route dashboards, an SLO, graceful shutdown proven under load, and a runbook.
Day five, the consumer's experience: a sandbox, a generated SDK that handles retries and pagination, a changelog, and a deprecation policy with headers.
I would block for any of: no idempotency on money-moving POSTs, missing object-level authorisation, offset pagination on an unbounded collection, secrets in query strings, or no contract gate in CI — because each is an incident with a date, not a style preference.
Everything else becomes a prioritised list with owners and a follow-up date.
Land it Contract, failure, security, operations, experience — and block only for the five things that are outages or breaches waiting to happen.
- "The partner team says the launch date is fixed and they can fix only two of your five blockers in time. Which two, and what happens to the other three?"
The two I would insist on are object-level authorisation and idempotency on money-moving POSTs, because those are the two whose failure is irreversible: a data breach cannot be un-leaked and a double charge is a refund plus a lost customer.
The other three are bad but bounded. Secrets in query strings leak into logs, so I would mitigate rather than fix: scrub the query string at the gateway's access log and set a thirty-day sunset on that parameter.
Offset pagination on an unbounded collection is a slow-burning performance problem, so I would cap the offset at, say, 10,000 and cap the page size at 100 at the gateway, which turns a future outage into a documented limit.
A missing contract gate is a process risk, so I would require the OpenAPI document to be versioned and frozen at launch and get the CI gate added within the first sprint.
Each of the three gets an owner, a date, and a line in the launch notes, and I would put that in writing to the partner team's manager, not just in a chat.
- "How would you actually run the two-user object-level authorisation test across an API with sixty endpoints in one day?"
I would automate it rather than click through it. From the OpenAPI document I generate the list of endpoints that take an id in the path or body.
Then I create two tenants with two users and one resource each, and a script that, for every endpoint, calls it as user A with user B's id, and asserts on a 403 or 404 rather than a 200 or a 500.
It runs in under an hour for sixty endpoints.
What the script cannot catch, I sample by hand: endpoints where the id is indirect, such as a filter parameter that accepts an account id, bulk endpoints that take a list of ids where one belongs to another tenant, and endpoints that return related objects, where the parent is checked but the children are not.
I also read the code for the authorisation check itself, because the common bug is a check that runs on the controller path but not on a second code path, such as an export or a search that bypasses the repository method that does the check.
- "What if the requirement changed and this were an internal API for two other teams, not a public one? What would you drop from the review?"
For an internal API I would drop most of day five: no sandbox, no published SDK, no formal deprecation policy, because the consumers are two teams I can talk to.
I would relax the versioning strategy to "additive changes only, and coordinate the rest", enforced by a contract test rather than a policy document. Rate limiting per consumer becomes optional and a bulkhead in the caller becomes the substitute.
What I would not drop, even internally: idempotency on writes, because an internal retry storm double-charges just as well as a public one; timeouts and deadlines, because an internal API with no timeout is how one slow team takes down three; and RFC 9457 errors with request ids, because the on-call engineer debugging across teams needs them more, not less.
The security day shrinks but does not vanish: service-to-service authentication and the object-level check stay, because "internal" networks are one misconfigured ingress away from being external.
- "Why is offset pagination on an unbounded collection a launch blocker rather than a performance ticket?"
Because its cost grows with the customer's success and the failure arrives on a date.
An offset query like
LIMIT 100 OFFSET 500000makes the database read and discard half a million rows before returning a hundred, so page 5,000 costs 5,000 times what page one costs.A partner who syncs by walking every page nightly will do that every night, and as the table grows, one night the query crosses the statement timeout and their sync breaks, usually at two in the morning.
Worse, once a public API ships offset pagination, changing it is a breaking change for every client that stored a page number, so the fix gets harder each month.
Cursor pagination, where the response carries an opaque token encoding the last row's sort key and the next query does
WHERE (created_at, id) < (?, ?)against an index, keeps every page at the cost of page one.I would block for a day of work now over a year of pain later, and I would say that with the growth number: at their projected row count the timeout is crossed in about four months.
- "After the review, how do you check in production that the things you approved actually behave as reviewed?"
I would turn each review item into something observable. The contract gate becomes a dashboard tile showing the response-validation mismatch rate from the gateway, which should read zero after launch.
Idempotency becomes a counter of replayed requests served from the key store, which proves the mechanism is exercised. Object-level authorisation becomes the two-user test running nightly against production with synthetic tenants, alerting on any 200.
Pagination becomes a p99-per-page-depth graph, which stays flat under cursors and climbs under offsets. Timeouts become a histogram of upstream call durations with a hard ceiling at the configured value; if I see durations above it, the timeout is not wired.
And the runbook gets its first drill in week two. The point is that a review is a snapshot, and the only way to keep it true is to make each finding a number someone looks at.
11 · RecapWhat You Can Do Now
- You can explain what each HTTP method promises to a proxy that has never read your docs, and why a GET with side effects is a correctness bug
- You can design an idempotency key store that survives a lost response, a crash between the claim and the write, and two retries in the same millisecond
- You can write the keyset query and the index that make page 150,000 cost the same as page 1, and say what you gave up
- You can define "breaking change" precisely, put it in a CI gate, and run a sunset with headers, brownouts, and a revenue-ranked list
- You can explain why gRPC load piles onto one pod, derive Protobuf's evolution rules from the wire format, and propagate a deadline through a chain
- You can run GraphQL safely — DataLoader on every relationship, depth and cost limits at validation, persisted queries for caching — and say when to refuse it
- You can validate a JWT the way an audit expects: algorithm pinned, issuer and audience checked, keys refreshed on rotation, tokens sender-constrained where they leak
- You can choose REST, gRPC, GraphQL, or events from who calls, how often, whether they need an answer now, and whether they can be down independently
Close the page and write down, from memory: the three states an idempotency-key record can be in and what the server returns for each on a repeated request; the SQL row-value comparison and the index for a newest-first cursor; and the five JWT checks a resource server must make before looking at scopes. Then reach back to Chapter E8: which isolation level and which locking pattern does If-Match on a PUT correspond to, and what does the database return when the precondition fails?