PrepStack › Backend › API Design: REST, GraphQL, gRPC

API Design: REST, GraphQL, gRPC interview cheat sheet

Resources, status codes, pagination, errors, idempotency, GraphQL, gRPC, real-time and evolution

API design rounds check whether you can build an interface other teams can use safely for years. Expect questions on REST basics (methods, status codes, naming), then practical design: pagination, errors, idempotency, versioning and rate limits. Senior rounds add GraphQL and gRPC trade-offs, real-time options, webhooks and how to change an API without breaking clients. Read the 15-minute revision first, then use Quiz mode and answer out loud.

15-minute revision

  1. REST = an architectural style (Fielding, 2000): client-server, stateless, cacheable, uniform interface, layered system, optional code-on-demand.
  2. Richardson Maturity Model: L0 one endpoint (RPC over HTTP) → L1 resources → L2 HTTP verbs + status codes → L3 hypermedia (HATEOAS). Most "REST" APIs are L2.
  3. URLs name resources with plural nouns (/orders/42/items); the HTTP method is the verb. Use kebab-case paths and keep nesting shallow.
  4. Safe = no state change (GET, HEAD, OPTIONS). Idempotent = same effect if repeated (safe ones + PUT, DELETE). POST and PATCH are not guaranteed idempotent.
  5. Key codes: 200 OK, 201 Created + Location, 202 Accepted, 204 No Content, 400, 401 (who are you?), 403 (not allowed), 404, 409 Conflict, 412, 422, 429, 500, 502, 503, 504.
  6. PUT replaces the whole resource; PATCH changes part of it (JSON Merge Patch RFC 7396 or JSON Patch RFC 6902).
  7. Versioning: URI (/v1) is most common and simplest; header/media-type versioning keeps URLs clean. Avoid breaking changes so you rarely need a new version.
  8. Offset pagination is simple but slow on deep pages and skips or repeats rows when data changes. Cursor (keyset) is stable and uses an index: WHERE (created_at, id) < (?, ?).
  9. Errors: use RFC 9457 Problem Details (application/problem+json with type, title, status, detail, instance) plus your own fields like errors[].
  10. Idempotency-Key header on POST: the server stores key → response, replays it on retry, returns 422 if the key is reused with a different body and 409 if the first call is still running.
  11. Rate limits: reply 429 Too Many Requests with Retry-After. Common headers are X-RateLimit-Limit/Remaining/Reset; the IETF RateLimit / RateLimit-Policy fields are still a draft.
  12. GraphQL: one endpoint, typed schema, client picks fields. Query = read, Mutation = write, Subscription = server push. Watch out for N+1 (fix with DataLoader) and query cost.
  13. gRPC: Protocol Buffers over HTTP/2, generated clients, deadlines, 4 call types (unary, server-stream, client-stream, bidi). Great for service-to-service, needs gRPC-Web/Connect in browsers.
  14. Real-time: long polling (simple, works everywhere), SSE (server → client text over HTTP, auto-reconnect), WebSockets (full duplex, binary, more ops work).
  15. Webhooks: sign the raw body with HMAC-SHA256 plus a timestamp, verify with a constant-time compare, retry with exponential backoff, and make receivers idempotent by event id.
  16. Backward compatible = add, don't change or remove: new optional fields and endpoints are safe; renaming, removing, retyping or making a field required is breaking. Clients must ignore unknown fields.

REST Foundations

REST constraints & Richardson maturity

REST is a set of constraints, not a protocol. The Richardson model measures how far an HTTP API follows them.

  • Roy Fielding defined REST in his 2000 dissertation. It describes how the web scales: client-server, stateless, cacheable, uniform interface, layered system and optional code on demand.
  • Stateless means each request carries everything needed to handle it (auth token, ids, paging info). The server keeps no client session, so any instance can serve any request.
  • Uniform interface has four parts: resources are identified by URIs, you change them through representations (JSON), messages are self-descriptive (method, headers, media type), and hypermedia drives state (HATEOAS).
  • Cacheable: responses say whether they can be cached (Cache-Control, ETag). Layered: clients cannot tell if they talk to the origin, a CDN, a proxy or a gateway.
  • The Richardson Maturity Model (described by Martin Fowler) has 4 levels. Level 2 (resources + verbs + status codes) is what most teams mean by REST. Level 3 adds links.
  • REST is not tied to JSON or even HTTP in theory, but in practice it means resource-oriented JSON over HTTP.

