Skip to lesson

Backward-compatible API changes

ShopLite's mobile app is installed on 200,000 phones, and many people never update it. If the API changes shape, thousands of apps break on the same morning. How do you change an API safely?

Your turn: change the price without breaking apps

ShopLite wants to sell abroad, so every price needs a currency. Today "price": 17999.00 is a plain number, and 200,000 installed apps read it that way.

Before you read on, think about these questions and write your plan in a few lines.

  • Which change would let old apps keep working while new apps get the currency?
  • If a breaking change cannot be avoided, where should it live, and how do users move over?
  • How would you know it is safe to switch the old version off?

Safe changes and breaking changes

Backward compatible means that every client that worked before a change still works after it. Adding things is usually backward compatible; removing or changing things is a breaking change.

A change is safe when old apps never notice it. The checker below classifies five proposed changes to ShopLite's product API.

Example 1 · Classifying a proposed product API change

CompatibilityChecker.javaJava
import java.util.LinkedHashMap;import java.util.Map;
record Field(String type, boolean requiredInRequest) {}
public class CompatibilityChecker {    static void compare(Map<String, Field> oldApi, Map<String, Field> newApi) {        for (String name : oldApi.keySet()) {            if (!newApi.containsKey(name)) {                System.out.println("BREAKING  removed or renamed field: " + name);            } else if (!oldApi.get(name).type().equals(newApi.get(name).type())) {                System.out.println("BREAKING  type of " + name + " changed: "                        + oldApi.get(name).type() + " -> " + newApi.get(name).type());            }        }        for (String name : newApi.keySet()) {            if (!oldApi.containsKey(name)) {                if (newApi.get(name).requiredInRequest()) {                    System.out.println("BREAKING  new required request field: " + name);                } else {                    System.out.println("safe      new optional field: " + name);                }            }        }    }
    public static void main(String[] args) {        Map<String, Field> v1 = new LinkedHashMap<>();        v1.put("id", new Field("integer", false));        v1.put("name", new Field("string", true));        v1.put("price", new Field("number", true));        v1.put("stock", new Field("integer", false));
        Map<String, Field> proposed = new LinkedHashMap<>();        proposed.put("id", new Field("integer", false));        proposed.put("title", new Field("string", true));        // "name" renamed        proposed.put("price", new Field("object", true));        // number -> {amount, currency}        proposed.put("stock", new Field("integer", false));        proposed.put("brand", new Field("string", false));       // optional, new        proposed.put("gstRate", new Field("number", true));
        compare(v1, proposed);    }}
Output
BREAKING  removed or renamed field: name
BREAKING  type of price changed: number -> object
BREAKING  new required request field: title
safe      new optional field: brand
BREAKING  new required request field: gstRate

What this code does

  • The checker compares field names, types and "required in requests" between v1 and the proposal. Renaming name to title shows up as a removal plus a new required field.
  • Only brand is safe. Four of five changes would break old apps, so the proposal must be reworked as additions or moved to v2.

Safe (additive) changes: a new endpoint, a new optional request field, a new field in a response, a new optional query parameter. Old clients never send or read them, so nothing changes for them.

Breaking changes: removing or renaming a field, changing its type or meaning, making an optional field required, or adding a new required request field. Old clients send or expect the old shape and fail. ShopLite's v1 contract follows exactly these rules.

Find the bug

Find the breaking change

Click the line of the new response or request that breaks old apps.

v1 returns id, name and price. Which line of the new response breaks old apps?

Round 1 of 3

Tolerant readers: clients ignore unknown fields

A tolerant reader is a client that reads the fields it needs and ignores unknown fields and unknown values. It lets the server add things without breaking the client.

A client that crashes on an unknown field turns every new field into an outage. The example sends a response with a new brand field to a strict and a tolerant app.

Example 2 · A new response field: strict client crashes, tolerant client is fine

TolerantReaderDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;
record ProductView(int id, String name, double price) {}
public class TolerantReaderDemo {    static final Set<String> KNOWN = Set.of("id", "name", "price");
    // Strict reader: fails on any field it does not know    static ProductView strict(Map<String, Object> json) {        for (String key : json.keySet()) {            if (!KNOWN.contains(key)) {                throw new IllegalStateException("unknown field '" + key + "'");            }        }        return tolerant(json);    }
    // Tolerant reader: takes what it needs, ignores the rest    static ProductView tolerant(Map<String, Object> json) {        return new ProductView((Integer) json.get("id"), (String) json.get("name"), (Double) json.get("price"));    }
    public static void main(String[] args) {        // The server added "brand" in a later v1 release        Map<String, Object> response = new LinkedHashMap<>();        response.put("id", 1);        response.put("name", "Redmi Note 13 5G");        response.put("price", 17999.00);        response.put("brand", "Xiaomi");
        try {            System.out.println("strict app:   " + strict(response));        } catch (IllegalStateException e) {            System.out.println("strict app:   crashed, " + e.getMessage());        }        System.out.println("tolerant app: " + tolerant(response));    }}
