Video in progress

How does the Liskov principle apply to API versioning? What do you need to follow so that a new version of an API can "substitute" for the old one?

The new version must be a substitute for old consumers in the Liskov sense: don't strengthen requirements on input, don't weaken promises on output. Adding a field is fine; adding a required parameter or changing a meaning is a breaking change.

📖 Answer

The LSP rule from a contract point of view: preconditions are not strengthened, postconditions are not weakened, invariants are preserved. This works the same in classes and in HTTP/event contracts.

Breaking (not a substitute):

  • a new required request field or stricter validation (the precondition got stronger);
  • removing a field from a response or making it possibly null (the postcondition got weaker);
  • changing a field's meaning: amount is now in tiyin;
  • a new error code in a situation the consumer didn't expect;
  • a new enum value, if the consumer wrote an exhaustive switch.

Non-breaking:

  • an optional request field, with a default value;
  • a new field in the response (if the consumer ignores unknown fields: a "tolerant reader");
  • widening the set of accepted values.
// v1: amount is in som, a whole number
record TransferRequestV1(String from, String to, long amount) {}

// v2: currency added, but with a default, so v1 consumers keep working
record TransferRequest(String from, String to, long amount, String currency) {
    public TransferRequest {
        if (currency == null) currency = "UZS";
    }
}

How I check:

  • Consumer-driven contract tests (Pact, Spring Cloud Contract): if a provider change breaks specific consumers, CI stops;
  • Schema compatibility checks: OpenAPI diff, and for Avro/Protobuf the compatibility mode in the schema registry (BACKWARD, FORWARD, FULL);
  • making tolerant reader the standard for consumers.

If a breaking change is unavoidable, use a new version (/v2) or a new event type, with both running in parallel and a clear removal date for the old one.