Interview questions

  • What is REST and what are its constraints?
  • What does "stateless" mean in REST, and why does it matter?
  • Explain the Richardson Maturity Model.
  • REST vs SOAP?

Resource naming & URL design

URLs are nouns for resources, HTTP methods are the verbs, and query strings filter collections.

  • Use plural nouns for collections and an id for one item: /users, /users/7. Keep the same plural form everywhere.
  • Show relationships with one level of nesting: /users/7/orders. Deeper chains (/a/1/b/2/c/3) are fragile; give sub-resources their own top-level URL when they have a global id.
  • Use lowercase kebab-case paths (/payment-methods), no trailing slash, no file extensions. JSON field names should follow one style (camelCase or snake_case) consistently.
  • Do not put verbs in paths (/getUser, /createOrder). For real actions that are not CRUD, model them as a sub-resource or a controller resource: POST /orders/42/cancellation or POST /orders/42:cancel (Google AIP style).
  • Use query parameters for filtering, sorting, paging and field selection, not for identifying the resource.
  • Never expose internal details like database table names or auto-increment ids if they leak business data; UUIDs or prefixed ids (ord_8fK2) are common.

Interview questions

  • How do you name REST endpoints?
  • How would you model an action like "cancel order" or "send email" in REST?
  • Should you nest resources deeply, like /customers/1/orders/2/items/3?

HTTP methods & status code mapping

Pick the method for its safety and idempotency guarantees, and return the status code that tells the client exactly what happened.

  • Safe methods (GET, HEAD, OPTIONS) must not change server state, so crawlers, caches and prefetchers can call them freely.
  • Idempotent methods (safe ones plus PUT and DELETE) have the same effect whether called once or ten times. Clients and proxies may retry them after a timeout.
  • POST creates or triggers processing and is not idempotent. PATCH is not guaranteed idempotent (for example {"op": "increment"}).
  • Creation returns 201 Created with a Location header. Async work returns 202 Accepted with a status URL. Success with no body is 204 No Content.
  • 401 means not authenticated (missing or bad credentials, send WWW-Authenticate). 403 means authenticated but not allowed. Some APIs return 404 instead of 403 to hide that a resource exists.
  • 400 is malformed input (bad JSON, wrong type). 422 Unprocessable Content is well-formed but fails business validation. 409 Conflict is a clash with current state (duplicate, version mismatch).
  • 5xx means the server failed: 500 bug, 502 bad upstream response, 503 overloaded or in maintenance (add Retry-After), 504 upstream timeout.

Interview questions

  • What is the difference between safe and idempotent methods?
  • 401 vs 403?
  • 400 vs 422 vs 409?
  • What should POST return after creating a resource?

PUT vs PATCH (and partial updates)

PUT sends the full new state and replaces the resource; PATCH sends only the changes in a defined patch format.

  • PUT means "store this representation at this URL". Fields you leave out are cleared or reset to defaults. It is idempotent.
  • PATCH (RFC 5789) applies a set of changes. The body format defines how: JSON Merge Patch (RFC 7396, application/merge-patch+json) or JSON Patch (RFC 6902, application/json-patch+json).
  • Merge Patch is a partial document: keys you send are set, null deletes a key, nested objects merge, but arrays are replaced whole.
  • JSON Patch is a list of operations (add, remove, replace, move, copy, test). It can edit array elements and has a test op for safe checks, but it is harder to write by hand.
  • PUT can also create at a client-chosen URL (PUT /configs/eu-west) and return 201; POST creates at a server-chosen URL.
  • To stop lost updates, use optimistic locking: GET returns an ETag, the client sends If-Match on PUT/PATCH, and the server returns 412 Precondition Failed if it changed.

Interview questions

  • PUT vs PATCH?
  • Is PATCH idempotent?
  • JSON Merge Patch vs JSON Patch?
  • How do you prevent two users overwriting each other's update?

API versioning strategies

Version only for breaking changes, pick one visible scheme, and give clients a deprecation timeline.

  • URI versioning (/v1/orders) is the most common: obvious, easy to route and cache, easy to test in a browser. Critics say the URL should identify the resource, not its version.
  • Header versioning (Api-Version: 2) or media-type versioning (Accept: application/vnd.acme.v2+json) keeps URLs stable but is harder to see, test and cache (needs Vary).
  • Query parameter (?api-version=2024-10-01) is used by Azure. Date-based versions pinned per account are used by Stripe: each account is pinned to the version it first used and upgrades when it chooses.
  • Use a major version only for breaking changes. Additive changes (new optional fields, new endpoints) ship without a version bump.
  • Run old and new versions side by side, often by translating old requests to the new model in a thin adapter layer.
  • Announce retirement with Deprecation and Sunset headers (RFC 8594 for Sunset), docs and emails, and track who still calls the old version.

