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 composing several AI microservices into a single request pipeline, for example intent detection, then slot-filling, then response generation, each with its own API. Design a versioned contract for this pipeline that lets you evolve any one service's schema without forcing a coordinated redeploy of the others, and describe what the caller sees if one of the stages returns a partial or degraded result.
Sample Answer
Give each stage (intent detection, slot-filling, response generation) its own independently versioned schema and its own deployment, and compose them through a stage contract every stage implements: accept a documented input shape for its declared version, return a documented output shape tagged with the version that produced it, and be able to return a degraded result instead of erroring outright when it cannot produce a full answer. The caller-facing response aggregates each stage's status and version rather than presenting one all-or-nothing result, so upgrading slot-filling's schema never requires redeploying intent-detection or response-generation in lockstep.
Per-stage versioning
Each stage publishes its own schema version (for example intent-detector.v2), independent of the others. The orchestrator's contract with each stage is version-negotiated: it declares the version it expects, and the stage either serves that version or responds with a documented version_unsupported status the orchestrator can react to, by falling back to a default or failing just that stage.
flowchart LR
A[Caller request] --> O[Orchestrator]
O -->|intent-detector.v2| B[Intent Detection]
O -->|slot-filler.v3| C[Slot Filling]
O -->|response-gen.v1| D[Response Generation]
B --> O
C --> O
D --> O
O --> R[Pipeline response envelope]
Schema evolution rule per stage
Within one version, changes are additive-only (new optional fields do not bump the version); a genuinely breaking change to one stage's input or output bumps only that stage's version. Because the orchestrator negotiates version per stage independently, slot-filling can move from v2 to v3 on its own release schedule while intent-detection stays on v2 and response-generation stays on v1, neither of the other two needs a coordinated redeploy.
The response envelope: what the caller sees on a degraded stage
This is the part of the design that most directly answers what the caller sees:
status:success(every stage returned a complete result),partial(at least one stage returned a lower-confidence or fallback result but the pipeline still produced an answer), orfailed(a required stage could not produce any usable result).- Each stage's result is tagged with its own
versionand adegradedboolean, so the caller can tell not just that something degraded, but which stage, and under which schema version, which matters for tracing a regression back to a specific stage's rollout. - A degraded stage returns a documented fallback shape instead of erroring: for response-generation, a clarifying question instead of a personalized reply; for slot-filling, the slots it did manage to resolve, with unresolved slots explicitly
nullrather than omitted, so the caller can tell "we don't have your departure city" apart from "we didn't attempt to resolve departure city."
Worked example
Pipeline response when slot-filling degrades to only partially resolving slots:
{
"status": "partial",
"traceId": "trace_88f2",
"intent": { "version": "intent-detector.v2", "degraded": false, "name": "book_flight", "confidence": 0.92 },
"slots": { "version": "slot-filler.v3", "degraded": true, "resolved": { "departure": "SFO", "arrival": null } },
"response": { "version": "response-gen.v1", "degraded": true, "text": "I have your departure as SFO, what's the arrival city?" }
}
A caller reading this envelope can see specifically that slot-filling is the degraded stage, not response-generation, even though response-generation's output also changed as a consequence, and can decide whether to retry that stage, show the clarifying question as-is, or escalate to a human agent, without knowing anything about why slot-filling degraded internally.
Trade-offs and pitfalls
Per-stage independent versioning adds real coordination overhead: the orchestrator has to know which version combinations are actually validated together, since v2 intent-detector paired with v3 slot-filler might never have been tested against v1 response-generation, so a compatibility matrix or a contract-test suite across stage-version combinations is not optional, it is the real cost of buying independent deploys. A common wrong turn is designing the envelope so a degraded stage simply omits its field instead of returning an explicit degraded marker: an omitted field is indistinguishable from "this stage does not exist in this pipeline version" to a client, whereas an explicit flag is unambiguous. Scope note: this design covers the contract and versioning boundary between stages; deciding when to mark a stage degraded in the first place, timeout policy, retry budget, circuit-breaker state, is a reliability-engineering decision that sits outside the interface contract itself and is not something this answer prescribes.
Design an API contract for a prediction service consumed by multiple client services across regions. Include endpoints, sample request/response schemas, your authentication and authorization approach, versioning strategy, error codes, and backward compatibility considerations.
Sample Answer
Direct answer
Design this as a small, versioned, resource-oriented contract: one endpoint for synchronous scoring, one for asynchronous batch scoring, and one for model metadata, each with an explicit JSON schema, a URL-based major version, bearer-token authentication scoped by tenant, and a structured error body so every client in every region gets the same shape whether the request succeeds or fails. The goal is to promise the client just enough that the model behind the endpoint can change without the promise changing.
Framework
Endpoints
| Method & path | Purpose |
|---|---|
POST /v1/models/{model_id}/score | Synchronous prediction for one request |
POST /v1/models/{model_id}/batch-jobs | Start an asynchronous batch scoring job, returns a job id |
GET /v1/batch-jobs/{job_id} | Poll batch job status and results |
GET /v1/models/{model_id} | Model metadata: current version, input/output schema |
Sample request/response
POST /v1/models/reco-v2/score
{
"request_id": "b6b8f8f0-6e2b-4a35-9b2e-6b6a2b6e2b6a",
"features": {
"user_id": "u_123",
"country": "US",
"candidate_items": ["A", "B", "C"]
},
"options": { "top_k": 2 }
}
200 OK
{
"request_id": "b6b8f8f0-6e2b-4a35-9b2e-6b6a2b6e2b6a",
"model_version": "2026-05-15",
"predictions": [
{ "item_id": "B", "score": 0.92 },
{ "item_id": "A", "score": 0.77 }
]
}
Authentication and authorization
- Bearer tokens: JSON Web Tokens (JWT), issued by a central identity service, carrying a tenant_id claim and scopes such as
predict:readandpredict:batch. - Authorization: role-based access control (RBAC). The gateway checks the token's scopes against the endpoint being called, and the tenant_id claim against the model's owning tenant, before forwarding the request.
- Transport: mutual Transport Layer Security (mTLS) between regional callers and the gateway, so both sides authenticate each other at the connection level, in addition to the per-request bearer token.
- Tokens are short-lived and refreshed through an OAuth 2.0 client-credentials flow (a machine-to-machine token exchange where the calling service, not a human user, proves its own identity to obtain a fresh token), so a leaked token has a bounded blast radius.
Versioning strategy
- The major version lives in the URL (
/v1/) because it is the version of the contract shape, what fields exist and what they mean, not the version of the model. The model's own version is a separate response field (model_version), since a model can change on its own schedule while the contract stays stable for months. - Minor, backward-compatible changes (new optional fields) ship without a version bump.
- A breaking change to the contract shape gets a new major version, and the old version is marked deprecated once the new one is stable.
Error codes
| Status | Meaning here | Retryable |
|---|---|---|
| 400 Bad Request | Malformed JSON, or a required top-level field is missing | No |
| 401 Unauthorized | Missing or invalid bearer token | No |
| 403 Forbidden | Token is valid, but its tenant or scope does not match the model | No |
| 404 Not Found | Unknown model_id or job_id | No |
| 422 Unprocessable Entity | Well-formed JSON, but a feature value fails semantic validation | No |
| 429 Too Many Requests | Caller exceeded its documented quota; response includes a Retry-After header | Yes, after the given delay |
| 503 Service Unavailable | Model temporarily unavailable, for example during a deploy | Yes |
{
"error_code": "MISSING_FEATURE",
"message": "features.user_id is required",
"request_id": "b6b8f8f0-6e2b-4a35-9b2e-6b6a2b6e2b6a",
"retryable": false
}
Quota is communicated, not enforced, at this layer: each response carries X-RateLimit-Limit and X-RateLimit-Remaining headers (a widely used convention, though not from a single ratified standard), and a caller that exceeds its quota gets 429 with a Retry-After value telling it how long to wait. Which limiting algorithm sits behind that response is an implementation detail of the service, not part of the contract a client codes against.
Backward compatibility
- Additive only within a major version: new optional request fields, new optional response fields. Clients are expected to ignore fields they do not recognize (a tolerant reader).
- A field's meaning or type is never repurposed within a version.
- An OpenAPI document (a machine-readable API description) is published per major version, so client libraries can be generated and diffed automatically against it.
Worked example
A concrete, backward-compatible evolution: version 1's response is predictions: [{item_id, score}]. A later minor release adds an optional explanation field without bumping the version:
{
"request_id": "b6b8f8f0-6e2b-4a35-9b2e-6b6a2b6e2b6a",
"model_version": "2026-06-01",
"predictions": [ { "item_id": "B", "score": 0.92 } ],
"explanation": { "method": "shap", "top_features": ["country", "recency"] }
}
Old clients that only read predictions are unaffected. New clients that know to read explanation get more detail. This is what "additive, optional field" means in practice, and it is why either side treating the field's absence as an error would be a bug, not a feature.
Trade-offs and pitfalls
- Keeping model version only in the response makes it hard for a client to pin an exact model for reproducible results. If that matters, add an optional
model_versionrequest field and return 409 Conflict if the pinned version no longer exists. - Tying authorization purely to a coarse scope like
predict:batchis simple but blunt. If a tenant later needs per-model access control, retrofitting that into the token shape is a breaking change, so it is worth reserving a model-scoped claim from the start even if it is unused initially. - A common pitfall is treating an async batch job as "the same request, just later." Batch has different failure semantics, partial success across many rows, that a single success/failure flag cannot represent, so the job-status endpoint needs its own richer schema with per-row outcome counts, not just a status string.
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.
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 a contract-testing approach that catches a breaking API change before it reaches production, given that the consuming clients are owned by different teams than the API itself. Explain how you would automate this in CI and how a team would find out their contract test failed.
Sample Answer
Direct answer
Use consumer-driven contract testing: each consuming team publishes the exact requests and expected responses it actually depends on, and the provider team's own continuous integration (CI) pipeline verifies the real API against every published consumer contract before a change can merge or deploy. This inverts the usual failure mode, where a consumer discovers a break after the provider has already shipped; here the provider's own pipeline fails first, and the consumer team is notified automatically through the same system that stores the contracts, not by someone noticing something broke in production.
Structured elaboration
The contract and where it lives:
- Each consumer team writes a small set of interactions ("when I call this endpoint with this request, I expect a response shaped like this") and publishes them to a shared, versioned contract registry (a broker), tagged with which environment or release they apply to.
- This is deliberately narrower than a full schema: the consumer only asserts the exact fields and shapes it actually reads, so the contract reflects real usage rather than the provider's entire response shape.
Automating verification in the provider's CI:
- On every pull request to the provider's API code, a CI step fetches the latest contracts tagged for the relevant environment, spins up (or points at a running instance of) the provider, replays each consumer's recorded requests against it, and asserts the actual responses still satisfy what each consumer expects. Any mismatch fails the build and blocks the merge.
- Before an actual deploy (not just before merge), a second gate checks whether the version about to be deployed is compatible with whichever consumer versions are currently running in production, not just the newest consumer contract, since a provider change can be compatible with a consumer's latest contract while still breaking a consumer instance that hasn't picked up its own latest release yet.
How the affected team finds out:
- The contract broker's webhook posts directly to the consumer team's own channel (chat integration or issue tracker) whenever a provider verification against their specific contract fails, naming the exact interaction that broke and linking to a diff between what was expected and what the provider now returns. The team learns about the break from an automated, targeted message tied to their own contract, not from a shared build dashboard they'd have to be watching.
Worked example
A consumer's published contract (one interaction, in a contract-broker style format):
{
"consumer": { "name": "checkout-web" },
"provider": { "name": "orders-api" },
"interactions": [
{
"description": "fetching an order by id",
"request": { "method": "GET", "path": "/orders/500" },
"response": {
"status": 200,
"body": { "id": "500", "status": "PAID", "total_cents": 4200 }
}
}
]
}
Provider CI step (illustrative, tool-agnostic pseudocode) that fails the build on a mismatch:
verify-contracts:
script:
- fetch-contracts --provider orders-api --tag production
- contract-verify --provider-base-url http://localhost:8080 --contracts ./contracts/*.json
# non-zero exit code on any interaction mismatch blocks the merge
Suppose a developer on the provider team renames total_cents to totalCents in a refactor. The verification step replays the recorded request, gets back a body missing the field the consumer's contract asserted, and the build fails with a message like: "interaction 'fetching an order by id' failed: expected field total_cents, field not present in actual response." The broker then posts that same message, with a link to the failing interaction, straight to the checkout-web team's channel, so they know about the incompatibility before it ever reaches a shared environment.
Trade-offs and pitfalls
- Contract testing only catches what a consumer actually asserted. If a consumer's published contract never checked the
total_centsfield in the first place, removing it silently passes; the technique is only as good as how faithfully each contract reflects real usage, which puts real responsibility on consumer teams to keep their contracts current as their own code changes. - Verifying against the latest contract at merge time is necessary but not sufficient; gating the actual deploy against what is compatible with consumer versions currently running in production (not just their newest published contract) is what catches the case where two independently-safe changes combine badly because of deploy ordering.
- This approach is faster and cheaper than full end-to-end integration testing, but it is not a replacement for it: contract tests verify shape and basic behavior, not real-world concerns like load, timing, or business-logic correctness across a full user flow.
- A pitfall on the process side: if publishing and updating contracts is treated as optional or bolted on late, teams tend to let contracts drift stale, at which point the safety net silently degrades and nobody notices until a real break gets through anyway.
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.