Skip to content
Tech Interview Prep

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-1

What is REST, and what do most so-called REST APIs actually implement?

Answer

The 90-second answer. REST is Roy Fielding's architectural style, defined in chapter 5 of his 2000 dissertation. Six constraints: client–server, stateless, cacheable, uniform interface, layered system, and code-on-demand. The last being the only optional one. The uniform interface has four parts: resources identified in the request, manipulation through representations, self-descriptive messages, and hypermedia as the engine of application state.

Most APIs that call themselves REST satisfy the first five loosely and drop hypermedia entirely. Leonard Richardson's maturity model (a 2008 QCon talk, written up by Martin Fowler in 2010) names the levels, and the overwhelming majority of public APIs sit at level 2:

LevelShapeExamples
0One URL, one verb, action in the bodySOAP, XML-RPC
1Many URLs, still POST for everything/getUser?id=7
2Resources + HTTP verbs + status codesGitHub, Stripe, most public APIs
3Level 2 + links that drive transitionsGitHub's Link header pagination; HAL, JSON:API

So the honest answer is: what most people build is HTTP + JSON RPC with resource-shaped URLs. That is a defensible engineering choice, but only if you know which constraints you dropped.

Two exchanges that show what the dropped constraints buy you.

Conditional GET, which only works because GET is safe and responses are self-descriptive:

GET /v1/charges/ch_3Px HTTP/1.1
Host: api.example.com
If-None-Match: "a1b2c3"

HTTP/1.1 304 Not Modified
ETag: "a1b2c3"
Cache-Control: private, max-age=60

The server compares the tag, finds the representation unchanged, and returns headers with no body. A 304 is a few hundred bytes of headers against a 40 KB JSON body: call it 99% of the bytes saved on a cache hit. That is the cacheability constraint paying rent.

Idempotent retry, which only works because the client can safely repeat the request:

POST /v1/charges HTTP/1.1
Idempotency-Key: 7f3c9a41-...

HTTP/1.1 201 Created
Location: /v1/charges/ch_3Px

The client times out before reading the response and retries with the same key. The server finds the stored response for that key and replays the same 201 and the same body; no second charge is created. Stripe documents this behaviour and a 24-hour retention window for keys. There is an IETF draft, draft-ietf-httpapi-idempotency-key-header, standardising the header: a draft, not an RFC.

Failure modes, and how you see them.

  • Retrying a POST that is neither safe nor idempotent double-charges. You detect it as duplicate rows or duplicate charges with near-identical timestamps, and fix it with an idempotency key.
  • Using POST for reads makes the response uncacheable by any intermediary and unsafe to retry after a timeout. Detection: cache hit ratio near zero on endpoints that are read-only.
  • Returning 200 OK with {"error": ...} in the body means every proxy, retry library and dashboard reads failure as success. Detection: your error-rate graph says 0% while support tickets say otherwise. Use the codes as defined in RFC 9110: 201 with Location, 204, 304, 409, 412, 429 with Retry-After, 503 with Retry-After.
  • Keeping client session state on the server breaks statelessness: a request that lands on another instance fails, so you add sticky sessions, and rolling deploys start dropping user sessions.

When full hypermedia is worth it. Long-lived public APIs with clients you do not control, where you want to add transitions without breaking callers. When one front end ships alongside the API, links in payloads are mostly ceremony.

The practical core: model resources, use HTTP semantics as defined rather than as convention, and keep no client session state on the server. An action endpoint where a noun would be contorted is fine, not knowing which constraint you dropped is not, because the bill arrives later as an API that cannot be cached, cannot be retried safely, or reports failures as successes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain safety and idempotency, and why they matter beyond documentation.

Answer

Safe means the client is not asking for a state change; idempotent means applying the request N times leaves the same end state as applying it once. RFC 9110 defines both. Safe: GET, HEAD, OPTIONS, TRACE. Idempotent adds PUT and DELETE. POST is neither, and PATCH is not idempotent unless you design it that way.

methodsafeidempotent
GET, HEAD, OPTIONS, TRACEyesyes
PUT, DELETEnoyes
POSTnono
PATCHnono (unless designed)

These are not documentation because intermediaries you do not control act on them. Caches store GET responses (RFC 9111). Browsers and prefetchers issue GETs speculatively. Crawlers follow every link. A GET that mutates gets fired by something no user intended: the admin panel whose delete links are <a href="/orders/123/delete"> is the standard casualty. On the other side, retry logic in clients, load balancers and service meshes retries idempotent methods automatically and refuses to retry POST, because a timeout is ambiguous: the request may have succeeded with the response lost.

Where POST is genuinely needed and retries matter, the fix is an idempotency key. Python 3.12, Redis-backed:

Python
def create_payment(req):
    key = req.headers["Idempotency-Key"]                 # client-generated UUID
    if not redis.set(f"idem:{key}", "in_progress", nx=True, ex=86400):
        stored = redis.get(f"idem:{key}")
        if stored == "in_progress":
            return 409, {"error": "request in flight"}   # concurrent duplicate
        return 200, json.loads(stored)                   # replay original result
    try:
        result = charge_card(req.json)                   # the side effect
        redis.set(f"idem:{key}", json.dumps(result), ex=86400)
        return 200, result
    except Exception:
        redis.delete(f"idem:{key}")                      # let the client retry
        raise

Trace of one $50 charge, key k1:

  1. SET idem:k1 in_progress NX EX 86400 → key absent, so it is set. Proceed.
  2. charge_card returns {"id": "ch_9", "amount": 5000}.
  3. SET idem:k1 to that JSON, TTL 86400.
  4. The 200 is lost: client times out at 2 s.
  5. Client retries the same body with the same key k1.
  6. SET ... NX returns nil. GET idem:k1 returns the JSON, not in_progress, so the handler returns 200 with the original body.
  7. Card charged once. Without the key, steps 4–5 charge twice: $100.

Two failure modes live in that snippet. If the process dies between step 1 and step 3, the key sits at in_progress and every retry gets 409 until the 86400 s TTL expires, so the TTL must exceed the client's retry window, and a crash-recovery sweep should clear stale in-progress keys. If the TTL is shorter than the retry window, the key is gone when the retry arrives and the charge repeats.

Idempotency is about end state, not response. DELETE /orders/123 returns 204, then 404 on the retry, and is still idempotent: the order is absent either way. Differing responses do not break it.

Retry amplification is why this is not academic. Three layers each retrying three times (client, load balancer, service mesh) turn one user action into up to 3³ = 27 attempts. On a non-idempotent POST that is 27 orders. On an idempotent PUT or a keyed POST it is one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How would you choose status codes for an API, and which distinctions matter most?

Answer

By using the standard meanings, because the audience is not only the client developer: it is caches, proxies, load balancers, monitoring and generic client libraries, all of which read the code and none of which read your documentation.

The ones I use routinely: 200 success with a body; 201 created, with Location; 202 accepted for asynchronous processing; 204 success with no body. 400 malformed; 401 not authenticated; 403 authenticated but not permitted; 404 not found; 409 conflict with current state; 422 well-formed but semantically invalid; 429 rate limited with Retry-After. 500 server fault; 503 temporarily unavailable, ideally with Retry-After.

The distinctions that matter most:

401 versus 403. 401 means authenticate and try again; 403 means authenticating differently will not help. Clients behave differently: a 401 triggers a token refresh, a 403 should not. Conflating them causes clients to loop refreshing tokens that were never the problem.

400 versus 422. Syntactically broken versus semantically wrong. It helps a client distinguish 'my serialisation is broken' from 'my data is wrong', which are different bugs.

404 versus 403 for hidden resources. Returning 403 for a resource the caller may not see confirms it exists, which can leak information. Returning 404 is often the right choice for that reason, and it is a deliberate decision rather than an accident.

4xx versus 5xx. 4xx means the client should change something; 5xx means the server failed and a retry may work. Getting this wrong corrupts error budgets and alerting: a validation failure counted as a server error creates noise, and a server fault reported as 400 hides a real problem.

The worst option is 200 with an error in the body. Every intermediary treats it as success, monitoring shows everything healthy, and generic clients do not notice. If I found that in a review it would be the first thing I raised.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How should an API report errors so clients can act on them?

Answer

An error response has to let a client decide three things without reading your docs: whose fault it is, whether retrying helps, and what exactly was wrong. The status code carries the first two; the body carries the third.

Status code = fault + retryability. 4xx means the client must change the request: resending the same bytes fails again. 5xx means the server failed and a retry may succeed. 429 and 503 carry Retry-After (seconds or an HTTP-date) so the client knows when. This is not cosmetic: generic HTTP clients and service meshes make retry decisions from the code alone, so a 500 returned for a validation failure produces a retry storm against a request that can never succeed.

Body = specifics. For the shape, the real choice is between a standard envelope and a bespoke one.

