Event Sourcing Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Sourcing runs in O(1) append time and O(n) space, in Java as in every other language.
- ✓A sealed interface Event permits Deposited, Withdrawn (Java 17) implemented by records (16) plus an exhaustive switch over the sealed type (21) gives a compiler-checked fold with no default arm.
- ✓Events are records: immutable, correct equals and hashCode for free, with a compact constructor for the invariants.
- ✓The Java trap: Generic erasure hits deserialisation hardest. mapper.readValue(json, List.class) compiles and runs and gives you a List of LinkedHashMap, so the ClassCastException fires later, inside the fold, pointing at your business logic instead of at the read; the fix is new TypeReference<List<Event>>() {}, an anonymous subclass whose supertype survives erasure.
- ✓Big-O hides a warmup cliff. C2 only inlines the monomorphic switch over the sealed hierarchy after roughly ten thousand iterations, so a benchmark that replays a stream once measures the interpreter and understates steady state by an order of magnitude.
What Event Sourcing actually is
Event Sourcing in Java: what you actually reach for
Java implementation
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(value = Deposited.class, name = "deposited"),
@JsonSubTypes.Type(value = Withdrawn.class, name = "withdrawn") })
sealed interface Event permits Deposited, Withdrawn {}
record Deposited(long cents, java.time.Instant at) implements Event {}
record Withdrawn(long cents, java.time.Instant at) implements Event {}
record Account(long cents, long version) {
// no default arm on purpose: sealed + exhaustive switch makes a new
// event type a COMPILE error here rather than a silent skip at runtime
Account apply(Event e) {
return switch (e) {
case Deposited d -> new Account(cents + d.cents(), version + 1);
case Withdrawn w -> new Account(cents - w.cents(), version + 1);
};
}
}
final class Replay {
// List<Event>.class does not exist; the anonymous subclass carries the type past erasure
static final TypeReference<java.util.List<Event>> EVENTS = new TypeReference<>() {};
static Account run(ObjectMapper m, byte[] json, Account snapshot) throws Exception {
Account acc = snapshot;
for (Event e : m.readValue(json, EVENTS)) acc = acc.apply(e);
return acc; // acc.version() is what the next append must compare-and-set on
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Event Sourcing?
A sealed interface Event permits Deposited, Withdrawn (Java 17) implemented by records (16) plus an exhaustive switch over the sealed type (21) gives a compiler-checked fold with no default arm. java.io.Serializable is disqualified for a log. The ecosystem standard is Jackson: com.fasterxml.jackson.databind.ObjectMapper with @JsonTypeInfo(use = Id.NAME, property = "type") and @JsonSubTypes to map tags to record classes, and com.fasterxml.jackson.core.type.TypeReference to read a generic list. java.time.Instant for timestamps, and a UNIQUE(stream_id, version) index surfacing as SQLIntegrityConstraintViolationException for the concurrency check.
What is the most common Java mistake when implementing Event Sourcing?
Generic erasure hits deserialisation hardest. mapper.readValue(json, List.class) compiles and runs and gives you a List of LinkedHashMap, so the ClassCastException fires later, inside the fold, pointing at your business logic instead of at the read; the fix is new TypeReference<List<Event>>() {}, an anonymous subclass whose supertype survives erasure. If you did reach for Serializable, adding one field changes the computed serialVersionUID and every historical event throws InvalidClassException. And autoboxing: a Map<String,Long> balance folded with map.get(k) + delta throws NullPointerException on the first event of a new key, and == on two boxed Longs above 127 is false.
How does Event Sourcing actually perform in Java?
Big-O hides a warmup cliff. C2 only inlines the monomorphic switch over the sealed hierarchy after roughly ten thousand iterations, so a benchmark that replays a stream once measures the interpreter and understates steady state by an order of magnitude. Jackson's reflection cost is amortised by its cached per-class serialisers after the first few objects. Every event is a heap object, but they die young so G1 or ZGC clears eden cheaply; the expense is the retained state map being promoted and driving mixed collections. Virtual threads (21+) do nothing for a CPU-bound fold, only for many I/O-blocked stream replays. Time complexity is O(1) append and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.