Skip to content

HTTP APIs in Production: Concepts for Mid and Senior Interviews

Learn HTTP method semantics, status codes, idempotency, caching, pagination, versioning, rate limiting, retries and API authorization for interviews.

18 min read9 conceptsTechnical testsAPIs and HTTP

Situational questions about HTTP APIs rarely test whether you have memorised a status code table. They test whether you can predict what happens when a client retries, when two users edit the same record, when a list changes while someone pages through it, or when a partner hammers your endpoint at 3 a.m. This guide covers the concepts behind strong answers. Each one uses an invented system, such as a bike-sharing fleet API, a payments service or a marketplace order feed. It explains the mechanics, shows a short example and lists the traps interviewers like to probe. Learn the reasoning, not the wording. Most good answers come down to semantics, failure modes and contracts that can change without breaking clients.

Study order

If time is short, go in this order.

  1. HTTP method semantics: safe, idempotent and neither

    Retries, caching and many later answers depend on knowing what each method promises.

  2. Status codes and machine-readable error contracts

    Almost every situational question ends with which response you return and how the client should react to it.

  3. Timeouts, retries and exponential backoff with jitter

    Failure handling between services is where senior candidates are separated from mid-level ones.

  4. Idempotency keys for safe retries of non-idempotent operations

    This is the standard answer to the double-charge or duplicate-order scenario, and interviewers push on atomicity.

  5. Authentication, tokens and object-level authorization

    Object-level authorization bugs are common and severe, and security questions show up in most API interviews.

  6. Pagination: offset versus cursor (keyset)

    A frequent design question whose good answer depends on understanding database access patterns and consistency.

  7. HTTP caching, ETags and optimistic concurrency

    ETags cover both performance and lost-update prevention, two topics that often come up together.

  8. Rate limiting, quotas and backpressure

    Common in system design follow-ups. Know the algorithms and the distributed-counter problem.

  9. API versioning and backward-compatible evolution

    Tests whether you can change a public contract without breaking clients, a core senior responsibility.

HTTP method semantics: safe, idempotent and neither

Every HTTP method makes a promise. Safe methods (GET, HEAD, OPTIONS) promise the client is not asking for a state change. Idempotent methods (PUT, DELETE and all safe methods) promise that sending the same request once or ten times leaves the server in the same state. POST makes neither promise, and PATCH is not idempotent by definition, although a specific patch format can be.

These promises are what proxies, browsers, SDKs and load balancers rely on when they decide whether to retry or prefetch. If GET /bikes/42/unlock actually unlocks a bike, a link-preview bot or a retrying proxy can unlock it for a stranger. If PUT /bikes/42 means "append a maintenance note", one timeout plus one retry gives you two notes.

Idempotency is about server state, not identical responses. A second DELETE /docks/7 may return 404 instead of 204, and it is still idempotent because the dock stays deleted. A full-replacement PUT is idempotent. A PATCH like {"op":"increment","field":"rides"} is not.

Text

# Bike-sharing fleet API

GET    /bikes/42                 safe, idempotent: read state
PUT    /bikes/42/status          idempotent: body {"status":"maintenance"} replaces the value
DELETE /bikes/42/reservation     idempotent: the reservation is gone after 1 or N calls
POST   /bikes/42/unlocks         neither: each call creates a new unlock event
PATCH  /bikes/42  {"battery":80}        idempotent in practice (sets a value)
PATCH  /bikes/42  {"addRides":1}        not idempotent (relative change)

The same resource exposed with methods whose semantics match their effects.

Traps

  • Putting side effects behind GET because it is convenient for a button or a link. Crawlers, prefetchers and caches will trigger them.
  • Assuming idempotent means the response must be identical on every call. Only the resulting server state has to match.
  • Treating PATCH as automatically idempotent. Relative operations like increments or list appends are not safe to retry blindly.
  • Using POST for everything and losing the ability of infrastructure to retry reads and replacements safely.

Status codes and machine-readable error contracts

Status codes are the first thing clients and monitoring branch on, so precision matters. 4xx means the client must change something before retrying. 5xx means the server failed and the same request may succeed later. The distinctions interviewers probe: 401 (no valid credentials) vs 403 (authenticated but not allowed); 400 (malformed request) vs 422 (well-formed but semantically invalid); 409 (conflicts with current state); 412 (a precondition such as If-Match failed); 429 (rate limited); 503 (temporarily unavailable, often with Retry-After).