formatshapewins whencost
RFC 9457application/problem+json with type, title, status, detail, instance + extensionsHTTP API, more than one client, you want shared toolingthe spec does not type your extension members, so per-field detail is still your own convention
custom envelope{"error": {"code", "message"}}one internal API, one client, full controlevery client writes bespoke parsing; no shared tooling
JSON:API errorstop-level errors[] with source.pointeryou already committed to JSON:API end to endheavy; only pays off if the whole API is JSON:API
GraphQL-styleerrors[] with path/extensions, often HTTP 200the transport is GraphQLthe status code stops signalling fault, so HTTP-level retry and alerting break

Deciding criteria, in order: does a generic client or mesh need to act on the status code? Is there more than one client? Do you need per-field validation detail? Is the transport GraphQL? If the first two are yes and the last is no, RFC 9457 is the default, but be honest that it buys you the envelope, not the field-level contract.

Worked example. A client POSTs an order and gets:

HTTP
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
X-Request-Id: 01HQ8Z7K3M

{
  "type": "https://api.example.com/problems/validation",
  "title": "Request failed validation",
  "status": 422,
  "detail": "2 fields are invalid",
  "errors": [
    {"field": "quantity", "code": "out_of_range", "message": "must be between 1 and 99"},
    {"field": "ship_to.postal_code", "code": "invalid_format", "message": "not a valid US ZIP"}
  ]
}

Trace the client's handler: (1) 422 is 4xx, so do not retry. Surface to the caller. (2) type routes to the validation handler rather than the generic one. (3) Iterate errors, map field onto form inputs, render message. (4) Log X-Request-Id so support can pull the server-side detail. The code is stable and machine-matched; message is free to be localised.

For a retryable case the same shape applies: 429 with Retry-After: 30 means sleep 30 s and retry once; if the header is absent, fall back to exponential backoff with jitter rather than hammering.

Failure modes to avoid. Returning 200 with an error body: meshes and alerting miss it entirely. 500 for client mistakes: retry storms. 429 without Retry-After: clients guess and synchronise into a thundering herd. Stack traces, SQL, internal hostnames and library versions in the body: they help an attacker and no legitimate client; the correlation id is the bridge instead. Three different shapes for validation, auth and server errors: clients write three parsers and get two wrong. And document the error cases in the API description next to the success cases: a client that has never seen a 409 will not handle it, and the first time it appears will be in production.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How would you decide what a resource should be in an unfamiliar domain?

Answer

I'd assume no API exists yet, I have read access to the schema, and I can get two hours with domain experts. Then four passes in order (nouns, workflows, ownership, lifecycle) and one real client screen built against the draft before anything is published.

1. Nouns from the experts, not the schema

Ask them to describe a normal day and write down every noun they say. Say the schema looks like this:

Domain experts saySchema saysAPI resource
clientowner/v1/clients
patientanimal/v1/patients
—owner_animal_linknot exposed
visitappointment + encounter/v1/visits
chart noteclinical_note/v1/visits/{id}/notes
vaccinationimmunization/v1/patients/{id}/vaccinations

Use the left column. owner_animal_link is a join table: an implementation detail, never a resource. animal vs patient matters: the consumers are front-desk staff and integrations, and they say patient.

2. Workflows decide what actually gets an address

Take the first screen a user sees and list the calls it needs. "Today's schedule" needs visits for a date range, each with patient name, client name, vet and status. That is one call if visit embeds summaries, three if it returns bare IDs:

GET /v1/visits?date=2024-06-03&include=patient,client

JSON:API's include is the mechanism; Stripe's expand[] is the same idea. On a 4G connection at roughly 80 ms RTT, three sequential calls is ~240 ms of dead time before the first pixel: worth designing away. List endpoints get cursor pagination with a documented default and cap; GitHub's REST API defaults per_page to 30 and caps it at 100, which is a reasonable shape to copy.

3. Ownership gives the hierarchy, and one level is usually enough

A chart note belongs to a visit; a vaccination belongs to a patient. So GET /v1/patients/{id}/vaccinations is right. GET /v1/clients/{id}/patients/{pid}/visits/{vid}/notes is not: three levels deep, and the client ID is redundant because a patient already implies its client. Flatten it to GET /v1/visits/{id}/notes.

4. Lifecycle decides the verbs

TransitionCallResponse
scheduled → checked-inPOST /v1/visits/{id}:check-in200, visit body
checked-in → in-progressPOST /v1/visits/{id}:start200
in-progress → closedPOST /v1/visits/{id}:close201 + invoice, or 202 if billing is async
illegal (closed → checked-in)same endpoint409 + RFC 9457 problem body
concurrent editPATCH with If-Match412 on ETag mismatch

The :verb suffix is Google's AIP-136 custom-method convention. A state change with no body is a custom method, not a PATCH of a status field: the status field is the thing clients would set illegally.

Signs the model is wrong

If the schedule screen needs more than two calls, granularity is too fine or embedding is missing. If visit has grown fields for lab orders, prescriptions and payments, three concepts have merged. If a client workflow has no endpoint that fits, a resource is missing. If I need more than a minute to explain the model to a domain expert, it doesn't match how they think: that's the signal I trust most.

Where I'd diverge deliberately

The internal model can be as complex as the domain needs; the API should be as simple as the use cases allow. The clinic's schema lets a patient have several owners (a family), but the front desk treats one as primary. Expose patient.client as a single object, keep the many-to-many internal, and add secondary_contacts only when a real client asks.

Prototype before publishing

Build the schedule screen against the draft. An hour of real client code finds the missing field and the wrong nesting faster than a day of modelling, and before publication the fix is free.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Explain how you would model an operation that is not naturally a resource.

Answer

Some operations are genuinely actions (cancel an order, send a password reset, retry a failed job, publish a draft) and forcing them into nouns produces worse APIs than accepting the exception.

There are three reasonable options, and I would choose by which reads most naturally.

Model the state change. PATCH /orders/123 with {"status": "cancelled"}. Works well when the action really is a state transition and the resource has a status field clients already understand. The weakness is that it implies any status change is permitted, when in reality only certain transitions are legal, so the server must validate them and return 409 or 422 for illegal ones, and the API does not communicate which are allowed.

Model the action as a resource. POST /orders/123/cancellations. This works genuinely well when the action has its own attributes (a reason, a timestamp, who performed it) because that thing is a real entity worth addressing, and you can then GET it. When the action has no attributes, the noun is invented and it reads as a contrivance.

Accept an action endpoint. POST /orders/123/cancel. Direct, unambiguous, and immediately understood. It uses POST correctly (not safe, not idempotent) and the only thing lost is URI purity.

My rule: if the action produces a thing worth recording and retrieving, model it as a resource. If it is a simple state transition with a well-understood status field, use PATCH. Otherwise use an action endpoint and stop worrying about it.

What I would avoid is inventing nouns nobody would use in conversation: a /orders/123/cancellationRequests collection with one member that exists only to satisfy a rule. That is worse for the reader than /cancel, and readability is the point of the convention in the first place.

And whichever is chosen, being consistent across the API matters more than the individual choice. Three different patterns for three similar actions is worse than any one of them applied uniformly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you handle partial updates to a resource?

Answer

PUT replaces the resource entirely. The client sends the complete representation and the server makes the resource match it. That is what makes PUT idempotent, and the consequence people miss is that omitting a field means clearing it, so a client that read a resource, changed one field, and PUT it back without a field it did not know about has just deleted that field's value. That is a silent data loss bug and it appears whenever the server adds a field the client's version does not know about.

PATCH applies a partial modification, so only the sent fields change. That avoids the problem and reduces payload size, but it introduces its own questions.

How do you express clearing a field? If omission means 'leave alone', explicit null usually means 'clear', but that must be documented, because it is not obvious and clients will assume differently.

How do you patch nested structures or arrays? Replace the whole array, or express element-level operations? JSON Merge Patch is simple and cannot express array element changes or distinguish 'set to null' from 'remove'. JSON Patch is fully expressive with an operation list, at the cost of being more awkward to produce and consume. For most APIs a simple merge-style PATCH is sufficient and I would document its exact semantics carefully rather than assume they are understood.

Is it idempotent? A merge-style PATCH usually is. An operation-based one, 'append to array', is not, which matters for retry safety and should be stated.

My default: PATCH for updates, with merge semantics, explicit null to clear, documented precisely. PUT where the client genuinely holds the whole representation and replacement is the intent: a configuration document, say.

And PATCH pairs well with optimistic concurrency: because two clients editing different fields do not conflict, an If-Match guard rejects only genuine conflicts rather than every concurrent edit, which is a better experience than PUT's all-or-nothing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

How would you handle concurrent updates to the same resource?

Answer

Without something in place, the default is last-write-wins: two clients read a resource, both update, and the second silently overwrites the first. The user whose changes vanished experiences it as the system losing their work, which is one of the more damaging bugs a product can have.

HTTP has a built-in mechanism: ETag with If-Match. The server returns an ETag, a version identifier, on GET. The client sends it back in If-Match on the update. If the resource changed since, the ETag no longer matches and the server returns 412 Precondition Failed. The client then re-reads and decides what to do.

I prefer this over a version field in the body because it is standard, works with generic clients and intermediaries, and keeps concurrency control out of the payload schema.