Interview questions

  • How do you version a REST API? Which approach do you prefer?
  • When do you actually need a new version?
  • How do you retire an old version?

Designing REST Endpoints

Pagination: offset vs cursor

Offset is simple but drifts and slows down on deep pages; cursor (keyset) pagination is stable and fast.

  • Offset/limit (?offset=40&limit=20 or ?page=3): easy, allows jumping to page N, but the database still reads and throws away the first 40 rows, so deep pages get slow.
  • Offset drifts when data changes: a new row at the top pushes items down and the next page repeats one; a delete makes you skip one.
  • Cursor (keyset) pagination remembers the last row's sort key and asks for rows after it: WHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESC LIMIT 21. It uses an index, so every page costs the same.
  • The sort key must be unique and stable. Add the primary key as a tiebreaker to non-unique columns like created_at.
  • Make cursors opaque (base64 of JSON, optionally signed) so clients cannot build them and you can change the format later.
  • Fetch limit + 1 rows to know if there is a next page without a COUNT(*). Total counts on big tables are expensive; make them optional.
  • Return paging info in the body (next_cursor, has_more) or as Link headers (rel="next"), which GitHub uses.

Interview questions

  • Offset vs cursor pagination?
  • Why is OFFSET 1000000 slow?
  • How do you build a cursor when the sort column is not unique?
  • How do you tell the client there are more pages without COUNT(*)?

Filtering, sorting & field selection

Expose filters and sorts through query parameters, but only for an allowlist of fields that are indexed.

  • Simple equality filters: ?status=active&category=shoes. Multiple values: ?status=active,draft.
  • Ranges need an operator syntax. Popular choices: ?price[gte]=10&price[lt]=50, ?price_min=10, or a small expression language like ?filter=price ge 10 (OData style).
  • Sorting: ?sort=-price,name means price descending, then name ascending. JSON:API uses this convention.
  • Sparse fieldsets (?fields=id,name,price) and expansion (?expand=customer) reduce over-fetching and extra calls.
  • Always use an allowlist of filterable and sortable fields. Map them to columns in code and pass values as bind parameters. Never paste user input into SQL.
  • Each allowed filter or sort should be backed by an index, or one curious client can run full table scans.

Interview questions

  • How would you design filtering and sorting for a list endpoint?
  • What are sparse fieldsets and when would you use them?
  • How do you stop filters from being a SQL injection or performance risk?

Error format: RFC 9457 Problem Details

Return errors as application/problem+json with a stable type, a human title, the status, and extra fields for details.

  • RFC 9457 (2023) replaces RFC 7807 and defines a standard JSON error body with media type application/problem+json.
  • Standard members: type (a URI that identifies the error kind, default about:blank), title (short summary of the type), status (HTTP status, advisory), detail (this occurrence, for humans), instance (URI for this occurrence).
  • You may add extension members, such as errors for field-level validation, balance, or a traceId. Clients must ignore extensions they do not understand.
  • Clients should branch on type, not on the title or detail text, which may change or be translated.
  • RFC 9457 adds a shared registry of common problem types and shows how to report multiple validation errors with a JSON Pointer to each field.
  • Never leak stack traces, SQL or internal hostnames in detail. Log them server-side and return a correlation id.

Interview questions

  • How should a REST API return errors?
  • What is RFC 9457 and how is it different from RFC 7807?
  • Should validation return one error or all of them?

Idempotency keys & safe retries

The client sends a unique Idempotency-Key with a POST; the server stores the result and replays it on retry, so the action happens once.

  • Networks fail after the server did the work but before the client got the response. Without protection, a retry of POST /payments charges twice.
  • The client generates a unique key (UUID v4) per logical operation and sends Idempotency-Key: <key>. Retries reuse the same key.
  • The server stores key → request fingerprint, status, response (scoped per client) with a TTL like 24 hours. A repeat with the same key returns the saved response without redoing the work.
  • The IETF draft (draft-ietf-httpapi-idempotency-key-header) suggests 400 if a required key is missing, 422 if the key is reused with a different body, and 409 if the first request is still being processed.
  • Insert the key with a unique constraint (or SETNX in Redis) before doing work, so two concurrent retries cannot both proceed.
  • Ideally store the key and the business change in the same database transaction. If the side effect is external (a card network), pass the key downstream too.