The status alone is not enough for a client to act. Return a stable, structured body. RFC 9457 Problem Details (application/problem+json) gives you type, title, status, detail and room for extension fields. Clients should branch on a stable type or code, never on English text that someone will reword.

Keep 5xx for real server faults. If a payout fails because the merchant's balance is too low, that is a 409 or 422 with a specific type. Returning 500 pages your on-call engineer, inflates error budgets and may trigger client retries that cannot succeed.

TypeScript

type DomainError =
  | { kind: "insufficient_balance"; balanceCents: number }
  | { kind: "payout_not_found" }
  | { kind: "validation"; fields: Record<string, string> };

interface Problem {
  type: string;
  title: string;
  status: number;
  detail?: string;
  [extension: string]: unknown;
}

function toProblem(err: DomainError): Problem {
  switch (err.kind) {
    case "insufficient_balance":
      return {
        type: "https://api.harbourpay.example/errors/insufficient-balance",
        title: "Insufficient balance",
        status: 409,
        balanceCents: err.balanceCents,
      };
    case "payout_not_found":
      return {
        type: "https://api.harbourpay.example/errors/not-found",
        title: "Payout not found",
        status: 404,
      };
    case "validation":
      return {
        type: "https://api.harbourpay.example/errors/validation",
        title: "Request validation failed",
        status: 422,
        fields: err.fields,
      };
  }
}

console.log(JSON.stringify(toProblem({ kind: "insufficient_balance", balanceCents: 1250 })));

Mapping domain errors of an invented payouts service to Problem Details with stable type identifiers.

Traps

  • Returning 200 with {"success": false}. Caches, monitoring and generic clients will all treat the failure as success.
  • Confusing 401 and 403. Sending 401 to a logged-in user without permission makes clients refresh tokens in a loop.
  • Returning 500 for business-rule failures. That triggers pointless retries and false alerts.
  • Leaking stack traces or SQL errors in error bodies.
  • Returning 403 instead of 404 for resources in another tenant. That confirms the resource exists.

Idempotency keys for safe retries of non-idempotent operations

A client sends POST /charges and the connection drops before the response arrives. Did the charge happen? The client cannot know, and a blind retry may charge the customer twice. Idempotency keys solve this. The client generates a unique key per logical operation, usually a UUID, and sends it in a header like Idempotency-Key. It reuses the same key for every retry of that operation.

The server records the key, scoped to the caller, with a fingerprint of the request and eventually the response. A retry with the same key and same body gets the stored response replayed without running the side effect again. The same key with a different body is a client bug, so reject it. A retry that arrives while the first attempt is still running should get a 409 rather than running concurrently.

The hard part in production is atomicity. Claiming the key must be a single atomic operation, such as a unique-constraint insert or a Redis SET NX. Otherwise two simultaneous retries can both pass a check-then-insert. Ideally the stored response is written in the same transaction as the business effect. Keys need a retention window, for example 24 hours, that is longer than any client's retry horizon.

TypeScript

type StoredResult =
  | { state: "in_flight"; fingerprint: string }
  | { state: "done"; fingerprint: string; status: number; body: unknown };

interface ChargeRequest { customerId: string; amountCents: number }
interface HttpResult { status: number; body: unknown }

// In production: a table with a unique index on (client_id, key), not a Map.
const store = new Map<string, StoredResult>();

async function createCharge(
  clientId: string,
  key: string | undefined,
  req: ChargeRequest,
  charge: (r: ChargeRequest) => Promise<{ id: string }>,
): Promise<HttpResult> {
  if (!key) return { status: 400, body: { error: "Idempotency-Key header required" } };

  const scoped = `${clientId}:${key}`;
  const fingerprint = JSON.stringify([req.customerId, req.amountCents]);
  const existing = store.get(scoped);

  if (existing) {
    if (existing.fingerprint !== fingerprint) {
      return { status: 422, body: { error: "Key reused with a different request" } };
    }
    if (existing.state === "in_flight") {
      return { status: 409, body: { error: "Original request still processing" } };
    }
    return { status: existing.status, body: existing.body };
  }

  store.set(scoped, { state: "in_flight", fingerprint });
  try {
    const result = await charge(req);
    const response = { status: 201, body: result };
    store.set(scoped, { state: "done", fingerprint, ...response });
    return response;
  } catch (err) {
    store.delete(scoped); // let the client retry a failed attempt
    throw err;
  }
}

