API design
Designing an API that survives retries, concurrent edits and years of change: status codes, offset against cursor pagination, idempotency keys, ETags, errors and a breaking-change checker, with REST compared to gRPC and GraphQL.
ConceptCore33 min readUpdated
- 4 API designs
- 9 code samples
- 7 interviewer follow-ups
- 5 self-checks
On this page14 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews
- Choose methods and status codes by what they promise under retry, and model slow work, actions and batches explicitly.
- Explain why offset pagination drifts and gets slower with depth, and implement cursor pagination.
- Make an unsafe operation idempotent with a client-supplied key, and say why the key must reach the downstream effect.
- Prevent lost updates with ETags and conditional requests.
- Classify a change to a request or a response as breaking or not, and plan an evolution and a deprecation.
8 code samples (330 lines), collapsed so the explanation stays in focus.
In a design round the API is the first concrete thing you write down, and it is where experience shows. A junior answer lists endpoints. A senior answer also says what happens when the client retries a payment, when two people edit the same record, when the list changes while someone is paging through it, and when a field has to change after ten thousand clients depend on it. Those four questions are this lesson: idempotency, concurrency, pagination and evolution. Resources, methods and status codes come first, briefly, because the rest builds on them. The claims about behaviour (drift, double charges, lost updates, breaking changes) are checked by small simulations.
Model the nouns (orders, payments, users) and the relationships between them, and let the HTTP methods carry the verbs. The methods differ in two properties that matter under failure. A method is safe if it does not change state, and idempotent if doing it twice has the same effect as doing it once. Clients, proxies and load balancers retry idempotent requests on their own, and they must not retry the others.
| Method | Use | Safe | Idempotent |
|---|---|---|---|
GET | Read a resource or a collection | Yes | Yes |
PUT | Replace a resource whole, or create it at an id the client chose | No | Yes |
PATCH | Change some fields | No | Depends on the patch: "set status to paid" is, "add 5 to the balance" is not |
DELETE | Remove a resource | No | Yes: the second call finds nothing left to remove |
POST | Create under a collection (the server chooses the id), or run an action | No | No, so it needs an idempotency key |
Conventions that save arguments later:
- Names. Plural nouns for collections (
/orders),/orders/{id}for an item, shallow nesting (/users/{id}/orders, not four levels). Ids are opaque strings. Sequential integers leak your volume and invite enumeration. - Queries. Filtering, sorting and field selection go in the query string:
?status=paid&sort=-created_at&fields=id,total. - Actions that are not create, read, update or delete get an explicit name, such as
POST /orders/{id}/cancel, and not a twistedPATCH. - Slow work returns
202 Acceptedand a resource to poll (/operations/{id}) or a webhook. A client must never hold a connection open for minutes. - Batches need an explicit rule for partial failure: all or nothing, or a result for each item.
- Representations. Dates are ISO 8601 in UTC. Money is an integer in minor units plus a currency code, never a float.
| Status | Meaning | Remember |
|---|---|---|
| 200, 201, 202, 204 | OK, created (with a Location), accepted for later, no content | Say which of 200 or 204 a DELETE returns, and keep it |
| 304 | Not modified | The answer to a conditional GET with a matching ETag |
| 400, 422 | Malformed request, and well-formed but invalid | 422 is also the answer to an idempotency key reused with a different body |
| 401, 403 | Not authenticated, not allowed | Answer 404 instead of 403 when the existence of the thing is itself secret |
| 404, 409 | Not found, and in conflict with the current state (a duplicate, a wrong state) | |
| 412, 428 | Precondition failed, and precondition required | The If-Match case, below |
| 429 | Too many requests | Send Retry-After (see rate limiting) |
| 500, 503 | Server error, unavailable | Retryable, with backoff and Retry-After |
A list endpoint that returns everything is a time bomb, so every collection is paginated from day one. There are two ways. Offset pagination (?offset=40&limit=20) is simple and lets a client jump to page 7, but it names a count of rows to skip. That count drifts when the data changes underneath it, and the database has to walk past every skipped row, so page 50,000 costs 50,000 times what page 1 costs. Cursor or keyset pagination names a position in the order: "the 20 items after this one". The cursor carries the sort key of the last item delivered, an index lookup finds that place in logarithmic time wherever it is, and changes elsewhere in the list cannot move it.
SELECT id, created_at, title
FROM posts
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 21; -- one more than the page: the extra row says whether there is a next pageThree requirements follow. The order must be total: created_at alone has ties, so the id breaks them, and the cursor holds both. An index on the same columns in the same order must exist, or the query scans. And the database must support comparing a pair of columns at once (PostgreSQL, MySQL and SQLite do), or the condition is written out as created_at < :c OR (created_at = :c AND id < :i). The sample builds a feed ordered newest first, reads it twice at 20 items a page, once by offset and once by cursor, and lets the feed change between pages.
C# · A row of a feed. The order is newest first, with the id breaking ties, so every item has…
using System;
using System.Collections.Generic;
using System.Linq;
// A row of a feed. The order is newest first, with the id breaking ties, so every item has exactly one position.
public sealed record Item(int Id, long CreatedAt);
public sealed class Feed
{
private readonly List<Item> items = new List<Item>(); // kept sorted: newest first, then highest id first
public long RowsRead; // work counter: rows a database would have to look at
public int Count => items.Count;
private static int Compare(Item a, Item b) => a.CreatedAt != b.CreatedAt ? b.CreatedAt.CompareTo(a.CreatedAt) : b.Id.CompareTo(a.Id);
public void Insert(Item item)
{
int at = items.BinarySearch(item, Comparer<Item>.Create(Compare));
items.Insert(at < 0 ? ~at : at, item);
}
public void Delete(int id) => items.RemoveAll(i => i.Id == id);
// Offset pagination: skip `offset` rows, then take `limit`. The database must walk past every skipped row.
public List<Item> Offset(int offset, int limit)
{
RowsRead += offset + limit;
return items.Skip(offset).Take(limit).ToList();
}
// Keyset pagination: continue after the last item the client saw. An index lookup finds the place in O(log n),
// whatever the depth, and the cursor names a position in the order and not a count of rows.
public List<Item> After(Item cursor, int limit)
{
int at = 0;
if (cursor != null)
{
at = items.BinarySearch(cursor, Comparer<Item>.Create(Compare));
at = at < 0 ? ~at : at + 1; // a cursor whose row is gone still has a position
}
RowsRead += (long)Math.Ceiling(Math.Log2(Math.Max(2, items.Count))) + limit;
return items.Skip(at).Take(limit).ToList();
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
Feed BuildFeed()
{
var feed = new Feed();
for (int i = 0; i < 1_000; i++) feed.Insert(new Item(i, 1_000 + i)); // 1,000 items; the newest has id 999
return feed;
}
// Read the whole feed 20 items at a time. `between` runs after each page and changes the feed, the way other users do.
List<int> ReadAll(Feed feed, bool keyset, Action<Feed, List<Item>> between)
{
var delivered = new List<int>();
Item cursor = null;
for (int page = 0; ; page++)
{
var items = keyset ? feed.After(cursor, 20) : feed.Offset(page * 20, 20);
if (items.Count == 0) return delivered;
delivered.AddRange(items.Select(i => i.Id));
cursor = items[^1];
between(feed, items);
}
}
int nextId = 1_000;
long clock = 5_000;
var removed = new HashSet<int>();
void ThreeNewItems(Feed feed, List<Item> page) { for (int n = 0; n < 3; n++) feed.Insert(new Item(nextId++, clock++)); } // other users post
void DeleteLastSeen(Feed feed, List<Item> page) { removed.Add(page[^1].Id); feed.Delete(page[^1].Id); } // an author deletes a post
int Duplicates(List<int> delivered) => delivered.Count - delivered.Distinct().Count();
int Missed(List<int> delivered) => Enumerable.Range(0, 1_000).Count(id => !delivered.Contains(id) && !removed.Contains(id)); // present all along, never delivered
// Three new items arrive before each next page.
var offsetFeed = BuildFeed();
var offsetInserts = ReadAll(offsetFeed, false, ThreeNewItems);
nextId = 1_000; clock = 5_000;
var keysetFeed = BuildFeed();
var keysetInserts = ReadAll(keysetFeed, true, ThreeNewItems);
Debug.Assert(Duplicates(offsetInserts) == 174 && Missed(offsetInserts) == 0); // every arrival pushes items down into the next page
Debug.Assert(Duplicates(keysetInserts) == 0 && Missed(keysetInserts) == 0); // the cursor does not move
Debug.Assert(offsetFeed.RowsRead == 36_600 && keysetFeed.RowsRead == 1_572); // 23 times less work for the same feed
// The last item of each page is deleted before the next one, which is also the cursor's row.
var offsetDeletes = ReadAll(BuildFeed(), false, DeleteLastSeen);
int offsetMissed = Missed(offsetDeletes);
removed.Clear();
var keysetDeletes = ReadAll(BuildFeed(), true, DeleteLastSeen);
Debug.Assert(offsetMissed == 47 && Duplicates(offsetDeletes) == 0); // every deletion pulls an item up past the offset
Debug.Assert(Missed(keysetDeletes) == 0 && Duplicates(keysetDeletes) == 0 && keysetDeletes.Count == 1_000);| Between pages | Offset pagination | Cursor pagination |
|---|---|---|
| Three new items arrive at the top (1,000 items, 20 a page) | 174 items delivered twice | 0 duplicates, 0 missed |
| The last item of each page is deleted | 47 items never delivered | 0 missed, although the cursor's own row is gone |
| Rows examined to read the whole feed | 36,600 | 1,572 |
Offset pagination broke in both directions. An arrival pushes every item down by one, so the next page repeats items the client already has, and a deletion pulls items up, so the next page starts past ones the client has never seen. Neither is rare on a live feed. The work grows with the depth: a page at offset one million examines a million rows, where the cursor examines a few dozen. Cursors have costs: no jumping to page 7, a cursor is valid for one sort order and one filter, and the client gets no total count (a count is as expensive as the scan). Design details:
- The cursor is opaque (the sort key and id, encoded), bound to the filter and the sort so a stale or forged one is rejected with a 400. Clients must not parse it, so you can change what is inside.
- Cap
limit(say 100), and returnnext_cursorandhas_more(fetch one extra row to know). Skip the total count, or offer an approximate one. - Offset is acceptable for small, mostly static collections, admin screens and anything a human pages through by number. Say so in the interview, and name the reason.
- note
- the cursor is opaque and valid for the same filter and sort. limit is capped at 100. There is no total count
- 200returns { "items": [ ... ], "next_cursor": "eyJ0Ijox...", "has_more": true }
- 400the cursor is malformed or belongs to a different filter or sort
A network offers at-least-once delivery. A request can be lost, executed and its reply lost, or executed twice by a retrying proxy, and the client cannot tell which. For GET, PUT and DELETE a retry is harmless by definition. For POST it is a double charge, a double order, two emails. The standard fix is the idempotency key: the client generates a unique value for each logical operation (a UUID) and sends the same value on every attempt, and the server makes sure that the operation takes effect once.
The server stores, under the key, a fingerprint of the request (so a key reused with a different body is detected), a state (in progress or complete) and the saved response. The cases:
- First arrival. Record the key as in progress, perform the operation, save the response, return it.
- A repeat of a completed request. Return the saved response exactly (same status and body), marked as a replay.
- A repeat while the first is still running. Answer
409, so the client waits and retries. Do not run it twice in parallel. - The same key with a different body. Answer
422: it is a client bug, and silently picking one is worse. - Expiry. Keys are kept for a window such as 24 hours, scoped to the caller, and then forgotten.
- headers
- Idempotency-Key: 6f1c2a64-9b3e-4a41-8f5d-2d0e7c1b9a10
- body
- { "account": "acct_1", "amount": 5000, "currency": "USD" }
- 201created, returns the payment. A replay of the same key returns the same response, with a header that says it was replayed
- 409the first request with this key is still running. Retry after a short delay
- 422this key was used before with a different body
The part that is easiest to get wrong is atomicity. The record of the key and the effect it protects must commit together, or the effect itself must be idempotent. If the server charges a card and crashes before it saves the key, the retry sees no record, charges again, and the key has protected nothing. When the effect lives in another system (a payment provider, a mail service), the fix is to forward the key, or one derived from it, so that the provider deduplicates too. The sample builds a payment API in front of a provider that deduplicates by key, and tries the designs with a lost reply and with a crash at the worst moment.
C# · Charge, Provider, Reply, …
using System;
using System.Collections.Generic;
public sealed record Charge(string Id, string Account, long Cents);
// A payment provider. Like real ones, it deduplicates by an idempotency key when it is given one.
public sealed class Provider
{
private readonly Dictionary<string, Charge> byKey = new Dictionary<string, Charge>();
public List<Charge> Charges { get; } = new List<Charge>();
public Charge Create(string account, long cents, string key)
{
if (key != null && byKey.TryGetValue(key, out var existing)) return existing;
var charge = new Charge("ch_" + (Charges.Count + 1), account, cents);
Charges.Add(charge);
if (key != null) byKey[key] = charge;
return charge;
}
}
public enum Reply { Created, Replayed, InProgress, KeyReuse }
// POST /payments with an Idempotency-Key header.
public sealed class PaymentApi
{
private sealed class Record { public string Fingerprint; public Charge Result; } // Result is null while the request is running
private readonly Dictionary<string, Record> records = new Dictionary<string, Record>();
private readonly Provider provider;
private readonly bool useKeys, forwardKey;
public PaymentApi(Provider provider, bool useKeys, bool forwardKey)
{
this.provider = provider;
this.useKeys = useKeys;
this.forwardKey = forwardKey; // pass the client's key on to the provider
}
// crashAfterProvider: the process dies after the provider has charged and before the result is saved.
public (Reply Reply, Charge Charge) Post(string key, string account, long cents, bool crashAfterProvider = false)
{
if (!useKeys)
{
var plain = provider.Create(account, cents, null);
if (crashAfterProvider) throw new InvalidOperationException("crash");
return (Reply.Created, plain);
}
string fingerprint = account + "|" + cents;
if (records.TryGetValue(key, out var record))
{
if (record.Fingerprint != fingerprint) return (Reply.KeyReuse, null); // the same key with a different body: a client bug
return record.Result != null ? (Reply.Replayed, record.Result) : (Reply.InProgress, null);
}
records[key] = new Record { Fingerprint = fingerprint };
var charge = provider.Create(account, cents, forwardKey ? key : null);
if (crashAfterProvider) throw new InvalidOperationException("crash");
records[key].Result = charge;
return (Reply.Created, charge);
}
// A record that never completed is stale once its lease runs out: remove it, and a retry starts again.
public void ExpireStale(string key)
{
if (records.TryGetValue(key, out var record) && record.Result == null) records.Remove(key);
}
}C# · Scenario 1: the charge succeeds, the reply is lost, and the client sends the same…
using System;
using System.Diagnostics;
// Scenario 1: the charge succeeds, the reply is lost, and the client sends the same request again.
int ChargesAfterLostReply(bool useKeys)
{
var provider = new Provider();
var api = new PaymentApi(provider, useKeys, forwardKey: true);
api.Post("order-17", "acct-1", 5_000); // charged, but the client never sees the reply
api.Post("order-17", "acct-1", 5_000); // the retry
return provider.Charges.Count;
}
Debug.Assert(ChargesAfterLostReply(false) == 2); // without a key: a double charge
Debug.Assert(ChargesAfterLostReply(true) == 1); // with a key: the retry gets the saved reply
// Scenario 2: the server dies after the provider charged and before the result was saved. The client retries once the stale record expired.
int ChargesAfterCrash(bool useKeys, bool forwardKey)
{
var provider = new Provider();
var api = new PaymentApi(provider, useKeys, forwardKey);
try { api.Post("order-18", "acct-1", 5_000, crashAfterProvider: true); } catch (InvalidOperationException) { }
api.ExpireStale("order-18"); // the lease on the stale record runs out
api.Post("order-18", "acct-1", 5_000); // the retry runs again
return provider.Charges.Count;
}
Debug.Assert(ChargesAfterCrash(useKeys: false, forwardKey: false) == 2);
Debug.Assert(ChargesAfterCrash(useKeys: true, forwardKey: false) == 2); // a key stored here is not enough: the provider charged twice
Debug.Assert(ChargesAfterCrash(useKeys: true, forwardKey: true) == 1); // forwarding the key makes the provider deduplicate too
// A retry right after the crash cannot tell whether the first run finished, so it is told to come back. A reused key is refused.
var crashApi = new PaymentApi(new Provider(), useKeys: true, forwardKey: true);
try { crashApi.Post("order-19", "acct-1", 5_000, crashAfterProvider: true); } catch (InvalidOperationException) { }
Debug.Assert(crashApi.Post("order-19", "acct-1", 5_000).Reply == Reply.InProgress);
var reuseApi = new PaymentApi(new Provider(), useKeys: true, forwardKey: true);
reuseApi.Post("k", "acct-1", 5_000);
Debug.Assert(reuseApi.Post("k", "acct-1", 5_000).Reply == Reply.Replayed);
Debug.Assert(reuseApi.Post("k", "acct-1", 9_999).Reply == Reply.KeyReuse);| Design | Reply lost, client retries | Crash after the charge, client retries |
|---|---|---|
| No idempotency key | 2 charges | 2 charges |
| Key stored by the API only | 1 charge | 2 charges |
| Key stored, and forwarded to the provider | 1 charge | 1 charge |
A key makes a lost reply harmless, and only a key that reaches the effect makes a crash harmless. That is the general rule for exactly-once effects: at-least-once delivery plus an idempotent effect, with the key carried all the way down. It is the same idea as the dedup key in the notification service and the outbox in distributed transactions. Where a key is awkward, other designs get idempotency for free: PUT /orders/{client-generated-id} (the id is the key), a unique constraint on a natural key such as (account, client_reference), or a conditional create (If-None-Match: *).
Two clients read a profile, both change it, both write it back. The second write silently erases the first: the lost update, the same anomaly as in the transactions lesson, now over HTTP, where a user may hold the form open for minutes. The API cannot hold a lock that long, so it uses optimistic concurrency. Every representation carries a version, the ETag. The client sends it back with the write in an If-Match header, and the server applies the write only if the resource is still at that version. Otherwise it answers 412 Precondition Failed, and the client reads again, merges and retries. A resource that must always be written conditionally can answer 428 Precondition Required to a request with no If-Match.
- headers
- If-Match: "7"
- 200updated. The new version is in the ETag header
- 412the profile changed since version 7. Read it again, reapply the edit and retry
- 428this resource requires If-Match and the request had none
The same header family serves caching: GET with If-None-Match: "7" returns 304 Not Modified and no body when nothing changed, which saves bandwidth and load. The sample runs ten clients, each adding 1 to a counter 100 times by reading it and writing back the value plus one, with the steps of different clients interleaved at random.
C# · A resource with a version, which an API exposes as its ETag.
using System;
// A resource with a version, which an API exposes as its ETag.
public sealed class Counter
{
public int Value { get; private set; }
public int Version { get; private set; }
public (int Value, int Version) Get() => (Value, Version);
// PUT with If-Match: refused with 412 Precondition Failed when the resource changed since the client read it.
public bool Put(int value, int? ifMatch)
{
if (ifMatch != null && ifMatch != Version) return false;
Value = value;
Version++;
return true;
}
}C# · 10 clients each add 1 to the counter 100 times. The scheduler picks a random client for…
using System;
using System.Diagnostics;
using System.Linq;
// 10 clients each add 1 to the counter 100 times. The scheduler picks a random client for each step, so reads and writes interleave.
(int Final, int Refused) RunClients(bool ifMatch)
{
var counter = new Counter();
var random = new Random(9);
var remaining = Enumerable.Repeat(100, 10).ToArray();
var read = new (int Value, int Version)?[10]; // what each client read and has not written back yet
int refused = 0;
while (remaining.Any(r => r > 0))
{
int client = random.Next(10);
if (remaining[client] == 0) continue;
if (read[client] == null) read[client] = counter.Get();
else
{
var seen = read[client].Value;
if (counter.Put(seen.Value + 1, ifMatch ? seen.Version : (int?)null)) remaining[client]--;
else refused++; // 412: read again and retry
read[client] = null;
}
}
return (counter.Value, refused);
}
var unguarded = RunClients(false);
var guarded = RunClients(true);
Debug.Assert(unguarded.Final == 187); // 813 of the 1,000 increments were lost
Debug.Assert(guarded.Final == 1_000 && guarded.Refused == 2_021); // none lost, at the price of retriesWithout If-Match the counter ended at 187 where 1,000 was right: 813 updates were silently lost. With it the counter was exactly 1,000, and the cost was 2,021 refused writes that the clients re-read and retried, which is what contention costs when ten writers fight over one resource. That is the right outcome. For a counter, a better design avoids the conflict altogether (an atomic increment on the server, or a commutative operation), and that is worth saying, but for documents, settings and profiles the version check is the general answer. Strong ETags are a version number or a content hash of the exact bytes. The weak form (W/"7") means semantically the same and is enough for caching but not for If-Match.
An API's errors are part of its contract, and clients write code against them. A consistent error body carries what a program and a person each need:
- note
- the shape follows RFC 9457, problem details for HTTP APIs. code is stable and for programs, message is for people and may change
- 400returns { "type": "https://api.example.com/errors/validation", "title": "Validation failed", "status": 400, "code": "validation_failed", "request_id": "req_8f21", "errors": [{ "field": "quantity", "code": "too_small", "message": "must be at least 1" }] }
- A stable machine-readable
codethat clients branch on. Never make them parse the message. - All field errors at once, so a form is fixed in one round trip and not five.
- A request id that is also in the logs and traces (see observability), so a support ticket leads straight to the evidence.
- Retryability is explicit. 429 and 503 carry
Retry-After. Say which errors are permanent, which are transient and which are safe to retry only with an idempotency key. - Nothing internal leaks: no stack traces, SQL or hostnames, and the same error for "wrong password" and "no such user".
- Status codes mean what they say, because SLOs and alerts count them: a 5xx spends the error budget, a 4xx usually does not (see SLOs), so a validation error returned as a 500 pages someone and one returned as a 200 hides a failure.
Once clients exist, the contract is a promise you cannot see the other half of. A change is breaking if a client written against the old contract stops working, and which changes break depends on the direction. For a request the client writes and the server reads, so anything that makes the server accept less, or demand more, breaks old clients. For a response the server writes and the client reads, so anything that gives the client something it did not expect breaks it. The rules are mechanical enough to write down as code, which is how a build can refuse a breaking change.
C# · Field, Direction, Compatibility
using System;
using System.Collections.Generic;
using System.Linq;
public sealed record Field(string Name, string Type, bool Required, string[] Values = null);
public enum Direction { Request, Response }
public static class Compatibility
{
// The changes between two versions of a message that would break a client written against the old version.
// Request: the client writes it and the server reads it. Response: the server writes it and the client reads it.
public static List<string> Breaking(Field[] before, Field[] after, Direction direction)
{
var problems = new List<string>();
var newer = after.ToDictionary(f => f.Name);
foreach (var old in before)
{
if (!newer.TryGetValue(old.Name, out var now)) { problems.Add($"{old.Name} removed"); continue; }
if (old.Type != now.Type) problems.Add($"{old.Name} changed type from {old.Type} to {now.Type}");
if (direction == Direction.Request && !old.Required && now.Required) problems.Add($"{old.Name} became required");
if (direction == Direction.Response && old.Required && !now.Required) problems.Add($"{old.Name} may now be missing");
if (old.Values != null && now.Values != null)
{
var gone = old.Values.Except(now.Values).ToArray();
var added = now.Values.Except(old.Values).ToArray();
if (direction == Direction.Request && gone.Length > 0) problems.Add($"{old.Name} no longer accepts {string.Join(", ", gone)}");
if (direction == Direction.Response && added.Length > 0) problems.Add($"{old.Name} can now be {string.Join(", ", added)}");
}
}
var older = before.ToDictionary(f => f.Name);
foreach (var added in after.Where(f => !older.ContainsKey(f.Name)))
if (direction == Direction.Request && added.Required) problems.Add($"{added.Name} added as required");
return problems;
}
}C#
using System;
using System.Diagnostics;
using System.Linq;
var orderV1 = new[]
{
new Field("id", "string", true),
new Field("amount", "int", true),
new Field("currency", "string", true),
new Field("status", "string", true, new[] { "pending", "paid", "shipped" }),
new Field("note", "string", false),
};
// Safe: a new optional request field, and a new response field.
Debug.Assert(Compatibility.Breaking(orderV1, orderV1.Append(new Field("coupon", "string", false)).ToArray(), Direction.Request).Count == 0);
Debug.Assert(Compatibility.Breaking(orderV1, orderV1.Append(new Field("tracking_url", "string", false)).ToArray(), Direction.Response).Count == 0);
// Breaking for a request: a type change, an accepted value removed, optional made required, and a new required field.
var requestV2 = new[]
{
new Field("id", "string", true),
new Field("amount", "string", true),
new Field("currency", "string", true),
new Field("status", "string", true, new[] { "pending", "paid" }),
new Field("note", "string", true),
new Field("channel", "string", true),
};
Debug.Assert(Compatibility.Breaking(orderV1, requestV2, Direction.Request).SequenceEqual(new[]
{
"amount changed type from int to string", "status no longer accepts shipped", "note became required", "channel added as required",
}));
// Breaking for a response: a field removed, a required field that may now be missing, and a new enum value the client has never seen.
var responseV2 = new[]
{
new Field("id", "string", true),
new Field("amount", "int", false),
new Field("status", "string", true, new[] { "pending", "paid", "shipped", "refunded" }),
new Field("note", "string", false),
};
Debug.Assert(Compatibility.Breaking(orderV1, responseV2, Direction.Response).SequenceEqual(new[]
{
"amount may now be missing", "currency removed", "status can now be refunded",
}));Two of those surprise people. A new enum value in a response breaks clients that switch on the old values and have no default branch, so either document from day one that enums are open (clients must handle unknown values) or treat a new value as breaking. And making a response field optional breaks clients that read it without checking. Everything else the checker passed was additive, and additive change is how an API evolves without a new version: add fields, add endpoints, add optional parameters, never repurpose a name or change a meaning. Clients must follow the tolerant reader rule: ignore unknown fields and unknown enum values.
When a break is unavoidable, choose how to ship it:
| Strategy | How | Good for | Cost |
|---|---|---|---|
Version in the path (/v2/orders) | A whole new surface | Public APIs, large breaks | Two surfaces to run, and clients migrate on their own schedule |
| Version in a header or media type | Accept: application/vnd.example.v2+json | Fine-grained, hidden from URLs | Harder to test and cache, easy to forget |
| Date-based version, pinned per client | The client is pinned to the date it integrated, and changes are opt-in (Stripe does this) | Many small changes over many years | The server carries every old behaviour, so a compatibility layer is needed |
| Additive only, with field-level deprecation | Mark a field deprecated, keep it, remove it after a sunset | Internal APIs and most evolution | Needs discipline and telemetry |
Whatever the choice, three practices decide whether it works. Measure who uses what, per version and per field, so a removal is a decision with a number behind it. Announce and enforce a deprecation timeline, with Deprecation-style notices in documentation and a Sunset header (RFC 8594) carrying the date. And check compatibility in CI: diff the schema against the last release (tools exist for OpenAPI and protobuf) and fail the build on a breaking change, which is the checker above run on every pull request. In protobuf, never reuse a field number and never change a field's type.
| REST over HTTP and JSON | gRPC | GraphQL | |
|---|---|---|---|
| Contract | OpenAPI, optional and often drifting | A .proto schema, required and compiled | A typed schema, required |
| Wire | Text, larger | Binary protobuf over HTTP/2, small and fast to parse | JSON over HTTP, usually one POST |
| Streaming | Server-sent events or WebSockets, outside the model | Built in: server, client and bidirectional streams | Subscriptions, less common |
| Browsers | Native | Needs a proxy (gRPC-Web) | Native |
| Caching | HTTP caching works for GET | Not through HTTP caches | Hard: one endpoint, varied queries |
| Strength | Public and third-party APIs, simplicity, tooling, caching | Service to service: codegen, deadlines that propagate, streaming, evolution rules | One round trip for many resources, clients choose fields |
| Watch for | Over- and under-fetching, many round trips | Debugging binary traffic, no browser support | N+1 queries behind a resolver, expensive queries, caching |
The interview answer is a rule of thumb with its reason. REST for public APIs, because every client and every proxy already understands it. gRPC between internal services, because the schema is enforced, the code is generated, deadlines propagate down the call chain and streaming comes with it. GraphQL in front of many backends for a UI that wants to assemble many resources in a round trip, with query cost limits and persisted queries so a client cannot ask for the world. Mixed designs are normal: gRPC inside, REST or GraphQL at the edge. For the asynchronous half of an API, a webhook or an event stream, the same rules apply with the roles reversed: the receiver must verify a signature, deduplicate by event id and accept retries (the encryption, secrets and abuse lesson tests exactly that).
- Limits are part of the contract. Publish rate limits and answer
429withRetry-After; tell clients how much quota is left with response headers. Cap page sizes, body sizes and batch sizes. - Deadlines and timeouts. A client that waits forever holds resources forever. Clients set a deadline, and in a call chain the remaining budget is passed down, as the tail latency lesson shows.
- Retries need a budget. Clients retry with exponential backoff, jitter and a cap, and only what is safe to retry. Otherwise a brief outage becomes a storm.
- Caching headers.
Cache-Controland an ETag onGETs that can be cached. Mark private data as private. - Authentication in a header, never in the URL, where it ends up in logs and browser history. Authenticate who is calling, and authorize each object (authentication and authorization).
- Field selection and expansion (
fields=,expand=customer) keep payloads small without a new endpoint for each screen.
| Failure | What goes wrong | Defence |
|---|---|---|
| Offset drift | Duplicates and gaps while paging a live list | Cursor pagination over a total order |
A double POST | A retry creates a second payment or order | An idempotency key, forwarded to the effect |
| A lost update | The second writer erases the first | ETag with If-Match, 412, and a retry |
| Unbounded lists | A client asks for a million rows | Pagination by default, a capped limit |
| A new enum value | An exhaustive client crashes | Declare enums open, or treat a new value as breaking |
| Ties in the sort key | Items repeat or vanish across pages | Add a unique tiebreaker such as the id |
| A stuck idempotency record | The key stays "in progress" forever after a crash | A lease that expires, and a retry that starts again |
| Retry storm | Clients retry in step and keep the service down | Backoff with jitter, a retry budget, Retry-After |
| Errors that leak | Stack traces and existence oracles | Stable codes, one message for "wrong user or password" |
| Silent breaking change | A rename breaks clients that nobody tracked | A schema diff in CI, per-field usage telemetry |
Interviewer follow-upL5When do you use PUT, POST and PATCH?How to answer
PUT replaces a resource at a known id and is idempotent, so a retry is safe. POST creates under a collection with a server-chosen id, or runs an action, and is not idempotent, so it needs an idempotency key. PATCH changes some fields and is idempotent only if the patch is (setting a status is, adding to a balance is not). Say what each promises under retry, because that is the point.
Interviewer follow-upL5Why is cursor pagination better than offset pagination, and when would you still use offset?How to answer
Offset names a count of rows to skip, so inserts and deletes shift it and produce duplicates and gaps (174 duplicates and 47 missed items in the test), and the database walks past every skipped row, so deep pages are slow. A cursor names a position in a total order and an index finds it in logarithmic time. Use offset for small or static data and anything people page through by number, and say that you give up random access with cursors.
Interviewer follow-upL6A client times out on POST /payments and retries. How do you make sure it is charged once?How to answer
An idempotency key chosen by the client for the logical operation and sent on every attempt. The server stores the key with a fingerprint of the request, the state and the saved response, and in one atomic step with the effect: a replay returns the saved response, a concurrent duplicate gets a 409, a different body under the same key gets a 422. If the charge happens in another system, forward the key so that the provider deduplicates too, because a crash between the charge and the saved result otherwise charges twice (the test did).
Interviewer follow-upL6Two users edit the same profile at once. How do you stop one erasing the other?How to answer
Optimistic concurrency with an ETag: the response carries a version, the client sends it back in If-Match, and the server applies the write only if the version still matches, otherwise answers 412 so the client re-reads, merges and retries. Without it 813 of 1,000 increments were lost in the test, with it none, at the price of retries. Use a lock only for short critical sections and never across a user's think time.
Interviewer follow-upL6Which changes to an API are breaking?How to answer
It depends on the direction. For requests: removing or retyping a field, making an optional field required, adding a required field, and narrowing the accepted values. For responses: removing or retyping a field, making a required field optional, and adding an enum value that clients do not know. Adding optional request fields and adding response fields is safe if clients ignore the unknown. Automate the check in CI with a schema diff.
Interviewer follow-upL7How would you evolve an API that 10,000 clients you do not control depend on?How to answer
Make almost every change additive and require clients to tolerate unknown fields and values. Instrument usage per version and per field so you know who is affected. For a real break, run the old and new side by side (a path or date version), deprecate with a published timeline and Sunset headers, tell the heaviest users directly, keep a compatibility layer until usage falls, and remove only against a number. Run a schema diff in CI and consumer contract tests so a break is caught before release, and design enums as open from the start.
Interviewer follow-upL7REST or gRPC for your internal platform, and why?How to answer
gRPC for service to service: a compiled schema with evolution rules, generated clients, HTTP/2 multiplexing, streaming and deadlines that propagate down the call chain, at the cost of binary debugging and a proxy for browsers. REST (or GraphQL) at the edge, for external clients, caching and tooling. Say that the contract and its evolution rules matter more than the wire format, and that you would enforce either with a schema diff in CI.
When asked to design the API for a system, write the contract and then say what happens when it fails.
- Resources and methods. The nouns, the methods, what each promises under retry, and the status codes.
- Lists. Cursor pagination over a total order, a capped limit, no total count.
- Unsafe operations. An idempotency key on every
POST, stored atomically with the effect and forwarded to it. - Writes that can race. ETags and
If-Match, with412and a retry. - Errors. One body shape, stable codes, retryability stated, a request id.
- Evolution. Additive by default, tolerant readers, a schema diff in CI, a deprecation timeline.
Model resources and let HTTP methods carry the verbs, choosing them by what they promise under retry: GET, PUT and DELETE are idempotent, POST is not. Paginate every list. Offset pagination drifts (174 duplicates and 47 missed items in the test) and gets slower with depth, while a cursor over a total order, with an index, was stable and did 23 times less work. Make POST idempotent with a client-supplied key stored with a request fingerprint and the saved response, atomically with the effect: a key made a lost reply harmless, and only forwarding it to the provider made a crash harmless. Prevent lost updates with an ETag and If-Match (813 of 1,000 increments were lost without, none with, at the price of retries). Return one error shape with stable codes, all field errors, explicit retryability and a request id. Know which changes break a client by direction, keep evolution additive with tolerant readers, run a schema diff in CI, and deprecate with a timeline. Use REST for public APIs, gRPC between internal services and GraphQL to aggregate for UIs, and publish limits, deadlines and retry rules as part of the contract.
Try answering out loud before you reveal each answer.
QuestionA client pages through a feed 20 items at a time while new items keep arriving at the top. What does offset pagination do, and what does a cursor do?Reveal answer
Offset pushes everything down by one for each arrival, so the next page repeats items the client already has (174 duplicates in the test). A cursor names a position in the order ("after this item"), which new arrivals at the top cannot move, so nothing repeats or is missed, and an index finds the position in logarithmic time (1,572 rows examined against 36,600).
QuestionA payment request times out and the client retries it. What must the server do, and what goes wrong if it only stores the key?Reveal answer
Look up the idempotency key: replay the saved response if the first request completed, answer 409 if it is still running, and 422 if the key was used with a different body. If the server only stores the key and the charge goes to a provider, a crash between the charge and saving the result makes the retry charge again, because the provider never saw the key. Forward the key to the provider, or make the record and the effect one atomic step.
QuestionWhy does a PUT without If-Match lose updates, and what does the server answer when the version is stale?Reveal answer
Two clients read the same version and both write, and the second write overwrites the first without knowing it existed. With If-Match the server compares the version in the header with the current one and answers 412 Precondition Failed when they differ, so the client re-reads, merges and retries. In the test 813 of 1,000 increments were lost without it and none with it.
QuestionIs adding a new value to a response enum a breaking change?Reveal answer
It can be. A client that switches on the old values and has no default branch fails on a value it has never seen. Either document from the start that enums are open and clients must handle unknown values, or treat a new value as breaking and version it. Adding a field to a response is safe only for clients that ignore unknown fields.
QuestionWhy use a unique id as a tiebreaker in the cursor?Reveal answer
A sort key such as created_at has ties, and a cursor that names only the timestamp cannot tell which of several items with that time was the last delivered, so the next page repeats or skips some. Adding a unique id gives every item exactly one position, and the cursor and the index hold both columns.
- IETF, RFC 9110, HTTP Semantics (opens in a new tab): the methods and which are safe and idempotent, status codes, and conditional requests (
ETag,If-Match,If-None-Match, 412, 428, 304). - IETF, RFC 9457, Problem Details for HTTP APIs (opens in a new tab): the error body shape. RFC 8594, The Sunset HTTP Header Field (opens in a new tab): announcing removal dates.
- IETF HTTPAPI working group, The Idempotency-Key HTTP Header Field (opens in a new tab) (an Internet-Draft), and Stripe, Idempotent requests (opens in a new tab): a widely copied practical design.
- Google, API Improvement Proposals AIP-158, Pagination (opens in a new tab) and AIP-180, Backwards compatibility (opens in a new tab): page tokens and what counts as a breaking change. Microsoft, REST API Guidelines (opens in a new tab).
- Markus Winand, We need tool support for keyset pagination (opens in a new tab), Use The Index, Luke: why offset is slow and how the seek method works.
- gRPC, Core concepts (opens in a new tab): deadlines, streaming and the call types.