Interview questions

  • How do you make a POST endpoint like "create payment" safe to retry?
  • Where do you store idempotency keys and what about race conditions?
  • Difference between an idempotent method and an idempotency key?

HATEOAS & OpenAPI contracts

HATEOAS puts next-step links in responses; OpenAPI describes the API in a machine-readable file for docs, codegen and validation.

  • HATEOAS (Hypermedia as the Engine of Application State) means the response tells the client what it can do next through links, like a web page does with buttons.
  • Formats include HAL (_links), JSON:API (links), Siren and plain Link headers. A cancelled order simply has no cancel link.
  • In practice few public APIs are full HATEOAS, because clients are usually written against docs, not discovered at runtime. Links for pagination and related resources are the common useful subset.
  • OpenAPI (formerly Swagger) describes paths, parameters, request and response schemas, auth and examples in YAML or JSON. Current versions are 3.1 (full JSON Schema alignment) and 3.2 (released September 2025).
  • Design-first: write the OpenAPI file, review it, generate mocks and clients, then implement. Code-first: annotate code and generate the spec. Design-first catches design mistakes earlier.
  • Use the spec in CI: lint it (Spectral), detect breaking changes between versions (oasdiff), and validate requests and responses against it in contract tests.

Interview questions

  • What is HATEOAS? Have you used it?
  • Swagger vs OpenAPI?
  • Design-first or code-first?
  • How do you catch breaking changes before they ship?

Rate limiting & rate limit headers

Limit requests per client with a token bucket or window, reply 429 with Retry-After, and tell clients their remaining quota in headers.

  • Rate limits protect the service from abuse and noisy neighbours and enforce plan tiers. Limit by API key, user or IP, and sometimes by endpoint cost.
  • Token bucket: tokens refill at a steady rate up to a capacity; each request takes one. Allows short bursts. Leaky bucket smooths output to a fixed rate. Fixed window counters are simple but allow double bursts at window edges; sliding window fixes that.
  • On limit, return 429 Too Many Requests with Retry-After (seconds or an HTTP date). 503 + Retry-After is for server overload, not per-client quotas.
  • De facto headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (GitHub and many others). Reset is epoch seconds for some APIs and seconds-until-reset for others, so document it.
  • The IETF RateLimit and RateLimit-Policy header fields are still an Internet-Draft, and their parameter names have changed between revisions. Check the latest draft before adopting them.
  • In a cluster, keep counters in a shared store like Redis (atomic INCR + EXPIRE or a Lua script) or enforce limits at the API gateway.

Interview questions

  • How would you implement rate limiting for an API?
  • Token bucket vs leaky bucket vs fixed window?
  • Which headers do you return for rate limits?

GraphQL

GraphQL schema, queries, mutations & subscriptions

GraphQL exposes a typed schema at one endpoint; clients send a query that names exactly the fields they want.

  • The schema (SDL) defines types, fields and their nullability. String! means non-null; [Post!]! is a non-null list of non-null posts.
  • Three root operation types: Query (read), Mutation (write, top-level fields run in order) and Subscription (a stream of events pushed by the server).
  • Clients choose fields, so there is no over-fetching (extra fields) or under-fetching (many round trips). One request can fetch a user, their posts and comment counts.
  • Usually served as POST /graphql with {query, variables, operationName}. Responses have data and an optional errors array, so partial success is possible.
  • Introspection lets tools (GraphiQL, codegen) read the schema. Many teams disable it in production for public APIs.
  • Subscriptions typically run over WebSockets (the graphql-ws protocol) or SSE. Other building blocks: fragments (reusable field sets), variables, directives like @include and @deprecated, interfaces, unions and input types.

Interview questions

  • What is GraphQL and what problem does it solve?
  • Query vs mutation vs subscription?
  • How does GraphQL handle errors?

Resolvers, the N+1 problem & DataLoader

Each field has a resolver; naive nested resolvers run one query per parent item, and DataLoader batches them into one.

  • A resolver is a function (parent, args, context, info) that returns the value of one field. If no resolver is given, the default returns parent[fieldName].
  • Execution walks the query tree: resolve posts, then for each post resolve author. With 100 posts that is 1 + 100 database calls: the N+1 problem.
  • DataLoader collects all load(id) calls made in the same tick of the event loop, then calls your batch function once with all ids (WHERE id IN (...)).
  • The batch function must return results in the same order as the keys, with null or an error for missing ones.
  • DataLoader also caches per request. Create new loaders for every request (put them in context) so users never see each other's data.
  • Other fixes: join or prefetch based on the requested fields (info), or tools like Hibernate batch fetching on the Java side.

