API design at scale practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
ShopLite's API now faces real users: flaky networks, huge lists and apps that never update. Four habits keep it reliable, and four common mistakes each break one of them.
Mistake 1: changing the contract in place
A rename, a type change or a change of meaning ("total now excludes delivery") inside v1 breaks every installed app that relied on the old shape. The example classifies five changes.
Example 1 · Safe or breaking, by kind of change
import java.util.List;
record Change(String description, String kind) {}
public class ChangeClassifier { static String classify(String kind) { return switch (kind) { case "add-endpoint", "add-response-field", "add-optional-request-field", "add-optional-param" -> "safe"; case "remove-field", "rename-field", "change-type", "add-required-request-field", "make-field-required", "change-meaning" -> "BREAKING"; default -> "check by hand"; }; }
public static void main(String[] args) { List<Change> changes = List.of( new Change("Add GET /api/v1/products/{id}/reviews", "add-endpoint"), new Change("Add \"brand\" to product responses", "add-response-field"), new Change("Rename \"fullName\" to \"name\"", "rename-field"), new Change("\"total\" now excludes delivery charges", "change-meaning"), new Change("Add optional ?inStock=true filter", "add-optional-param"));
for (Change c : changes) { System.out.printf("%-8s %s%n", classify(c.kind()), c.description()); } }}safe Add GET /api/v1/products/{id}/reviews
safe Add "brand" to product responses
BREAKING Rename "fullName" to "name"
BREAKING "total" now excludes delivery charges
safe Add optional ?inStock=true filterWhat this code does
classifymaps each kind of change to safe or breaking. Additions are safe; renames, type changes and changes of meaning are not.- The "total excludes delivery" change keeps the same field and type, yet breaks apps that show it as the amount to pay.
The last kind is the sneakiest: the JSON looks the same, but the number means something else.
The habit: add new fields and endpoints in v1, keep old ones working, and put unavoidable breaking changes in v2 with a deprecation plan. Review: Backward-compatible API changes (opens in a new tab).
Mistake 2: retries with no rules
A loop that retries every failure at once and for ever turns one bad request into hundreds of calls. A 400 will never succeed, however often it is sent. The example counts the calls.
Example 2 · What a rule-free retry loop costs
public class RetryLoopCost { // How many calls one client makes in 10 seconds while the server answers 400 every time public static void main(String[] args) { double callMs = 20; // one round trip
// Bad: retry everything, no delay, no limit long badCalls = (long) (10_000 / callMs); System.out.println("no rules: " + badCalls + " calls in 10 s, all 400, forever");
System.out.println("with rules: 1 call, error shown to the user");
long waited = 100 + 200 + 400; System.out.println("503 case: 4 calls over " + (4 * (long) callMs + waited) + " ms, then give up"); }}no rules: 500 calls in 10 s, all 400, forever with rules: 1 call, error shown to the user 503 case: 4 calls over 780 ms, then give up
What this code does
- Retrying a
400with no delay sends 500 useless calls in 10 seconds from just one client. - With rules, a
400costs one call, and even a retryable503costs four calls spread over under a second before giving up.
The habit: retry only temporary failures (timeouts, 429, 502, 503, 504), wait with exponential backoff and jitter, stop after a few attempts, and retry a POST only with an idempotency key.
Review: Timeouts and retries with backoff (opens in a new tab).
Mistake 3: deep offsets on huge lists
OFFSET reads every skipped row. On a billion-row table, the example shows how much work a full export with offset pages does compared with keyset pages.
Example 3 · Exporting a billion rows: OFFSET vs keyset
public class BillionRows { public static void main(String[] args) { long rows = 1_000_000_000L; int size = 100; long pages = rows / size;
// Simplified model: OFFSET reads skipped rows; keyset reads only the page long lastPageOffsetReads = (pages - 1) * size + size; long allPagesOffsetReads = pages * (pages + 1) / 2 * size; // 1 + 2 + ... + pages, times size long allPagesKeysetReads = rows;
System.out.println("pages of " + size + ": " + pages); System.out.println("last page with OFFSET reads " + lastPageOffsetReads + " rows"); System.out.printf("whole export, OFFSET: about %.1e row reads%n", (double) allPagesOffsetReads); System.out.printf("whole export, keyset: about %.1e row reads%n", (double) allPagesKeysetReads); }}pages of 100: 10000000 last page with OFFSET reads 1000000000 rows whole export, OFFSET: about 5.0e+15 row reads whole export, keyset: about 1.0e+09 row reads
What this code does
- With offset pages of 100, the last page alone reads a billion rows, and the whole export about 5 × 10¹⁵ row reads in this simplified model.
- Keyset pages read each row once: about 10⁹ reads in total.
The last pages of an offset export read almost the whole table each time, so they time out.
The habit: offset pages for small lists where users want page numbers; keyset (cursor) pages, WHERE id > :lastId ORDER BY id LIMIT n, for big, live or endless lists and exports. Review: Pagination for very large lists (opens in a new tab).
Mistake 4: a create endpoint that is not idempotent
Double taps, frozen screens and automatic retries after timeouts all send the same POST twice. The example taps twice on a create endpoint that has no protection.
Example 4 · A double tap creates two orders
import java.util.ArrayList;import java.util.List;
public class DoubleTapBug { static List<String> orders = new ArrayList<>();
// POST /orders with no idempotency key static String createOrder(String customer, int total) { String id = "order-" + (501 + orders.size()); orders.add(id + " " + customer + " Rs " + total); return "201 " + id; }
public static void main(String[] args) { // Meena taps "Place order", the screen freezes, she taps again System.out.println("tap 1 -> " + createOrder("meena", 1299)); System.out.println("tap 2 -> " + createOrder("meena", 1299)); System.out.println("orders: " + orders); }}tap 1 -> 201 order-501 tap 2 -> 201 order-502 orders: [order-501 meena Rs 1299, order-502 meena Rs 1299]
What this code does
createOrderhas no idempotency key, so the second tap is treated as a brand new order.- Meena is charged twice for one pair of earbuds. Practice 5 fixes it with a key.
Without protection, each tap creates an order and charges the customer.
The habit: the client sends an Idempotency-Key per user action; the server claims the key atomically, stores the first response and replays it for every repeat. Review: Idempotency keys (opens in a new tab) and Handling slow work asynchronously (opens in a new tab).
Finish up
Mark complete & continue
Next: Project: ShopLite reliable order API simulation