Video in progress

Domain objects are stored as JSON in a database or in Kafka. When the class changes, how do you stay compatible with old data?

Stored JSON is not code, it's a contract: it outlives the class. So I only add fields, rename and remove them in stages, and for a sharp change I add a version field and an upcaster (code that converts the old shape into the new one on read).

📖 Answer

A typical problem: an @JdbcTypeCode(SqlTypes.JSON) Delivery delivery column inside Order. A developer split the Delivery.address field into street and city, and the tests passed. On prod, reading the old 2 million rows, Jackson either fails or silently gives null. In Kafka, the consumer breaks when it replays old messages.

Here's what I do:

  1. Adding is safe, removing is not. A new field is optional and has a default. On read we ignore unknown fields (FAIL_ON_UNKNOWN_PROPERTIES = false), so an old version can also read the new JSON.
  2. Renaming takes two steps. First we read both names (@JsonAlias("address")) and write the new one; once all the data has moved, we remove the old one.
  3. A version field plus an upcaster. When the structure changes sharply:
record DeliveryV2(String street, String city, int schemaVersion) {}

Delivery read(JsonNode n) {
    int v = n.path("schemaVersion").asInt(1);
    return switch (v) {
        case 1 -> fromV1(n);            // split the "address" string
        case 2 -> mapper.treeToValue(n, DeliveryV2.class).toDomain();
        default -> throw new IllegalStateException("noma'lum versiya " + v);
    };
}
  1. The stored shape is not the domain class. If you serialize the domain class directly, every refactoring changes the schema. Write a separate "persisted" record and a mapper: the cost is small.
  2. Tests. Keep sample JSON files from every version in src/test/resources and write a test that checks they can still be read. This is the cheapest protection.

For Kafka, Avro/Protobuf and a Schema Registry check these rules (backward/forward compatibility) automatically. With JSON, discipline and tests do that job.