Skip to content
Tech Interview Prep
Technical interview guide

Working with APIs & Technical Specs

Reading and reviewing technical specs and API contracts well enough to catch problems before they ship.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: OpenAPI 3.2.0, HTTP RFC 9110/9111, Problem Details RFC 9457, OAuth Security BCP RFC 9700, JSON Schema 2020-12, OWASP API Top 10:2023, gRPC, Protobuf proto3, and W3C Trace Context current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-21

Review a spec that uses 200 for every response.

Answer

Stance. Treat this as a protocol bug, not a style preference. The status line is the only field every intermediary (CDN, gateway, service mesh, generated SDK, retry library, dashboard) parses without knowing your schema. Overloading 200 deletes that signal. Before approving the spec I'd want three answers: public or internal, are there shipped consumers, and what sits in front of it (shared cache, API gateway, generated clients)? Those decide whether you fix it in place or version it.

The mapping.

OutcomeStatusNotes
GET success200
POST created201plus Location
Accepted, async202
DELETE, no body204
Malformed syntax400
Missing/invalid credentials401plus WWW-Authenticate
Authenticated, not allowed403
Unknown resource404
Wrong method405plus Allow
State conflict409
Precondition412 / 428
Semantic validation422
Rate limited429plus Retry-After
Upstream failure502 / 503 / 504
Unhandled500

Domain detail belongs in the body as RFC 9457 problem details: application/problem+json with type, title, status, detail, instance. The status member must equal the status line: a mismatch is its own bug.

Why it breaks: the mechanism.

Caching. RFC 9110 §15.1 lists 200 as heuristically cacheable. A shared cache may store a 200 that carries no explicit freshness and reuse it. Trace: client A sends GET /orders/42 with an expired token; the server replies 200 with {"error":"token_expired"} and no Cache-Control. The cache stores it. Client B, a different user with a valid token, requests the same URL and is served A's error body as a fresh 200. 401 is not heuristically cacheable, so the correct status would have prevented this outright. Fix: correct statuses plus Cache-Control: no-store on error responses.

Retry. Retry middleware keys on status. A POST /payments returning 200 {"status":"failed","retryable":true} is never retried by a client that retries on 5xx/429: the payment is silently dropped. Invert the middleware to retry on 200-with-error and you replay a non-idempotent POST; without an Idempotency-Key you double-charge. 429 with Retry-After is the one case where the status line tells the client exactly what to do.

Circuit breaking. Envoy outlier detection and most mesh breakers eject hosts on consecutive 5xx. All-200 means a dead dependency keeps taking traffic.

Monitoring. SLO burn-rate alerts, APM error rates and gateway dashboards all classify on status. Everything is 200, so the error budget never burns and nothing pages.

Generated clients. OpenAPI-generated clients throw typed exceptions on non-2xx. With all-200 every caller hand-parses the body and the error taxonomy leaves the type system.

Failure modes and how you'd catch them.

  • Cross-user error served from cache: send a synthetic request with a bad token, then one with a good token, and assert the second isn't the first's body; watch cache hit ratio on error paths.
  • Silent payment drop: count Idempotency-Key duplicates and compare accepted against attempted POSTs.
  • Undetected outage: alert on divergence between the 200 rate and the error field inside the body. That divergence is the migration's own smoke alarm.
  • Breaker never trips: confirm Envoy's outlier_detection.ejections_enforced_total is non-zero during a known dependency failure.

Migration. If consumers already parse the envelope, don't flip statuses under them. Negotiate: serve the old shape on the existing media type or path, the corrected one on a new version, log which clients use which, and set a deprecation date. Canary it and watch the divergence metric above.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design a useful API error model.

Answer

Core answer. Use RFC 9457 application/problem+json (it obsoletes RFC 7807) and split every error across two axes clients branch on separately: the HTTP status code for the coarse class that proxies, SDKs and retry libraries already understand, and a stable type URI that is the real contract. Nothing should require parsing prose.

Two axes because status codes are a closed set of roughly sixty values shared by the whole ecosystem: they cannot distinguish "insufficient funds" from "card expired". Type URIs are open-ended, dereferenceable to docs, and versionable: you can ship .../v2/insufficient-funds without touching the status. The cost is that clients must handle an unknown type, so define the default explicitly: unknown type means non-retryable, log instance, show title.

Retry semantics are the one thing clients cannot infer, so make them explicit. Don't make a retryable boolean the primary signal: use Retry-After on 429 and 503, which proxies and SDKs already honour. A boolean is a hint; the header is the mechanism.

FailureStatusRetry?Client action
Unparseable body400nofix request
Field validation422nofix fields via errors[]
Missing/expired token401 + WWW-Authenticate: Bearer error="invalid_token"once, after refreshrefresh, then retry
Authenticated, not permitted403nostop, surface to user
Version conflict (If-Match)412nore-read, re-apply
Idempotency key reused, different body409nonew key
Rate limited429 + Retry-Afteryes, after delaybackoff
Dependency down503 + Retry-Afteryesbackoff with jitter
Bug500maybe oncereport instance
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
Cache-Control: no-store

{
  "type": "https://errors.example.com/validation-failed",
  "title": "Validation failed",
  "status": 422,
  "detail": "2 fields are invalid.",
  "instance": "/requests/01HQ8Z2K9V",
  "errors": [
    {"pointer": "/amount",   "code": "AMOUNT_NOT_POSITIVE"},
    {"pointer": "/currency", "code": "CURRENCY_UNSUPPORTED"}
  ]
}