Simplified idempotency handling for an invented charges endpoint. A Map is atomic here only because Node runs this check synchronously in one process.

Traps

  • Generating a new key on each retry. The key must identify the logical operation, not the HTTP attempt.
  • Implementing check-then-insert without atomicity, so two concurrent retries both execute the side effect.
  • Not scoping keys per client or tenant, which lets one client's key collide with another's.
  • Ignoring body mismatches and replaying a stored response for a different request.
  • Caching 5xx responses forever under a key, which prevents a legitimate retry after a transient failure.

HTTP caching, ETags and optimistic concurrency

Cache-Control decides who may store a response and for how long. max-age=60 lets any cache reuse it for 60 seconds. private restricts storage to the end user's cache, which matters for anything personalised. no-cache means store it but revalidate before each use. no-store means never store it. s-maxage overrides max-age for shared caches like CDNs. Vary tells caches which request headers change the response, such as Accept-Language or Authorization.

An ETag is a version identifier for a representation. For reads, the client sends If-None-Match: "v7". If nothing changed, the server answers 304 Not Modified with no body, which saves bandwidth even when the server still does the lookup.

For writes, the same ETag gives you optimistic concurrency. Two warehouse managers open stock item 881 at version "v7". The first saves with If-Match: "v7" and succeeds, moving it to "v8". The second save also carries If-Match: "v7" and gets 412 Precondition Failed instead of silently overwriting the first edit. Servers can require preconditions on writes and answer 428 when they are missing.

Text

GET /stock-items/881
<- 200 OK
   ETag: "v7"
   Cache-Control: private, max-age=0, must-revalidate
   {"sku":"BOLT-M6","onHand":340}

GET /stock-items/881
If-None-Match: "v7"
<- 304 Not Modified            (no body, client reuses its copy)

PUT /stock-items/881           (manager A)
If-Match: "v7"
{"sku":"BOLT-M6","onHand":320}
<- 200 OK   ETag: "v8"

PUT /stock-items/881           (manager B, stale copy)
If-Match: "v7"
{"sku":"BOLT-M6","onHand":355}
<- 412 Precondition Failed     (B must re-fetch and merge)

Revalidation and lost-update prevention on an invented inventory API.

Traps

  • Serving per-user data with public caching headers, so a CDN hands one customer's data to another.
  • Forgetting Vary when the response depends on a header, which causes cache poisoning across languages or formats.
  • Computing ETags from data that differs between replicas, such as timestamps with different precision, so revalidation never matches.
  • Treating no-cache as 'do not cache'. That is no-store.
  • Doing read-modify-write without If-Match or a version column, which allows silent lost updates.

Pagination: offset versus cursor (keyset)

Offset pagination (?page=40&size=50 or OFFSET 1950) is simple and supports jumping to page N. It has two production problems. The database still has to walk and discard every skipped row, so deep pages get progressively slower. And when rows are inserted or deleted between requests, items shift across page boundaries, so clients see duplicates or miss records.

Cursor (keyset) pagination remembers where the last page ended, for example the (created_at, id) of its final row, and asks for rows strictly after that position. With a matching composite index, each page costs roughly the same no matter how deep you go. Concurrent inserts do not shift earlier results. The sort key must be unique, so you always add a tiebreaker such as the primary key.

Expose the cursor as an opaque token, such as base64-encoded JSON, so you can change its internals later. Fetch limit + 1 rows to know whether a next page exists without a separate count query. Exact totals on large tables are expensive, so make them optional or approximate.

SQL

-- Marketplace order feed for one shop, newest first.
-- Supporting index:
-- CREATE INDEX orders_shop_feed ON orders (shop_id, created_at DESC, id DESC);

-- First page (limit 50, fetch 51 to detect has_more)
SELECT id, created_at, total_cents
FROM orders
WHERE shop_id = $1
ORDER BY created_at DESC, id DESC
LIMIT 51;