Output
strict app:   crashed, unknown field 'brand'
tolerant app: ProductView[id=1, name=Redmi Note 13 5G, price=17999.0]

What this code does

  • The server adds brand to the product response. The strict reader fails on the unknown key, which in a real app is a crash for every user.
  • The tolerant reader takes only id, name and price. Additive server changes are safe only if clients read this way.

Additive changes are only safe if clients cooperate. A strict client that fails on unknown fields turns every additive change into an outage.

Note the two directions in ShopLite's contract. The server rejects unknown fields in requests with 400, to catch client typos. Clients must ignore unknown fields in responses; with Jackson that is FAIL_ON_UNKNOWN_PROPERTIES set to false. Apps should also treat an unknown enum value, such as a new order status, as "other" instead of crashing.

Predict the output

Strict or tolerant

The server adds something new. Predict what the app does.

Round 1 of 2

The server adds the new order status OUT_FOR_DELIVERY. What does this app show?

String status = "OUT_FOR_DELIVERY";
String label = switch (status) {
case "PLACED" -> "Received";
case "SHIPPED", "DELIVERED" -> "On its way or done";
default -> "In progress";
};
System.out.println(label);

Versioning: /v1 in the path or in a header

Path versioning puts the API version in the URL, such as /api/v1/products and /api/v2/products, so two versions can run side by side and are easy to see in logs and to route.

When a breaking change is truly needed, it goes into a new version that runs beside the old one. The example routes requests by path and by Accept header.

Example 3 · Routing by path version and by Accept header

VersionRouter.javaJava
public class VersionRouter {    // Path versioning: the version is part of the URL    static String byPath(String path) {        if (path.startsWith("/api/v2/")) {            return "v2 handler";        }        if (path.startsWith("/api/v1/")) {            return "v1 handler";        }        return "404 unknown version";    }
    // Header versioning: one URL, the version in the Accept header    static String byHeader(String accept) {        if (accept != null && accept.contains("application/vnd.shoplite.v2+json")) {            return "v2 handler";        }        return "v1 handler (default)";    }
    public static void main(String[] args) {        System.out.println("GET /api/v1/products/1 -> " + byPath("/api/v1/products/1"));        System.out.println("GET /api/v2/products/1 -> " + byPath("/api/v2/products/1"));        System.out.println("GET /api/v3/products/1 -> " + byPath("/api/v3/products/1"));        System.out.println("Accept: application/vnd.shoplite.v2+json -> " + byHeader("application/vnd.shoplite.v2+json"));        System.out.println("Accept: application/json                 -> " + byHeader("application/json"));    }}
Output
GET /api/v1/products/1 -> v1 handler
GET /api/v2/products/1 -> v2 handler
GET /api/v3/products/1 -> 404 unknown version
Accept: application/vnd.shoplite.v2+json -> v2 handler
Accept: application/json                 -> v1 handler (default)

What this code does

  • byPath reads the version from the URL prefix, so v1 and v2 handlers can run side by side. An unknown version gets 404.
  • byHeader keeps one URL and looks for the vendor media type; with no version asked it falls back to v1, so old clients keep working.

Path versioning is easy to see in logs, easy to route and to test with curl, and it is what ShopLite uses. Header versioning keeps one URL and reads the version from a header such as Accept: application/vnd.shoplite.v2+json: cleaner URLs, but harder to see and to cache.

Bump the major version only for breaking changes. Adding fields or endpoints stays in v1. Many teams go years on v1 by designing changes additively.

Deprecation: announce, run both, measure, remove

The Sunset header tells clients the date an old API version will be removed (RFC 8594). It is sent together with a Deprecation header on every response from the old version.

Retiring an old version is a process, not a delete. During the process, every response from the old version carries headers like these.

Text
HTTP/1.1 200 OKDeprecation: @1793491200Sunset: Wed, 31 Mar 2027 23:59:59 GMTLink: <https://docs.shoplite.example/migrate-v2>; rel="deprecation"

Example 4 · Deciding when v1 can really be removed

