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.
You are seeing intermittent duplicates and missing items in a paginated transaction list shown to clients, and the backend has concurrent writes. Describe a troubleshooting plan: which logs, traces, and client telemetry you would collect; synthetic tests to reproduce it; short-term mitigations you could ship quickly; and the long-term fix.
Sample Answer
Direct answer
Intermittent duplicates and missing rows in a paginated list under concurrent writes are almost always a symptom of a pagination contract that counts position (offset) rather than anchoring to a specific row's identity, reading a list that keeps moving underneath it. The fix path is: collect telemetry that lets you correlate a client's exact requests against what changed on the backend, reproduce it deterministically with a synthetic test rather than chasing it live, ship a contained mitigation, then replace the contract itself.
Telemetry to collect
- Per-request: the exact pagination parameters used (cursor or offset, limit), a request ID, and the item IDs actually returned, logged on both client and server so the two logs can be joined.
- Per-write: a monotonic write sequence number or commit timestamp for every insert, update, or delete against the transaction table, so you can reconstruct exactly which writes landed between two page fetches.
- Aggregate dashboards: rate of duplicate-ID and gap incidents (a page that skips an ID present in a request one page earlier) bucketed by client, endpoint, and page size, so you can tell whether the rate correlates with write volume or a specific client behavior (e.g. slow scrolling, background tab refetches).
Synthetic reproduction
The fastest way to confirm the hypothesis is a small, fully deterministic script rather than a live capture: insert a row between two page fetches and check whether the second fetch repeats or skips an item. This is directly runnable and needs no production access:
class Store:
def __init__(self, items):
self.items = items # newest first
def insert_at_head(self, item):
self.items.insert(0, item)
def page_by_offset(self, offset, limit):
return self.items[offset: offset + limit]
def page_by_cursor(self, after_id, limit):
start = 0 if after_id is None else self.items.index(after_id) + 1
return self.items[start: start + limit]
store = Store(["txn-5", "txn-4", "txn-3", "txn-2", "txn-1"])
page1 = store.page_by_offset(0, 2) # fetch page 1 before the insert
store.insert_at_head("txn-6") # concurrent write lands
page2 = store.page_by_offset(2, 2) # fetch page 2 after the insert
print("OFFSET page1:", page1)
print("OFFSET page2:", page2)
print("txn-4 in both pages:", "txn-4" in page1 and "txn-4" in page2)
print("txn-2 skipped entirely:", "txn-2" not in page1 and "txn-2" not in page2)
Running this prints OFFSET page1: ['txn-5', 'txn-4'] and OFFSET page2: ['txn-4', 'txn-3'], with both follow-up checks printing True: txn-4 appears in both pages (duplicate) and txn-2 never appears in either page (skipped entirely), reproduced with a handful of lines and no timing dependency.
Re-running the same scenario against a cursor-anchored implementation instead:
store2 = Store(["txn-5", "txn-4", "txn-3", "txn-2", "txn-1"])
page1c = store2.page_by_cursor(None, 2)
store2.insert_at_head("txn-6")
page2c = store2.page_by_cursor(page1c[-1], 2)
print("CURSOR page1:", page1c)
print("CURSOR page2:", page2c)
print("no overlap between pages:", set(page1c).isdisjoint(page2c))
This prints CURSOR page1: ['txn-5', 'txn-4'], CURSOR page2: ['txn-3', 'txn-2'], and no overlap between pages: True. This is the reproducible evidence that anchors the fix, not a guess.
Short-term mitigation vs long-term fix
| Timeframe | Action | What it buys | What it does not fix |
|---|---|---|---|
| Immediate (same day) | Shrink page size; log cursor/offset plus returned IDs on every request | Smaller inconsistency window, faster correlation when a user reports it | Root cause is untouched |
| Short-term (days) | Client-side de-dup by transaction ID; detect a gap and re-fetch the missing range | Masks the user-visible symptom quickly | Adds client complexity, still fragile under heavier write load |
| Long-term (weeks) | Replace offset with a cursor anchored on a deterministic key such as (commit_ts, id) | Removes the failure mode structurally, matches the pattern in the previous scenario's fix | Requires every consumer to migrate off page-number semantics |
Trade-offs and pitfalls
It is tempting to chase this as a backend consistency problem (replica lag, read quorum) rather than a pagination contract problem. If the storage layer is genuinely eventually consistent, that is worth knowing, but the API-level fix here does not require tuning consensus or replication internals: it requires the endpoint to commit to an explicit, anchored ordering contract and, if staleness is possible, to say so in the response (for example a snapshot or version marker the client can compare) so the client can detect it rather than silently rendering wrong data. Conflating "our replication is laggy" with "our pagination contract is unanchored" leads teams to spend weeks on the wrong layer.
A related pitfall: fixing this only on the read path while leaving deletes unhandled. A cursor anchored on a row that gets deleted between pages needs an explicit signal (do not silently skip past it or error opaquely) so the client knows to discard that cursor rather than retry it forever.
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.
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.
Design API endpoints and backend read models for an analytics dashboard that needs aggregated counts and top-k lists, without pushing heavy aggregation onto the client. Discuss the trade-offs between freshness, storage cost, and query complexity in how you shape those endpoints.
Sample Answer
Expose two endpoint shapes, one for time-bucketed aggregated counts and one for top-k lists, and never let the client request an ungoverned ad-hoc aggregation. Every response carries an explicit freshness field (an asOf timestamp and a precision flag of exact or approximate) so the client-visible contract, not just the internal pipeline, states what freshness the caller is actually getting; the backend may route a request to a fast precomputed view or a slower exact path, but that routing choice is invisible to the caller except through this field.
Endpoints
GET /metrics/counts?metric=events&start=...&end=...&granularity=hour&dim=region: a time series of pre-aggregated buckets.GET /metrics/top?metric=clicks&k=10&start=...&end=...&dim=category: a ranked top-k list.- Both accept a
freshnessquery parameter as a request-side contract:freshness=fast(accept approximate or slightly stale data, get the lowest latency) versusfreshness=exact(route to an exact recompute, higher latency, and the contract documents a range cap or async fallback rather than letting the request hang indefinitely for a huge range).
The staleness contract, in the response itself
Every response includes asOf (the timestamp through which data is complete) and precision. This is the part of the design that belongs squarely to an API-contract discussion: it turns an internal trade-off (how fresh is the backing view) into an explicit, documented, client-visible field, so a caller building a dashboard can show an "as of 2 minutes ago" badge instead of silently trusting a number that might be stale.
| Client-visible option | What the caller gets | What it costs to offer |
|---|---|---|
freshness=fast (default) | Sub-second response, precision: "approximate" for top-k, asOf typically within the last minute | Requires precomputed rollups for common ranges; the contract must cap which dim combinations are supported, since only precomputed ones can be fast |
freshness=exact | Exact counts, precision: "exact", asOf reflects true request time | Higher, less predictable latency; the contract caps the allowed date range for this mode and documents a slower service-level agreement (SLA: a documented commitment about a specific response characteristic, here latency), so callers don't assume it is always fast |
| Arbitrary ad-hoc dimension or filter | Maximum flexibility | Not offered directly: the contract restricts dim to an enumerated, indexed set and returns a documented 400 Bad Request for an unsupported dimension, rather than silently running an expensive query |
Bounding and shaping the response
k is capped server-side (for example, a maximum of 100) regardless of what the client requests, and the response documents the cap via requestedK and returnedK, so a client cannot silently receive a truncated list without knowing it was truncated. The response is already the final shape the dashboard renders, bucketed counts or a ranked list; the client never receives raw event rows and aggregates them itself. That is the same overfetch-avoidance principle as any other read-heavy endpoint: the API promises a specific, small, pre-shaped payload, not a firehose the client has to post-process.
Worked example
GET /metrics/counts?metric=events&start=2026-07-18T00:00Z&end=2026-07-18T03:00Z&granularity=hour&freshness=fast
{
"metric": "events",
"granularity": "hour",
"asOf": "2026-07-18T03:00:42Z",
"precision": "approximate",
"buckets": [
{ "start": "2026-07-18T00:00Z", "count": 48210 },
{ "start": "2026-07-18T01:00Z", "count": 51330 },
{ "start": "2026-07-18T02:00Z", "count": 49980 }
]
}
GET /metrics/top?metric=clicks&k=5&start=2026-07-18T00:00Z&end=2026-07-18T03:00Z&dim=category&freshness=fast
{
"metric": "clicks",
"asOf": "2026-07-18T03:00:42Z",
"precision": "approximate",
"requestedK": 5,
"returnedK": 5,
"items": [
{ "key": "footwear", "count": 9120 },
{ "key": "outerwear", "count": 7040 },
{ "key": "accessories", "count": 5210 },
{ "key": "electronics", "count": 4880 },
{ "key": "home", "count": 3990 }
]
}
Trade-offs and pitfalls
The biggest interview-relevant trade-off is that offering freshness=exact at all is a contract commitment: once a caller can request it, some caller eventually will, on a huge date range, and the API needs a documented, bounded answer (a hard range cap, a queued and pollable async job, or an explicit rejection) rather than an unbounded query that degrades the whole service. A common wrong turn is exposing a single endpoint that "just returns the data" with no freshness or precision field, leaving the client to guess whether a number is authoritative; once a dashboard has shown a number without a staleness caveat, a later "actually that was approximate" correction reads as the API being wrong, when the real defect was an underspecified contract. Enumerating allowed dim values, rather than accepting any column name, trades flexibility for the ability to document, cap, and index every supported query shape; a genuinely open-ended analytics need should be pointed at a dedicated data-warehouse query interface, not bolted onto this API.
Two clients read the same resource through your API, both submit an update, and the second write silently overwrites the first client's change without either client finding out. Design a request/response contract that prevents this kind of lost update, and walk through what the client sees when its update is rejected because the resource changed underneath it.
Sample Answer
Direct answer
Make every write conditional on the version of the resource the client actually read. The server attaches an ETag (entity tag: an opaque fingerprint that changes whenever the resource changes) to every representation it returns; the client must echo that value back in an If-Match request header on its update. If the resource changed since the client's read, the current ETag no longer matches, and the server rejects the write with 412 Precondition Failed instead of silently overwriting, so the client finds out immediately instead of losing the first writer's change.
Contract
GET /orders/42returns200 OKwith headerETag: "5"and the resource body.PUT /orders/42must include headerIf-Match: "5". If the resource's current version is still5, the server applies the write and returns200 OKwith the newETag: "6".- If someone else already wrote first (current version is now
6, not5), the server returns412 Precondition Failedand does not apply the write at all. - If the client omits
If-Matchentirely on an endpoint that requires it, return428 Precondition Requiredrather than allowing an unconditional overwrite by default. This closes the gap where a client that never learned about conditional writes would otherwise clobber silently, which is the exact bug this contract exists to prevent.
What the client sees on a rejected write
HTTP/1.1 412 Precondition Failed
Content-Type: application/json
{
"error": "precondition_failed",
"message": "Resource has changed since you last read it.",
"currentETag": "6",
"currentValue": {"orderId": "42", "status": "shipped", "quantity": 3}
}
The client now has everything it needs to recover on its own: reload the current value, decide whether to merge its pending change into it or discard it, and retry the write with the fresh If-Match: "6".
Worked example
sequenceDiagram
participant C as Client
participant A as API
participant D as Database
C->>A: GET /orders/42
A->>D: read order 42
D-->>A: value=v1, version=5
A-->>C: 200 OK, ETag: "5"
C->>A: PUT /orders/42 (If-Match: "5")
A->>D: compare-and-swap on version 5
D-->>A: mismatch (version now 6)
A-->>C: 412 Precondition Failed
Trace it through concretely: Client A reads at ETag: "5". Before Client A writes, Client B also read at ETag: "5" and successfully wrote, moving the server to ETag: "6". When Client A's PUT arrives with If-Match: "5", the server's compare-and-swap against the current version 6 fails, so Client A gets 412 Precondition Failed with the current state in the body, exactly the outcome that prevents its write from silently erasing Client B's change.
Trade-offs and pitfalls
ETag and If-Match are HTTP-native, so they interoperate for free with generic HTTP caches, CDNs, and client libraries that already understand conditional requests, unlike a bespoke version field buried only in the JSON body. A weak ETag, written as W/"5", signals "semantically equivalent," and is comparable with looser equality rules; a strong ETag (no W/ prefix) signals byte-for-byte identical representations. Pick weak ETags for most application-level version checks since exact byte identity is rarely what you actually need.
The sharpest pitfall is implementing the check and the write as two separate application-code steps (read current version, compare, then write) without an atomic compare-and-swap at the storage layer: that reintroduces a race window between the check and the write, which silently recreates the exact lost-update bug this pattern is meant to eliminate. The comparison and the write must be one atomic operation, typically a conditional update expression the database itself evaluates.
Optimistic concurrency control (detecting conflicts at write time rather than locking on read) works well for low-contention resources. Under heavy contention on the same resource, clients retrying after repeated 412 responses can thrash; that is a signal to consider a different concurrency strategy for that specific hot resource, not evidence that the ETag contract itself is wrong.
Unlock Full Question Bank
Get access to all 34 API and Interface Design for Distributed Services interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.