422 is "Unprocessable Content" in RFC 9110 (renamed from RFC 4918's "Unprocessable Entity"). pointer is an RFC 6901 JSON Pointer, so a client can highlight the exact field without string matching.

Trace: idempotent retry. Using the IETF Idempotency-Key draft header:

POST /payments  Idempotency-Key: 7f3c…  {"amount": 50.00}
→ 201 Created, Location: /payments/p_8812

client times out, retries the identical request
POST /payments  Idempotency-Key: 7f3c…  {"amount": 50.00}
→ 201 Created, Location: /payments/p_8812   (stored response replayed; no second charge)

same key, different body
POST /payments  Idempotency-Key: 7f3c…  {"amount": 75.00}
→ 409 Conflict, type .../idempotency-key-reuse

The 409 is the design decision: silently charging 75.00 would be worse than failing, and the client can tell the two cases apart without reading detail.

Trade-offs. If you are gRPC-first, google.rpc.Status with Any-packed details is the better fit: the status enum is already machine-readable and the details carry structured payloads. Problem+json wins on HTTP because every gateway, CDN and off-the-shelf client library already understands it. A bespoke envelope only beats both when you must carry a large structured payload (a full validation report) or every client is first-party and you ship the SDK; the price is losing all that free ecosystem handling.

Failure modes and how you catch them.

  • Internals leaking. Stack traces, SQL or internal hostnames in detail. Detect with a CI assertion that no error body matches a denylist (Exception, SELECT, internal hostnames), plus a canary endpoint that throws and must return a generic 500 carrying only instance.
  • Gateways rewriting bodies. Some ingress controllers replace 4xx/5xx bodies with HTML. Detect with a contract test through the real ingress, not the app port, asserting Content-Type: application/problem+json and that type survives.
  • 401/403 confusion. Clients retry 403 forever. Alert on both rates: a 401 spike means token refresh broke, a 403 spike means an authorization rule changed.
  • Unmodelled paths. Count responses where type == "about:blank"; that ratio is your coverage metric for the error model.
  • Idempotency-key reuse. A rising 409 rate is a client retry bug, not a server one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you choose and declare a versioning scheme for an API, and what does that choice commit the team to?

Answer

Core. Versioning is a contract-management decision, not a naming one. Two facts decide the scheme: who consumes the API, and how fast the contract changes. For a public or partner HTTP API I default to a major version in the URI path, /v2/orders, because it is visible in access logs, CDN cache keys, gateway routes and a curl command, and adopting it needs no client library change. Header and media-type versioning are more faithful to REST's resource model, but they push the version into a dimension most caches and log pipelines ignore, so they cost Vary correctness and discoverability.

SchemeDeclared inCache keyClient sees it
Path /v2/ordersservers[].urlURL alonein every log line
Header X-API-Version: 2required header parameterneeds Vary: X-API-Versiononly if echoed back
Media type Accept: application/vnd.acme.v2+jsoncontent mapneeds Vary: Acceptonly if echoed back

What counts as breaking. A consumer that worked yesterday fails today. Removing or renaming a field, tightening a schema (adding additionalProperties: false, turning a free string into an enum), changing a type or unit, changing the problem type URI or status codes, changing the default page size, changing an OAuth scope, or changing idempotency semantics. Adding an optional response field is non-breaking for a tolerant reader and breaking for a strict one: proto3 ignores unknown fields, a JSON Schema client with additionalProperties: false rejects them. That asymmetry is why the versioning scheme and the client-generation strategy have to be chosen together.

Declaration. The trap is info.version in OpenAPI: it versions the document, not the API. Setting info.version: 2.0.0 versions nothing. The API version must live where the request can carry it.

yaml openapi: 3.2.0 info: title: Payments API version: 2.4.1 # document revision, not the API version servers:

  • url: https://api.acme.com/v2 # this is the API version paths: /orders: get: parameters: - name: X-API-Version in: header required: true schema: { type: string, enum: ["1", "2"] }

Introduce and retire. Ship v2 alongside v1; never mutate v1 in place. Serve both from one codebase behind a routing layer so v1 contract tests keep running. Mark v1 deprecated with a response header on every v1 response and a published sunset date, then return 410 Gone after it, not 404, which clients read as a wrong URL and retry. Do the arithmetic before committing: a major every 9 months with a 24-month support window means three live versions at steady state, each with its own test matrix, security review and on-call surface. If that is too much, lengthen the interval or make changes additive.

Discovery. A client should never have to guess which version answered. Echo it in a response header, or make it self-evident in the path. For header and media-type versioning, an unsupported value must fail loudly with 406 Not Acceptable or 400 rather than silently falling back to the default: silent fallback is how a client ships against v1 while believing it is on v2.

Failure modes. Header versioning without Vary lets a CDN serve a v1 body to a v2 client; detect it by comparing the echoed version header against the cache hit ratio. A gateway route that strips the path prefix sends every version to the latest handler; detect it with a contract test per prefix. Clients sending Accept: */* get the default media type silently; detect it by logging the Accept distribution. Two services both claiming v2 with different shapes means the version was declared in prose, not in the spec.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Decide whether an API change is backward compatible.

Answer

Core answer (say this first). Backward compatibility is a property of the consumers, not of the schema. A change is backward compatible when every client already in production keeps parsing the new responses and keeps getting the behavior it was written against, with no client redeploy. So the decision is: list the consumers you cannot redeploy on your schedule, and for each change ask whether it alters bytes or meaning that an existing reader depends on. If it does for any of them, it is breaking: no matter what the schema diff says.

State your assumptions out loud: direction (old client against new server. That is what "backward" means), whether all consumers are internal and deployable together, and the wire format (protobuf binary, protojson, or plain JSON), because the format decides most of the answers.

Why "additive is safe" is only presumptive. Unknown-field handling is a reader setting, not a schema property. Jackson's ObjectMapper fails on unknown properties by default (FAIL_ON_UNKNOWN_PROPERTIES is on); Spring Boot's auto-configured mapper turns it off. The same added field is a no-op for one Java service and a 400 for the next. Protobuf binary ignores and preserves unknown fields (since 3.5), but the protojson spec says parsers should reject unknown fields by default. Identical schema change, opposite outcome.

ChangeVerdictWhy
Add optional response fieldSafe only if readers tolerate unknownsJackson default and protojson default both reject
Add required request fieldBreakingOld clients never send it
Remove or rename a response fieldBreakingReaders that bind it get null or throw
Reuse a protobuf field number with a new typeBreaking, silentWire types collide; values decode as garbage
Add an enum valueDependsproto3 enums are open; a Java closed enum throws
int32 to int64 in JSONBreaking for JS clientsValues above 2^53−1 round silently
Change units (s to ms)Breaking, silentNo parse error, wrong numbers
200-with-error-body to 4xxBreakingClients that only check status now throw

Failure modes and how you catch them. A Java consumer with a closed enum throws InvalidFormatException on a new value unless READ_UNKNOWN_ENUM_VALUES_AS_NULL is set, and the error surfaces on the consumer's dashboards while the provider stays green, so watch consumer 5xx, not provider 4xx. An int64 sent as a JSON number is worse: JavaScript clients round above 2^53−1 with no error at all, detectable only by asserting values (a checksum or canary comparison), not by status codes. Stored payloads are the third trap: Kafka events, cached responses and DB rows written under the old schema fail revalidation under a stricter new one. Replay the last N days of stored payloads through the new validator before shipping.

Choosing between the options. Ship the additive change when every consumer is verified tolerant. Dual-serve (emit both shapes for a window) when meaning must change but consumers cannot move at once: it costs a compatibility branch and a doubled test matrix, so give it a deadline. Version the surface (a new /v2 path, or a new protobuf field number with the old one deprecated) when consumers are external or unknown; you pay for two code paths until the deprecation date. Coordinate the deploy when you own every consumer and can ship atomically: cheapest, but only valid if your consumer list is actually complete.

Tooling that makes this checkable: buf breaking for protobuf, oasdiff for OpenAPI, Pact for consumer-driven contracts, plus shadow traffic against the new version before cutover.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Introduce a new required field into an API workflow.

Answer

What I'd say in the first two minutes

"Required" is three separate switches, and they don't have to flip together: required in the wire contract (the server rejects a request that omits it), required in storage (the column is NOT NULL), and required in the domain (the business rule says every charge has a currency). The mistake is flipping all three at once, because the wire switch is the only one that breaks clients you don't control.

Assumptions: a JSON/HTTP API described by OpenAPI, Postgres behind it, and a client population I can't force-upgrade. Mobile apps and partner integrations. If I owned every client and could deploy them in lockstep, I'd add the field and move on; everything below is about the case where I can't.

The rollout

Phase 1: add it optional, accept and synthesize. The field is optional in the schema. When a request omits it, the server derives a value and records that it derived it. It never rejects.

Phase 2: backfill and instrument. Backfill stored rows where the value is derivable from data you already have. Emit a counter per client version for synthesized writes.

Phase 3: enforce. Only when the synthesized-write counter is zero across a full traffic cycle (a week, to cover weekly batch jobs) do you make it required.

Phase 1 must accept-and-synthesize rather than reject because an old client omitting the field is not sending a malformed request; it's sending a request that was valid when it shipped. Rejecting turns a schema change into an outage for every un-upgraded client.

The failure mode that bites

Silent default corruption. Default currency to "USD" and every old client's writes get labeled USD whether or not that's true. You now have rows indistinguishable from genuinely-USD rows, and the default becomes a reconciliation incident months later. Detection is the synthesized-write counter, tagged by client version and by the value synthesized. If you can't tell defaulted rows from real ones, you can't enforce, and you can't backfill correctly either. The fix is to make the derived value actually derivable (from the account's currency, say) not a constant.

Worked trace (Python 3.12, illustrative)

Python
def validate_charge(body, client_version, metrics):
    if "currency" not in body:
        derived = account_currency(body["account_id"])
        metrics.incr("charge.currency.synthesized",
                     tags={"client": client_version, "value": derived})
        body["currency"] = derived
    if body["currency"] not in SUPPORTED:
        raise ValidationError(422, "currency")
    return body

Three requests through it:

  1. New client sends {"account_id": "a1", "currency": "EUR"} → no synthesis, counter untouched.
  2. Old client (v3.2) sends {"account_id": "a1"} → derived "EUR" from the account, counter charge.currency.synthesized{client=v3.2, value=EUR} +1.
  3. Old client sends {"account_id": "a9"} where the account has no currency set → derivation fails. This is the case that decides the design. Reject and you break the client; pick a constant and you get silent corruption. The honest answer is you cannot enforce requiredness until a9-style accounts are resolved, so the derivation-failed counter is the real gate, not the synthesized counter.

Trade-offs and when not to

  • If the field is genuinely optional in the domain, don't make it required at all. Enforce it in the client's form validation and leave the wire optional.
  • If you can version the API, make it required in /v2 and leave /v1 alone. Cost: two code paths and two sets of docs. Benefit: no synthesis window.
  • If you can't tolerate a synthesis window at all (regulated data, say) the alternative is a hard cutover with a coordinated client release. That's only viable when you own the clients.

Arithmetic to size the window: if 0.4% of 2M daily requests come from clients older than 18 months, enforcing early breaks 8,000 requests/day. That number, not a calendar, decides whether the window is two weeks or two quarters.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Plan the deprecation of a widely used endpoint.

Answer

Treat this as a migration with a deadline, not an announcement. The endpoint is dead when the last consumer stops calling it, so the plan is: make every caller visible and attributable, ship a replacement that is at least as good, then delete the old path only after traffic has been zero for a sustained window.

Assumptions I'd state up front: it's an internal HTTP API, say GET /v1/users/{id}/profile, we control the server and the internal clients, and a handful of external partners may be on contract. If partners are involved, the support window is set by contract, not by us.

Attribution comes first. You cannot deprecate what you cannot see. Add a per-consumer identity to every request: API key, OAuth client_id, mTLS cert CN, or at minimum a User-Agent carrying service name and version. Without it, shadow consumers are invisible and the sunset date is a guess. Pull 90 days of access logs and group by that identity.

Classify, because the long tail is the real work.

Consumer classCountShare of trafficNoticeExit criterion
Owned internal services34080%90 days0 requests for 14 days
Partner (contractual)618%180 days0 requests for 30 days
Unattributed / shadow?2%n/aidentified, then owned

335 of 346 consumers may be 20% of traffic but 100% of the "who do I email" problem. The 6 partners are 18% of traffic and the only ones who can block you.

Publish machine-readable deprecation. Return Deprecation and Sunset headers on every response (RFC 9745, RFC 8594):

HTTP
HTTP/1.1 200 OK
Deprecation: Tue, 01 Apr 2025 00:00:00 GMT
Sunset: Wed, 01 Apr 2026 00:00:00 GMT
Link: <https://api.example.com/v2/users/{id}/profile>; rel="successor-version"

After the sunset date, return 410 Gone with the same Link header, not 404, so callers can tell "removed on purpose" from "typo".

Make migration cheap. Ship a compatibility shim or adapter so a consumer switches with a config change, not a rewrite. Dual-run: call both endpoints, diff responses, alert on divergence. That catches behavior drift (null vs empty string, changed pagination, different error codes) before it becomes a production incident.

Track adoption, not announcements. The metric is requests to the old endpoint per consumer, not email open rates. Alert when a consumer's traffic is flat for 7 days; escalate at 30 days before sunset.

Failure modes worth naming:

  • A monthly cron caller looks migrated in aggregate. Detect with per-consumer last-seen timestamps, not totals.
  • Unattributed traffic you cannot email. Detect via egress proxy or service-mesh logs.
  • A security fix lands mid-window. You still patch the old endpoint; budget the engineering time.
  • Path reuse. Reserve the old route so a future team does not resurrect it by accident.

Removal. Delete the route, then the backing code, then the credentials and infrastructure: only after the sustained-zero window and with a rollback plan. Keep the route reserved.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Resolve disagreement over REST versus gRPC.

Answer

Core answer (first 60–120 seconds): Separate the two traffic directions. Internal service-to-service (east–west) and external client-to-server (north–south). The disagreement usually comes from trying to pick one for both. For internal services you control, gRPC is the better default. For browsers, partners, or public APIs, REST/JSON over HTTP is usually right. If you need both, bridge with grpc-gateway or Envoy.

Why gRPC needs HTTP/2: gRPC uses HTTP/2 for multiplexed streams over one TCP connection, binary framing, and trailers for status. HTTP/1.1 cannot multiplex, so gRPC requires HTTP/2. That gives no head-of-line blocking at the HTTP layer, lower per-call overhead, and native unary, server streaming, client streaming, and bidirectional streaming. Protobuf encodes fields as tag–value pairs with varints. Suppose a 1 KB JSON payload; the equivalent protobuf message is ~200 bytes. At 10k req/s, that is 80 Mbps versus 16 Mbps: a 5x bandwidth reduction. Deadlines propagate through the call chain, so a slow downstream does not hang the whole graph.

Why browser reach requires grpc-web: Browsers do not expose HTTP/2 trailers to JavaScript, so gRPC cannot be called directly from fetch or XHR. gRPC-Web solves this with a proxy (Envoy, grpc-gateway) that translates to HTTP/1.1 or HTTP/2 with base64 encoding. It supports unary and server streaming only: no client or bidirectional streaming. REST also gives human-readable payloads, curl, Postman, and OpenAPI for documentation and code generation.

Deciding criteria: If you need streaming, strict schemas, and low latency between polyglot services, gRPC. If you need broad reach, easy debugging, and cache-friendly semantics, REST. When not to use gRPC: browsers without a proxy, or a team without protobuf tooling and a loose latency budget. When not to use REST: bidirectional streaming or sub-10 ms p99 between services, or when payload size dominates cost.

DimensionREST/JSONgRPC
TransportHTTP/1.1 or HTTP/2HTTP/2 required
PayloadText JSON, ~1 KB typicalBinary protobuf, ~200 B typical
StreamingSSE, chunked, no bidirectionalUnary, server, client, bidirectional
BrowserNativeNeeds grpc-web proxy
SchemaOpenAPI, JSON Schema.proto, field numbers
Debuggingcurl, browser devtoolsgrpcurl, grpcui, reflection
GovernanceOpenAPI diff, contract testsbuf breaking, reserved fields

Failure modes: With gRPC, forgetting a deadline can exhaust your thread pool and cascade. Detect it with context deadline exceeded errors and a rising p99. With REST over HTTP/1.1, a burst of small requests can exhaust the connection pool and cause head-of-line blocking. Detect it with connection wait time and p99 latency. Schema evolution: in gRPC, changing a field number or removing a field without reserved breaks old clients; catch it with buf breaking in CI. In REST, changing a field type breaks consumers; catch it with OpenAPI diff and contract tests.

Worked decision: A team argues about a new internal API for a payment service. It must stream transaction events to a fraud detector, and clients are Go, Java, and Python. gRPC wins: bidirectional streaming, generated clients, and deadlines. The public API for merchants stays REST/JSON with OpenAPI, because merchants use browsers and curl. They bridge with grpc-gateway so the same service exposes both.

Resolution: Do not frame it as style. Pick per boundary. Default to gRPC inside, REST outside, and bridge deliberately.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Review a gRPC service specification.

Answer

The 90-second answer

I read the .proto as a wire contract before I read it as an API. Assumptions I'd state up front: proto3, gRPC over HTTP/2, and clients already in the field that I can't force to upgrade. If any of those is wrong, the review changes.

Then I check four things in order: the wire contract, the RPC shape, the runtime semantics, and the security boundary.

Wire contract. Field numbers are the contract; names are not. Numbers 1–15 encode in one byte, 16–2047 in two, and 19000–19999 are reserved by protobuf, so I look for hot fields numbered above 15, and for any number that was ever used and then deleted without a reserved statement. In proto3, scalar fields have no presence unless declared optional (protobuf 3.15+) or placed in a oneof, so int32 retry_count = 3; cannot distinguish "unset" from "zero". If the spec needs that distinction, it's a bug. Enums in proto3 are open: an unknown value is preserved as its number, so a server that switches on an enum needs a default branch, and every enum needs a zero value that means UNSPECIFIED rather than a real state.

Protobuf
// v1
message Order { int32 id = 1; string status = 2; }
// v2, breaking: same number, different wire type
message Order { int32 id = 1; int32 status = 2; }  // old clients: status silently unset
// v2, safe
message Order { int32 id = 1; reserved 2; reserved "status"; string state = 3; }

RPC shape. Unary unless there's a reason. Streaming buys incremental delivery and lower per-message overhead; it costs per-RPC load balancing (a long stream pins to one backend), transparent retries (a stream that dies at message 400 can't be replayed), and proxy compatibility. My rule: stream when the response is unbounded or the client needs the first item before the last is produced; otherwise paginate a unary call. Client-streaming uploads are usually better as a unary chunk call plus a commit call, because that makes resumption and idempotency explicit instead of implicit in stream position.

Runtime semantics. Deadlines are absolute and propagate in the grpc-timeout header, so the server sees only the remaining time: a spec that says "30 second timeout" without saying whether that's per-attempt or end-to-end is ambiguous. Cancellation is cooperative: the server must check ctx.Done() inside loops or it keeps working for a client that's gone. Retries are off by default (maxAttempts is 1 unless a service config sets a retry policy), and a retry policy is only safe on idempotent methods, so I want to see which methods are idempotent and how, usually a client-supplied request ID rather than an assumption. Error detail belongs in google.rpc.Status.details as typed Any payloads, not in a stringly-typed message field.

statusretryablewhat the spec must say
UNAVAILABLE (14)yes, with backoffbackoff bounds and a retry budget
DEADLINE_EXCEEDED (4)yes, if idempotentwhether the deadline is per-attempt or end-to-end
INVALID_ARGUMENT (3)nowhich field failed, in BadRequest details
RESOURCE_EXHAUSTED (8)only with backoffthe limit that was hit and its configured value

Limits. Default max receive message size is 4 MiB (4,194,304 bytes) across C-core, Java and Go; the send limit is effectively unlimited by default, which is how a server ships a 40 MiB response that every client rejects. HTTP/2 flow control starts at a 64 KiB per-stream window, so a fast producer with a slow consumer blocks on the window rather than on memory: that's the backpressure mechanism, and it means "streaming" is not a way to stop thinking about consumer speed. grpc-go leaves the server's max concurrent streams unbounded unless you set it, so I want an explicit number in the spec.

Security. Metadata is just headers: anything a client sends in authorization or a custom x-tenant-id is attacker-controlled unless it's derived from a verified credential. Per-RPC credentials or mTLS for authentication; per-method or per-resource authorization on the server, never trusting a tenant ID from metadata. Binary metadata keys end in -bin and are base64 on the wire.

Evolution. Adding a field is safe; changing a wire type, renumbering, or removing without reserved is not. Old clients against new servers and new clients against old servers both need fixtures, not hope.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Evaluate offset versus cursor pagination.

Answer

The 90-second answer

Assume a list endpoint over a table that is being written to continuously, and the client wants "next page" navigation. Default to keyset (cursor) pagination. Use offset only when the client genuinely needs random access to page N and the dataset is small or effectively static.

Offset pagination is LIMIT 20 OFFSET 10000. The database cannot jump to row 10000: it walks the index or heap, discards 10,000 rows, then returns 20. Cost is O(offset + limit), so page 500 does 500× the work of page 1, and the tail of a deep scroll is where your p99 lives. Keyset pagination is WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20. With a btree index on (created_at, id) the planner seeks straight to the boundary and reads 20 entries: O(log n + limit), flat regardless of depth.

The second difference is correctness under writes, and it is the one that bites. Offset is positional: it counts rows in the current result set. Insert a row at the head between page 1 and page 2 and everything shifts down by one, so the last row of page 1 reappears as the first row of page 2. Delete a row and one row is skipped entirely: the user never sees it. Keyset is anchored to a value, not a position, so a concurrent insert at the head is simply not in the window and nothing shifts.

SQL
-- Postgres 16
-- offset: walks and discards
SELECT id, created_at, title FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 10000;

-- keyset: index seek to the boundary
SELECT id, created_at, title FROM posts
WHERE (created_at, id) < ('2024-05-01T10:00:00Z', 918273)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The id tie-breaker is not optional. If two rows share created_at, created_at < x alone either skips or repeats them; the composite (created_at, id) makes the ordering total, which is what makes the cursor a real boundary.

Cursor design: base64url of {created_at, id, filter_hash, tenant_id, exp}, signed with HMAC-SHA256. Bind the filter hash so a cursor from ?status=open cannot be replayed against ?status=closed and silently return a different result set. Bind the tenant so a cursor cannot be used to cross an authorization boundary. Expire it (say 24h) so a stale boundary does not pin an old index. On a bad signature, expired timestamp, or mismatched filter, return 400 with a machine-readable code: never silently fall back to page 1, which hides bugs and can loop clients.

Failure modes and how you see them:

  • Duplicate rows across pages: client-side dedupe by id, or a test that inserts at the head between page fetches and asserts no id appears twice. Offset fails this; keyset passes.
  • Skipped rows: the same test with a delete. Offset fails.
  • Deep-page latency: p99 on OFFSET 100000 climbs with depth; alert on it. Keyset is flat.
  • Cursor replay across tenants: integration test that takes tenant A's cursor and calls as tenant B, expects 400/403.
  • Unstable ordering: if the sort column is not unique and has no tie-breaker, both schemes can repeat rows. Detect with a test that fetches all pages and asserts the concatenation equals the full ordered set.

When offset is right: admin tables with a page-number UI, small or append-only datasets, or exports where the client wants "jump to page 47". There the O(offset) cost is bounded and the drift is acceptable because the user is looking at a snapshot-ish view anyway. Offset is also the only one that gives you true random access and a total count.

Neither gives a consistent snapshot. Both read the current committed state at each query. If you need a stable view across pages, you need a snapshot: a repeatable-read transaction held open (bad for long scrolls), a materialized or versioned view, or a cursor that encodes a high-water mark (created_at <= snapshot_ts) so later inserts are excluded.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Specify pagination for a rapidly changing feed.

Answer

For a rapidly changing feed I'd use keyset pagination on a stable, unique sort key: typically (created_at DESC, id DESC). The cursor is an opaque, HMAC-signed token encoding the last seen (created_at, id) plus filter, sort, tenant, and an expiry. Default page size 20, max 100, cursor TTL 5 minutes. This gives live traversal: items inserted after the cursor don't appear until the client refreshes, but existing items are neither duplicated nor skipped.

Why keyset over offset: offset pagination counts rows from the top, so any change above the window shifts it.

Trace: insert. Feed sorted created_at DESC, id DESC, page size 3. Initial: A(10:00, id=1), B(09:59, id=2), C(09:58, id=3), E(09:57, id=5). Page 1 (offset 0, limit 3) returns A, B, C. Now D(10:01, id=4) is inserted. Order becomes D, A, B, C, E. Page 2 (offset 3, limit 3) skips D, A, B and returns C, E: C is duplicated. The insert pushed the window forward; nothing was skipped.

Trace: delete. Same initial state. Page 1 returns A, B, C. Delete B. Order becomes A, C, E. Page 2 (offset 3, limit 3) skips A, C, E and returns nothing: E is omitted. Deletion pulled the window back.

Keyset avoids both. After page 1 the cursor is (09:58, 3). Page 2 queries WHERE (created_at, id) < (09:58, 3) ORDER BY created_at DESC, id DESC LIMIT 3. With D inserted, that returns E: no duplicate of C, no omission. With B deleted, it still returns E. The window is anchored to a key, not a row count.

The one thing keyset can't absorb is a mutation of the sort key itself. If created_at changes, the row can reappear or vanish. Keep the sort key immutable, or route updates through a separate mechanism.

Failure modes and detection:

  • Unsigned cursor: client edits tenant or page size. Detect by HMAC validation; reject 400. Cost: cross-tenant data leak.
  • Cursor expiry: TTL too short returns 410 to slow clients. Monitor 410 rate. Cost: client restarts traversal, extra load.
  • Non-unique sort key: ties in created_at cause duplicates or omissions. Test concurrent inserts with identical timestamps. Cost: inconsistent feed.
  • Oversized page: p99 latency spikes. Monitor p99; cap at 100. Cost: timeouts.

If exact snapshot semantics are required, use a snapshot token: a timestamp T0, query created_at <= T0. Consistent view, but needs an index on created_at and can be expensive. Or a per-user feed table with a monotonic sequence. Trade-off: snapshot gives consistency at higher latency and storage; live keyset gives lower latency but new items appear only on refresh. State the weaker guarantee explicitly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Specify the idempotency-key contract for unsafe operations in your API: which header carries the key, its scope and uniqueness, how long keys are retained, what the server returns when the same key is replayed with the same and with a different payload, and how that interacts with retries and concurrent duplicates?

Answer

Start with the contract, not the storage. The key travels in Idempotency-Key: a de facto convention (Stripe, Square, PayPal), not something RFC 9110 defines. RFC 9110 only tells you which methods are idempotent by definition, and POST is not one; the header is what makes a POST retryable.

Scope and uniqueness. The key is unique within (authenticated principal, method + route template, key value). Not global: two tenants must be able to use the same UUID without colliding, and the same key on POST /v1/payments and POST /v1/refunds is two different operations. The client generates it, UUIDv4 or ULID, and the server bounds it (say 1–255 chars, reject empty) without parsing it. In OpenAPI, declare it as a required header parameter on every unsafe operation so generated clients surface it.

Retention. Keep the record at least as long as the client's maximum retry window plus clock skew. 24 hours is the common published default; anything shorter than your retry budget turns a retry into a second charge. Store key → request fingerprint + the full response (status, headers, body) with a TTL.

Replay matrix.

incomingserver stateresponse
same key, same fingerprintcompletedstored status + body, Idempotent-Replay: true
same key, different fingerprintcompleted409 Conflict, application/problem+json
same key, any fingerprintin flight409 Conflict with Retry-After
new key—execute, persist before responding

Fingerprint = hash of method, route and canonicalized body (sorted keys, no insignificant whitespace). Compare the hash, not raw bytes: otherwise a client that re-serializes JSON gets a spurious conflict. Use 409 for the mismatch; 422 only if you treat a differing payload as a validation failure rather than a key-reuse bug.

Concurrency is the part people get wrong. Insert the key row with a unique constraint and state in_progress before doing any side effect. The second concurrent request hits the constraint and gets 409 instead of executing. The alternative, block until the first finishes and return its response, is friendlier but holds a connection for the operation's duration; only do it with a short bounded wait (a few hundred ms) and a 409 fallback. Never execute first and record after: a crash between the two is exactly the duplicate you were preventing.

Retries then compose cleanly. The client reuses the key for retries of the same logical operation and mints a new one for a new operation. A retry after a timeout is safe because either the original committed (replay) or it did not (execute).

Failure modes worth naming. Retention shorter than the retry window → duplicate execution after TTL expiry. Key not scoped per principal → one tenant's replay returns another's response body. Response stored unencrypted → PII at rest in a table nobody classified. Unbounded key cardinality → storage growth, so TTL plus per-tenant quotas. Non-deterministic fields (server timestamps, request IDs) replayed verbatim: fine, but document it. Detect with replay-rate and conflict-rate metrics, and keep a unique business constraint (one charge per order) as the backstop that catches a broken key contract in production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design retries for a mutation with an ambiguous timeout.

Answer

Clarify and assume. The mutation is a payment charge: POST /payments, non-idempotent, and a timeout tells the client nothing about whether the charge committed. I'll assume one logical operation per user intent, a client that can generate a UUID, and a server that owns a durable store. The core answer: give the operation a client-generated idempotency key, make the server deduplicate on it, and retry only outcomes that are safe to retry. The key is what turns an ambiguous timeout into a resolvable one: the client retries with the same key, and the server either replays the stored response or rejects conflicting reuse.

Mechanism. The client sends Idempotency-Key: 7f3a… (UUIDv4) plus a SHA-256 fingerprint of method + path + body. The server runs INSERT … ON CONFLICT (account_id, key) DO NOTHING into a table with a unique index on (account_id, key). If the insert wins, this request owns the operation: write state=in_progress, call the processor, then write state=succeeded and the response body. If the insert loses, read the row: in_progress returns 409 with Retry-After, succeeded returns the stored response verbatim. Same key with a different fingerprint returns 422, which catches a client that reused a key across two operations.

Retention: Stripe keeps idempotency keys 24 hours. That covers a client retrying for minutes, not days. Seven days costs storage and blocks legitimate key reuse; an hour risks a duplicate when a client retries after expiry. Pick 24h and alert if any client's retry window approaches it.

Retry policy.

OutcomeRetry?Why
Connection refused / DNS failureYesRequest never sent, no mutation possible
Reset or timeout after sendYes, same keyAmbiguous: the key resolves it
502 / 503 / 504YesProxy or upstream failure
429Yes, honor Retry-AfterRate limited
400 / 401 / 403 / 409 / 422NoRequest is wrong; retrying repeats the error

Propagate a total deadline (10s) and set each attempt's timeout to the remaining budget, so a slow attempt doesn't get a fresh full timeout. Backoff is full jitter: sleep = random(0, min(2s, 100ms * 2^attempt)), max 4 attempts. Worst case that's 100+200+400+800 = 1.5s of sleep plus four request timeouts.

Trace. t=0 client POSTs with key 7f3a. Server inserts the row, calls the processor, processor commits the charge at t=0.2s. The response is lost; the client times out at t=1s. t=1.1s the client retries the same key → insert conflicts → row is in_progress → 409 Retry-After: 1. t=2.1s the client retries → row is succeeded → server returns the stored 201. One charge.

Failure modes. In-flight lock never released (server crashed after insert): give the row a 30s lease; a retry after the lease takes over, and a unique constraint on (account_id, operation_id) in the ledger makes the second commit a no-op. Key expiry mid-retry: the client retries after 24h, gets a new operation, duplicate charge. Detect with a nightly reconciliation comparing ledger entries on (account, amount, 5-min window) and alert on duplicates. Status endpoint: GET /operations/{key} must be authorized by account_id, or one tenant reads another's payment. Detect fingerprint mismatches (422s) in logs: a spike means a client bug, not a server one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Model partial updates without lost writes.

Answer

Assume a JSON document resource behind HTTP, several clients doing read-modify-write, and a relational store. Lost updates happen in the gap between a client's read and its write, so the fix has to close that gap: the read hands back a token, the write is conditional on that token, and the comparison happens inside the same atomic statement as the write. Everything else (PATCH semantics, field ownership, idempotency) is detail around that spine.

The chain

  1. GET returns the document plus ETag: "7", derived from a monotonic version column, not a timestamp.
  2. Client sends PATCH /docs/42 with If-Match: "7".
  3. Server turns the patch into a conditional update:
SQL
UPDATE documents
   SET title = $1, version = version + 1, updated_at = now()
 WHERE id = $2 AND version = $3;   -- $3 = 7

Zero rows affected means someone else won; one row means you did. The WHERE is not a separate check: under READ COMMITTED the second writer blocks on the row lock, then re-evaluates the predicate against the committed row. That re-evaluation is the compare-and-swap.

Trace, two writers on version 7

  • A: UPDATE ... WHERE version = 7 → 1 row, version becomes 8.
  • B: same statement, arriving after A commits → blocks on the row lock, re-checks, sees version 8, matches nothing → 0 rows.
  • Server returns 412 Precondition Failed with the current ETag and the current representation, so B can re-apply its patch to fresh state.

Without the WHERE, B's write lands and A's title edit is gone: silently, which is the whole problem.

PATCH semantics

Omitted versus null is where most implementations leak. JSON Merge Patch (RFC 7396) cannot express "set to null": null means delete. JSON Patch (RFC 6902) can.

intentMerge PatchJSON Patch
leave field aloneomit the keyno op for that path
set field to nullnot expressible{"op":"replace","path":"/x","value":null}
remove field{"x": null}{"op":"remove","path":"/x"}

Pick one and document it; mixing them is how a client clears a field it meant to leave alone. Validate the merged result, not just the patch: a patch that is valid alone can produce an invalid document. Enforce authorization per field after parsing, and fail the whole request if any field is not writable by that caller rather than applying the rest.

Trade-offs

A whole-document ETag is simple but conflicts on disjoint fields: two clients editing title and tags collide even though nothing is lost. Per-field versions, or splitting hot fields into their own rows, cut false conflicts at the cost of a more complex API and more write amplification. Last-write-wins is fine for genuinely idempotent, low-stakes fields, a last_seen_at, and wrong for anything a human typed. Say which fields are which.

Failure modes

  • Retry storm: every conflicting client retries at once. Cap retries at 3 with jitter; at a 10% per-attempt conflict rate, 3 attempts succeed 99.9% of the time, and the rest should surface as a conflict, not a spin.
  • ABA: a timestamp ETag can repeat at coarse resolution. Use a monotonic integer or a content hash.
  • Unknown fields: rejecting them (400) breaks forward compatibility; ignoring them silently drops data from newer clients. Reject on write, ignore on read, and version the media type.
  • Old clients: a PUT without If-Match reintroduces the bug. Require the precondition on every mutating verb, or answer 428 Precondition Required.
  • Idempotency: merge patch is idempotent for the same body; JSON Patch add to an array is not. Retried requests carry an Idempotency-Key the server stores alongside the response.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Review a bulk API operation.

Answer

First thing I check is what the endpoint promises when part of the batch fails, because that one decision drives the response shape, the retry story and the transaction scope. Limits, idempotency and async all follow from it.

Take a concrete endpoint: POST /v1/messages:batch, up to 500 items or 5 MB body, whichever hits first. Oversize gets 413, malformed JSON 400, and both are rejected before any item is touched: validation is a separate pass from execution, so a bad item never costs a downstream call.

The core decision is atomic versus best-effort. Atomic means one transaction, all-or-nothing, 200 or 4xx. It is right when items are interdependent, a debit/credit pair, but it holds locks for the whole batch and one bad item fails the other 499. Best-effort returns 207 Multi-Status (RFC 4918) with a per-item result array keyed by a client-supplied id. That is my default for independent items, and it is what makes retries tractable: the client resends only the failed ids.

A three-item batch shows why the distinction matters. Item a is valid and returns 201. Item b is missing a required field, so it fails validation with 400 and is never sent downstream. Item c is valid but the downstream returns 503, so it comes back as 502. The aggregate is 207 with {succeeded: 1, failed: 2}, and because b and c carry different codes the client retries only c. Collapse those into one "batch failed" error and the client either retries everything, duplicating a, or nothing.

Idempotency is what makes that retry safe. Require an Idempotency-Key header, store the response against it for a 24-hour window, and replay the stored response on a repeat. Without it, the worst case is a client timeout after partial commit: the server committed 300 of 500, the client saw a timeout and resends the whole batch, and you get 300 duplicates. Duplicate ids inside one batch are a separate case: reject the batch with 400 rather than guessing last-wins, because the client's intent is ambiguous.

Fan-out is where bulk endpoints hurt. One request becomes N downstream calls, so rate-limit on items, not requests: a tenant sending 10 batches/sec at 500 items is 5,000 items/sec. Cap in-flight downstream calls at 8. With a downstream p99 of 400 ms, 500 items is ceil(500/8) = 63 waves × 400 ms ≈ 25 s: too close to a 30 s gateway timeout. Either cap the batch at 200 (25 waves ≈ 10 s) or return 202 with a job id and let the client poll or take a webhook. Async is the honest answer once the work exceeds the request budget; a synchronous endpoint that sometimes takes 25 s is worse than one that admits it is a job.

Authorization is per object, not per collection. Checking that the caller can use the endpoint but not that they own each id is a cross-tenant write. Return 403 per item, and be careful that a 404-versus-403 split does not leak whether another tenant's id exists.

Failure modes I would test explicitly: mixed validity in one batch, overload past the item rate limit, a downstream that fails for a subset of items, and replay of an idempotency key after a partial commit. Each has a detection path (per-item error codes, 429 with Retry-After, and the stored idempotency response) so the on-call engineer can tell which one they are looking at.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

What must an API spec state about throttling responses so clients back off correctly under load?

Answer

A 429 is only useful if the spec makes four things unambiguous: what the status means, when to come back, what the limit is, and whose limit it is.

Start with the guarantee. The spec should say a 429 means the request was rejected before any side effect: no write, no charge, no message sent. That one sentence is what lets a client retry a POST safely; without it, every 429 on a non-idempotent call is an ambiguous outcome, and clients either duplicate work or give up. RFC 9110 defines 429 as too many requests in a given amount of time and leaves the rest to you.

Retry-After (RFC 9110 §10.2.3) is the only interoperable timing signal: either delta-seconds or an HTTP-date. Prefer delta-seconds. An HTTP-date depends on the client's clock, and a client 30 seconds fast retries immediately and gets throttled again. The spec must also say what happens when the header is absent, because gateways drop headers: require exponential backoff with jitter and a cap.

Then the limit headers. There is no RFC here. X-RateLimit-Limit/Remaining/Reset is a de-facto convention; the IETF draft draft-ietf-httpapi-ratelimit-headers, still a draft, uses RateLimit-Limit/Remaining/Reset. Units are where clients break: in the draft, Reset is delta-seconds, while the older X-RateLimit convention frequently emits a Unix epoch second. A client that assumes the wrong one either hammers the API or sleeps for 55 years. Pick one, state it, and declare it in the OpenAPI response object.

headerunitmeaning
Retry-Afterdelta-seconds (or HTTP-date)when to retry this request
RateLimit-Limitrequestsquota for the current window
RateLimit-Remainingrequestsquota left in the window
RateLimit-Resetdelta-secondsseconds until the window resets

Scope is the part teams skip. Say whether the limit is per API key, per tenant, per endpoint, or a tenant-wide bucket shared across endpoints: a per-endpoint limit lets a client fan out over 20 endpoints and get 20x the throughput, which is rarely the intent. Also state whether a rejected request counts against the quota, whether enforcement sits at the gateway or the service (they drift), and whether the headers appear on 2xx responses too. Clients need Remaining on success to pace themselves before they ever see a 429.

The error body should be RFC 9457 problem details (type, title, status, detail) plus an extension member naming the scope that was exhausted. Mark the response Cache-Control: no-store: RFC 9111 lets a shared cache reuse a stored response, and a cached 429 replayed to other clients is a self-inflicted outage.

Client behaviour the spec requires: honour Retry-After when present; otherwise exponential backoff with full jitter, base 1s, cap 60s, max 5 attempts; a retry budget so retries stay under roughly 10% of traffic; and no retry at all for 401, 403 or 422. Those are not throttling.

python

client backoff, Python 3.12

import random

def delay(attempt: int, retry_after: float | None) -> float: if retry_after is not None: return float(retry_after) # delta-seconds return min(60.0, random.uniform(0, 1.0 * 2 ** attempt)) # full jitter

Failure modes worth naming: a client that retries immediately on 429 turns a soft limit into a hard outage; a spec documenting X-RateLimit-Reset as epoch while the gateway emits delta-seconds produces clients that sleep for years; limits enforced at the gateway but not in the service let internal callers bypass them; and returning 429 for auth failures hides a credential problem behind a backoff loop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design rate limits for a multi-tenant API.

Answer

What I'd say first

Assumptions: shared SaaS, tenants authenticated by API key or tenant ID, one tenant can be 1000× another, and the API mixes cheap reads with expensive searches. The fairness unit is the tenant, not the connection, because one tenant can open many connections. I'd enforce a token bucket per (tenant, operation class) with weighted costs, a per-tenant concurrency cap, and a global concurrency limiter as the backstop that protects the service when tenant limits are misconfigured or bypassed.

Mechanism

Token bucket: capacity = burst, refill rate = sustained. Weighted cost makes a search cost more than a read. Example tier: 100 tokens/sec sustained, capacity 200. A read costs 1 token, a search costs 10. So the tenant sustains 100 reads/sec or 10 searches/sec, and can burst 20 searches back-to-back before throttling.

Trace: bucket full at 200. Tenant fires 20 searches at t=0 → 200 tokens consumed, bucket empty. At t=0.05s a 21st search arrives; refill is 100×0.05 = 5 tokens, cost is 10, so it's rejected with 429 and Retry-After: 1 (it needs 5 more tokens = 0.05s, rounded up to the next second). At t=0.1s the bucket holds 10 tokens and the search passes.

Enforcement across instances: a purely local bucket per instance lets N instances each admit the full rate. 20 instances at 100 rps is 2000 rps, not 100. So the tenant-wide cap lives in Redis (atomic Lua script, or GCRA, which stores one timestamp per key at O(1) memory), while each instance keeps a local bucket sized rate/N for cheap pre-filtering. Redis adds roughly 1 ms p99 per check; local pre-filtering keeps most requests off it.

Alternatives

AlgorithmBurst behaviorMemoryWhen to pick
Fixed window2× at boundaryO(1)crude, cheap, internal only
Sliding window logexactO(requests)low-volume, audit-grade
Sliding window counterapproximate, bounded errorO(1)good default at scale
Token bucket / GCRAsmooth, tunable burstO(1)weighted costs, per-tenant tiers

I'd pick token bucket/GCRA because weighted costs and burst control are the actual requirements; fixed window's boundary doubling is exactly the abuse pattern I'm defending against.

Failure modes and detection

  • Redis unavailable. Fail open → overload; fail closed → total outage. I'd fail open for reads and fail closed for expensive writes, with the global concurrency limiter as the backstop. Detect: Redis error rate and the gap between admitted and completed requests.
  • Hot key. One large tenant's counter pins one Redis shard. Detect: per-shard CPU and key-level latency; mitigate by sharding the counter and pre-aggregating locally.
  • Identifier rotation. An attacker rotating keys or IPs gets fresh buckets. Authenticated tenants are keyed by tenant ID, so rotation doesn't help; unauthenticated traffic is keyed by IP+ASN. Cost: NAT'd offices share an IP and get false positives. Detect by watching 429 rate per IP against the number of distinct tenant IDs behind it.
  • Retry storms. 429 without jitter synchronizes clients. Return Retry-After plus a jitter recommendation; detect by request-rate spikes at the Retry-After boundary.
  • Clock skew. GCRA timestamps drift across instances; use Redis server time as the single clock.

Tuning

Track 429 rate per tenant, false-positive rate (throttled requests that would have succeeded), and p99 latency at the limiter. Raise a tenant's burst only when its 429s cluster at legitimate peaks, not when they cluster at a single principal: that's abuse, not a tier problem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Define caching for a personalized GET endpoint.

Answer

The 90-second answer

Assume a shared CDN sits in front of the origin and the endpoint returns per-user data: say GET /api/v1/me/feed. The safe default is: don't let a shared cache store it. Send Cache-Control: private, no-store and let the browser cache nothing either. That's correct, and it's also the answer that costs the most origin load, so the real work is deciding which parts you can safely share.

Three things decide it: who the response is for, how stale it may be, and what happens when the answer changes.

Why Vary fails in practice

A shared cache keys on the URL plus the values of the headers named in Vary. If the response depends on Authorization or Cookie and you don't list it, the cache stores user A's body under that URL and serves it to user B. That's the principal-mixing leak, and it's silent: no error, just someone else's data. Listing Vary: Authorization fixes correctness but destroys the hit rate, because every token is a distinct key: 100k users means 100k entries and roughly 0% sharing. Vary: Cookie is worse: session cookies rotate, so the same user misses on every request. Vary: * always fails to match, which is honest but equivalent to no-store.

So shared caching only pays when you can move the personalization out of the body: split the response into a shared shell and a per-user fragment fetched separately.

directiveeffect on a shared cacheuse for
privatebrowser may store, shared cache may notper-user body
no-storenothing may store ittokens, secrets
s-maxage=60shared TTL, overrides max-ageshared shell
stale-while-revalidate=30serve stale up to 30s while revalidatingtolerate 30s staleness
must-revalidateno stale after expiryentitlement-gated data

Validation instead of freshness

If you can't share, you can still avoid re-sending bytes. Return an ETag and let the client send If-None-Match; a match gives 304 with no body. That saves bandwidth, not origin work: the origin still runs the handler. Last-Modified/If-Modified-Since is coarser (HTTP dates have one-second resolution) and weaker under concurrent writes.

Invalidation and failure

TTL is the only invalidation you can rely on; purges are best-effort. CDN purge propagation is typically 1–5 s and can stretch to 30 s under load, so a logout or entitlement downgrade leaves a window where the old body is still served. Size the TTL to what that window costs. stale-if-error=300 keeps you up during an origin outage but serves stale personal data for five minutes: usually the wrong trade for anything entitlement-gated.

What to measure

Log cache status per request (X-Cache: HIT|MISS) and alert on origin QPS, not just hit rate. A 92% overall hit rate can hide 0% per-user hits if one anonymous endpoint dominates traffic. Run a canary that fetches the same URL with two different tokens and diffs the bodies; that catches a missing Vary before a customer does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Review an asynchronous export API.

Answer

Assumptions: multi-tenant SaaS, exports up to ~10 GB, results land in object storage, clients are browsers and backend jobs. The review comes down to three things: the acceptance contract, the idempotency key, and who owns the terminal state. The rest is detail.

Acceptance. POST /exports returns 202 Accepted with Location: /exports/{id} and Retry-After. 202 is the honest code: RFC 9110 defines it as accepted for processing but not completed. A 200 with a job id in the body implies the work is done; a 201 implies the client can GET the resource it just created, which it can't yet. The body carries the job id, state and created_at, and nothing the client can't act on.

Idempotency. The client sends Idempotency-Key. Keep a unique index on (tenant_id, key) next to a hash of the request body. A retried POST returns the same job id; the same key with a different body hash returns 409 Conflict. That's Stripe's convention, now an IETF draft. Skip it and a network timeout on a 10 GB export bills you for two.

Lifecycle.

stateentered whenlegal next
queuedaccepted, not claimedrunning, canceled, expired
runningworker claims itsucceeded, failed, canceled
succeededfinal object writtenexpired
failedterminal error recorded—
canceledclient DELETE, or deadline passed—
expiredretention window closed—

Progress is the part teams get wrong. A percentage is fiction for most pipelines; report bytes written or rows scanned and label it an estimate. Terminal errors need a stable code plus a human message: never the raw exception, which leaks table names.

Duplicate workers. The queue delivers at least once, so the worker must be idempotent. Claim with UPDATE jobs SET state='running', worker_id=$1, heartbeat=now() WHERE id=$2 AND state='queued' and check the row count, or SELECT ... FOR UPDATE SKIP LOCKED (Postgres 9.5+). Write output to a temp prefix and flip to succeeded only after the final object lands, so a crash leaves a partial object nothing points at.

Trace it: two workers pull job 7. A's UPDATE returns 1 row, B's returns 0 and B exits. A dies mid-write. The SQS visibility timeout (default 30 s) expires, the message is redelivered, worker C claims it, sees running with a heartbeat older than the 5-minute lease, and takes over. Output keys are deterministic, exports/{tenant}/{job}/part-*, so C overwrites rather than appends.

Polling vs callback. Polling a 20-minute export at 1 s is 1,200 requests per client; 5,000 concurrent exports is 5,000 rps of pure status traffic. Callbacks with an HMAC signature, at-least-once delivery and a delivery id the client dedupes on are cheaper, but you now own retries and a dead-letter queue, and the client needs a public endpoint. Default to polling with Retry-After and exponential backoff with jitter; offer callbacks to clients who ask.

Download. Presigned URL, 5–15 minute TTL, generated only after an authorization check on the job. SigV4 presigned URLs cap at 7 days with long-term credentials: don't hand out a week-long URL for a PII export. Retention is a lifecycle rule on the prefix plus a row deletion, and the two must agree or you get orphaned objects.

Failure modes and detection. Stuck jobs: alert on the age of the oldest queued row exceeding p99. Duplicate output: object count per job above expected. Orphaned partials: lifecycle rule deletes the temp prefix after 24 h. Tenant leak: an integration test asserting a cross-tenant GET returns 404, not 403. 403 confirms the job exists. Dependency failure: a failed export must not leave the job in running; the deadline check moves it to failed with a code the client can branch on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Specify webhooks for business-critical events.

Answer

First 90 seconds. Webhooks cross an org boundary, so assume every delivery can be duplicated, delayed, reordered, or lost. Pin three assumptions: we own the sender and not the receiver; some events move money, so a lost one must be recoverable; the receiver can return a fast 2xx. If we owned both ends I would argue for a broker instead: a Kafka topic or SQS queue gives ordering, replay and backpressure without inventing them. The contract below has five parts.

Envelope. event_id (UUIDv7, time-sortable), type (invoice.paid), schema_version (integer), occurred_at in RFC 3339 UTC, sequence monotonic per resource, and data carrying ids plus a data_url rather than the full object. Ordering scope is per resource: we partition on resource id internally, so events for invoice X arrive in order while X and Y interleave. Putting that sentence in the docs matters, because consumer assumptions of global order are the most common integration bug. Schema changes are additive; a breaking change ships as a new type plus a version bump, and consumers ignore unknown fields.

Authenticity. HMAC-SHA256 (RFC 2104) over the raw request bytes. Header: X-Signature: t=1767225600,v1=<hex>,kid=k2; the signed string is t + "." + raw_body. The timestamp has to sit inside the signed material: sign only the body and a captured delivery replays forever. The receiver verifies with a constant-time compare (hmac.compare_digest, crypto.timingSafeEqual) and rejects when the absolute gap between now and t exceeds 300 s; Stripe's documented default tolerance is 300 seconds, and below about 60 s you start failing on ordinary NTP skew. Verify before parsing: parse-then-reserialize changes whitespace and key order and the MAC stops matching. Rotation keeps two secrets under kid: sign with current, accept current and previous, retire previous one retry window later.

Retries. Eight attempts, exponential with jitter: 10 s, 30 s, 2 min, 10 min, 1 h, 3 h, 6 h, 12 h, then dead-letter at 24 h. The endpoint gets 5 seconds to return 2xx; any 4xx or 5xx counts as failure, and 410 Gone permanently disables it. Alert when DLQ depth passes 100 or the oldest entry passes 15 minutes; replay from the delivery log once the receiver confirms the fix is deployed.

Consumer side. At-least-once is the only honest default, so duplicates are mandatory rather than a bug. Dedup and side effect commit together:

SQL
INSERT INTO processed_events (consumer_id, event_id, received_at)
VALUES ($1, $2, now())
ON CONFLICT (consumer_id, event_id) DO NOTHING;
-- 0 rows affected => already processed, return 200, touch nothing else

The unique index is the linearization point: two concurrent deliveries race on it, exactly one commits, the loser sees zero rows and stops. The side effect has to be in that same transaction, otherwise the row commits while the email never goes out. Prune processed_events after 30 days, which must outlive the 24 h retry window plus clock skew plus any manual replay.

Detection.

symptomsignalusual cause
events stallingoldest undelivered > 15 minreceiver down or slow
auth failures spike401s grouped by kidrotation with no overlap, or skew
duplicate side effectsdedup hit rate dropstable pruned early
delivery p99 risingsender worker queue depthslow endpoint eating the 5 s budget

Trade-offs. Symmetric HMAC is fine for a handful of consumers; with many, publish an asymmetric key instead (Ed25519, as a JWK set) so no shared secret sits in every partner's config. If the events are low-value and the consumer can poll, GET /events?since=<cursor> is far less machinery than delivery, retries and replay. And a destination URL change is the classic exfiltration move: require out-of-band re-confirmation before a webhook target can be repointed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Threat-model an API that consumes third-party URLs.

Answer

The 90-second version

Clarify first: who supplies the URL, is the caller authenticated, and what does the fetched content feed? Assume an authenticated but untrusted caller, an arbitrary internet target, and a service running in a VPC where 169.254.169.254 serves instance credentials.

The whole threat is that the caller's string becomes a request our network makes: SSRF by construction. So the rule is: the caller's string never reaches a socket. Parse it, allowlist scheme (https only) and port (443), resolve the hostname ourselves, check every returned IP against special-use ranges, then connect to the validated IP with the original Host header. Every redirect repeats the check.

Mechanism

Scheme and port. Only https:443. This blocks file://, gopher://, dict://, ftp://: gopher and dict have been used to speak to Redis and SMTP on internal hosts.

IP validation. Reject 127.0.0.0/8, 10/8, 172.16/12, 192.168/16, 169.254/16, 100.64/10, 0.0.0.0/8, ::1, fc00::/7, fe80::/10. The metadata endpoint is 169.254.169.254 on AWS/GCP/Azure and fd00:ec2::254 on AWS IPv6.

Encoding. http://2130706433/, http://0x7f000001/, and http://0177.0.0.1/ all resolve to 127.0.0.1 in permissive parsers. Parse with a strict library and reject anything that is not a canonical dotted-quad or a normal hostname.

DNS rebinding. The attacker's DNS returns a public IP on the first lookup and 127.0.0.1 on the second. Fix: resolve once, validate, then connect to that exact IP. Do not let the HTTP client re-resolve.

Redirects. Cap at 3 and re-validate each hop. The classic is a 302 to http://169.254.169.254/latest/meta-data/iam/security-credentials/.

Egress. Run the fetch from a dedicated subnet behind a proxy that permits only 443 to public IPs. This is the backstop if validation has a bug.

Response handling. Cap the body at 10 MB, cap decompression ratio (1 KB of gzip can expand to 1 GB), validate Content-Type against what you expect, and parse in a sandboxed process holding no credentials.

Credentials and errors. Never forward the caller's Authorization header or our service credentials to the third party. Return a generic failure: echoing the resolved IP or upstream body turns the endpoint into an oracle.

Trade-offs

Denylist of private ranges is the default because the target space is the whole internet. If the API only ever fetches from known partners, a hostname allowlist is stronger and I would push for it; the cost is onboarding friction and breakage when a partner changes domains. Blocking all private ranges also breaks legitimate internal fetches, if those are needed, give them a separate path with its own egress and no metadata route.

Failure modes and detection

  • SSRF to metadata: alert on any egress connection to 169.254.169.254; the incident shape is stolen instance credentials.
  • DNS rebinding: log resolved IP vs connected IP; a mismatch is a bug, not a false positive.
  • Slow response: a server sending 1 byte/10 s; detect via connect-timeout vs total-timeout metrics.
  • Decompression bomb: memory spike in the parser sandbox.
  • Redirect to internal: log every hop's resolved IP and alert on any special-use range.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Review authentication and authorization in an OpenAPI file.

Answer

The 90-second version

Assume OpenAPI 3.0 or 3.1, OAuth2/OIDC bearer tokens, and a gateway in front of the service. The spec is a claim about who can call what. My job is to read the claim, then find where it is actually enforced, and those are three separate places: the gateway route config, the application handler, and the token issuer's claims. Nothing in the file binds them together, so the review is mostly about finding where they disagree.

Read the schemes, then read the requirements

Start at components.securitySchemes. For type: oauth2, check the flow: authorizationCode with PKCE (RFC 7636, S256 challenge) for anything a browser or mobile client touches; clientCredentials for service-to-service. Redirect URIs must be exact string matches (RFC 6749 §3.1.2.3): no wildcards, no path-prefix matching. For type: http with scheme: bearer, the spec tells you nothing about the token format; bearerFormat: JWT is a hint, not a constraint.

Then the part people get wrong: an operation-level security block replaces the root requirement. It does not merge with it.

YAML
openapi: 3.1.0
components:
  securitySchemes:
    bearer: {type: http, scheme: bearer}
    oauth:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://idp.example.com/authorize
          tokenUrl: https://idp.example.com/token
          scopes: {read:items: Read items, admin:items: Administer items}
security:
  - bearer: []
paths:
  /items:
    get:
      security:
        - oauth: [read:items]
  /health:
    get:
      security: []

Trace it. The root block says every operation needs a bearer token. GET /items overrides that with oauth: [read:items]: the bearer requirement is gone, not added. GET /health sets security: [], which removes auth entirely. A reviewer who reads the root block and stops has missed both. Grep for security: [] and for every operation-level security block; that is where the surprises live.

Why declarations diverge from enforcement

The scopes map is documentation. Nothing in the spec, and no mainstream generator, turns read:items into a runtime check. openapi-generator and swagger-codegen emit route stubs and client SDKs; the handler body is yours. So the scope string in the spec and the scope string your middleware checks are two independent strings that drift apart silently.

The token side is where it actually fails. A JWT access token carries aud (RFC 7519). If the resource server does not validate that aud contains its own identifier, RFC 9068 says it MUST, then a token minted for the billing service is accepted by the items service. Same story for iss, exp, and the signature algorithm: accepting alg: none, or verifying HS256 with the RSA public key as the HMAC secret, is a known forgery path.

How heavy to go

Three postures. Read-and-spot-check: read the spec, then hit the running service with a missing, expired, wrong-audience and over-scoped token. Cheap, catches drift, does not scale past a handful of endpoints. Contract tests: assert per-operation that the declared scheme is the enforced one, run in CI. Worth it once the surface is large or several teams own it. Generating middleware from the spec: only worth it if that generated code is the single enforcement point. If a gateway policy also exists, you have added a second place to drift, not removed one.

Failure modes worth naming

Cross-tenant IDOR: the spec has no way to express "this path parameter must belong to the caller's tenant," so it is never checked. Admin functions exposed by a missing operation-level security. apiKey with in: query: leaks into access logs and referrers. Revocation: bearer tokens are valid until exp, so check whether there is a denylist or a short TTL.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Review an API spec for creating payments.

Answer

What I'd say first. Before reviewing anything, I'd pin down what the spec is a contract for. Assumptions I'd state out loud: REST/JSON over TLS, a PSP sitting behind this API, amounts as integers in minor units, and the caller is a merchant's server, not a browser. Then I'd review in four passes (the money path, the state machine, the error contract, and the operational edges) and I'd say which of those the spec actually settles versus leaves to the reader.

Idempotency is the first thing I check, because it's the one that costs real money. The spec must require an Idempotency-Key header on POST /payments, and must say what the server does with it: store key → response for a bounded window (Stripe documents 24 hours), and on replay return the stored body and the original status code, not a fresh charge. The mechanism matters because a client that times out on the socket cannot distinguish "never created" from "created, response lost." Without the key, the retry double-charges. Two details the spec usually omits and must not: the key is scoped per merchant and per endpoint, and reusing a key with a different request body must be rejected. Stripe returns an error rather than silently replaying the old response. If the spec lets a new body ride an old key, it has a silent-corruption bug.

State machine. I want the spec to name every state and mark which are terminal. A card payment typically goes created → requires_action (3-D Secure) → processing → succeeded | failed. processing is not terminal, and the spec has to say so, because the common integration bug is treating it as success and shipping goods.

Synchronous versus accepted is a real trade-off, and the deciding criterion is whether the payment method has a synchronous authorization step. Card authorization answers in well under two seconds, so return the final state in the response. Bank transfer, voucher, and some wallets settle out of band, so return 202 with a resource in pending and drive the outcome by webhook. Getting this backwards has a cost either way: force everything synchronous and you hold connections open on methods that can't answer; return 202 for cards and clients poll or, worse, assume success.

Error contract. I'd ask for a table like this, and reject the spec if declines and errors share a code:

StatusMeaningClient action
400Validation, param names the fieldFix request, do not retry
402Decline, with a decline_codeSurface to customer, do not retry
409Idempotency key reused with different bodyBug, alert
429Rate limited, Retry-After presentBack off
5xx / timeoutUnknown, not failedReconcile, never show "declined"

That last row is the one people get wrong. A 502 means we don't know whether the charge exists.

Failure modes, with how I'd detect each. Timeout after commit: a daily reconciliation job pulls the PSP's settlement or balance-transaction feed and matches on our idempotency key or the PSP reference; alert when unmatched rows are non-zero. Duplicate submission via a new key on retry: detect by clustering same merchant + amount + currency + card fingerprint inside a short window. Forged or replayed webhooks: verify the HMAC over timestamp plus raw body, reject timestamps older than the tolerance (Stripe's default is 5 minutes), and dedupe on event id, because delivery is at-least-once.

One piece of arithmetic worth doing in the room. If the client retries with exponential backoff capped at a minute for ten attempts, that's roughly ten minutes: comfortably inside a 24-hour key window. But a batch job that retries the next day with the same key gets a fresh charge. So the key must be derived from the order id, not generated per attempt. That single sentence is usually the difference between a safe integration and a duplicate-charge incident.

Currency. Amount and currency must be validated together: 1000 is $10.00 in USD and ¥1000 in JPY, because ISO 4217 gives JPY zero decimal places. The spec should state the minor-unit convention and reject unknown currency codes rather than guessing an exponent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Investigate a specification that diverges from production.

Answer

Core answer

A published spec is a contract, not documentation. When it diverges from production, the first move is not to fix either side: it is to decide which side is authoritative, because that is a product/ownership call, not a technical one. Then diff three layers in order: source spec, generated artefacts, live behaviour. Fix the wrong side, ship a migration, and add a gate so it cannot drift silently again.

Assumptions I'd state up front: the spec is versioned in git and published to consumers; there is a gateway in front of the service; at least one consumer generates a client from the spec.

Why divergence happens

Two roots, and they need different fixes.

Code-first. The spec is a projection of code: springdoc-openapi reads annotations, FastAPI emits OpenAPI from route signatures. The spec drifts the moment someone changes a handler and does not regenerate. The code is authoritative; the spec is stale.

Spec-first. The spec is the source and clients are generated with openapi-generator. Drift appears when a hand-edit lands in a generated client, or the server quietly ignores the spec.

Gateway rewriting. The third layer people miss. Kong's request-transformer/response-transformer plugins, AWS API Gateway VTL mapping templates, or an Envoy Lua filter can rename fields or change status codes without touching spec or service. Spec and service agree; the wire does not.

Worked trace

Hypothetical: POST /orders.

layerobservedverdict
source spec201, orderId: stringok
generated clientorder_id: strok
live response200, {"id": 42}gateway response-transformer renamed and retyped

Spec-vs-service contract tests pass here. Only a test run through the gateway catches it. That is the detection signal: run Schemathesis or Dredd against the gateway URL, not the pod.

Which side wins

  • Consumers already depend on the deployed shape and it is not security- or data-breaking → deployed behaviour is the de facto contract. Update the spec, mark the old field deprecated, set a removal date.
  • Deployed behaviour leaks internals or breaks a documented guarantee → the code is wrong. Fix it and migrate consumers.
  • Never silently regenerate clients. That changes the contract for every consumer at once, on their next build, at runtime rather than compile time.

Failure modes

  • Silent regeneration. A consumer's generated client changes field names on next build; it breaks at runtime. Detect with Pact can-i-deploy failing verification.
  • Gateway masking. Spec and service agree, gateway disagrees. Detect by running contract tests through the gateway.
  • Spec-vs-spec-only drift check. oasdiff or openapi-diff comparing two spec files catches nothing about runtime. Pair it with a live check.

CI gate

Shell
openapi-generator generate -i openapi.yaml -g python -o /tmp/client
git diff --exit-code /tmp/client   # fails if committed client != regenerated

Blast radius arithmetic: 3 consumers. 2 internal on latest, 1 external pinned to v1.2.0. Only the pinned one is safe from a silent regeneration; the two internal ones are the migration cost.

Record why governance failed (a spec that was never regenerated in CI, or a gateway change with no spec review) because that is the fix that stops the next one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Create a contract-test strategy for an API platform.

Answer

What I'd say first

Assume ~40 services, each owning an OpenAPI 3.1 document in its repo, three or four consumer teams per provider, independent deploys, one shared staging environment. If a provider has exactly one consumer and both ship from the same repo, I'd skip consumer-driven contracts: the coordination cost buys nothing. The strategy below is for the case where consumers live outside the provider's repo and the provider cannot enumerate them.

Four layers, four different oracles

The reason to have more than one layer is that each uses a different thing as its source of truth, and so fails differently.

LayerToolOracleCatchesBlind to
Spec lintSpectral, spectral:oas rulesetstyle and consistency rulesmissing operationId, undocumented 4xx, inconsistent casingeverything at runtime
Breaking-change diffoasdiff, released spec vs PR specthe last released specremoved response fields, narrowed enums, newly required request paramsa spec and its implementation changed together
Schema-driven property testsSchemathesis against stagingthe provider's own spec500s on unhandled enum values, responses that don't match the declared schemathe same coordinated change
Consumer-driven contractsPact + brokerthe consumer's recorded expectationsprovider changes that break a real consumeranything no consumer exercises

The last two are not redundant, and this is the point most candidates miss. Schemathesis asks "does the provider match its own spec?" If a team renames status to state in both the spec and the code in one PR, Schemathesis passes: the spec moved with the code. Pact asks "does the provider still satisfy what checkout-web actually sends and reads?" That oracle lives in a different repo, so a coordinated change cannot move it.

What a pact actually is

A pact file is the consumer's recorded interactions, not a copy of the spec:

JSON
{
  "consumer": { "name": "checkout-web" },
  "provider": { "name": "orders-api" },
  "interactions": [{
    "description": "a request for order 42",
    "providerStates": [{ "name": "order 42 exists" }],
    "request": { "method": "GET", "path": "/orders/42" },
    "response": {
      "status": 200,
      "body": { "id": 42, "status": "shipped" },
      "matchingRules": {
        "$.body.status": { "match": "regex", "regex": "^(pending|shipped|delivered)$" }
      }
    }
  }],
  "metadata": { "pactSpecification": { "version": "3.0.0" } }
}

The matchingRules entry is the whole design decision. A regex matcher on status lets the provider add cancelled without breaking checkout-web. An exact-value matcher would not. Every field the consumer doesn't read should be matched by type, not value.

Trace: provider renames status to state

  1. Spectral: passes. The document is still valid.
  2. oasdiff against the released spec: flags the removed response property. PR blocked.
  3. If it slipped through: provider CI runs pact verify against the broker's pacts. checkout-web's regex matcher finds no status field, so verification fails and the provider build goes red.
  4. can-i-deploy in the broker refuses the provider's deploy because a consumer version in production has no verified pact against it.

Step 3 is the one that matters: the failure surfaces in the provider's pipeline, not as a null field in checkout-web's UI three days later.

Failure modes and how I'd detect them

  • Over-specified pacts freeze the provider. Symptom: every field addition becomes a negotiation. Detection: review pact diffs in PRs and count exact-value matchers on fields the consumer's code never reads. Fix: type matchers.
  • Flaky provider verification. Usually a shared staging database with no seeded state. Symptom: teams start ignoring red builds. Detection: track verification pass rate per provider over 30 days; quarantine a provider below ~95% and fix the state handler rather than retrying.
  • Spec drift. The spec declares an enum, the provider returns free text. Detection: nightly Schemathesis run against staging with response-schema conformance enabled; a failure here means the spec is a lie, which is worse than a missing spec.

The gate order I'd ship

Spectral and oasdiff on every PR (seconds, no environment). Schemathesis nightly against staging. Pact verification on every provider PR, can-i-deploy before every production deploy. That ordering puts the cheapest, most deterministic checks first and the environment-dependent ones where a flake costs least.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design distributed tracing requirements for an API.

Answer

Assumptions: HTTP/gRPC services, OpenTelemetry SDKs, an OTel Collector, and a backend (Tempo/Jaeger) that indexes by service and operation. Multi-tenant.

Core answer. Accept W3C Trace Context at the first trusted boundary. If a valid traceparent arrives, continue that trace; if it is missing or malformed, start a new one. Every service sets its own span id as parent-id; only the root sets trace-id. Propagate through every hop, including async. Keep span attributes low-cardinality. Sample so errors and slow traces survive. Treat trace data as sensitive.

The header. traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01: version 00, 16-byte trace-id (not all zeros), 8-byte parent-id, flags where bit 0 means sampled. tracestate carries vendor state and the spec caps it at 32 list members and 512 bytes; reject or truncate beyond that. Never use either for identity or authorization: both are attacker-controlled.

Why low cardinality. Attribute values become index keys in the backend. http.route = /users/{id} is one series; http.route = /users/12345 is one per user. A user.id attribute across 1M users creates 1M series per operation, and query latency and storage grow with series count, not request count. Put high-cardinality values in span events or logs. OTel caps attributes at 128 per span by default.

Sampling. Head-based: decide at the root, propagate via the sampled flag. Cheap, one decision, but you commit before you know which traces matter. Tail-based: the collector buffers spans for the trace duration (say 30s), then keeps all traces with errors or p99 latency and samples the rest at 1-5%. Costs memory and requires all spans of a trace to reach the same collector: load-balance by trace-id.

head-basedtail-based
decision pointrootcollector, after trace ends
cost~zerobuffer memory, collector CPU
keeps errorsonly if sampledyes, by policy
use whenhigh volume, cost-bounddebugging matters more than volume

Failure modes.

  • Malformed traceparent → each hop starts a new trace; traces fragment. Detect: more than one root span per request, or orphan spans.
  • Async work drops context → queue consumers emit parentless spans. Detect: spans with no parent in consumer services.
  • Cardinality explosion → index growth. Detect: series count per attribute.
  • Sampling drops the error trace → trace error rate diverges from metric error rate. Detect: compare the two.
  • Cross-tenant leakage → trace shows another tenant's data. Detect: tenant id in trace vs request mismatch.

When not to trace. Don't trace health checks, static assets, or high-volume batch jobs where metrics answer the question; sample them at 0 and keep the metrics.

Curated: · Written: · Reviewed:

Difficulty: Hard