Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A shared event library deserializes Envelope<T> payloads with generic types, and consumers often get maps instead of their types. How would you redesign the library API?

Consumers get maps because the library deserializes Envelope<T> with a type that has lost T to erasure, so Jackson builds LinkedHashMaps for the payload. I would redesign the API so the payload type is always explicit: consumers pass a Class or JavaType, or the envelope carries a logical type id that a registry of allowed types maps to a class, never a Java class name. On top of that come typed helper methods for common events, validation that only registered types can be created, and a test for every event type in the library.

Why this question is asked

A shared event library is used by every team that produces or consumes messages, so a confusing API in it multiplies into dozens of bugs. Here, the bug is always the same: a consumer writes Envelope<OrderPlaced> event = library.read(bytes), the code compiles, and a ClassCastException appears later because the payload is a map. Interviewers ask this scenario to see whether we can fix the cause in the API design rather than patching each consumer. In this answer, we will see why the current API produces maps, then redesign it in steps: explicit types, a type id with a registry, typed helpers, safety checks and tests.

1Why the Current API Returns Maps

The typical problem API looks generic but has no way to know what T is. Java erases generic type arguments at runtime, so inside the library T is just Object, and Jackson's natural mapping for a JSON object read as Object is a LinkedHashMap.

Java
public record Envelope<T>(String eventId, String type, Instant occurredAt, T payload) {}
// Current library method
public <T> Envelope<T> read(byte[] bytes) throws IOException {
return mapper.readValue(bytes, Envelope.class); // raw Envelope: payload is Object
}
Envelope<OrderPlaced> e = events.read(bytes); // compiles with an unchecked warning
e.payload().getClass(); // LinkedHashMap
OrderPlaced p = e.payload();
// ClassCastException: LinkedHashMap cannot be cast to OrderPlaced

Notice that the method signature promises Envelope<T> for any T the caller likes, but nothing in the call tells the library which T was meant. A variant that uses new TypeReference<Envelope<T>>() {} inside the library fails the same way, because it captures the type variable T, not the caller's class. The API itself makes the bug impossible to avoid.

2Fix 1: Require the Payload Type Explicitly

The first change is to make the payload type a required argument. The library builds a full JavaType at runtime from it, so Jackson knows exactly what to create. Accepting a JavaType as well supports generic payloads such as a list of items.

Java
public <T> Envelope<T> read(byte[] bytes, Class<T> payloadType) {
JavaType type = mapper.getTypeFactory().constructParametricType(Envelope.class, payloadType);
return mapper.readValue(bytes, type);
}
public <T> Envelope<T> read(byte[] bytes, JavaType payloadType) {
JavaType type = mapper.getTypeFactory().constructParametricType(Envelope.class, payloadType);
return mapper.readValue(bytes, type);
}
Envelope<OrderPlaced> e = events.read(bytes, OrderPlaced.class);
e.payload().getClass(); // OrderPlaced

We remove the old read(byte[]) method, first deprecating it with a clear message, because an API that can silently return maps will keep producing the bug as long as it exists. This fix works when a consumer knows which type it expects, for example one topic per event type.

3Fix 2: A Type Id in the Envelope With a Registry

Many topics carry several event types, and the consumer only learns which one it got by reading the message. For that case the envelope carries a logical type id, such as "order.placed.v1", and the library holds a registry that maps each allowed id to a payload class. The library reads the envelope header first, looks up the class, and then deserializes the payload with it.

Java
public final class EventTypeRegistry {
private final Map<String, Class<?>> types = new ConcurrentHashMap<>();
public EventTypeRegistry register(String typeId, Class<?> payload) { types.put(typeId, payload); return this; }
Class<?> resolve(String typeId) {
Class<?> c = types.get(typeId);
if (c == null) throw new UnknownEventTypeException(typeId); // never guess, never load by name
return c;
}
}
public Envelope<?> readAny(byte[] bytes) {
JsonNode root = mapper.readTree(bytes);
Class<?> payloadType = registry.resolve(root.path("type").asText());
JavaType type = mapper.getTypeFactory().constructParametricType(Envelope.class, payloadType);
return mapper.treeToValue(root, type);
}
registry.register("order.placed.v1", OrderPlaced.class).register("order.cancelled.v1", OrderCancelled.class);
events.readAny(bytes).payload(); // OrderPlaced or OrderCancelled
Step throughReading an envelope with a type registry
  1. Read the envelope headereventId, type, occurredAt
  2. Is the type id registered?e.g. order.placed.v1
    YesLook up the payload classNoReject: dead-letter the message
  3. Build JavaType Envelope<Class>constructParametricType
  4. Deserialize the payloadTyped object, never a map
  5. Dispatch to the handlerHandler for that type

