Event Sourcing CQRS Java Implementation Without Hype
Implement event sourcing and CQRS in Java: an event store, aggregates rebuilt from events, projections for reads, snapshots and when the cost is justified.

Event sourcing and CQRS get described together, and they are separate ideas that happen to fit. Event sourcing stores the history of changes to an entity as a sequence of immutable events, and derives the current state by replaying them. CQRS splits the model that handles commands from the models that answer queries. Each solves a real problem and each brings costs that are easy to underestimate. This post implements both in plain Java with records on JDK 25, with no framework, so the mechanics are visible, and then lists the costs honestly. For a framework that packages the pattern, see Axon.
Events and an aggregate
An event is a fact in the past tense that cannot be changed. Records are the natural representation:
public sealed interface AccountEvent {
String accountId();
record Opened(String accountId, String owner) implements AccountEvent {}
record Deposited(String accountId, long cents) implements AccountEvent {}
record Withdrawn(String accountId, long cents) implements AccountEvent {}
record Closed(String accountId) implements AccountEvent {}
}The aggregate decides whether a command is allowed, and returns events. It does not store state in the database; it rebuilds its state from events.
public final class Account {
private String id;
private long balance;
private boolean open;
public static Account replay(List<AccountEvent> history) {
var account = new Account();
history.forEach(account::apply);
return account;
}
public List<AccountEvent> withdraw(long cents) {
if (!open) throw new IllegalStateException("account is closed");
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
if (balance < cents) throw new IllegalStateException("insufficient funds");
return List.of(new AccountEvent.Withdrawn(id, cents));
}
private void apply(AccountEvent event) {
switch (event) {
case AccountEvent.Opened e -> { id = e.accountId(); open = true; }
case AccountEvent.Deposited e -> balance += e.cents();
case AccountEvent.Withdrawn e -> balance -= e.cents();
case AccountEvent.Closed e -> open = false;
}
}
}There are two kinds of method, and keeping them apart is the discipline. A command method validates against the current state and returns the events that result; it does not change the state. The apply method changes the state and never validates or throws, because it runs for every historical event, including those recorded under rules that no longer hold. A change to a business rule must not make an old stream fail to load. Because AccountEvent is sealed, the switch is exhaustive: adding an event type is a compile error until apply handles it.
The event store
The store appends events to a stream per aggregate and reads them back in order. The one rule it must enforce is optimistic concurrency: two commands that both load version 7 must not both append version 8.
create table event (
stream_id varchar(64) not null,
version integer not null,
type varchar(100) not null,
payload jsonb not null,
created_at timestamptz not null default now(),
primary key (stream_id, version)
);void append(String streamId, int expectedVersion, List<AccountEvent> events) {
int version = expectedVersion;
for (AccountEvent e : events) {
jdbc.update("insert into event(stream_id, version, type, payload) values (?,?,?,?::jsonb)",
streamId, ++version, e.getClass().getSimpleName(), json.write(e));
}
}The primary key on (stream_id, version) is the guard: a second writer inserting the same version gets a unique violation, which the application reports as a conflict and retries by reloading. No lock is held while the command is being decided. A command handler loads the stream, replays it into an Account, calls the command method, and appends the returned events with the expected version, all in one transaction. Staleness conflicts are expected, as in the locking problems in optimistic locking failures. The unit that must stay consistent defines the aggregate, which is the idea from aggregates in domain-driven design; keep it small, since all its events load together.
CQRS: separate read models
Queries over an event stream are awkward: "all accounts with a balance over 1,000" would replay every stream. CQRS accepts that and builds a separate model for reading, updated from the events:
@Component
class BalanceProjection {
void on(AccountEvent event) {
switch (event) {
case AccountEvent.Opened e -> jdbc.update("insert into balance(id, owner, cents) values (?,?,0)", e.accountId(), e.owner());
case AccountEvent.Deposited e -> jdbc.update("update balance set cents = cents + ? where id = ?", e.cents(), e.accountId());
case AccountEvent.Withdrawn e -> jdbc.update("update balance set cents = cents - ? where id = ?", e.cents(), e.accountId());
case AccountEvent.Closed e -> jdbc.update("update balance set closed = true where id = ?", e.accountId());
}
}
}The projection is an ordinary table shaped for a particular query, and a service can have several: one for the account list, one for monthly statements, one for a fraud search. The read side can use a different database, such as a search index. Each projection is derived data: delete it, replay all events, and it is rebuilt, which is also how you add a new view of old history. The write side stays small and focused on rules.
The projection runs after the event is stored, usually asynchronously, by polling the event table or consuming a message. That makes the read model eventually consistent: a user who makes a deposit and reloads the page may not see it yet. Handle that in the design, by returning the new state from the command, or by the interface refreshing until the projection catches up. Projection handlers must be idempotent, since delivery is at-least-once; record the last processed event position with the projection data in one transaction, as described in idempotent consumers.
Snapshots
Replaying a stream of fifty thousand events on every command is slow. A snapshot stores the aggregate's state at a version; loading reads the latest snapshot and replays only the events after it. Take a snapshot every few hundred events, and treat snapshots as a disposable cache: if the format changes, discard them and replay. Most aggregates never need snapshots, because a well-bounded aggregate has dozens of events, not thousands. A stream that grows without bound is a sign the aggregate is modelled too coarsely.
The costs
These are the reasons to hesitate, in the order teams meet them. Event schema evolution: events are stored forever, so changing a field means writing an upcaster that converts old events when reading, or versioned types. Plan for it from the first event. Eventual consistency in the interface, as above. The learning curve and the volume of code: a simple CRUD screen takes several classes. Debugging and operations: the database no longer shows current state in one table, so you need tools to read streams and to monitor projection lag. Privacy: deleting a person's data from an immutable log is hard, and the usual answers are encrypting personal fields with a per-subject key that can be destroyed, or keeping personal data out of events. Reporting that spans aggregates needs projections for each question. And the temptation to publish internal events as the public contract; events inside a service and events between services are different things, with different compatibility rules.
The benefits are real where they apply: a complete audit trail by construction, the ability to answer "what did this look like last Tuesday", new read models built from old history, and a natural fit with message-driven integration and with sagas. Use it for domains where the history is the product, such as ledgers, orders with a long life cycle and compliance-heavy workflows. For a typical CRUD application a normal relational model with an audit table is simpler. The Java 21 and later features that make the code compact, sealed types, records and pattern matching, are covered in the modern Java guide.
Where this does not apply
Do not apply event sourcing to every entity in a system; apply it to the aggregates that earn it, and keep the rest ordinary. CQRS can be used without event sourcing, with a separate read table updated in the same transaction as the write. The patterns are described by Martin Fowler in Event Sourcing and in Microsoft's CQRS pattern guide.


