Versions tested. Axon Framework 5.4.2 (the newest release on Maven Central when this was written; the 5.4.2 files were published on 16 November 2026, and 5.0.0 on 18 November 2025 according to the Central file timestamps), Spring Boot 4.1.1, Java 25 (Temurin 25.0.5.1), Hibernate 7.4.5.Final, H2 2.4.240. Each version was read from the dependency resolution of the module, not from a release announcement.
Check the Maven coordinates before you copy anything. Search results still showorg.axonframework:axon-spring-boot-starter. For Axon 5 that coordinate stops at5.0.0-preview: itsmaven-metadata.xmllists nothing newer and the5.4.2pom does not exist (a request for it returns 404). The 5.x Spring Boot starter lives under a different group:org.axonframework.extensions.spring:axon-spring-boot-starter. The core modules (axon-messaging,axon-eventsourcing,axon-modelling) kept the old group, so one project ends up using both groups.
Store what happened, and calculate the rest
Look at the two designs side by side. On the left, the current state is the only thing you keep. On the right, you keep every change as an immutable event and derive the state from them.0 + 500 - 120 = 380. Nothing stores 380. When the next command arrives, the code reads the three events, adds them up, and then decides whether a withdrawal is allowed. That decision-maker is called an event-sourced entity (Axon 4 called it an aggregate).
Two words you will see throughout: a command is a request (“withdraw 120”) that can be refused; an event is a fact (“120 was withdrawn”) that already happened and cannot be refused. Commands are named as orders, events in the past tense.
Going deeper: why not just keep an audit table next to the state?
You can, and many systems do. The difference is which copy wins when they disagree. With an audit table, the state is the truth and the audit rows are a best-effort diary written beside it. With event sourcing the events are the truth and the state is a disposable calculation, so the two can never drift apart: there is only one copy.
The price is that every read of current state needs either a replay or a separately maintained read model. The rest of this post is mostly about that price.
- Axon reference: aggregate migration (4.x to 5) — how Axon 5 reshaped the old aggregate model
- Axon reference: major releases — what changed between 4.x and 5.x
The smallest thing that works: one entity, three commands
The module has one entity,BankAccount, and three commands: open an account, deposit, withdraw. First the dependencies. Note the two groups from the callout above:
<artifactId>axon-spring-boot-starter</artifactId>
<version>${axon.version}</version>
</dependency>
That is the starter dependency from pom.xml. The starter configures everything else: it finds annotated classes by component scanning, and because this module has no Axon Server connector on the classpath, it stores events in the application’s own database through JPA. There is no Axon-specific bootstrap code in Application.java.
Commands and events are plain Java records. The only Axon-specific parts are two annotations that name the account: @TargetEntityId on the command says “this command is for account x”, and @EventTag on the event says “this event belongs to account x”.
import org.axonframework.modelling.annotation.TargetEntityId;
/** Command: open an account. {@code @TargetEntityId} tells Axon which entity instance this command is for. */
public record OpenAccount(@TargetEntityId String accountId, String owner) {
}
/**
* Event: an account was opened. The {@code @EventTag} puts the tag {@code accountId=<id>} on the
* stored event. When the entity is loaded, Axon asks the store for "all events tagged with this
* entity's tag" - so the tag key here must equal the {@code tagKey} on the entity.
*/
public record AccountOpened(@EventTag(key = "accountId") String accountId, String owner) {
}
Those are OpenAccount.java and AccountOpened.java (the import is kept in the first, the comment in the second). Now the entity itself, from BankAccount.java:
@EventSourced(tagKey = "accountId")
public class BankAccount {
private final String accountId;
private long balance;
/** Called with the first AccountOpened event when an existing account is loaded. */
@EntityCreator
public BankAccount(AccountOpened first) {
this.accountId = first.accountId();
}
/** Static = creational: runs only when no entity exists for this id. */
@CommandHandler
public static void handle(OpenAccount command, EventAppender appender) {
appender.append(new AccountOpened(command.accountId(), command.owner()));
}
@CommandHandler
public void handle(Deposit command, EventAppender appender) {
if (command.amount() <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
appender.append(new MoneyDeposited(accountId, command.amount()));
}
@CommandHandler
public void handle(Withdraw command, EventAppender appender) {
if (command.amount() > balance) {
throw new IllegalStateException(
"Insufficient funds: balance " + balance + ", requested " + command.amount());
}
appender.append(new MoneyWithdrawn(accountId, command.amount()));
}
@EventSourcingHandler
void on(MoneyDeposited event) {
this.balance += event.amount();
}
@EventSourcingHandler
void on(MoneyWithdrawn event) {
this.balance -= event.amount();
}
}
Read it by the three jobs its methods do. The constructor marked @EntityCreator builds the object from the account’s first event. The @CommandHandler methods look at the current balance and either throw or append a new event; they never change a field. The @EventSourcingHandler methods change fields and do nothing else, because they also run for events written years ago and must never behave differently with time. That split — decide in one place, evolve in another — is the whole discipline of event sourcing.
Run the three commands and look at what the write side stored:
$ POST /accounts/acc-1?owner=Asha
HTTP 201 {"accountId":"acc-1","status":"opened"}
$ POST /accounts/acc-1/deposit?amount=500
HTTP 200 {"accountId":"acc-1","deposited":500}
$ POST /accounts/acc-1/withdraw?amount=120
HTTP 200 {"accountId":"acc-1","withdrawn":120}
# Stored events (aggregate_event_entry), the only thing the write side persists
seq=0 aggregate_type=accountId com.ankurm.axondemo.domain.AccountOpened {"accountId":"acc-1","owner":"Asha"}
seq=1 aggregate_type=accountId com.ankurm.axondemo.domain.MoneyDeposited {"accountId":"acc-1","amount":500}
seq=2 aggregate_type=accountId com.ankurm.axondemo.domain.MoneyWithdrawn {"accountId":"acc-1","amount":120}
# Read model, filled by the event handlers
$ GET /accounts/acc-1
HTTP 200 {"accountId":"acc-1","owner":"Asha","balance":380,"eventsApplied":3}
That is the verbatim transcript 01-command-flow.txt, written by EventSourcingTranscriptTest (which also asserts the numbers, so the post cannot go stale without the build failing). Three requests, three rows in aggregate_event_entry, sequence numbers 0, 1, 2, and a read model that arrived at 380 on its own. The read model is the subject of a later section.
Going deeper: how Axon finds the right events for an account
When Deposit(acc-1, 500) arrives, Axon needs to know which stored events belong to acc-1. Two annotations cooperate. @TargetEntityId on the command supplies the id. @EventSourced(tagKey = "accountId") on the entity says which tag key to use when building the query. Events carry that tag through @EventTag(key = "accountId"). If you leave tagKey empty, Axon falls back to the entity’s simple class name, which is the Javadoc order of resolution in @EventSourcedEntity.
The query “all events with tag accountId=acc-1” is the new idea in Axon 5. Axon 4 hard-wired one identifier per aggregate; Axon 5 expresses it as a tag query so that, with a store that supports it, one command can load events from several tags. Whether your store does is the subject of the failure section below.
Going deeper: the stored event name is the full class name
The type column in the transcript above shows com.ankurm.axondemo.domain.AccountOpened. That is the default: Axon’s @Event annotation (in org.axonframework.messaging.eventhandling.annotation) lets you pin a stable name and version instead; left empty, the name defaults to the class’s simple name and the namespace to its package. I did not test renaming or moving an event class against stored data, so treat “pin the name before the first production event” as a precaution drawn from how the name is stored, not as something this module demonstrates.
- BankAccount.java — the entity with its Javadoc
- 01-command-flow.txt — the transcript above
- Axon reference: Spring Boot integration
The entity has no table — it is rebuilt for every command
It is easy to readprivate long balance and imagine Axon saving that field. It does not. Here is every table in the database after the scenario above:
table: account_balance
table: aggregate_event_entry
table: token_entry
no table named bank_account: BankAccount.balance exists only while a command runs
That is 03-no-entity-table.txt. There is no bank_account table. The field exists only while a command runs: Axon loads the account’s events, creates a BankAccount from the first one, feeds the rest through the @EventSourcingHandler methods, hands the freshly rebuilt object to the command handler, and throws the object away.
- An account with no events does not exist. There is nothing to build the object from.
- A
staticcommand handler (handle(OpenAccount, ...)above) is creational: it runs only when the entity does not exist. That is how an account comes into being. - A non-static handler (
Deposit,Withdraw) needs an existing entity. Sent to an id with no events, it fails withEntityMissingForInstanceCommandHandlerException. - Sending the creational command to an id that does have events fails with
EntityAlreadyExistsForCreationalCommandHandlerException.
opened flag or an “is it initialised” check: existence is a property of the event stream.
Going deeper: snapshots, for accounts with long histories
Rebuilding from the first event gets slower as an account accumulates thousands of events. Axon’s answer is a snapshot: a saved copy of the entity state so that only events after it need replaying. In 5.4.2 the Javadoc of @EventSourcedEntity says you enable it declaratively by adding @Snapshotting next to the entity annotation, and that by default a snapshot is taken after every 50 events sourced. I read that in the source and did not run it here: the module’s accounts have three events, so a snapshot would never trigger, and I did not check which storage engines support it. Measure your real event counts before reaching for this — most entities never need it.
- 03-no-entity-table.txt — the table listing above
- Axon reference: aggregate migration (4.x to 5)
What happens when a command is wrong
Commands can be refused. A refused command must leave no trace in the event store — the events are the truth, and nothing true happened. Here are three refusals, each producing a different exception:$ POST /accounts/acc-1/withdraw?amount=9999
HTTP 409 {"error":"Insufficient funds: balance 380, requested 9999"}
$ POST /accounts/acc-1?owner=Again
HTTP 409 {"error":"Account already exists"}
$ POST /accounts/nobody/deposit?amount=5
HTTP 404 {"error":"No such account"}
events in the store after three rejected commands: 3 (still the 3 from the first scenario)
From 02-rejections.txt. The overdraft is rejected by your code (the IllegalStateException in handle(Withdraw, ...), mapped to HTTP 409 in AccountController.java). The other two are rejected by Axon because of the creational/instance rule from the previous section, and the controller maps them to 409 and 404. The last line is the one that matters: after three refused commands the store still holds exactly three events.
Map the Axon exceptions yourself. Left alone,EntityMissingForInstanceCommandHandlerExceptionandEntityAlreadyExistsForCreationalCommandHandlerExceptionsurface as HTTP 500 in a Spring MVC controller. While writing this module, both showed up as bare 500 responses before I added the two@ExceptionHandlermethods.
Three behaviours that surprised me
These were found by running the code, not by reading about it. Each is reproduced by broken-variants.sh, which copies the module to a temporary directory, swaps in a deliberately broken file fromsrc/broken/, and captures the real exception text.
1. An id-only @EntityCreator does not create the entity
The Javadoc of @EntityCreator says a constructor with no payload, taking at most the entity id, “will always initialize the entity, even if no events are found”. My first version of BankAccount relied on that; the reproduction in src/broken/id-only-creator keeps just the constructor part:
@EntityCreator
public BankAccount(@InjectEntityId String accountId) {
this.accountId = accountId;
}
with an ordinary, non-static handle(OpenAccount, ...). Result:
OpenAccount[accountId=v-1, owner=Asha] -> org.axonframework.modelling.entity.EntityMissingForInstanceCommandHandlerException: Entity was missing for instance command handler for command [com.ankurm.axondemo.domain.OpenAccount#0.0.1]
Deposit[accountId=v-1, amount=10] -> org.axonframework.modelling.entity.EntityMissingForInstanceCommandHandlerException: Entity was missing for instance command handler for command [com.ankurm.axondemo.domain.Deposit#0.0.1]
That is 06-variant-id-only-creator.txt. Even OpenAccount, the very first command, fails: there is no entity to run the instance handler on. The source of AnnotationBasedEventSourcedEntityFactory explains it — with no first event, a creator whose parameters are all the entity id returns null unless it is annotated @ForcedEntityCreator. Two fixes work: make the open handler static (what this module does), or mark the constructor @ForcedEntityCreator. I only ran the first; the second is from the annotation’s Javadoc.
2. The tag key is ignored when events are loaded from JPA
You would expect a typo intagKey to break loading, since the tag query would find nothing. I changed the entity to @EventSourced(tagKey = "account") while the events stay tagged accountId:
OpenAccount[accountId=v-1, owner=Asha] -> OK
Deposit[accountId=v-1, amount=10] -> OK
From 05-variant-tag-key-mismatch.txt. Nothing failed. The JPA event storage engine works in what its source calls aggregate mode: it reads the tag value as the aggregate identifier and queries by that alone; the key is stored in the aggregate_type column (you can see aggregate_type=accountId in the first transcript). The lesson is not “keys do not matter” — it is that this JPA store cannot tell you that you got them wrong, so a mismatch would not be flagged here. I did not test any other store.
3. The JPA store allows exactly one tag per event
Axon 5’s headline idea is that an event can carry several tags, so one command can load events across several entities. I put a second@EventTag on MoneyDeposited:
OpenAccount[accountId=v-1, owner=Asha] -> OK
Deposit[accountId=v-1, amount=10] -> org.axonframework.eventsourcing.eventstore.TooManyTagsOnEventMessageException: An Event Storage engine in Aggregate mode does not support multiple tags per event
From 07-variant-two-tags.txt. Opening worked (that event has one tag); the first deposit was refused at append time with TooManyTagsOnEventMessageException. In the source, the JPA engine is the “aggregate-based” one and validates that no event has more than one tag. So the default setup behaves like classic one-entity-per-command event sourcing. Whether the multi-tag capability is available on another store is something the Axon documentation covers and I have not verified here.
The fingerprint of each failure. Entity was missing for instance command handler on the very first command → your creator needsstaticor@ForcedEntityCreator. TooManyTagsOnEventMessageException → one tag per event on the JPA store. Everything works but a tag key looks wrong → the JPA store is not checking it.
Going deeper: why the JPA store behaves this way
The JPA engine in axon-eventsourcing is named AggregateBasedJpaEventStorageEngine and its table is aggregate_event_entry. Its limits (one tag, key stored as the aggregate type, value as the identifier) are those of a store keyed by aggregate. The Spring Boot starter configures it through JpaEventStoreAutoConfiguration when you have not defined an event store of your own and no Axon Server connector has provided one.
- broken-variants.sh — reproduces all three variants
- src/broken/ — the deliberately broken sources, outside the build
- Axon reference: Spring Boot integration — storage options and the Axon Server fallback
Reading the data back: a projection builds the read model
You cannot answer “what is the balance of acc-1?” by querying an event store without replaying it, and a web page should not do that on every refresh. So a second component listens for events and maintains an ordinary table shaped for reading. Axon calls the listener an event handler and the thing running it an event processor.@Component
public class AccountBalanceProjection {
private static final Logger log = LoggerFactory.getLogger(AccountBalanceProjection.class);
private final JdbcClient jdbc;
public AccountBalanceProjection(JdbcClient jdbc) {
this.jdbc = jdbc;
}
@EventHandler
void on(AccountOpened event) {
log.info("projection: AccountOpened {}", event.accountId());
jdbc.sql("INSERT INTO account_balance (account_id, owner, balance, events_applied) VALUES (?, ?, 0, 1)")
.params(event.accountId(), event.owner())
.update();
}
@EventHandler
void on(MoneyDeposited event) {
log.info("projection: MoneyDeposited {} +{}", event.accountId(), event.amount());
jdbc.sql("UPDATE account_balance SET balance = balance + ?, events_applied = events_applied + 1 WHERE account_id = ?")
.params(event.amount(), event.accountId())
.update();
}
@EventHandler
void on(MoneyWithdrawn event) {
log.info("projection: MoneyWithdrawn {} -{}", event.accountId(), event.amount());
jdbc.sql("UPDATE account_balance SET balance = balance - ?, events_applied = events_applied + 1 WHERE account_id = ?")
.params(event.amount(), event.accountId())
.update();
}
/** Called once when the processor is reset for a replay, before the first old event arrives. */
@ResetHandler
void reset() {
int rows = jdbc.sql("DELETE FROM account_balance").update();
log.info("projection: reset, cleared {} rows", rows);
}
}
That is the class body of AccountBalanceProjection.java, without the imports. It is a normal Spring bean with @EventHandler methods and a JdbcClient; nothing in it knows about replays, tokens or threads. The processor that feeds it is declared in one small bean:
@Configuration
public class ProjectionConfig {
public static final String PROCESSOR = "account-balance";
@Bean
EventProcessorDefinition accountBalanceProcessor() {
return EventProcessorDefinition.pooledStreaming(PROCESSOR)
.assigningHandlers(d -> AccountBalanceProjection.class.equals(d.beanType()))
.notCustomized();
}
}
From ProjectionConfig.java. By default Axon would put a handler in a processor named after its package; naming one explicitly just makes logs and the replay code readable. The processor is a pooled streaming processor: it reads the event store in order, hands events to your handlers on a thread pool, and writes its position into token_entry — that table appeared in the listing earlier. After a restart it continues from the saved position instead of starting over.
The read model for acc-1 appeared at the end of the first transcript: {"balance":380,"eventsApplied":3}. The transcript test waits for eventsApplied to reach 3 before reading it, and that waiting is not decoration: the processor runs asynchronously, so a GET issued immediately after a POST can see the old value. That is eventual consistency, and it is the cost of separating the two sides.
Going deeper: the processor defaults, and what to tune
From the source of EventProcessorProperties (5.4.2): a processor defaults to the pooled streaming mode, 16 segments on first start, 4 threads, and batch size 1. The log of this module confirms the segment count with the line “Processor [account-balance]. Initializing (16) segments”. Segments are how Axon splits one processor so several threads (or several application instances) can work in parallel while events for the same sequence still arrive in order. You override them under axon.eventhandling.processors.<name>.* in application.properties.
Two things worth knowing before production. First, events are spread over segments handled by several threads (the log of the test run shows the handlers executing on threads -0 to -3), so never assume global ordering across accounts; per-account ordering is Axon’s default sequencing policy, which I did not test here. Second, the insert in on(AccountOpened) would fail on the primary key if an event were ever delivered twice; an upsert is the safer shape for anything beyond a demo.
- AccountBalanceProjection.java — the handlers
- ProjectionConfig.java — the named processor
- application.properties — storage and polling settings
- Pairs well with the earlier plain-Spring take on read models: CQRS in Spring Boot Without a Framework
Lose the read model, get it back: replays
This is the payoff. Because the events are the truth, any read model is disposable. Drop the table, reset the processor to the start, and it rebuilds itself.StreamingEventProcessor.resetTokens() is documented to fail unless the caller has stopped the processor first, because a reset must claim every token. The @ResetHandler method in the projection, which runs once during the reset, empties the table so the old rows do not mix with the rebuilt ones. The code that drives it, from ReplayService.java:
public void replay() throws Exception {
StreamingEventProcessor processor = configuration.getComponents(StreamingEventProcessor.class)
.entrySet().stream()
.filter(e -> e.getKey().contains(ProjectionConfig.PROCESSOR))
.map(java.util.Map.Entry::getValue)
.findFirst()
.orElseThrow(() -> new IllegalStateException(
"No streaming processor named " + ProjectionConfig.PROCESSOR));
if (!processor.supportsReset()) {
throw new IllegalStateException("Processor does not support reset");
}
processor.shutdown().get(10, TimeUnit.SECONDS);
processor.resetTokens().get(10, TimeUnit.SECONDS);
processor.start().get(10, TimeUnit.SECONDS);
}
Wired to POST /admin/replay in ReplayController.java (protect or delete that endpoint in a real service). The test deletes every row to simulate a lost read model, shows that reads now return 404 while the events are untouched, runs the replay and reads the accounts again:
# Simulate a lost or corrupted read model: DELETE FROM account_balance (2 rows)
$ GET /accounts/acc-1
HTTP 404
events still in the store: 5
$ POST /admin/replay
HTTP 200 {"status":"replay started"}
# After the replay
$ GET /accounts/acc-1
HTTP 200 {"accountId":"acc-1","owner":"Asha","balance":380,"eventsApplied":3}
$ GET /accounts/acc-2
HTTP 200 {"accountId":"acc-2","owner":"Ravi","balance":40,"eventsApplied":2}
events in the store after the replay: 5 (a replay reads events, it never writes them)
That is 04-replay.txt. Two accounts came back with the right balances (380 and 40), and the number of stored events is the same before and after: five. The replay read them; it wrote nothing.
A replay re-runs your handlers, all of them. This module’s handler only updates a table, so running it twice is harmless. A handler that sends an email or calls a payment API would do that again for every historic event. The Axon 5 jar ships@AllowReplayand@DisallowReplayannotations (inorg.axonframework.messaging.eventhandling.replay.annotation) for exactly this, and aReplayStatusyou can inspect. I have not exercised them in this module; check how they apply to your handler before replaying a processor that has side effects.
Going deeper: how the processor was found, and a Spring Boot 4 detail
The Spring Boot starter exposes an AxonConfiguration bean, and getComponents(StreamingEventProcessor.class) returns a map of the streaming processors by name. ReplayService picks the entry whose key contains account-balance; I matched on contains because I did not read the exact key format from the source, only observed that it works. Call supportsReset() first: it is false if a handler on the processor forbids resets.
Also in the source of EventProcessingAutoConfiguration: processor settings are bound through the Spring Environment rather than an injected properties object, with a comment that Boot 4 produced a cyclic context when the application configures Web MVC (Axon issue 4010).
- ReplayService.java — stop, reset, start
- EventSourcingTranscriptTest.java — the test that produces every transcript
- run-all.sh — regenerates every file in output/
Should you do this at all?
Honestly: usually not, and the cost is not where people expect. Event sourcing earns its keep when the history is the product: ledgers, audit-heavy domains, anything where “what did we believe at 3 pm last Tuesday” is a real question. For an ordinary CRUD service it adds an eventually consistent read side, a replay story, event-versioning obligations that last as long as the data does, and a framework that must stay on your classpath because your data cannot be read without it. This module needed fourteen Java classes and two tables beyond the event table for a bank account with three commands. Add the cost of explaining it to the next engineer before you add the first@EventSourced.
If you only want separate read and write models, you do not need event sourcing for that: the plain-Spring version in the CQRS post does it with no event store. And if what you really need is reliable publication of events to other services, look at the outbox pattern first.
Run it yourself
$ cd spring-modulith-demo/axon-event-sourcing
$ ./scripts/run-all.sh
That runs the test suite (which writes output/01 to 04) and the three broken variants (05 to 07). ./scripts/run.sh starts the application on port 8080 if you want to curl it yourself; GET /accounts/{id}/events prints the raw stored events and is a diagnostic you should delete before shipping. There is deliberately no docs/ folder: the depth lives in the collapsible sections above, next to the paragraph each one extends. All source: axon-event-sourcing.
Further reading
- Companion module: spring-modulith-demo/axon-event-sourcing
- CQRS in Spring Boot Without a Framework: Separate Read Models and Projections (ankurm.com)
- Debezium CDC with Spring Boot, and when to prefer the outbox (ankurm.com)
- Axon reference: Spring Boot integration
- Axon reference: aggregate migration (4.x to 5)
- Axon reference: major releases
No Comments yet!