DeprecationTracker.javaJava
import java.time.LocalDate;
public class DeprecationTracker {    static final LocalDate SUNSET = LocalDate.of(2027, 3, 31);
    static String decide(LocalDate week, long v1Calls, long v2Calls) {        double v1Share = 100.0 * v1Calls / (v1Calls + v2Calls);        String share = String.format("v1 %.1f%%", v1Share);        if (week.isBefore(SUNSET)) {            return share + " -> keep both; v1 responses carry Deprecation and Sunset headers";        }        if (v1Share >= 1.0) {            return share + " -> past sunset but still used: contact the remaining clients";        }        return share + " -> remove v1 (410 Gone with a link to the migration guide)";    }
    public static void main(String[] args) {        System.out.println("Sunset: " + SUNSET);        System.out.println(LocalDate.of(2026, 11, 2) + "  " + decide(LocalDate.of(2026, 11, 2), 90_000, 10_000));        System.out.println(LocalDate.of(2027, 1, 4) + "  " + decide(LocalDate.of(2027, 1, 4), 30_000, 70_000));        System.out.println(LocalDate.of(2027, 4, 5) + "  " + decide(LocalDate.of(2027, 4, 5), 4_000, 96_000));        System.out.println(LocalDate.of(2027, 5, 3) + "  " + decide(LocalDate.of(2027, 5, 3), 300, 99_700));    }}
Output
Sunset: 2027-03-31
2026-11-02  v1 90.0% -> keep both; v1 responses carry Deprecation and Sunset headers
2027-01-04  v1 30.0% -> keep both; v1 responses carry Deprecation and Sunset headers
2027-04-05  v1 4.0% -> past sunset but still used: contact the remaining clients
2027-05-03  v1 0.3% -> remove v1 (410 Gone with a link to the migration guide)

What this code does

  • Before the sunset date both versions run and v1 responses carry Deprecation and Sunset headers.
  • After the date, v1 is removed only when its share of traffic falls below 1%; at 4% the team contacts the remaining clients first. 410 Gone tells late clients clearly what happened.

Announce the change with a date and a migration guide. Run both versions side by side, with the Deprecation and Sunset headers on the old one. Measure who still calls v1, per client or app version.

Remove only after the sunset date and when traffic is close to zero, after contacting the remaining clients. Removed endpoints answer 410 Gone with a link to the guide, not a confusing 404.

Order of execution

Order the retirement of v1

Put the steps for retiring an old API version in order.

Worked example: price from a number to {amount, currency}

ShopLite wants to sell abroad, so price must become an object with an amount and a currency. The example prints the response in three stages.

Example 5 · ShopLite price: v1, v1 with priceMoney, and v2

PriceMigrationDemo.javaJava
import java.math.BigDecimal;
// One internal model; each API version decides how to show itrecord Product(int id, String name, BigDecimal amount, String currency) {}
public class PriceMigrationDemo {    // Before: v1 as it shipped    static String v1Original(Product p) {        return "{\"id\":" + p.id() + ",\"name\":\"" + p.name() + "\",\"price\":" + p.amount() + "}";    }
    // Step 1 (still v1, additive): old field kept, new optional field added    static String v1WithMoney(Product p) {        return "{\"id\":" + p.id() + ",\"name\":\"" + p.name() + "\",\"price\":" + p.amount()                + ",\"priceMoney\":{\"amount\":" + p.amount() + ",\"currency\":\"" + p.currency() + "\"}}";    }
    static String v2(Product p) {        return "{\"id\":" + p.id() + ",\"name\":\"" + p.name() + "\",\"price\":{\"amount\":" + p.amount()                + ",\"currency\":\"" + p.currency() + "\"}}";    }
    public static void main(String[] args) {        Product phone = new Product(1, "Redmi Note 13 5G", new BigDecimal("17999.00"), "INR");        System.out.println("v1 today:         " + v1Original(phone));        System.out.println("v1 + priceMoney:  " + v1WithMoney(phone));        System.out.println("v2:               " + v2(phone));    }}
Output
v1 today:         {"id":1,"name":"Redmi Note 13 5G","price":17999.00}
v1 + priceMoney:  {"id":1,"name":"Redmi Note 13 5G","price":17999.00,"priceMoney":{"amount":17999.00,"currency":"INR"}}
v2:               {"id":1,"name":"Redmi Note 13 5G","price":{"amount":17999.00,"currency":"INR"}}

What this code does

  • All three responses come from one Product record with a BigDecimal amount and a currency. The versions differ only in how they present it.
  • The middle line is the key step: an additive change in v1 lets new apps move to the object form while old apps keep reading the number.

Changing the type in v1 would crash every old app that reads a number, so the change happens in steps. Step 1, still in v1: keep price as a number and add a new optional field priceMoney with the object. New apps read priceMoney; old apps ignore it.

Step 2: publish v2, where price is the object, and run it beside v1 from the same internal model. Step 3: deprecate v1 with a sunset date, measure, and remove it when traffic is gone.

Next step

Check your understanding

11 quick questions