-- Next page: $2, $3 decoded from the opaque cursor = last row of previous page
SELECT id, created_at, total_cents
FROM orders
WHERE shop_id = $1
  AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 51;

Keyset pagination in PostgreSQL using a row-value comparison and a unique tiebreaker.

Traps

  • Sorting by a non-unique column like created_at alone, which drops or duplicates rows that share a timestamp at page boundaries.
  • Exposing raw cursor fields in the API, which locks you into the current sort implementation.
  • Letting clients change filters or sort order while reusing a cursor from a different query.
  • Running COUNT(*) on every page request over a large table.
  • Promising random page access with cursor pagination. It only supports next and, with extra work, previous.

API versioning and backward-compatible evolution

The cheapest version bump is the one you never need. Additive changes are generally backward compatible: new optional request fields, new response fields, new endpoints. Breaking changes include removing or renaming fields, changing types or units, making optional inputs required, tightening validation and changing default behaviour. Adding a value to an enum that clients switch on is a quieter break, and you should treat it as one unless clients were told to expect unknown values.

When you must break, pick a visible mechanism. URL path versions (/v2/shipments) are explicit and easy to route and cache. Header or media-type versions keep URLs stable but are easier to forget and need Vary. Date-based versions pinned per client account let you ship many small changes and upgrade clients one at a time, at the cost of maintaining transformation layers.

Evolution needs both sides. Servers announce deprecation ahead of time, for example with the Deprecation and Sunset response headers. They watch traffic to see who still calls the old version and remove it only after usage has drained. Clients follow the tolerant reader principle: ignore unknown fields, handle unknown enum values gracefully and depend only on the fields they use.

TypeScript

type ShipmentStatus = "created" | "in_transit" | "delivered" | "unknown";

interface Shipment {
  id: string;
  status: ShipmentStatus;
  weightGrams: number;
}

const KNOWN: ReadonlySet<string> = new Set(["created", "in_transit", "delivered"]);

// Tolerant reader: pick only what we need, ignore extra fields,
// map unrecognised enum values instead of crashing.
function parseShipment(raw: unknown): Shipment {
  if (typeof raw !== "object" || raw === null) throw new Error("not an object");
  const r = raw as Record<string, unknown>;
  if (typeof r.id !== "string" || typeof r.weightGrams !== "number") {
    throw new Error("missing required fields");
  }
  const status =
    typeof r.status === "string" && KNOWN.has(r.status)
      ? (r.status as ShipmentStatus)
      : "unknown";
  return { id: r.id, status, weightGrams: r.weightGrams };
}

// The server later adds "held_at_customs" and a new "carrier" field: this client keeps working.
console.log(parseShipment({ id: "shp_9", status: "held_at_customs", weightGrams: 1200, carrier: "Northwind" }));

A client for an invented shipping API that survives additive server changes.

Traps

  • Renaming a field 'for consistency' in place. To clients, that is a removal plus an addition.
  • Changing units or semantics, such as dollars to cents, while keeping the same field name and type.
  • Generating strict client models that reject unknown fields, which turns every additive change into an outage.
  • Bumping the major version for every small change, leaving several versions to maintain with no real benefit.
  • Removing an old version on the announced date without checking whether traffic has actually drained.

Rate limiting, quotas and backpressure

Rate limiting protects shared capacity and enforces fairness between tenants. The common algorithms differ in burst behaviour. A fixed window (100 requests per calendar minute) is cheap but allows up to double the rate across a window boundary. A sliding window smooths that edge. A token bucket refills at a steady rate up to a capacity, which allows controlled bursts while bounding the long-run average. A leaky bucket or queue smooths output to a constant rate.

Pick the limit key on purpose: API key, user, tenant, IP or endpoint. You often need several layers, for example a per-tenant limit plus a much tighter limit on an expensive export endpoint. When a request is rejected, return 429 with Retry-After so well-behaved clients back off rather than guessing. Many APIs also expose remaining quota in response headers.

With multiple API instances, per-process counters let each instance grant the full limit, so the effective limit grows with instance count. Shared state (Redis with atomic scripts, or a dedicated limiter service) gives a global limit at the cost of a network hop. A fallback policy decides what happens when that store is down.

TypeScript