Server-side it must be atomic. Checking the ETag and then writing is check-then-act, which races: two requests can both find a match and both write. The check must be part of the write (a conditional update guarded by the version, verifying one row was affected) or the whole mechanism is theatre that works in testing and fails under load.

What the client does on 412 is a product decision, not a technical one. Re-read and retry automatically is right when the update is mechanical. Showing the user what changed and letting them decide is right when they authored content: silently discarding either version is what we were trying to avoid.

Partial updates reduce conflicts. If two clients edit different fields, a PATCH with only the changed fields can succeed for both, where a PUT replacing the whole resource makes them conflict unnecessarily. That is a real argument for PATCH beyond payload size.

When it is not needed: single-writer resources, append-only collections, and commutative operations like incrementing a counter, which merge without conflict. Adding concurrency control everywhere costs clients complexity for no benefit, so I would apply it to resources several actors genuinely edit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain HTTP caching and how an API should use it.

Answer

The 90-second answer. HTTP already ships a two-part caching model: freshness (may I reuse this without asking?) and validation (has it changed since I stored it?). An API should set Cache-Control explicitly on every response and emit an ETag on anything cacheable. Freshness absorbs load; validation makes the stale case cheap. Most APIs do neither, then bolt a lastUpdated field onto the payload, which only works for clients that opt in, and gets no help from any CDN or proxy sitting in front of them.

Freshness. Cache-Control decides whether a stored response can be reused without a round trip.

DirectiveMeaning
max-age=60Fresh for 60s in any cache
s-maxage=300Overrides max-age for shared caches (CDN, gateway)
privateOnly the browser may store it
publicShared caches may store it even when Authorization is present
no-cacheMay store, but must revalidate before every reuse
no-storeMust not store at all
stale-while-revalidate=30Serve stale for up to 30s while refreshing in the background

The one people get wrong: no-cache does not mean "do not cache". It means "cache it, but check first". no-store is the one that forbids storage.

Validation. An ETag is an opaque version token for the representation. A client holding a stale copy sends it back in If-None-Match; if the server's current tag matches, it answers 304 Not Modified with headers only and no body.

Worked trace (hypothetical figures, but the header flow is exact):

t=0s    GET /v1/products/42
        -> 200 OK
           Cache-Control: public, max-age=60
           ETag: "a1b2c3"
           body: 40 KB JSON

t=30s   GET /v1/products/42
        -> served from cache. Zero bytes on the wire.

t=90s   GET /v1/products/42
        If-None-Match: "a1b2c3"
        -> 304 Not Modified, ~250 bytes of headers, no body.
           Client reuses the stored 40 KB.

t=120s  product edited; GET with If-None-Match: "a1b2c3"
        -> 200 OK, ETag: "d4e5f6", new 40 KB body.

The arithmetic: at 1,000 req/s with 40 KB responses, that endpoint pushes 40 MB/s of egress. With max-age=60 and a 95% fresh-hit rate it drops to roughly 2 MB/s. The remaining 5% revalidate at ~250 bytes instead of 40 KB: about 0.6% of the bytes for the same correctness.

Vary is where this goes wrong. Any response that depends on a request header must name it: Vary: Accept-Encoding, Vary: Accept-Language, and above all Vary: Authorization on anything user-specific. Without it, a shared cache keys only on the URL and will hand user A's response to user B. That is the worst failure in this area, and it is silent. Pair it with private on personalised responses: private alone is not enough if the response also varies on something the cache can't see.

Conditional requests do double duty. The same ETag drives If-None-Match for caching and If-Match for optimistic concurrency: a client that read version "a1b2c3" sends If-Match: "a1b2c3" on its PUT, and the server answers 412 Precondition Failed if someone else wrote first. One mechanism, two uses: no separate version column needed.

What I would not do is invent a bespoke scheme in the payload: a lastUpdated timestamp clients are expected to compare, or a ?version= query parameter. That reimplements validation badly, works only with clients that implement it, and forfeits every intermediary that already speaks HTTP.

The practical rule: set Cache-Control on every response, including no-store on the ones that must never be stored. Defaults differ between browsers, CDNs and gateways, and an unspecified policy means the behaviour is whatever some proxy decided: a stale-data bug that is genuinely hard to diagnose because nothing in your code is wrong.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How would you design pagination for a large collection endpoint?

Answer

First: pagination is not optional and must exist from the first release, because adding it later is a breaking change. Existing clients silently start receiving fewer results, which is worse than an error because nobody notices.

Cursor-based is my default for anything large or frequently changing. The response returns items plus an opaque cursor for the next page; the client passes it back. The server implements it as a keyset query: WHERE (created_at, id) < (:cursor_time, :cursor_id) ORDER BY created_at DESC, id DESC LIMIT :n.

That solves both problems offsets have. Cost: an offset requires generating and discarding every skipped row, so page 5,000 is genuinely slow, while a cursor seeks directly. Correctness: with offsets, an insert between requests shifts everything, so the client sees a row twice or misses one entirely. For an export or a job iterating every page, that is silent data corruption rather than a UX annoyance.

The cursor should be opaque, base64 of the key values, so its structure is not part of the contract and can change without breaking clients. It should also encode the sort order it was issued for, so a client cannot change sorting mid-pagination and get incoherent results.

Offsets remain acceptable for small, bounded collections where users genuinely want page numbers. Admin tables with a few thousand rows are fine, and simplicity has value.

The rest of the contract: a default page size and a server-enforced maximum, because a client will otherwise request everything. A consistent envelope across every collection endpoint, the same field names for items and cursor, so learning one teaches all of them. And total counts only if genuinely needed, since an exact count over a large filtered set can cost more than the page itself; an approximate count or none at all is often better, and 'has more' is usually the only thing the UI actually needs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How would you design an endpoint for a long-running operation?

Answer

Holding the connection open doesn't work. nginx's proxy_read_timeout defaults to 60s, an ALB's idle timeout defaults to 60s, and mobile clients give up sooner than either. So the operation becomes a resource the client can check.

POST /v1/reports returns 202 Accepted (RFC 9110 §15.3.3) with Location: /v1/jobs/8f3c1a and Retry-After: 5. The client polls GET /v1/jobs/8f3c1a until the state is terminal. Making the job a resource is what makes this clean: it has an id, it can be fetched, listed, and audited.

Worked trace

POST /v1/reports HTTP/1.1
Host: api.example.com
Idempotency-Key: 7d1f9c2e-4a11-4b0e-9c33-2f6a1d8e5b70
Content-Type: application/json

{"from":"2024-01-01","to":"2024-03-31","format":"csv"}
HTTP/1.1 202 Accepted
Location: /v1/jobs/8f3c1a
Retry-After: 5

{"id":"8f3c1a","state":"pending"}

Poll at t+5s:

GET /v1/jobs/8f3c1a

200 OK
Retry-After: 5

{"id":"8f3c1a","state":"running",
 "progress":{"done":12000,"total":48000},
 "started_at":"2024-04-03T10:00:05Z"}

Poll at t+40s:

200 OK

{"id":"8f3c1a","state":"succeeded",
 "result":{"url":"/v1/jobs/8f3c1a/result",
           "bytes":18432000,
           "expires_at":"2024-04-10T10:00:00Z"}}

Re-sending the POST with the same Idempotency-Key returns the same 202 and the same Location: no second job.

Poll schedule

The server sets Retry-After from observed progress rather than a fixed interval. 12,000 of 48,000 rows in 5s means roughly 15s remaining, so 5–10s is the right next wait; cap it at 30s so a stalled job doesn't leave the client blind.

pollRetry-Afterelapsed
15s5s
25s10s
310s20s
420s40s
530s (cap)70s

Without Retry-After, clients pick 100ms and the status endpoint becomes the load problem.

Cost arithmetic

10,000 concurrent jobs polling every 5s is 2,000 rps on the status endpoint. At ~200 bytes per response that's 400 KB/s: fine for a read replica or Redis, not fine if every poll reads the row the worker is writing. Keep job state in a store that tolerates that read rate, and have the worker push progress rather than the poller recompute it.

Failure path

A failed job stays retrievable with something the client can act on:

{"state":"failed",
 "error":{"code":"source_unavailable",
          "message":"upstream warehouse returned 503 after 3 retries",
          "retryable":true}}

Retention is stated, not implied: job records kept 7 days after a terminal state, result blobs 7 days, with expires_at on the result so clients know how long they may collect it.

Idempotency

Idempotency-Key is a convention (Stripe popularised it; an IETF draft exists) rather than an RFC-defined header, so document it. Store key → job id with a 24h TTL, scoped per account. Same key with a different body returns 409.

Alternatives

A webhook avoids polling but requires the client to run an endpoint and requires you to handle delivery failures, retries and signature verification. SSE or WebSocket suits a UI watching in real time, but it reintroduces the long-lived connection we were avoiding. Offer polling regardless; the others are options.

If the operation reliably finishes under ~10s, do it synchronously: the job resource, retention and idempotency machinery isn't worth it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

What makes an API easy to consume, from a client developer's perspective?

Answer

