Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Events between services use polymorphic JSON with type information. How would you design this so producers and consumers can evolve independently?

I would identify event types by stable logical names with Id.NAME, never Java class names, so producers can rename and move classes freely. Consumers ignore unknown fields and handle unknown event types gracefully, for example by logging and skipping them, so producers can add things first. Event types and their fields are documented in a schema registry or written contracts, every change is additive and never changes the meaning of an existing field or type, and CI tests compatibility against previous versions of the contracts and real sample payloads.

Why this question is asked

In an event-driven system, producers and consumers are deployed by different teams on different days. A producer that adds a new event type on Tuesday cannot wait for twelve consumers to release first, and a consumer cannot stop processing because a message contains a field it does not know. Polymorphic JSON, where a type field decides the class, makes this both easier and riskier: easier because one topic can carry several event types, riskier because an unknown type or a class name in the payload can stop a consumer cold. Interviewers ask this design question to see whether we can keep the two sides independent. In this answer, we will look at the event envelope and type names, make consumers tolerant, write down the contracts, define the evolution rules, and test compatibility in CI.

1Logical Type Names, Never Class Names

The type id in an event is part of the public contract, so it must be something we can keep forever. A logical name such as order.paid is chosen once and documented. A class name such as com.acme.orders.events.v2.OrderPaidEvent changes whenever someone refactors a package, and it ties every consumer to the producer's code structure. It is also a security risk if consumers let it pick the class to create.

A related trap is easy to miss. Spring Kafka's JSON serializer adds a header with the producer's fully qualified class name by default, and the matching deserializer can use it to pick the target class from a list of trusted packages. That works only while both sides share the same classes. For independent teams, we disable those type headers or map them to logical names with the type mapping setting, and let the consumer decide its own target types (check the property names for your Spring Kafka version).

Java
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true, // fallback can read "type"
defaultImpl = UnknownOrderEvent.class) // unknown types do not fail
@JsonSubTypes({
@JsonSubTypes.Type(value = OrderPaid.class, name = "order.paid"),
@JsonSubTypes.Type(value = OrderShipped.class, name = "order.shipped")
})
public interface OrderEvent { String eventId(); Instant occurredAt(); }
@JsonIgnoreProperties(ignoreUnknown = true)
public record OrderPaid(String eventId, Instant occurredAt, String orderId, Money amount) implements OrderEvent {}
// {"type":"order.paid","eventId":"e-1","occurredAt":"2024-05-01T08:30:00Z","orderId":"ord-42",
// "amount":"12.50 EUR","paymentProvider":"acme-pay"} new field -> ignored by this consumer

2Consumers That Tolerate What They Do Not Know

The tolerant reader principle says a consumer should read only what it needs and ignore the rest. For fields, Spring Boot's ObjectMapper already ignores unknown properties, and @JsonIgnoreProperties(ignoreUnknown = true) makes it explicit on the event classes, so it also holds with a differently configured mapper.

For types, a consumer that only handles order.paid should not crash on order.refunded. With defaultImpl, an unknown type becomes an UnknownOrderEvent. The listener logs it with the type name, increments a metric, and acknowledges it. The reason this matters so much with Kafka is ordering: if a consumer throws on a message it can never parse, it either retries it forever, blocking the partition behind it, or sends it to a dead-letter topic, which for a perfectly valid new event type is just noise. Skipping a known-unknown is the correct behaviour.

Java
@KafkaListener(topics = "orders")
void on(OrderEvent event) {
switch (event) {
case OrderPaid p -> billing.recordPayment(p);
case OrderShipped s -> notifications.shipped(s);
case UnknownOrderEvent u -> {
log.info("Skipping unknown order event type {}", u.type()); // consumer not yet updated
unknownEvents.increment(); // a rise means: update me
}
default -> throw new IllegalStateException("Unhandled " + event);
}
}
Step throughA producer adds a type before the consumer knows it
Producer v2Kafka topicConsumer v1
order.paid (with new field paymentProvider)
deliver
OrderPaid read, unknown field ignored
order.refunded (new type)
deliver
UnknownOrderEvent: log, count, acknowledge

6 messages in order. Play them, or step through them one at a time.

Old consumers keep working while new ones are rolled out.

Notice that skipping is only right for types the consumer has no business with. If the consumer must process every event, for example an audit log, an unknown type is a signal to update the consumer quickly, and the metric makes that visible without stopping the flow.

3Writing Down the Contracts

Independence needs a shared source of truth that is not anyone's code. One option is a schema registry, a service that stores a schema for each event type and version and checks new versions against compatibility rules before they are accepted; Confluent Schema Registry supports JSON Schema as well as Avro and Protobuf. Another is a contracts repository with JSON Schema or AsyncAPI documents, reviewed like code. Each event type has its name, its fields with types and meanings, which fields are required, and an example payload.