class TokenBucket {
  private tokens: number;
  private lastRefill: number;

  constructor(
    private readonly capacity: number,
    private readonly refillPerSec: number,
    now: number = Date.now(),
  ) {
    this.tokens = capacity;
    this.lastRefill = now;
  }

  tryTake(now: number = Date.now()): { allowed: boolean; retryAfterSec: number } {
    const elapsedSec = (now - this.lastRefill) / 1000;
    this.tokens = Math.min(this.capacity, this.tokens + elapsedSec * this.refillPerSec);
    this.lastRefill = now;
    if (this.tokens >= 1) {
      this.tokens -= 1;
      return { allowed: true, retryAfterSec: 0 };
    }
    return { allowed: false, retryAfterSec: Math.ceil((1 - this.tokens) / this.refillPerSec) };
  }
}

// Report-export endpoint: bursts of 5, sustained 1 request every 2 seconds.
const bucket = new TokenBucket(5, 0.5, 0);
for (let i = 0; i < 7; i++) {
  console.log(i, bucket.tryTake(0)); // calls 5 and 6 are rejected with retryAfterSec: 2
}

An in-memory token bucket. To enforce a global limit across instances, keep the same logic in a shared store.

Traps

  • Counting per instance behind a load balancer and believing the limit is global.
  • Returning 429 without Retry-After, so clients retry immediately and amplify the overload.
  • Keying only by IP, which punishes users behind a shared NAT and is easy to evade with many addresses.
  • Applying the same limit to cheap reads and expensive exports or searches.
  • Failing closed when the limiter store is unavailable and taking the whole API down with it, without deciding that trade-off explicitly.

Timeouts, retries and exponential backoff with jitter

Every outbound HTTP call needs a timeout. Without one, a slow dependency holds sockets, threads and memory until your own service falls over. Think in deadlines. If your endpoint promises a response within 800 ms, a downstream call cannot be given 2 seconds, and each hop should get only what remains of the caller's budget.

Retry only what is safe and likely to succeed: network errors, timeouts, 502, 503, 504 and 429, and only for idempotent requests or requests carrying an idempotency key. Do not retry 400, 401, 403, 404 or 422. The same request will fail the same way.

Space retries with exponential backoff plus jitter. Without jitter, thousands of clients that failed together retry together and hit the recovering service in synchronised waves. With full jitter, the delay is random between zero and an exponentially growing cap. Respect Retry-After when the server sends it. Cap the total attempts. Remember that retries multiply across layers: three retries at each of four layers can turn one user request into dozens of calls to the deepest service, so retry at one layer, ideally the outermost that understands the operation.

TypeScript

const RETRIABLE = new Set([429, 502, 503, 504]);

const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

// Full jitter: random delay in [0, min(cap, base * 2^attempt)).
const backoffMs = (attempt: number) => Math.random() * Math.min(10_000, 200 * 2 ** attempt);

async function fetchWithRetry(url: string, init: RequestInit = {}, maxAttempts = 4): Promise<Response> {
  for (let attempt = 1; ; attempt++) {
    try {
      const res = await fetch(url, { ...init, signal: AbortSignal.timeout(2_000) });
      if (!RETRIABLE.has(res.status) || attempt === maxAttempts) return res;

      const retryAfterSec = Number(res.headers.get("Retry-After"));
      const delay = retryAfterSec > 0 ? retryAfterSec * 1000 : backoffMs(attempt);
      await res.body?.cancel(); // release the connection before waiting
      await sleep(delay);
    } catch (err) {
      if (attempt === maxAttempts) throw err;
      await sleep(backoffMs(attempt));
    }
  }
}

// Only call this for GET/PUT/DELETE, or for POST with an Idempotency-Key header.

A fetch wrapper with per-attempt timeouts, Retry-After support and full-jitter backoff (Node 18+ or modern browsers).

Traps

  • Leaving HTTP clients on their default timeouts, which are often very long or infinite.
  • Retrying non-idempotent POSTs without an idempotency key, which creates duplicates.
  • Retrying at every layer of a call chain, which multiplies load during an outage.
  • Exponential backoff without jitter, which keeps clients synchronised and causes retry storms.
  • Giving each attempt a fresh full timeout, so the total time exceeds what the caller can wait.