The 90-second answer. An API is easy to consume when I can predict the next call from the last one, when a failure tells me exactly what to change, and when I can build against it without touching production data. Predictability is the big one: one pagination shape, one error shape, one timestamp format, one auth scheme, one naming convention. If GET /v1/orders returns {"data": [...], "next_cursor": "..."}, then GET /v1/customers must return the same envelope. An API where each endpoint was designed by a different team forces me to read the docs for every call, and I will still get it wrong.

Errors that name the fix. Compare what comes back:

hard to consumeeasy to consume
media typeapplication/jsonapplication/problem+json (RFC 9457)
body{"error":"Invalid request"}{"type":"https://api.example.com/errors/validation","title":"Validation failed","status":422,"detail":"email is not a valid address","errors":[{"field":"email","code":"invalid_format"}]}
retry signalnone429 with Retry-After: 30 (RFC 9110)

Retry-After is the difference between a client that backs off correctly and one that hammers you. Same for rate-limit headers: the IETF draft defines RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (delta-seconds); GitHub ships x-ratelimit-limit, x-ratelimit-remaining and x-ratelimit-reset (epoch seconds). Without them I discover the limit by hitting it, in production.

Concurrency and retries. An ETag on the read plus If-Match on the write gives me 412 Precondition Failed when someone else changed the row first: a lost-update bug I never have to debug. For POSTs, an Idempotency-Key header (Stripe's convention) means a retry after a timeout doesn't create a second order.

Data I can use without a second call. Hypothetical but typical: 100 orders, each response carries author_id, and I need the name. Serial fetch at 40 ms RTT is 100 × 40 ms = 4 s of wall clock, and HTTP/2 multiplexing removes the connection overhead, not the 100 units of server work. ?expand=author or a fields= parameter turns that into one request. If you can't include it, offer expansion: an N+1 across the network is the most common integration bug I've written.

Sensible defaults. If the simple case needs twelve parameters, most with an obvious value, that is friction on every call. Default limit=20, a default sort, UTC timestamps.

A sandbox or test mode. Without one, my integration is developed against production, which is bad for both of us.

Docs generated from a spec (OpenAPI) so they cannot drift. Docs that contradict behaviour are worse than none, because I trust them and then debug the wrong thing.

Stability. Breaking changes with notice and a migration path. Awkward design is a one-off cost; instability is continuous.

The thing I would tell a team shipping one: build something real on your own API before publishing. Most of these problems show up within an hour of consuming it and are invisible from the inside: cheap to fix before you have clients, expensive after.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain how an API description like OpenAPI changes how a team works.

Answer

The 90-second answer. An OpenAPI document is a machine-readable contract, so reference docs, client SDKs, request/response validation and mocks all derive from one file instead of four hand-maintained copies. The workflow change is that the interface becomes reviewable before it is built, and CI can fail a pull request that breaks it. The file itself is not the win; the enforcement around the file is.

What actually derives from it

  • Reference docs: Swagger UI or Redoc render the same YAML.
  • Clients: openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o clients/ts, one command per target language.
  • Validation: express-openapi-validator middleware with validateResponses: true rejects a handler that returns a shape the spec does not allow.
  • Mocks: prism mock openapi.yaml serves the spec's examples, so a consumer can build against GET /orders/{id} before the handler exists.

Worked example: a rename that looks harmless

v1 requires id, status, total_cents on the 200 response. A PR changes it to:

YAML
# v2 (excerpt)
required: [id, status, total, currency]
properties:
  total:    { type: integer }
  currency: { type: string, enum: [USD, EUR] }

Trace it through the pipeline:

  1. spectral lint openapi.yaml --fail-severity=warn: passes. The document is well-formed; style linting cannot see the break.
  2. oasdiff breaking v1.yaml v2.yaml: reports the removed response property total_cents and the newly required currency as breaking, exits non-zero, PR blocked.
  3. If it merged anyway, the regenerated TypeScript client changes total_cents: number to total: number; currency: string, so every consumer fails at compile time instead of reading undefined at runtime.
  4. At runtime, validateResponses: true turns a handler still emitting total_cents into a 500 at the boundary rather than a silent contract violation.

Step 2 is the one that changes how the team works: the breaking change is visible in a diff, on the PR, before deploy.

ToolRunsCatchesDoes not catch
spectralCI lintstyle, missing examples, unused componentsimplementation drift
oasdiff breakingCI, on the diffremoved fields, new required params, narrowed enums, type changessame-type, different-meaning changes
openapi-generatorbuild—drift if clients are not regenerated
express-openapi-validatorruntimeresponses that violate the schemabusiness-logic correctness
prism mocklocal dev—serves examples only

Caveats. The spec binds only if something checks it; without the diff job and response validation it drifts exactly like the docs it replaced. Code-first generation (springdoc-openapi, swagger-jsdoc) keeps the spec in sync automatically but describes what the code does rather than what the contract should be, which forfeits the design review. Over-specification (pinning every field with maxLength, pattern and exhaustive enums) turns the spec into a second implementation nobody updates; specify what consumers depend on. On versions, 3.0.x remains the safest target for tooling; 3.1.0 (February 2021) aligns with JSON Schema 2020-12 and changes nullable and example, so confirm your generator supports it first.

Preference. Description-first for a new public API, where the interface deserves deliberate design and external review. Code-first for internal services whose consumers are colleagues and where drift is the bigger risk than design quality.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you test an HTTP API?

Answer

First I'd pin down what the API actually promises: the OpenAPI document, the auth model, and whether it is public or internal. Then I test in layers, each catching a class of defect the layer below structurally cannot.

LayerRuns againstCatchesIllustrative runtime
Unitfunction calls, no HTTPbusiness rules, edge arithmetic<1 ms per test
Requestreal server over real HTTProuting, status codes, headers, serialisation, auth10–50 ms per test
Contractthe OpenAPI 3.1 documentdrift between description and behaviourseconds
Compatibilitya recorded request corpusaccidental breaking changesseconds

Most business-rule coverage belongs in unit tests. Request tests are where the HTTP surface is actually verified, and they are the ones I would not skip.

Cross-user authorisation, every endpoint. This is the defect class that gets exploited and the one most often missing. A request-level test, not a unit test:

Python
# pytest 8.1 + httpx 0.27, against a live server on localhost:8000
import httpx, pytest
from concurrent.futures import ThreadPoolExecutor

BASE = "http://localhost:8000"

@pytest.fixture
def alice():
    with httpx.Client(base_url=BASE) as c:
        c.headers["Authorization"] = "Bearer " + login(c, "alice")
        yield c

def test_cannot_read_another_users_order(alice, bob_order_id):
    r = alice.get(f"/orders/{bob_order_id}")
    assert r.status_code == 404        # not 403: 403 confirms the id exists
    assert "bob" not in r.text.lower()

def test_concurrent_update_loses_nothing(alice, order_id):
    etag = alice.get(f"/orders/{order_id}").headers["ETag"]   # e.g. W/"7"
    def patch(qty):
        return alice.patch(f"/orders/{order_id}", json={"qty": qty},
                           headers={"If-Match": etag})
    with ThreadPoolExecutor(2) as pool:
        a, b = [f.result() for f in [pool.submit(patch, 2), pool.submit(patch, 3)]]
    assert sorted([a.status_code, b.status_code]) == [200, 412]

httpx.Client is thread-safe, so both PATCHes genuinely race. Fired sequentially the same test passes even on a server with no precondition check at all: the second write silently overwrites the first, and you get [200, 200].

Pagination, traced. 100 orders, GET /orders?limit=20&offset=0, ordered by created_at.

  1. Page 1 returns orders 1–20.
  2. Order 1 is deleted.
  3. Page 2, offset=20, now indexes into a 99-item list: positions 21–40, i.e. orders 22–41.

Order 21 is never returned by any page. Keyset pagination, GET /orders?limit=20&after=<cursor> compiled to WHERE (created_at, id) > ($1, $2) ORDER BY created_at, id LIMIT 20, has no such window, because the cursor is a position in the data, not an offset into a shifting list. Test the empty collection, the last partial page, and a mutation between pages.

Status codes I assert explicitly, because they are cheap to get wrong and clients branch on them:

SituationStatusNote
Missing or invalid token401include WWW-Authenticate
Valid token, someone else's resource404403 leaks existence
Body fails schema400 or 422RFC 9110 names 422 "Unprocessable Content"
Wrong Content-Type415
Body over the limit413RFC 9110 names it "Content Too Large"
Stale If-Match412
Rate limited429include Retry-After

Error bodies: assert the shape, not the wording. If you emit RFC 9457 problem details (application/problem+json with type, title, status, detail, instance), assert those fields exist and that no stack trace or SQL fragment appears in detail.

Contract tests run the OpenAPI document against the implementation in both directions: schemathesis generates cases from the spec and checks responses validate; a coverage check asserts every documented path is exercised and every live path is documented. Without this the description drifts and becomes worse than nothing.

What I would avoid: testing only through a generated client, which hides raw protocol problems a third-party client hits; mocking the HTTP layer inside request tests, which tests the mock; and asserting exact error message strings, which breaks on every copy edit and catches nothing.

For a published API, add compatibility tests: oasdiff in CI to flag removed fields and narrowed types, plus a corpus of recorded requests from the previous version replayed against the new build before release.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How would you design an API's authentication and authorisation surface?

Answer

The 90-second answer. Authentication establishes who is calling; authorisation establishes what they may do to which object. They are separate mechanisms with separate failure modes, and the status codes keep them apart: 401 (carrying a WWW-Authenticate header, per RFC 9110) means the credential is missing or invalid; 403 means the credential is good and the answer is still no. A client that treats 403 as "refresh and retry" loops forever on a token that was never the problem.

The design I'd argue for: authenticate once at the edge, then authorise every request against the specific object, enforced in the data layer rather than by each handler remembering. The class this prevents is OWASP API1:2023, Broken Object Level Authorization, the top entry in the 2023 API Security Top 10, where an authenticated caller substitutes an ID in a URL and reads someone else's record. "Can this user read orders" is not the question; "can this user read this order" is.

Credentials.

mechanismfitsrevocationcost
JWT access token, RFC 9068 profileuser-facing APIsnot before exp without a denyliststateless verify, no hop
Opaque token + introspection, RFC 7662when revocation must be immediateinstantone network hop per request; cache for a few seconds
API keyserver-to-server, no user contextdelete the keymust be scoped and rotated
mTLS-bound token, RFC 8705high-value B2Bcert revocationtoken is useless if stolen

Access tokens 5–15 minutes, refresh tokens rotated on use. Never credentials in URLs: they land in access logs, browser history and Referer headers.

Object-level authorisation, enforced structurally. Postgres row-level security, so a handler that forgets the check still cannot leak:

SQL
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;  -- without FORCE, the table owner bypasses RLS

CREATE POLICY orders_owner ON orders
  USING (owner_id = current_setting('app.user_id')::uuid);
Python
def get_order(order_id, ctx):
    with db.transaction() as tx:
        tx.execute("SET LOCAL app.user_id = %s", (ctx.user_id,))
        row = tx.execute(
            "SELECT id, owner_id, total FROM orders WHERE id = %s", (order_id,)
        ).fetchone()
    if row is None:
        raise NotFound()          # 404, not 403
    return row

Trace. User 7 sends GET /orders/1043 with a token whose sub is 7. Order 1043 belongs to user 9.

  1. Middleware verifies the signature against the issuer's JWKS, checks exp and aud, sets ctx.user_id = 7.
  2. Handler opens a transaction and runs SET LOCAL app.user_id = '7'.
  3. Postgres rewrites the query with the policy predicate: WHERE id = 1043 AND owner_id = '7'.
  4. Zero rows. The handler raises NotFound → 404.
  5. Commit discards SET LOCAL with the transaction.

Step 5 is why it is SET LOCAL and not SET: plain SET persists on the pooled connection, so the next request on that connection inherits user 7's identity. Without the policy, step 3 returns user 9's row and the handler answers 200 with someone else's order.

404 versus 403. Return 404 where the existence of the resource is itself sensitive: an order ID, a document ID. Return 403 where the resource is public knowledge and only the action is denied, because 404 makes legitimate debugging harder. Apply it per resource class, not everywhere.

Logging and tests. Log every authorisation denial with caller ID, route, target object ID and decision, so a burst of them reads as enumeration. Then test it: for each endpoint, a case where user A requests user B's object and asserts 404 or 403. It is tedious, it is the test that catches the vulnerability class that actually gets exploited, and it is almost always the one missing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you protect an API from abuse and overload?

Answer

The 60-second answer. Assume a public HTTP API in front of a Postgres primary, p99 target 200 ms. Nothing a client controls should be unbounded. I'd put four limits in front of the work (rate per client identity, concurrency per client, bounded inputs, and timeouts) then shed load by priority when the limits aren't enough. Rate limiting is a fairness measure first: most breaches are a retry bug, not an attacker.

Rate limit: token bucket, per client identity. Key on the API key or account ID, not IP. IPs are shared behind NAT and trivially spoofed. Bucket capacity 10, refill 5 tokens/s, so a client can burst 10 then sustain 5 rps.

Trace, 12 requests arriving at t=0:

t (s)requesttokens beforedecisiontokens after
0.001–1010 → 02000
0.00110429, Retry-After: 10
0.00120429, Retry-After: 10
0.20—refill 5/s—1
1.00———5

Retry-After: 1 because the next token lands at t=0.2s and the header is whole seconds. Return X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset so a well-behaved client paces itself instead of discovering the limit by hitting it.

Concurrency, not just rate. A client can issue 1000 parallel requests inside a 5 rps limit if it doesn't wait. Cap in-flight per client. Arithmetic: at 200 rps and 150 ms p99, Little's Law gives 200 × 0.15 = 30 requests in flight. A Postgres pool of 20 connections means 10 queue, and queue wait pushes p99 past the 200 ms target. Size the pool to the in-flight you intend to admit, and cap per-client concurrency at, say, 10.

Bounded inputs. Max page size 100, max body 1 MB, max array length 1000, max query depth or complexity where the API composes. Each is otherwise a request for unbounded work.

Timeouts. Client-facing request timeout 2 s, DB statement_timeout 1 s. An expensive query is the usual way one request degrades the whole service.

Order the checks cheapest-first: validate → authenticate → authorise → work. Auth before expensive work so unauthenticated callers can't trigger it.

Graceful degradation. Shed by priority: 503 + Retry-After for low-value traffic, protect core paths. Decide what's sheddable before the incident, not during it.

Monitoring per client so one misbehaving integration is throttled specifically rather than degrading everyone.

Failure modes: keying on IP punishes NAT neighbours; a single global limit lets one client starve the rest; a limit without Retry-After turns a retry bug into a retry storm.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What does it mean for an API to be well-observed in production?

Answer

The 60-second answer. An API is well-observed when you can answer three questions without shipping new code: is it broken, who is affected, and why. "Is it broken" is per-route RED metrics: rate, errors, duration. "Who is affected" is per-client. "Why" is a trace or log line reachable from the metric. If any of the three needs a deploy or a guess, the API is not well-observed, however green the dashboard.

This matters more for an API than for a UI because your users are programs. They retry, they swallow errors, and their developer files a ticket a week later. Observability has to substitute for the feedback a human user would give you.

What to instrument, and what each signal costs.

SignalQuestion it answersCost
Per-route rate/error/duration histogramsIs it broken, and whereLow: bounded by route count
Errors split by status classOurs (5xx) vs theirs (4xx)Low
Per-client error countersWho is affectedHigh: cardinality
Trace context (traceparent, W3C) returned and loggedWhich request was that ticketNear zero
Exemplars on latency histogramsWhich trace explains this p99Low (Prometheus 2.26+)
Synthetic checks from outsideIs it reachable at allLow
Deprecated-route usage per clientCan we remove itLow

Worked example: the aggregate that lies. 1,000,000 requests in a 5-minute window. POST /v1/orders is 1% of traffic (10,000 requests) and 10% of them fail. Everything else is clean. Aggregate error rate: 1,000 / 1,000,000 = 0.1%, exactly the 99.9% SLO budget. Nothing pages. One endpoint is failing one call in ten.

Now add the client label. One integration sends 6,000 of those 10,000 requests and fails 16% of them: 960 errors. So 96% of every error in the system comes from one client on one route. That is the difference between a week of "intermittent 500s" and a one-line answer.

The trade-off you have to state. Per-client labels are the expensive part. 200 routes × 500 clients × 6 status classes × 12 histogram buckets = 7.2M active series. Prometheus will not hold that; you get scrape timeouts and head-block OOM before you get insight. The bounded version: keep the full label set on the aggregate (200 × 6 × 12 = 14,400 series) and put client_id only on a plain error counter for your top 50 clients by traffic (200 × 50 = 10,000 series). ~25k series, and you still answer "who".

What to drop first under constraint. In order: per-client labels on every route; payload-size and page-size histograms; full-fidelity traces (move to tail-based sampling that keeps 100% of errors and 1% of successes). Keep last: per-route RED metrics, error counters by status class, correlation IDs, and synthetic checks. Those four are cheap and cover "is it broken" and "which request".

Failure modes worth naming. Cardinality explosion shows up as rising prometheus_tsdb_head_series and scrape duration, not as a clean error. Metrics that lie: a 200 with an error body, or a load balancer's 503 that never reaches your app. Synthetic checks catch both. Head sampling at 1% will miss the rare error, which is exactly the one you need.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How would you design an API endpoint that returns data from several sources?

Answer

The 90-second answer. Decide three things before writing code: what happens when one source fails, what the latency budget is, and whether this endpoint should exist at all. Then fan out in parallel with a per-dependency timeout shorter than the budget, put a circuit breaker in front of each dependency, cache per source with a TTL that matches how often that source changes, and make the response say which sections are degraded.

Partial failure. Three defensible options: fail the whole request (correct when the data is meaningless without that part), return partial data with an explicit marker (correct when the rest is still useful), or substitute a degraded default. Silently omitting a field is the worst choice: the client cannot tell "no recommendations" from "recommendations unavailable" and renders the wrong thing. Pick per dependency, not per endpoint.

JavaScript
// Node 20.11 — global fetch, AbortSignal.timeout (Node 17.3+)
const BUDGET_MS = 250;

async function getJson(url, ms) {
  const res = await fetch(url, { signal: AbortSignal.timeout(ms) });
  if (!res.ok) throw new Error(`${url} -> ${res.status}`);
  return res.json();
}

async function productPage(id) {
  const started = Date.now();
  const [catalog, pricing, inventory, recs] = await Promise.allSettled([
    getJson(`/catalog/${id}`, 100),
    getJson(`/pricing/${id}`, 150),
    getJson(`/inventory/${id}`, 100),
    getJson(`/recs/${id}`, 200),
  ]);

  if (catalog.status === 'rejected') {
    return { status: 502, body: { error: 'catalog_unavailable' } };
  }

  const degraded = [];
  const body = { id, catalog: catalog.value };
  for (const [name, r] of [['pricing', pricing], ['inventory', inventory], ['recommendations', recs]]) {
    if (r.status === 'fulfilled') body[name] = r.value;
    else degraded.push(name);
  }
  return { status: 200, body: { ...body, degraded, elapsed_ms: Date.now() - started } };
}

Trace, /recs hangs. t=30 ms inventory resolves, t=40 catalog, t=60 pricing. At t=200 ms AbortSignal.timeout(200) fires and the fetch rejects with a TimeoutError DOMException. allSettled resolves at ≈200 ms with three fulfilled and one rejected. Catalog is present, so no 502. Response: 200, body {id, catalog, pricing, inventory, degraded: ["recommendations"], elapsed_ms: 200}. The page renders without the recommendations panel.

Trace, /catalog returns 500 at t=20 ms. getJson throws Error: /catalog/42 -> 500. Catalog is rejected, so the handler returns 502 {"error":"catalog_unavailable"}, but only at ≈200 ms, because allSettled waits for the slowest promise. That is the cost of the simple version. If a required dependency failing fast should fail the request fast, race the required set with Promise.all and cancel the rest through a shared AbortController.

Latency budget. Sequential p50 is 40+60+30+120 = 250 ms; parallel p50 is the max, 120 ms. Tail latency is the trap: if each dependency independently exceeds 250 ms with probability 1%, the composed endpoint exceeds it with probability 1 − 0.99⁴ ≈ 3.9%. Composition makes the endpoint's p99 worse than any single dependency's, which is the argument for the per-dependency timeouts below.

dependencyrequiredtimeoutcache TTLon failure
catalogyes100 ms5 min502, whole request fails
pricingno150 ms30 somit, degraded: ["pricing"]
inventoryno100 ms5 somit
recommendationsno200 ms10 minomit

Isolation. One circuit breaker per dependency, so a persistently failing source is skipped instead of costing a timeout on every request. Resilience4j's defaults are a 100-call sliding window, a 50% failure-rate threshold, 60 s in the open state and 10 permitted calls in half-open: start there and tune the window to your traffic. Hystrix is in maintenance; if you run a mesh, Envoy/Istio outlier detection does the same job at the sidecar. On gRPC, set the deadline on the client so it propagates, and treat DEADLINE_EXCEEDED (code 4) as the timeout path.

Caching. Per source, with the TTLs above, and say so in the response: Cache-Control: public, max-age=30, stale-while-revalidate=60, stale-if-error=300 (the last two are RFC 5861). stale-if-error is what turns a dependency outage into a stale-but-served section rather than a degraded one.

Should this endpoint exist? Composition at the API boundary is convenient and couples you to every source's availability and failure modes. Several focused endpoints called in parallel by the client is often better for a web client that renders progressively. Compose when the client is mobile and round trips are expensive, or when the composition is genuine server-side business logic rather than presentation assembly. Return 200 with an explicit degraded array rather than 207 Multi-Status: that status is WebDAV's (RFC 4918) and generic clients do not handle it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Explain the trade-offs of exposing internal identifiers in an API.

Answer

The short answer. Don't put the primary key in the URL. Give each row a second, opaque identifier and expose that; keep the sequential key internal. The three costs of exposing the internal key are enumeration, leakage of volume, and permanent coupling, and the benefit people claim for opaque IDs, that they fix authorisation, is not one of them.

Enumeration. A sequential key is a map of your table. If GET /orders/4891 returns someone else's order because an ownership check is missing, the attacker does not have to find that bug twice: they walk 4891, 4892, .... A six-digit order number is 10^6 candidates, and at 100 requests/second the whole space falls in under three hours. A UUIDv4 has 122 random bits, so with 10^6 live orders the chance a single guess hits one is about 10^6 / 2^122 ≈ 2 × 10^-31. The opaque ID does not fix the missing check: it removes the ability to enumerate around it.

Leakage. Order 4,891 tells a competitor roughly how many orders you have taken. UUIDv7 and ULID fix enumeration but leak creation time to millisecond precision, because the first 48 bits are a Unix timestamp. If that matters, use v4.

Coupling. Once a client stores the ID, it is in their database and their logs. Changing the key strategy, merging two records, or migrating off the old system becomes a breaking change you cannot schedule. This is the cost that outlives the others.

The shape I'd use. Internal bigint primary key for index locality, separate uuid public column with a unique index:

SQL
-- PostgreSQL 16
CREATE TABLE orders (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- internal only
  public_id  uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,  -- what the API returns
  total_cents integer NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

gen_random_uuid() is built into PostgreSQL 13+ (it lived in pgcrypto before). The API returns public_id; lookups go through the unique index on it. Insert three rows and you get id 1, 2, 3 and three unrelated public_id values: the sequence stays internal, the contract stays opaque.

Cost: one extra 16-byte column and one extra index. In a B-tree, an index entry is the key plus ~12 bytes of tuple header and line pointer, so a bigint entry is ~24 bytes and a uuid entry ~32 bytes after alignment: about a third more, not double.

Public identifierKey sizeGuessableIndex localityLeaks
bigint identity8 Btriviallyappend-onlyrow count, growth rate
UUIDv416 B122 random bitsrandom inserts scatter B-tree leavesnothing
UUIDv7 (RFC 9562) / ULID16 B74 random bitsmonotonic, appends at the right edgecreation time, ms precision
bigint internal + uuid public8 B + 16 Bnoappend-only on the PKnothing

When exposing the internal ID is fine. Service-to-service calls inside a boundary you control: no untrusted caller to enumerate, and you can change both sides in one deploy. The moment a third party or a browser holds it, the calculus changes.

The caution. An opaque identifier is not an authorisation check. Unguessability is not a control: IDs get shared, logged, pasted into tickets, and sent in Referer headers. Enforce ownership per object on every request. The opaque ID shrinks the blast radius of a missing check; it does not replace it. If someone answers "the IDs are UUIDs" when you ask how object-level authorisation works, they have answered a different question.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How would you version an API and manage breaking changes?

Answer

The 90-second answer. Assume the clients are external and I do not control their deploy cadence. Then: design so most changes are additive, version only when a break is unavoidable, and treat the old version as a product with a published end-of-life date rather than something that quietly rots. Concretely: URI version (/v2/orders), one implementation behind a translation layer at the edge, Sunset and Deprecation headers on old responses, and removal gated on measured client usage, not on a calendar.

Classify the change before deciding anything.

changebreaking?why
new optional response fieldnoprovided clients ignore unknown fields
new enum valuenoonly if clients were told to tolerate unknown values
new required request parameteryesexisting callers omit it
rename or remove a field, change a typeyesparse failure
same shape, new meaningyes, worstnothing fails; clients silently misread

The precondition for the first two rows is a documented rule that clients must ignore unknown fields. OpenAPI's additionalProperties defaults to true, so the spec permits extra fields: that says nothing about what a generated client does with them, which is why the rule belongs in the docs and in a contract test.

The translation layer is what makes two versions affordable. One internal model; the old contract is a projection at the edge.

Python
# Python 3.12
from datetime import datetime, timezone

def to_v1(order: dict) -> dict:
    """Project the current internal model onto the frozen v1 contract."""
    return {
        "id": order["id"],
        "created": datetime.fromtimestamp(order["created_at"], timezone.utc)
                            .strftime("%Y-%m-%dT%H:%M:%SZ"),
        "status": order["state"],
    }

Trace it. Internal model {"id": 42, "created_at": 1704448800, "state": "active"}:

  • datetime.fromtimestamp(1704448800, timezone.utc) → 2024-01-05 10:00:00+00:00
  • .strftime("%Y-%m-%dT%H:%M:%SZ") → "2024-01-05T10:00:00Z"
  • returns {"id": 42, "created": "2024-01-05T10:00:00Z", "status": "active"}

The mapping is pure and in-process, so it costs microseconds per response: the p99 delta is under a millisecond, not a second network hop. What it does not do is hide a semantic change: if v2 redefines state, the projection has to encode the old meaning explicitly, and that is the case where you write the mapping by hand and test it against recorded v1 responses.

Running the sunset. Both versions served concurrently. Old responses carry Sunset: Wed, 01 Apr 2026 00:00:00 GMT (RFC 8594) and a Deprecation header, plus a Link to the migration guide. Window: 12 months for external clients, 90 days internal. The removal gate is measured, not assumed: log api_version and client_id per request, and require both under 0.1% of traffic and zero distinct client IDs seen in the last 30 days. Teams routinely believe they have migrated; the log is what settles it. If a client will not move, that is a commercial conversation with a named owner, not a reason to keep the endpoint forever.

Failure modes. Header versioning (Accept: application/vnd.acme.v2+json) is cleaner in theory and harder to reproduce: you cannot paste a URL into a browser, and cache keys get subtle, which is why I default to the URI. Date-based versions pinned per account, as Stripe does with Stripe-Version, and explicit version headers like GitHub's X-GitHub-Api-Version: 2022-11-28, both work; the point is that the version is explicit in every request, never inferred. Kubernetes publishes its own policy, roughly 9 months for beta APIs and 12 for GA, and the value is that the number is written down before anyone needs it.

Design the hard-to-change parts first: identifier format, pagination, error shape, date format. Those propagate into every endpoint, so a mistake there is a mistake everywhere, and it is the one thing versioning cannot cheaply fix.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

What is the cost of an API that is hard to change, and how do you reduce it?

Answer

The 60-second answer. Once a client you don't control depends on a response shape, that shape is a contract. The cost isn't the one-off migration: it's a permanent tax. Every version you keep alive is code you build, test and deploy forever, and every field you exposed is a field you can never remove. The indirect cost is worse: the contract freezes the implementation behind it, so a resource model you regret in year one is still dictating your schema in year five.

What it costs, in numbers. Take 40 endpoints and three live versions: 120 handler paths to test on every release, and every cross-cutting change (auth, error shape, rate limiting) applied three times. If supporting the two legacy versions eats 15% of a six-engineer team, that's 0.9 FTE, roughly $180k/year at a $200k fully-loaded cost, spent on code that ships no new capability. (Illustrative arithmetic, not a benchmark.)

Reducing it.

  1. Expose less. Return identifiers by default and let clients ask for more: Stripe's expand parameter is the pattern. A field added "because it was there" is a permanent liability.
  2. Don't mirror internal structures. A response shaped like a database row makes every schema change an API change.
  3. Publish extension rules before clients exist. "Clients must ignore unknown fields; new optional fields and new enum values may appear." Ship an OpenAPI 3.1 document so generated clients are tolerant by construction. This is not free: Jackson's FAIL_ON_UNKNOWN_PROPERTIES is on by default, so a Java client that never disabled it will throw on your additive change.
  4. Opaque IDs and cursors. Stripe's cus_/ch_ prefixes, GitHub's opaque cursors. If a cursor is a base64-encoded offset, clients will decode it and you can never change the encoding.
  5. Version by date, whole-API. Stripe pins each account to a dated version (2024-06-20) and lets a request override with Stripe-Version; GitHub takes X-GitHub-Api-Version: 2022-11-28. Per-endpoint versions give you a version matrix nobody can reason about.
  6. Fix cross-cutting decisions first: ID format, pagination, error shape, timestamps (RFC 3339, UTC), naming. A mistake here is a full-API version.
  7. Instrument per-field and per-endpoint usage from day one, and retire with a Sunset header (RFC 8594) plus 410 Gone. You cannot remove what you cannot prove is unused.

What is actually safe to change.

changesafe?why
add optional response fieldyes, if clients ignore unknown fieldstolerant readers skip it; strict ones throw
add optional request fieldyesold servers ignore it if they are tolerant too
add an enum valueonly if enums are openJava and Swift enums throw on an unknown value
remove or rename a fieldnoevery reader breaks
widen a type (int to string)noparsers reject it
tighten validationnorequests that used to succeed now return 400

Failure modes. Version sprawl is the common one: clients pin and never move, and the version you cannot drop is the 0.5%-of-traffic one that belongs to a single enterprise account. Detect it with a per-version traffic dashboard, not a support ticket. The second is the "safe" additive change that isn't, because one client's deserializer is strict. The third is deprecating without telemetry, which leaves you guessing which fields are dead.

An API outlives the code behind it. Design it as the longer-lived artefact it is.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How should an API communicate deprecation to its clients?

Answer

What I'd say first. Assume a public HTTP API, a versioned surface, and clients I cannot force to upgrade. The signal has to travel with the response, not sit in a changelog nobody reads. Every call to a deprecated path returns Deprecation and Sunset headers and a link to the migration guide; the OpenAPI deprecated: true flag is secondary, because it only reaches developers who regenerate their client. Then I measure usage per client, contact the largest callers directly, and remove only when usage is near zero: with 410 Gone, not 404.

The headers. RFC 8594 (2019) defines Sunset: an HTTP date after which the resource is expected to stop responding. RFC 9745 (March 2025) defines Deprecation as an HTTP date, when the resource was deprecated, and registers the deprecation link relation. Older drafts used a boolean Deprecation: true; a client built against the draft parses that and a client built against the RFC does not, so pick one and document which. Don't reach for Warning: RFC 9111 obsoleted it.

GET /v1/charges HTTP/1.1
Host: api.example.com

HTTP/1.1 200 OK
Deprecation: Sat, 01 Mar 2025 00:00:00 GMT
Sunset: Sat, 01 Nov 2025 23:59:59 GMT
Link: <https://api.example.com/docs/migrate-v2>; rel="deprecation"; type="text/html"

The headers go on success responses, not just errors. A client that only ever sees 200s is exactly the client that never notices.

Measuring. Usage per client is the only reliable basis for the removal decision, and it has to be counted at the deprecated path, not inferred from a version header.

Python
# Python 3.12, FastAPI 0.115
from fastapi import FastAPI, Request, Response
from collections import Counter

app = FastAPI()
calls = Counter()  # swap for a real metric sink

@app.middleware("http")
async def deprecation(request: Request, call_next):
    response: Response = await call_next(request)
    if request.url.path.startswith("/v1/"):
        calls[request.headers.get("x-client-id", "unknown")] += 1
        response.headers["Deprecation"] = "Sat, 01 Mar 2025 00:00:00 GMT"
        response.headers["Sunset"] = "Sat, 01 Nov 2025 23:59:59 GMT"
        response.headers["Link"] = '<https://api.example.com/docs/migrate-v2>; rel="deprecation"'
    return response

Trace: GET /v1/charges with x-client-id: acme → calls['acme'] goes 0→1, three headers set, 200 returned. GET /v2/charges → no counter increment, no headers. That counter is what tells you whether the deprecation is working; teams sincerely believe they have migrated and are often wrong.

Timeline. Proportional to the change and the audience. Internal consumers move in weeks; external paying integrations need months. A worked example for a breaking change to a public endpoint:

DayAction
0deprecated: true in OpenAPI, headers on every /v1 response, migration guide published
0–30top callers by volume contacted directly: in this example, 12 of 400 clients accounted for 91% of /v1 calls
90second notice; per-client usage dashboard shared with the client-facing team
270first brownout: /v1 returns 503 for 2 hours, Tuesday 10:00 UTC, announced 14 days ahead
300second brownout, 4 hours
365removal; /v1 returns 410

Escalation. Brownouts, brief deliberate outages of the old path, get attention when nothing else has, provided they are announced and bounded. They are aggressive and they work; I would only use them after the softer measures, and never as a surprise.

Removal. Return 410 Gone, not 404. 410 says the resource existed and is deliberately gone; 404 is indistinguishable from a typo'd path, so clients retry and page their on-call for a bug that isn't there.

The decision nobody wants to make. Some clients will never migrate. Break them, support them indefinitely, or charge for extended support: that is a business call, and it should be made deliberately rather than defaulting to indefinite support because nobody wanted to make it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Compare REST with GraphQL and gRPC, and say when you would choose each.

Answer

Core answer. Three styles, three bets. REST bets that a uniform interface plus the HTTP stack you already run (CDNs, proxies, curl, browser devtools) is worth more than a tailored response shape. GraphQL bets that clients know which fields they need and that the server can serve arbitrary shapes safely. gRPC bets that both ends can share one schema and generate code from it. Pick per boundary, not per organisation: a public REST API in front of internal gRPC services is ordinary.

REST. GET /v1/orders/1234 returning Cache-Control: max-age=60, stale-while-revalidate=30 and ETag: "a1b2" gets you a CDN and a 304 on revalidation with no application code. That is the whole argument. The cost is a fixed shape: either the client gets fields it ignores, or it makes several calls. Versioning is coarse: a new /v2/ path, or additive fields.

GraphQL. One POST /graphql, client picks fields:

GRAPHQL
query {
  user(id: 42) {
    name
    orders(last: 20) { id totalCents items { sku qty } }
  }
}

Two costs follow directly. First, a POST body is not cacheable by a shared cache, so you reimplement caching: typically Automatic Persisted Queries so the request becomes a cacheable GET /graphql?extensions=..., plus CDN caching keyed on the query hash. Second, the resolver layer is where N+1 lives:

JavaScript
// Node 20, graphql-js 16, dataloader 2.x
const orderLoader = new DataLoader(async (userIds) => {
  const rows = await db.query(
    'SELECT id, user_id, total_cents FROM orders WHERE user_id = ANY($1)',
    [userIds],
  );
  const byUser = new Map();
  for (const r of rows) {
    if (!byUser.has(r.user_id)) byUser.set(r.user_id, []);
    byUser.get(r.user_id).push(r);
  }
  return userIds.map((id) => byUser.get(id) ?? []);
});

const resolvers = { User: { orders: (user) => orderLoader.load(user.id) } };

Trace it: 20 sibling orders resolvers fire in the same tick, DataLoader coalesces them into one load call carrying 20 keys, the batch function issues one SELECT ... WHERE user_id = ANY($1), and the rows are split back per key in the order the keys arrived. Without the loader that is 20 queries; with 50 users on a page it is 50 versus 1. Depth and cost limits (graphql-depth-limit, graphql-query-complexity) are mandatory, not optional: an unauthenticated client can otherwise write a query that fans out exponentially.

gRPC. proto3 schema, HTTP/2 transport, generated stubs, four streaming shapes. Payload arithmetic on one record, hand-encoded:

encodingbyteswhy
JSON {"id":123456,"total_cents":4999,"status":"PAID"}48field names on the wire, ASCII digits
protobuf, same three fields9tag byte + varint per field; names never sent

id=123456 is a 3-byte varint, total_cents=4999 is 2 bytes, status is a 1-byte enum, each preceded by a 1-byte tag. Roughly 5x on this record; the ratio shrinks as strings dominate. Costs: browsers need grpc-web plus an Envoy proxy, curl does not work (use grpcurl), and because gRPC holds long-lived HTTP/2 connections, an L4 load balancer balances per connection and can leave one backend hot. You want an L7 proxy or client-side round-robin.

Worked example. A screen showing user 42, their 20 latest orders, and each order's line items:

approachround tripsDB queries
REST, no embedding22 (user, orders, 20 item lists)22
REST with ?expand=items22, over-fetches fields
GraphQL, no batching122
GraphQL + DataLoader13
gRPC GetUserWithOrders11–2

Defaults. REST for public APIs and any consumer you do not control. gRPC for internal service-to-service where generated clients and binary framing pay for themselves. GraphQL when clients are heterogeneous and over-fetching is measured, not assumed, and only with depth limits, persisted queries and batching in place.

Pushback. Choosing GraphQL to avoid designing an API does not work. The design work is identical; it moves from endpoints to schema and resolvers, and skipping it produces the same problems in a less familiar form.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

What would you look for when reviewing an API design?

Answer

The 90-second answer. I review in order of cost to change, because that is what decides how much scrutiny each item earns. First, consistency (naming, pagination, error shape, date and ID formats) since an inconsistency shipped now propagates to every client and is expensive to remove. Then method semantics: nothing unsafe behind GET, PUT and DELETE used where they are correct, and non-idempotent operations that clients will retry protected by an idempotency key. Then status codes: 401 and 403 distinguished, nothing returning 200 with an error body, 4xx and 5xx correct because alerting keys off the split. Then unbounded work: collections without pagination, bodies without size limits, queries without complexity limits. Then authorisation on every endpoint, including fetching any identifier returned elsewhere. Then the client's call count, if one screen needs a call per item, that is a network N+1. Then error actionability and the OpenAPI description. Last: what happens when a client misbehaves.

Worked review. Take GET /v1/orders returning every order as a bare top-level JSON array, and POST /v1/payments with no idempotency key.

Problems, in cost order:

  • Unbounded: no pagination, no limit cap. A client with 2M orders pulls 2M rows.
  • Breaking-change risk: a bare top-level array can never gain a next_page_token or total field without breaking every parser.
  • Retry safety: a client that times out on POST /v1/payments and retries charges twice.

Fixed:

GET /v1/orders?limit=50&page_token=eyJvIjoiMjAyNC0wMy0wMVQxMDowMDowMFoifQ
200 OK
{
  "orders": [ ... ],
  "next_page_token": "eyJvIjoiMjAyNC0wMy0wMVQxMTowMDowMFoifQ"
}
POST /v1/payments
Idempotency-Key: 8f14e45f-ea0f-4b1e-9c1a-2b3c4d5e6f70

The key is stored alongside the response; a replay returns the original response instead of charging again. Stripe's Idempotency-Key header behaves this way and expires keys after 24 hours.

Cursor versus offset. page_token above is an opaque cursor. Offset (?offset=200) is simpler to build and lets a client jump to page 7, but it double-counts or skips rows when items are inserted or deleted mid-scan, and a large OFFSET makes the database scan and discard that many rows. A cursor is stable and cheap with the right index, but you cannot jump to an arbitrary page and you need a stable sort key.

DecisionChooseWhen the other side wins
PaginationCursor (page_token)Offset when the dataset is small, static, and clients need random page access
Error bodyEnvelope {"error": {"code", "message", "request_id"}}RFC 9457 Problem Details when you want a standard schema and no custom one
StyleREST/JSON over HTTPgRPC when both ends are yours and you want streaming and generated clients

When this advice does not apply. For an internal service-to-service API with one consumer, cross-API consistency is a smaller concern, and gRPC hands you a schema and status codes for free. A single-consumer endpoint can skip pagination if the result is bounded by construction, but say so explicitly, because the next consumer will not know.

The question I ask last. What happens when a client sends a field twice, sends null where a value is expected, retries a request that already succeeded, or calls endpoints out of order? Real clients do all of these, and a design that has thought about them is markedly more robust than one that assumes cooperation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you introduce a new API into an organisation that has none?

Answer

The 90-second answer. Don't write a standards document first. Pick one API a real consumer is already blocked on, say the orders API the mobile team needs, and build it end to end with the conventions you'd want everywhere. Then write down what you actually did, ship it as a shared library plus a one-page doc, and make the next team start from it. Conventions derived from a working service are specific; conventions written in advance are guesses, and they're usually over-specified in the easy places and silent in the hard ones.

Decide these once, before endpoint three. Each one propagates into every endpoint, so the cost of agreeing it is fixed and the cost of changing it later scales with the surface.

DecisionPickWhy this one
PaginationCursor: ?limit=&cursor=, response {data, next_cursor, has_more}Offset pagination skips or duplicates rows when the underlying set changes mid-scan; a cursor over (created_at, id) doesn't
ErrorsRFC 9457 application/problem+json with type, title, status, detail, instanceOne parse path for every failure; RFC 9457 obsoleted RFC 7807 in 2023
TimestampsRFC 3339, UTC, 2024-03-11T09:14:22ZNo local-time ambiguity, no epoch-unit guessing
IDsUUIDv7 (RFC 9562) or prefixed opaque strings, ord_01HQ8...Sortable, and the prefix tells you what you're holding in a log line
Versioning/v1/ in the pathVisible in every trace and curl command; header versioning hides it
AuthOAuth 2.0 bearer (RFC 6750), plus Idempotency-Key on every POSTRetries are inevitable; without the key they double-charge
Rate limits429 with Retry-After (RFC 9110)Clients can back off without a bespoke header

Make the conventional path the easy path. A shared library that emits the problem+json body, parses the pagination envelope and attaches the bearer token means the right thing is also the shortest thing. Guidelines alone get followed about half the time; guidelines plus a library get followed because the alternative is more work.

Description-first, with CI enforcement. Design in OpenAPI 3.1 (it aligns with JSON Schema 2020-12, so your validators and your spec agree). Then enforce it, or it drifts within a quarter:

schemathesis run openapi.yaml --base-url http://localhost:8080 --checks all

That generates requests from the spec and fails the build when a response doesn't match. A spec nobody checks is documentation of what someone intended in March.

A worked trace. GET /v1/orders?limit=2 returns:

JSON
{
  "data": [
    {"id": "ord_01HQ8A", "total_cents": 4200, "created_at": "2024-03-11T09:14:22Z"},
    {"id": "ord_01HQ8B", "total_cents": 1500, "created_at": "2024-03-11T09:15:01Z"}
  ],
  "next_cursor": "eyJ0IjoiMjAyNC0wMy0xMVQwOToxNTowMVoifQ",
  "has_more": true
}

The cursor is opaque: base64 of the last row's sort key. GET /v1/orders?limit=2&cursor=eyJ0... returns the one remaining order with "next_cursor": null, "has_more": false. A failure on the same endpoint:

JSON
{
  "type": "https://errors.example.com/insufficient-funds",
  "title": "Insufficient funds",
  "status": 402,
  "detail": "Account acc_123 holds 1500 cents; order requires 4200.",
  "instance": "/v1/orders/ord_01HQ8A"
}

Failure modes worth naming. Cursor pagination over a non-unique sort key duplicates rows at page boundaries: tie-break on (created_at, id). An Idempotency-Key header with no server-side key→response store does nothing; you need the mapping retained for at least the client's retry window. And a 500 from an upstream proxy returns HTML, not problem+json, so the client library must handle a body it can't parse.

Conventions versus rules. Authorisation on every endpoint is a rule. Pagination envelope shape is a convention. Conflating them either makes the rules negotiable or makes the conventions oppressive.

Curated: · Written: · Reviewed:

Difficulty: Medium