API and Interface Design for Distributed Services Questions
Designing the contracts between services and clients: REST, gRPC, and GraphQL tradeoffs, versioning and backward compatibility, pagination, rate limiting, and idempotent endpoints. Covers request/response modeling, error contracts, and API gateway responsibilities. Focuses on the interface layer that ties distributed components together, not internal data schemas.
A public API needs a new required field added to its request schema, and it's used by many client versions whose release cadence you don't control. Walk through how you would roll this out with zero downtime and minimal disruption to existing clients, including how you would eventually know it's actually safe to enforce the field as required.
Sample Answer
Direct answer
Ship the server change so it accepts requests both with and without the new field, defaulting it server-side when absent, so nothing breaks the moment the change deploys. Roll enforcement in behind a flag keyed by caller or client version, expanding gradually while watching a "requests missing this field" metric drop toward zero, and only flip the field to actually required once that metric shows it is safe for the population of clients you cannot update directly, not on a fixed calendar date.
Framework
Phase 0: ship tolerant, observe only
Deploy server code that accepts the field as optional, applies a sensible default when it is missing, and logs, tagged by caller and client version, every request that arrives without it. Nothing is rejected in this phase. This is what makes the eventual rollout zero-downtime: the deploy that adds validation never also has to add the field, because those are two separate deploys.
Phases 1-3: progressive enforcement
Behind a server-side feature flag keyed by caller id or client version, start rejecting requests missing the field for a small, known-safe slice of traffic first, for example your own internal callers, who you can fix immediately if they break. Widen the slice in stages, a percentage of external traffic, then all traffic from clients above a known-good version, watching the missing-field rate and the resulting error rate at each stage before widening further.
Phase 4: flip to required
Once the missing-field rate across all remaining traffic is at, or has been driven to, zero, or the only remaining non-compliant callers are ones identified by name who have either been fixed directly or have explicitly accepted the breakage, remove the tolerant path and the flag. The field is now genuinely required, not just documented as required while the server quietly still accepts its absence.
Worked example
Concretely: at Phase 0, telemetry shows 12% of requests lack the new field. Enabling strict validation for 1% of traffic, Phase 1, internal callers only, shows 0% errors, since internal callers were already updated first. Widening to 25% of external traffic, Phase 2, surfaces a 2% error rate concentrated in exactly 3 identifiable partner API keys still on an old integration version; those 3 keys are contacted directly and updated. Phase 3 widens to 100% traffic and the error rate returns to 0%, confirming it is now safe to make Phase 4's flip permanent and delete the tolerant path.
Rollback plan, defined before the rollout starts, not improvised during an incident: the fastest rollback is flipping the enforcement flag back to "accept missing field" for the affected slice, which takes effect without a new deployment. If the underlying server change itself is the problem, not just the validation strictness, redeploy the previous server version behind the same gradual-traffic mechanism used to roll it forward, rather than an all-at-once revert.
Trade-offs and pitfalls
- Splitting "accept the field" and "require the field" into two separate deploys costs an extra release cycle compared to shipping both at once, but it is what makes the rollout genuinely zero-downtime instead of a bet that every client updates before a single deploy lands.
- A common pitfall is widening the enforcement percentage on a fixed schedule, day 1 at 10%, day 7 at 50%, day 14 at 100%, instead of on the observed missing-field rate at each stage. A schedule that ignores what the data is saying can either drag on longer than necessary, or worse, widen past a real problem simply because a date arrived.
- Another pitfall is treating "0% errors so far" as proof of safety when the current traffic slice does not yet include the population most likely to be non-compliant, batch jobs that run monthly, or mobile clients on very old versions most users have already updated away from. Widen enforcement along dimensions that specifically include the slowest-moving clients before declaring the rollout complete.
You are designing an API for a social feed consumed by both mobile and web clients, and the mobile team keeps complaining the responses are heavy and hard to work with. Walk through how you would shape the API to minimize client complexity, and justify your protocol choice given the mobile bandwidth constraints.
Sample Answer
Direct answer
The mobile team's complaint ("responses are heavy and hard to work with") is really two separate problems: the payload carries fields nobody on that screen needs, and the client has to reshape what it gets before it can render. The fix is to stop shipping one fixed shape to every consumer and let the server compute exactly the fields each client asks for, while keeping the underlying feed data model the same. Given that mobile and web genuinely want different shapes from the same feed and mobile is bandwidth-constrained, GraphQL's field-selection model is the better protocol fit here, as long as it is constrained (persisted, allow-listed queries; depth and cost limits) so no client can accidentally request an expensive, unbounded query.
Structured elaboration
Requirements to design against: less client-side reshaping work, smaller mobile payloads, predictable caching behavior, and one schema that serves both clients without diverging codepaths.
Protocol comparison for this consumer mix:
| Concern | REST (fixed resource shape) | GraphQL (client-selected fields) | gRPC |
|---|---|---|---|
| Matches "mobile wants less, web wants more" | Poor without ad hoc ?fields= params | Native fit, one query per client shape | Poor, schema is fixed per RPC method |
HTTP-level caching (CDN, Cache-Control) | Strong, stable URLs | Weak by default, needs persisted-query IDs to get cacheable URLs back | Not HTTP-cacheable in the browser sense |
| Browser/mobile-web client support | Native | Native (plain HTTP POST/GET) | Needs gRPC-Web plus a proxy translating HTTP/2 trailers, extra moving part for a browser client |
| Risk of one client hurting others | Low, server controls the shape | Real, a deep nested query can be expensive; needs depth/cost limits | Low |
| Payload compactness for text-heavy feed data | Medium (JSON) | Medium (JSON, but only requested fields) | Best (binary), but the win is smaller for a feed that's already mostly short strings and IDs |
Response-shaping principles regardless of protocol:
- Cursor-based pagination (opaque
next_cursortoken) instead of offsets, so the feed stays stable while new posts are inserted. - Embed hot-path fields the card renders unconditionally (author name, avatar URL, like count); reference cold-path data the card doesn't render by default (full bio, high-resolution media, comment thread) via a separate call or a nested field the client only selects when it needs it.
- Serve media as pre-generated size variants (thumbnail/medium/full URLs) rather than one large image URL the client has to resize client-side; this is a bigger bandwidth win for mobile than almost any protocol choice.
Making GraphQL safe for a bandwidth-constrained mobile client:
- Ship the mobile app with a fixed set of persisted queries (each identified by a hash the client sends instead of the query text). The server only executes registered query hashes and rejects anything else with a 400 response; this closes off arbitrary expensive queries and lets a CDN cache responses by persisted-query hash the same way it would cache a REST URL.
- Enforce query depth and complexity limits server-side so a client cannot nest
author.posts.author.posts...into an expensive fan-out. - Keep the REST fallback in mind: a much lower-effort alternative that gets most of the same benefit is REST with a sparse-fieldset query parameter (
?fields=id,text,author.name,author.avatar_url); it is worth naming as the pragmatic choice for a smaller team that isn't ready to run a GraphQL server.
Worked example
Same feed item, shaped two different ways from one underlying schema.
REST, default embedding (what the mobile team is complaining about):
{
"id": "post_9182",
"text": "Shipped the new onboarding flow today",
"created_at": "2026-07-18T14:02:00Z",
"author": {
"id": "u_4471",
"name": "Priya Shah",
"avatar_url": "https://cdn.example.com/avatars/u_4471_full.jpg",
"bio": "Product engineer, ex-Stripe, likes climbing",
"follower_count": 3821,
"following_count": 512
},
"media": [
{ "url": "https://cdn.example.com/media/m_1.jpg", "width": 4032, "height": 3024 }
],
"like_count": 214,
"comment_count": 18,
"geo": { "lat": 37.7749, "lng": -122.4194 }
}
Everything the card actually renders on mobile is five fields; the rest (bio, follower/following counts, full-resolution image, precise geo) is dead weight on that screen.
GraphQL query the mobile client sends for a feed row (persisted, hash-identified in production; shown here as text for clarity):
query MobileFeed($cursor: String) {
feed(cursor: $cursor, limit: 20) {
edges {
node {
id
text
createdAt
likeCount
author { id name avatarThumbUrl }
media { thumbnailUrl }
}
}
pageInfo { endCursor hasNextPage }
}
}
Response for one edge:
{
"id": "post_9182",
"text": "Shipped the new onboarding flow today",
"createdAt": "2026-07-18T14:02:00Z",
"likeCount": 214,
"author": { "id": "u_4471", "name": "Priya Shah", "avatarThumbUrl": "https://cdn.example.com/avatars/u_4471_thumb.jpg" },
"media": [{ "thumbnailUrl": "https://cdn.example.com/media/m_1_thumb.jpg" }]
}
The web client, on the same schema, asks a different query for the same node and legitimately gets bio, counts, and full-resolution media because its screen renders them; no server-side branching by client type, no separate mobile endpoint to maintain.
Trade-offs and pitfalls
- GraphQL's caching story is genuinely worse than REST's out of the box (an arbitrary query has no stable URL); persisted queries recover most of it by giving each allowed shape a stable, cacheable identifier, but that is an extra piece of infrastructure to build and operate, not a free win.
- The classic GraphQL trap is the N+1 resolver problem: naively resolving
authorper feed item issues one database call per post instead of one batched call for all authors in the page. This needs a batching layer (a per-request data loader that collects author IDs across the whole response and issues one query) or the fix does not show up until load testing. - Over-embedding (putting the full author profile in every feed item) reproduces the original complaint under a new protocol; under-embedding forces one extra round trip per screen, which is worse than a slightly larger response on a high-latency mobile network. The embed-vs-reference line should be drawn by "does this screen render it unconditionally," not by what's convenient to fetch.
- A REST sparse-fieldset compromise is a legitimate answer for a team not ready to operate a GraphQL server; naming it as the deliberately-rejected alternative (and why the full field-selection model wins here specifically because mobile and web diverge so much) is what separates a considered answer from a technology-preference answer.
Describe how you would design API pagination and sync endpoints for a mobile app that must support partial offline sync. The endpoints should let the client reconcile local mutations with server state and fetch only deltas since the last sync point. Provide the high-level request/response contract and how you would surface conflicts to the caller.
Sample Answer
Direct answer
Split the contract into two endpoints threaded together by one opaque sync token: a push endpoint that accepts the client's local mutations tagged with the server version they were based on (so the server can detect conflicts), and a paginated pull endpoint that returns only the deltas since that token plus a new token to resume from. The client always pushes before it pulls, so its own pending changes are reflected in the server state it is about to reconcile against.
Contract shape
Push (client to server), sends local mutations:
POST /sync/push
{
"clientId": "device-abc",
"baseSyncToken": "tkn-123",
"mutations": [
{"localId": "c1", "type": "update", "resource": "note", "id": "srv-45", "baseVersion": 77, "payload": {"title": "New title"}}
]
}
Push response, tells the client what happened to each mutation:
{
"applied": [
{"localId": "c1", "serverId": "srv-45", "status": "applied", "serverVersion": 78}
],
"conflicts": [],
"newSyncToken": "tkn-124"
}
Pull (server to client), paginated deltas since the token:
GET /sync/pull?since=tkn-124&pageToken=null
{
"items": [
{"serverId": "srv-46", "resource": "note", "op": "upsert", "payload": {"title": "Meeting notes"}, "version": 12}
],
"nextPageToken": null,
"newSyncToken": "tkn-125"
}
Conflict signaling
Every mutation in the push request carries baseVersion, the server version the client last saw for that resource. The server compares it to the resource's current version before applying:
| Strategy | When to use | What the client sees |
|---|---|---|
| Reject and surface the conflict | Data loss risk is high (financial fields, anything a human should review) | {"localId": "c2", "reason": "version_mismatch", "serverState": {...}} in the conflicts array; client shows the current server value alongside the pending local change |
| Last-writer-wins by timestamp | Low-stakes fields where losing a rare concurrent edit is acceptable | The mutation applies silently; client sees status: "applied" even though its base version was stale |
| Field-level merge | Structured objects where two edits touch different fields | Server merges non-overlapping fields and returns the merged serverVersion; only overlapping-field conflicts surface |
Whichever strategy is chosen, baseVersion is what makes the push idempotent and safe to retry after a network drop: replaying the same push twice against an already-applied localId returns the same applied result rather than double-applying it.
Worked example
sequenceDiagram
participant C as Mobile client
participant S as Sync API
C->>S: POST /sync/push {baseSyncToken, mutations}
S-->>C: {applied, conflicts, newSyncToken}
C->>S: GET /sync/pull?since=newSyncToken&pageToken=null
S-->>C: {items, nextPageToken=abc, newSyncToken}
C->>S: GET /sync/pull?since=newSyncToken&pageToken=abc
S-->>C: {items, nextPageToken=null, newSyncToken}
Note over C: pull loop ends when nextPageToken is absent
Tracing the token through the exchange above: the push response's newSyncToken (tkn-124) becomes the since value on the first pull; each pull response echoes back the same newSyncToken (it only advances once a full pull pass completes) until nextPageToken comes back absent, which is the client's signal to stop paging and consider itself caught up as of that token.
Trade-offs and pitfalls
Deletes need a tombstone record (a marker saying "this resource was removed," not just its absence) so a client pulling deltas can distinguish "never existed" from "existed then got deleted." Tombstones cannot be kept forever: they need a retention window and a background cleanup pass that garbage-collects (permanently purges) tombstones older than the window, after which a client that reconnects past that window can no longer compute a delta and must fall back to a full resync instead of a partial pull.
A client that reconnects after a very long offline period is the sharpest edge case: if its baseSyncToken predates the server's retained history, the pull endpoint must detect that explicitly (rather than silently returning an incomplete delta) and tell the client to discard local state and re-fetch a full snapshot.
Monotonic version numbers per resource are enough for the common single-writer-per-record case. True multi-device, multi-writer scenarios (the same resource edited concurrently from two devices before either has synced) need richer causality tracking than a single version number can express; that machinery belongs to your consistency model, not this contract, so treat it as a known limitation to flag rather than something to solve inside the sync endpoints themselves.
You manage a public ingestion API used by external partners. Propose an API versioning and deprecation strategy that minimizes breaking changes while allowing the payload schema to evolve, including how you would communicate changes and roll out deprecations safely.
Sample Answer
Direct answer
Version the payload schema so that most evolution never requires a new API version at all: additive, optional-field changes ship into the existing version, and only a genuinely breaking change (removing or renaming a field, changing a type, changing meaning) earns a new major version. Communicate and execute deprecation through machine-readable signals, not just documentation and email, so that automated partner integrations, not just the humans who read the changelog, find out a version is going away and when.
Structured elaboration
Classifying changes so most of them don't need a version bump:
| Change | Breaking? | Why |
|---|---|---|
| Add an optional field | No | Existing clients ignore fields they don't recognize (the tolerant-reader pattern) |
| Add a new enum value | Usually no, if clients are told to treat unknown values as a documented default | Existing clients that switch on known values still work |
| Remove or rename a field | Yes | Existing clients that read it break |
| Change a field's type or unit | Yes | Existing clients that parse it break silently, often worse than an error |
| Change existing validation to be stricter | Yes | Previously-valid payloads start being rejected |
Rollout stages for a genuinely breaking change:
- Preview. The new major version is available opt-in (a new URI path or an explicit request header) so partners can test against it before it is the default.
- Dual-run. Both versions are served in production for a defined overlap window; usage of the old version is measured per partner so the team knows who still needs to migrate, not just that traffic to it is declining in aggregate.
- Deprecation announced. The still-serving old version starts returning a
Deprecationheader on every response (standardized in RFC 9745, March 2025, on the IETF Standards Track) carrying the date deprecation took effect, plus aSunsetheader (RFC 8594, Informational status) carrying the exact date the version will stop serving entirely. TheDeprecationheader's Standards Track status is actually the stronger of the two. Both are machine-readable, so a partner's own monitoring can alert on them without a human reading a changelog. - Sunset. After the
Sunsetdate passes, the old version stops serving.
410 versus 404 after sunset, the definitional point: once a version is actually sunset, the correct response is 410 Gone, not 404 Not Found. 404 means "nothing is here," which is ambiguous to a caller debugging a broken integration, it could be a typo in the URL just as easily as a real removal. 410 says explicitly "this used to exist, on purpose, and it is not coming back," which is exactly the information a caller needs to know it must migrate rather than fix a typo. The 410 response body should still explain what happened and where to go next.
Worked example
While the old version is deprecated but still serving:
HTTP/1.1 200 OK
Deprecation: Wed, 01 Jul 2026 00:00:00 GMT
Sunset: Thu, 31 Dec 2026 23:59:59 GMT
Link: <https://api.example.com/v2/ingest>; rel="successor-version"
After the sunset date has passed:
HTTP/1.1 410 Gone
Content-Type: application/json
{
"error": {
"code": "endpoint_sunset",
"message": "API v1 was sunset on 2026-12-31. Migrate to /v2/ingest; see the migration guide linked in this response.",
"request_id": "req_9f21"
}
}
The dates in the headers and the body agree, so a partner's monitoring, its on-call engineer reading a log line, and its API client's own error message all tell the same story.
Trade-offs and pitfalls
- Relying only on a changelog and email is the most common failure mode; automated partner integrations do not read email, and by the time a human notices the deprecation notice it may already be close to the sunset date. Machine-readable headers close that gap.
- Returning
404for a sunset endpoint (instead of410) is a small-looking choice with a real cost: it makes "this API version is gone on purpose" indistinguishable from "you mistyped the URL," which slows down every partner's own debugging. - Dual-running two versions is real, ongoing engineering cost (two schemas, two sets of compatibility tests, two things that can each break), not a one-time expense; the overlap window needs a firm end date from the start, or "temporary" dual-running quietly becomes permanent.
- A subtler pitfall: bumping the major version for a change that could have been additive (for example, renaming a field instead of adding a new one alongside the old, deprecated one) creates breaking-change churn that erodes partner trust in the version number actually meaning something.
Design API contracts for two endpoints: an online, single-request inference call, and an asynchronous batch prediction job. Specify the request/response shapes, error handling, the idempotency guarantees each one offers, and how a client should poll for or otherwise receive the batch job's results.
Sample Answer
Direct answer
The two endpoints need genuinely different contracts because they fail differently. Sync inference has to answer inside the caller's request timeout, so its idempotency concern is narrow: protect against the caller re-sending a request when it can't tell whether the first one actually landed. Batch prediction runs long enough that the caller cannot hold a connection open for it, so the contract has to hand back a durable job handle immediately and give the caller a way to observe progress without blocking, and its idempotency concern is broader: protect against accidentally launching the same expensive job twice.
Structured elaboration
Endpoint 1: online single-request inference (synchronous)
POST /v1/models/{model_id}/infer
- Headers:
Authorization: Bearer <token>, optionalIdempotency-Key,Content-Type: application/json. - The model is a pure function of its pinned version and input, so the computation is naturally idempotent; the
Idempotency-Keyexists purely to protect against duplicate execution when the caller retries after a timeout and can't tell if the first call succeeded. Server storeskey -> responsefor a bounded window (documented, e.g., 24 hours) and replays the same response on a repeat with the same key and payload; a repeat with the same key but a different payload is a client error.
Endpoint 2: asynchronous batch prediction
POST /v1/models/{model_id}/batch-predict returns a job handle immediately (202 Accepted), never the result inline.
- Idempotency here is about job creation, not the underlying computation: if the caller retries the submit call (because the first response was lost, not because the job failed), the server must recognize the same
Idempotency-Keyand return the existingjob_idrather than starting a second, redundant, possibly expensive job. - Job status is observed with
GET /v1/jobs/{job_id}, a plain state read, not a mutation, so it needs no idempotency key at all; polling it repeatedly is always safe by construction. - Result delivery: the caller either polls the status endpoint until it reaches a terminal state, or supplies a webhook URL at submission time and the server pushes the terminal status once, with retries on delivery failure.
Error taxonomy shared by both endpoints:
| Status | Meaning | Retry advice to the caller |
|---|---|---|
| 400 | Request failed schema validation (with field-level detail) | Fix the request, do not retry as-is |
| 401 / 403 | Missing or insufficient auth | Fix credentials, do not retry as-is |
| 404 | Model or job id does not exist | Do not retry |
| 409 | Idempotency-Key reused with a different payload | Fix the client bug, do not retry as-is |
| 422 | Request is well-formed but semantically invalid for this model (e.g., wrong feature count) | Fix the request, do not retry as-is |
| 429 | Rate limit exceeded | Retry after the documented wait, honoring the standard Retry-After header |
| 500 / 503 | Transient server-side failure | Safe to retry with backoff, same Idempotency-Key |
Worked example
Sync inference request and response:
// POST /v1/models/churn-classifier/infer
{
"model_version": "2026-05-01",
"input": { "tenure_months": 14, "monthly_spend_cents": 3499, "support_tickets_90d": 2 }
}
// 200 OK
{
"request_id": "req_a1f9",
"model_version": "2026-05-01",
"predictions": [{ "label": "churn", "score": 0.31 }]
}
Batch job submission, status, and completion, shown as a sequence so the polling contract is explicit:
sequenceDiagram
participant C as Client
participant A as API
C->>A: POST /batch-predict (Idempotency-Key: b-7741)
A-->>C: 202 Accepted, job_id=job_5820, status=queued
loop poll every backoff interval
C->>A: GET /jobs/job_5820
A-->>C: 200, status=running, progress=40
end
C->>A: GET /jobs/job_5820
A-->>C: 200, status=succeeded, result.output_location
// 202 Accepted (submit)
{ "job_id": "job_5820", "status": "queued", "submitted_at": "2026-07-18T15:00:00Z" }
// GET /jobs/job_5820 while running
{ "job_id": "job_5820", "status": "running", "progress": 40 }
// GET /jobs/job_5820 once finished
{
"job_id": "job_5820",
"status": "succeeded",
"completed_at": "2026-07-18T15:04:00Z",
"result": { "output_location": { "type": "s3", "uri": "s3://predictions/job_5820/" } }
}
A caller that supplied notify_webhook at submission time receives one POST of the same final body once the job reaches succeeded or failed, with retries on delivery failure, so it does not need to poll at all.
Trade-offs and pitfalls
- Retrying the sync endpoint blindly on every 5xx without an
Idempotency-Keyrisks running the (cheap but not free) inference twice; retrying the batch submit endpoint blindly without one risks launching a genuinely expensive duplicate job. The stakes differ enough that batch submission should treat the key as effectively mandatory, not optional. - Polling too aggressively on a long batch job wastes both client and server resources; the contract should hand the client a documented backoff hint (a growing poll interval) rather than leaving the client to guess, and the webhook path should be presented as the preferred option for anything longer than a few status checks.
- A common design mistake is putting the batch input/output data inline in the request body; for anything past a small payload, the contract should take a reference to storage (as shown) rather than embed the data, since inline batch payloads hit request-size limits and make retries expensive.
- 409 on a reused idempotency key with a different payload must be a hard error, not a silent overwrite. Silently accepting a changed payload under the same key is what causes a client bug (accidentally mutating the request before a retry) to produce a confusing, hard-to-reproduce result days later.
Unlock Full Question Bank
Get access to all 35 API and Interface Design for Distributed Services interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.