5 steps in order. Play them, or step through them one at a time.

The message names a logical type; only the consumer's registry decides which class is created.

Notice that the type id is a logical name, not a Java class name. Putting class names in messages would tie every producer and consumer to the same package structure, break on refactoring, and, most importantly, let a message choose which class the consumer instantiates, which is the root of Jackson's polymorphic deserialization vulnerabilities. With a registry, the set of creatable types is closed and defined by the consumer.

4Fix 3: Typed Helper Methods for Common Events

Even a correct API can be tedious. For the ten events most teams use, the library can offer typed helpers and a handler interface, so consumers write no type plumbing at all. A sealed interface for a topic's events lets consumers switch over the cases with the compiler checking that every type is handled.

Java
public sealed interface OrderEvent permits OrderPlaced, OrderCancelled {}
public interface EventHandler<T> {
Class<T> payloadType();
void handle(Envelope<T> envelope);
}
// Library helpers
public Envelope<OrderPlaced> readOrderPlaced(byte[] bytes) { return read(bytes, OrderPlaced.class); }
// Consumer code
switch (events.readAny(bytes).payload()) {
case OrderPlaced p -> fulfil(p);
case OrderCancelled c -> refund(c);
default -> log.warn("unexpected payload");
}

The handler interface is the cleanest long-term shape: the consumer declares the type it handles, the library does all deserialization, and there is nowhere left for a raw Envelope to leak.

5Fix 4: Validate Allowed Types and Test Each Event

The registry is also a security control, so it must not have back doors. The library must never fall back to Class.forName on a type id, never enable default typing on its mapper, and never use @JsonTypeInfo with Id.CLASS on Envelope. An unknown type id is an error that sends the message to a dead-letter topic, not something to guess about.

Finally, the library ships a test for every registered event type: a stored example message per type and version, read through readAny, asserting the payload's class and key fields, and a round trip through the library's own writer. A test that iterates over the registry and fails if any type has no example keeps new events from being added without one.

Java
@ParameterizedTest
@MethodSource("registeredTypes")
void everyEventTypeDeserializesToItsClass(String typeId, Class<?> payloadType) throws Exception {
byte[] example = read("examples/" + typeId + ".json"); // fails if the example is missing
Envelope<?> e = events.readAny(example);
assertEquals(typeId, e.type());
assertInstanceOf(payloadType, e.payload()); // never a LinkedHashMap
}

6Follow-up questions

How do you roll out the new API without breaking every consumer at once?

I would add the new methods in a minor release, deprecate read(byte[]) with a message pointing to the replacements, and log a warning when it is called so we can see which services still use it. After those services have moved, the next major version removes the old method.

What about producers on older versions that do not set the type id?

For a transition period, the consumer can map a topic to a default type id when the field is missing, configured explicitly per topic. Producers are updated to set the id, and once all of them do, the default is removed so missing ids become errors.

Why not use Jackson's @JsonTypeInfo with Id.NAME on the payload instead of a custom registry?

That is a good option when all payload types share a base type the library knows, such as a sealed interface per topic, because @JsonSubTypes is then exactly the allow list. A registry is more flexible when consumers add their own types without changing the library. Both keep the set of types closed, which is the important part.

7Conclusion

In this answer, we saw that the shared library returned maps because its API let T be erased before Jackson saw it. We redesigned it so consumers pass a Class or JavaType, or the envelope carries a logical type id resolved through a registry of allowed types, never class names in messages. We added typed helpers and a handler interface for common events, refused unknown types to avoid polymorphic deserialization risks, and tested every event type in the library.

What to say in the interviewAbout 80 seconds aloud

Open with

The maps come from erasure. The library has something like public T Envelope of T read of bytes, which deserializes a raw Envelope.class, so T is Object inside and Jackson builds a LinkedHashMap for the payload; the consumer's cast fails later.

Then, if they want more

Using a TypeReference of Envelope of T inside the library does not help, because it captures the type variable. So I would change the API so that the payload type is always explicit. For topics with one event type, consumers pass a Class or a JavaType, and the library builds Envelope of that type with constructParametricType.

For topics with several event types, the envelope carries a logical type id such as order.placed.v1, and the library resolves it through a registry of allowed types to a class.

I would never put Java class names in messages, both because it couples everyone to package names and because letting a message choose the class is exactly the polymorphic deserialization risk Jackson has had so many advisories about. Unknown ids are rejected to a dead-letter topic.

Then I would add typed helpers and a handler interface where the consumer declares its payload type, deprecate the old untyped method, and ship a test per registered event type with an example message asserting the payload class.

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 "A shared event library deserializes Envelope<T> payloads with generic types, and...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/7b1377e36a/