Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Event Sourcing Implementation in Java

19 min readadvanced
Website QA and SEO audits

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 keeps the append-only log of what happened as the system of record and derives current state by folding that log with a pure function, state = events.reduce(apply, seed). Nothing overwrites; a correction is another event. The interesting constraint is that the log outlives both the process and the code that wrote it, so every event you ever append becomes a permanent input to a function you have not written yet. That forces three things the naive version skips: snapshots so replay does not grow unbounded, upcasting so a 2019 payload still folds under 2026 code, and a compare-and-set on the stream version so two writers cannot both append version 8. The eight languages diverge because those three things are serialisation and closed-set problems, not algorithm problems. Rust, Swift and Java can make the event set a real sum type and let the compiler prove the fold is exhaustive; C# can model the same shape with records but has no closed union, so a switch expression over it cannot be proven exhaustive and a discard arm guarding a runtime throw stays mandatory; Go and Python and JavaScript must dispatch on a tag string; TypeScript can express the union but erases it before the bytes arrive.

Event Sourcing in Java: what you actually reach for

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.

Java implementation

Events are records: immutable, correct equals and hashCode for free, with a compact constructor for the invariants. Reviewers reject a default arm in the fold, because sealed plus exhaustive switch is precisely what turns adding an event type into a compile error at every call site. They reject Serializable on an event, reject checked exceptions escaping apply, and insist the aggregate's version field comes from the log rather than a field the writer increments.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(1) append

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. The asymptotic cost is the same in every language, O(1) append time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Event Sourcing between languages.

Real-World Applications

Event Sourcing is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Event Sourcing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Event Sourcing appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Event Sourcing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Event Sourcing to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.