The documentation is also where meaning lives. amount in order.paid is the gross amount including tax, in the order's currency. That sentence is part of the contract, because a producer could change the meaning without changing the type, and no schema check would notice.

4Additive Changes Only

The rules for evolution follow from the tolerant reader. Producers may add new optional fields and new event types. They never remove a field that consumers may read, never rename a field or a type, never change a field's type, and never change a field's meaning. If the meaning must change, for example amount should now exclude tax, we add a new field (netAmount) or a new event type, keep the old one for a deprecation period, and remove it only when no consumer reads it.

The order of rollout also follows: a consumer that must understand a new type is deployed first, then the producer starts sending it. Because consumers skip unknown types, it is safe if the order slips, but planning it this way means no events are skipped that someone needed.

Is this change safe for independent consumers?
ChangeSafe?How to do it instead
Add an optional fieldYesconsumers ignore it until they need it
Add a new event typeYesconsumers map it to the unknown fallback
Rename a field or type nameNoadd the new one, deprecate the old
Change a field's typeNonew field with the new type
Change a field's meaningNonew field or new event type
Remove a fieldOnly after deprecationcheck that no consumer reads it
Every unsafe change has an additive alternative.

5Testing Compatibility in CI

Rules only hold if a build fails when they are broken. On the producer side, CI checks the new schema against the previous versions in the registry or contracts repository, using the registry's compatibility check (for example backward and forward compatibility) or a JSON Schema diff tool, and fails on a removed or retyped field. On the consumer side, CI keeps a folder of real sample payloads for every event type and version, including future-looking ones with extra fields and an unknown type, and asserts the consumer reads them all. When a producer adds a new version, its samples are added to the shared folder, so every consumer's next build tests against them.

Java
@ParameterizedTest
@MethodSource("samplePayloads") // contracts/order-events/*.json, all versions
void consumerReadsEveryKnownPayload(Path sample) throws Exception {
OrderEvent e = mapper.readValue(Files.readString(sample), OrderEvent.class);
assertThat(e.eventId()).isNotBlank();
}
@Test
void unknownTypeBecomesFallback() throws Exception {
OrderEvent e = mapper.readValue("{\"type\":\"order.refunded\",\"eventId\":\"e-9\"}", OrderEvent.class);
assertThat(e).isInstanceOf(UnknownOrderEvent.class);
}

6Follow-up questions

Should the event carry a version number?

It can help, for example a schemaVersion field or a version in the type name such as order.paid.v2 for a genuinely different event. With strictly additive changes, most events never need a new version. A new version, as a new type name, is the tool for incompatible changes, and both versions are published side by side during the migration.

What should UnknownOrderEvent contain?

At least the type name and the common envelope fields such as eventId and occurredAt, so the consumer can log and correlate it; the type name only reaches it when @JsonTypeInfo has visible = true, as in the example. It ignores all other properties. Some teams also keep the raw JSON, so the event can be reprocessed after the consumer is updated.

Why not use Avro or Protobuf instead of JSON?

They give stronger schema enforcement and compact payloads, and the same evolution rules apply: add optional fields, never reuse or retype them. JSON with JSON Schema is easier to read and debug and works well when payloads are small. The design choices in this answer, logical type names, tolerant consumers, a registry and compatibility tests, matter more than the format.

7Conclusion

In this answer, we designed polymorphic events so producers and consumers can evolve independently. Event types are identified by logical names with Id.NAME, and class-name type headers are turned off. Consumers ignore unknown fields and map unknown types to a fallback that is logged, counted and skipped instead of blocking a partition. Contracts live in a schema registry or a reviewed contracts repository that also records meaning, every change is additive with new fields or types for new meanings, and CI checks schemas against previous versions and runs consumers against sample payloads from every version.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd start with the type id: a logical name like order.paid with Id.NAME and @JsonSubTypes, never a class name, because names are a contract we can keep while classes get refactored.

Then, if they want more

I'd also turn off Spring Kafka's default class-name type headers, or map them to logical names, so consumers aren't tied to the producer's packages. Then consumers must be tolerant readers. Unknown fields are ignored, which Boot does by default and I'd make explicit with @JsonIgnoreProperties.

Unknown types go to a defaultImpl like UnknownOrderEvent, which the listener logs, counts and acknowledges, instead of throwing and blocking the partition or flooding a dead-letter topic with valid events. The contracts live in a schema registry or a reviewed contracts repository with JSON Schema or AsyncAPI, including what each field means, like whether amount includes tax.

Evolution is additive only: new optional fields and new types are fine; renaming, retyping, removing or changing meaning is not, and each of those has an additive alternative, a new field or a new event type with a deprecation period. Consumers that need a new type deploy first.

And CI enforces it: producers check new schemas against previous versions, and consumers run against a shared folder of sample payloads from every version, plus one with an unknown type, so a breaking change fails a build instead of production.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Events between services use polymorphic JSON with type information. How would you design...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/950ff481ea/