Authentication, tokens and object-level authorization

Authentication answers who is calling. Authorization answers whether they may do this to this specific resource. APIs usually authenticate with bearer tokens. These are either opaque tokens checked against the issuer or a store, or self-contained tokens like JWTs that the API validates locally by checking the signature with an expected algorithm and key, then exp, iss and aud. Local validation is fast, but a JWT cannot be revoked before it expires unless you add a denylist. That is why access tokens are short-lived and paired with refresh tokens.

For delegated access, such as a third-party app acting for a user, use OAuth 2.0. Browser and mobile apps use the authorization code flow with PKCE, and server-to-server calls use client credentials. Scopes limit what the token can do, but they are coarse. A scope like invoices:read does not say which invoices.

The most common serious API flaw is broken object-level authorization. The endpoint checks that the caller is logged in, then loads /invoices/{id} without checking that the invoice belongs to the caller's tenant. Enforce ownership in the data access path itself, for example by always filtering on the tenant ID taken from the verified token, never from the request body.

TypeScript

interface Principal { userId: string; tenantId: string; scopes: string[] }
interface Invoice { id: string; tenantId: string; totalCents: number }

interface InvoiceRepo {
  // The tenant filter lives in the query, so it cannot be forgotten by a handler.
  findForTenant(tenantId: string, invoiceId: string): Promise<Invoice | null>;
}

async function getInvoice(
  principal: Principal | null,
  invoiceId: string,
  repo: InvoiceRepo,
): Promise<{ status: number; body: unknown }> {
  if (!principal) return { status: 401, body: { error: "authentication required" } };
  if (!principal.scopes.includes("invoices:read")) {
    return { status: 403, body: { error: "missing scope invoices:read" } };
  }
  const invoice = await repo.findForTenant(principal.tenantId, invoiceId);
  // 404, not 403: do not reveal that another tenant's invoice exists.
  if (!invoice) return { status: 404, body: { error: "invoice not found" } };
  return { status: 200, body: invoice };
}

Scope check plus tenant-scoped lookup for an invented billing API. The principal comes from a verified token, never from request parameters.

Traps

  • Checking authentication but not ownership, so any logged-in user can read other tenants' objects by changing an ID.
  • Trusting a tenantId or userId from the request body or query string instead of the verified token.
  • Accepting a JWT without pinning the algorithm and checking aud, which lets tokens issued for another service work against yours.
  • Issuing long-lived JWT access tokens with no way to revoke them after a compromise.
  • Using sequential IDs and assuming they are secret. Unguessable IDs reduce enumeration but never replace authorization.

Common questions

Short answers to the usual doubts.

Should I use PUT or PATCH for updates?

Use PUT when the client sends the full representation and the server replaces it. It is idempotent and easy to reason about, but clients must send every field or risk wiping some. Use PATCH for partial updates, with a defined format such as JSON Merge Patch or JSON Patch. Pair either one with If-Match when concurrent edits are possible.

When is 404 better than 403?

When the caller should not even learn that the resource exists, typically for objects owned by another tenant or user. Use 403 when the caller can know the resource exists but lacks permission for the action, for example a viewer trying to delete a document in their own workspace.

Is REST still the default, or should I talk about GraphQL and gRPC?

Know the trade-offs. Resource-oriented HTTP APIs get caching, broad tooling and simple debugging. GraphQL lets clients shape responses, but it moves caching, rate limiting and query cost control onto you. gRPC suits internal service-to-service calls with strict schemas and streaming. The concepts in this guide, such as idempotency, timeouts, authorization and evolution, apply to all three.

How do I explain the difference between idempotency and exactly-once delivery?

Over an unreliable network you cannot guarantee a message is delivered exactly once. You get at-least-once with retries. Idempotency makes processing it more than once harmless, so the observable effect is exactly once. That is why idempotency keys and deduplication are the practical answer.

Do I need to memorise every status code?

No. Know the common ones precisely: 200, 201, 202, 204, 301, 304, 400, 401, 403, 404, 409, 412, 422, 429, 500, 502, 503 and 504. Above all, know the reasoning: whether the client should change the request, retry later or stop.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide3 of 4 · Frontend and APIsGraphQL APIs in Production: Concepts for Mid and Senior EngineersRead the next one