Interview questions

  • What is the N+1 problem in GraphQL?
  • How does DataLoader solve N+1?
  • Why must DataLoader instances be per request?
  • What do the four resolver arguments mean?

GraphQL pros, cons & production concerns

GraphQL gives clients flexibility and a typed contract, but makes caching, security and performance control harder on the server.

  • Pros: exact data per screen, one round trip, a strong typed schema with great tooling, evolution without versions (add fields, deprecate old ones), and a natural fit for a BFF or for federating many services.
  • HTTP caching is harder: most queries are POSTs to one URL. Use client caches (Apollo, Relay normalized cache), persisted queries sent as GET, or field-level caching.
  • Query cost: clients can ask for deep or wide queries. Protect with depth limits, complexity/cost analysis, timeouts, pagination limits and rate limiting by cost.
  • Persisted queries / allowlists: the client sends a hash of a pre-registered query. Smaller requests, GET caching, and only known queries can run.
  • Authorization belongs in the business layer (or per field), not only at the endpoint, because one request touches many types.
  • Other costs: file uploads are not in the spec, monitoring needs per-operation metrics (every call is POST /graphql), and error handling differs from HTTP status codes.

Interview questions

  • When would you choose GraphQL over REST?
  • What are the main drawbacks of GraphQL?
  • How do you secure a public GraphQL API against expensive queries?
  • How do you cache GraphQL responses?

gRPC & Choosing a Style

gRPC: protobuf, HTTP/2 & streaming

gRPC is a contract-first RPC framework that sends Protocol Buffers over HTTP/2, with generated clients and four call types.

  • You define services and messages in a .proto file. protoc (or buf) generates typed client stubs and server interfaces for many languages.
  • Protocol Buffers is a compact binary format. Each field is sent as a field number plus value, not a name, so messages are smaller and faster to parse than JSON.
  • gRPC runs on HTTP/2: many concurrent calls multiplexed over one TCP connection, header compression (HPACK), and full-duplex streams.
  • Four call types: unary, server streaming, client streaming and bidirectional streaming.
  • Built-in deadlines propagate across services, plus cancellation, metadata (headers), interceptors and its own status codes (OK, INVALID_ARGUMENT, NOT_FOUND, DEADLINE_EXCEEDED, UNAVAILABLE, …).
  • Browsers cannot speak raw gRPC (they lack the needed control over HTTP/2 frames and trailers), so web clients use gRPC-Web via a proxy, Connect, or a REST gateway (grpc-gateway, JSON transcoding).
  • Long-lived HTTP/2 connections break simple L4 load balancing: one connection pins to one backend. Use L7 (request-level) load balancing, a service mesh, or client-side balancing.

Interview questions

  • What is gRPC and why is it fast?
  • Explain the four gRPC streaming types.
  • When would you use gRPC instead of REST?
  • What are the challenges of running gRPC in production?

REST vs GraphQL vs gRPC

REST for public resource APIs, GraphQL for flexible client-driven reads, gRPC for fast typed service-to-service calls.

  • REST: resource-oriented, uses HTTP fully (methods, status, caching), human-readable JSON, universal tooling. Weak at aggregating many resources per screen.
  • GraphQL: one endpoint with a typed schema, client selects fields, great for varied frontends. Harder caching, cost control and N+1 issues.
  • gRPC: contract-first, binary protobuf over HTTP/2, streaming, deadlines. Best inside the data center; poor native browser support.
  • They are often combined: gRPC between microservices, a GraphQL or REST BFF at the edge, and REST webhooks to partners.
  • Choose based on consumers (public, browser, internal), data shape (graphs vs resources vs RPC actions), performance needs and team skills.

Interview questions

  • Compare REST, GraphQL and gRPC.
  • You are designing APIs for a mobile app backed by 20 microservices. What do you choose?
  • Why not use gRPC for a public API?

Real-time, Integration & Evolution

WebSockets vs SSE vs long polling

Long polling fakes push with held requests, SSE streams text one way from the server, and WebSockets give a full-duplex channel.

  • Short polling: the client asks every N seconds. Simple but wasteful and laggy.
  • Long polling: the server holds the request open until there is data or a timeout, then the client immediately asks again. Works everywhere, but each message costs a new request.
  • Server-Sent Events (SSE): one long HTTP response with Content-Type: text/event-stream. Server → client only, UTF-8 text, browser EventSource auto-reconnects and sends Last-Event-ID so the server can resume.
  • WebSockets (RFC 6455): start as an HTTP request with Upgrade: websocket, server replies 101 Switching Protocols, then both sides send text or binary frames at any time.
  • SSE works with normal HTTP infrastructure (auth headers, proxies, HTTP/2 multiplexing). Over HTTP/1.1, browsers allow only about 6 connections per domain, which limits SSE tabs.
  • WebSockets need sticky or stateful infrastructure: connection-aware load balancing, heartbeats (ping/pong), your own reconnect and resume logic, and a pub/sub backplane (Redis, Kafka) to fan out across servers.

Interview questions

  • WebSockets vs SSE vs long polling: how do you choose?
  • How does a WebSocket connection start?
  • How do you scale WebSockets to millions of connections?

Webhooks: signing, retries & delivery

Webhooks POST events to a URL the customer registers; sign them, retry with backoff, and expect receivers to dedupe.

  • A webhook is a reverse API: when an event happens, your server sends an HTTP POST to the subscriber's URL. It replaces polling.
  • Sign every delivery: compute HMAC-SHA256(secret, timestamp + '.' + rawBody) and send it in a header. The receiver recomputes it over the raw bytes and compares in constant time.
  • Include a timestamp in the signed data and reject old ones (for example older than 5 minutes) to block replay attacks. Support secret rotation by allowing two valid signatures.
  • Delivery is at-least-once: retry on timeouts and non-2xx responses with exponential backoff (and jitter) for hours or days, then mark the endpoint as failing and alert the owner.
  • Receivers should return 2xx fast and process asynchronously (queue), and dedupe by event id, because duplicates and out-of-order delivery happen.
  • Send a thin payload (event type + id) or a full snapshot. Thin events plus a fetch avoid stale or out-of-order data issues. The Standard Webhooks spec defines common headers (webhook-id, webhook-timestamp, webhook-signature).

Interview questions

  • How would you design a reliable webhook system?
  • How does a receiver verify a webhook is genuine?
  • Why should a webhook receiver respond quickly?
  • Webhooks vs polling vs a streaming connection?

API gateway & Backend for Frontend (BFF)

A gateway is one shared entry point for cross-cutting concerns; a BFF is a client-specific backend that shapes data for one frontend.

  • An API gateway sits in front of services and handles routing, TLS termination, authentication (JWT/OAuth validation), rate limiting, CORS, request logging, metrics and sometimes caching and protocol translation (REST ↔ gRPC).
  • Examples: Kong, AWS API Gateway, Azure API Management, Apigee, Envoy-based gateways, Spring Cloud Gateway, NGINX.
  • Keep the gateway thin. Business logic in the gateway creates a distributed monolith that every team must change.
  • A BFF (Backend for Frontend) is a separate backend per client type (web, iOS, partner). It aggregates calls to many services and returns exactly what that UI needs, owned by the frontend team.
  • BFFs reduce chattiness on mobile networks and let each client evolve independently. The cost is duplicated logic across BFFs; push shared rules down into services.
  • A GraphQL server is often used as a single flexible BFF. A service mesh (Istio, Linkerd) handles east-west (service-to-service) traffic, while the gateway handles north-south (client-to-system) traffic.

Interview questions

  • What is an API gateway and what should it do?
  • What is the BFF pattern and when would you use it?
  • API gateway vs BFF vs service mesh?

Backward compatibility & API evolution

Evolve APIs by adding, never by changing or removing; clients must tolerate unknown data, and breaking changes need a new version and a migration path.

  • Backward compatible means existing clients keep working without changes. Assume every field you ever returned is used by someone (Hyrum's law).
  • Safe changes: add an endpoint, add an optional request field, add a response field, add an optional query parameter, relax a validation.
  • Breaking changes: remove or rename a field, change a type or format, make an optional input required, tighten validation, change default behaviour, change status or error codes, change URL or auth.
  • Clients must follow the tolerant reader rule: ignore unknown fields and handle unknown enum values. Servers follow Postel's idea carefully: be strict about what you send.
  • For renames, use expand and contract: add the new field, write both, migrate clients, watch usage drop to zero, then remove the old one.
  • Protobuf: never change or reuse a field number; mark removed ones reserved. GraphQL: add fields, mark old ones @deprecated, and remove them only when usage metrics show zero.

Interview questions

  • What makes a change backward compatible?
  • How do you rename a field in a live API used by mobile apps?
  • How do you evolve protobuf messages safely?