Getting started
This guide builds a bank account aggregate and handles commands against the in-memory backend. The same code runs unchanged on PostgreSQL and KurrentDB.
Model the domain
An aggregate has commands, events and state. Commands ask for something. Events record what happened. State is what you get by folding the events in order.
sealed interface AccountCommand {
data class Open(val owner: String) : AccountCommand
data class Deposit(val amount: Long, val reference: String? = null) : AccountCommand
data class Withdraw(val amount: Long) : AccountCommand
data class SendTransfer(val toAccountId: String, val amount: Long) : AccountCommand
}
sealed interface AccountEvent {
data class Opened(val owner: String) : AccountEvent
data class Deposited(val amount: Long, val reference: String?) : AccountEvent
data class Withdrawn(val amount: Long) : AccountEvent
data class TransferSent(val toAccountId: String, val amount: Long) : AccountEvent
/** Records the idempotency identity of the command that produced the events before it. */
data class IdempotencyApplied(override val idempotency: CommandIdempotency) :
AccountEvent, IdempotencyEvent
/** A stored event the domain no longer acts on. It still occupies its stream version. */
data object Retired : AccountEvent
}
data class AccountState(
override val aggregateId: String,
val owner: String,
val balance: Long,
val idempotency: CommandIdempotencyTracker = CommandIdempotencyTracker(),
) : AggregateState
State implements AggregateState, which only requires the aggregate's ID. The idempotency tracker and the IdempotencyApplied and Retired events are explained in Idempotency and Events and codecs; you can leave them out of a first aggregate.
Decide
A decider turns a command into events, or refuses it. decideFirst runs when the stream does not exist yet and must produce at least one event. decideExisting runs against current state and may also return NoChange.
object AccountDecider : AggregateDecider<AccountState, AccountCommand, AccountEvent> {
override suspend fun decideFirst(command: AccountCommand): FirstEventDecision<AccountEvent> =
when (command) {
is AccountCommand.Open -> FirstEventDecision.Accepted(AccountEvent.Opened(command.owner))
else -> FirstEventDecision.Rejected("Account is not open")
}
override suspend fun decideExisting(
currentState: AccountState,
command: AccountCommand,
): EventDecision<AccountEvent> =
when (command) {
is AccountCommand.Open ->
if (command.owner == currentState.owner) EventDecision.NoChange
else EventDecision.Rejected("Account is already open for another owner")
is AccountCommand.Deposit ->
if (command.amount <= 0) EventDecision.Rejected("Deposit must be positive")
else accepted(AccountEvent.Deposited(command.amount, command.reference))
is AccountCommand.Withdraw ->
if (command.amount > currentState.balance) EventDecision.Rejected("Insufficient funds")
else accepted(AccountEvent.Withdrawn(command.amount))
is AccountCommand.SendTransfer ->
if (command.amount > currentState.balance) EventDecision.Rejected("Insufficient funds")
else accepted(AccountEvent.TransferSent(command.toAccountId, command.amount))
}
private fun accepted(event: AccountEvent) = EventDecision.Accepted(listOf(event))
}
Keep deciders free of side effects. They must not change state, call other services or read the clock. Resolve anything external before you build the command, and put the result in it.
Evolve
An evolver applies one committed event to state. It must be deterministic, because it runs every time the aggregate is loaded.
object AccountEvolver : AggregateEvolver<AccountState, AccountEvent> {
override fun evolveStep(
currentState: AccountState?,
committedEvent: CommittedEvent<AccountEvent>,
): AccountState {
val event = committedEvent.event
if (currentState == null) {
check(event is AccountEvent.Opened) { "An account stream must start with Opened" }
return AccountState(committedEvent.aggregateId, owner = event.owner, balance = 0)
}
return when (event) {
is AccountEvent.Opened -> error("Account ${currentState.aggregateId} was opened twice")
is AccountEvent.Deposited -> currentState.copy(balance = currentState.balance + event.amount)
is AccountEvent.Withdrawn -> currentState.copy(balance = currentState.balance - event.amount)
is AccountEvent.TransferSent ->
currentState.copy(balance = currentState.balance - event.amount)
is AccountEvent.IdempotencyApplied ->
currentState.copy(idempotency = currentState.idempotency.apply(event.idempotency))
AccountEvent.Retired -> currentState
}
}
}
The first event of a stream arrives with a null state. The account ID comes from the committed event, not from the event payload, so events do not need to repeat it.
Name the events and define the aggregate
Every event class gets a stable name that is stored with the event. Stores use the names to filter and route, so they are declared separately from the classes and never derived from them. Renaming a class then changes nothing on disk.
val AccountEventTypes =
EventTypeNames.ForAggregate(
aggregate = "Account",
events =
mapOf(
AccountEvent.Opened::class to "AccountOpened",
AccountEvent.Deposited::class to "AccountDeposited",
AccountEvent.Withdrawn::class to "AccountWithdrawn",
AccountEvent.TransferSent::class to "AccountTransferSent",
AccountEvent.IdempotencyApplied::class to "AccountIdempotencyApplied",
// Keeps the name its events were stored under, so subscriptions still deliver them.
AccountEvent.Retired::class to "AccountFlagged",
))
val AccountDefinition =
AggregateDefinition(
decider = AccountDecider,
evolver = AccountEvolver,
eventTypes = AccountEventTypes,
eventCodec = AccountEventCodec,
idempotency =
AggregateIdempotency(
tracker = AccountState::idempotency,
event = AccountEvent::IdempotencyApplied,
),
)
AggregateDefinition is the single description of the aggregate. Services, repositories, subscriptions and snapshot tooling are all built from it. The eventCodec is covered in Events and codecs.
Handle commands
Commands travel in a CommandEnvelope, which adds the aggregate ID, a command ID, and optional correlation and causation references. A small helper keeps call sites short:
fun AccountCommand.forAccount(
accountId: String,
idempotency: CommandIdempotency? = null,
correlationId: CorrelationId? = null,
causedBy: EventReference? = null,
): CommandEnvelope<AccountCommand> =
CommandEnvelope(
command = this,
aggregateId = accountId,
commandId = CommandId(Uuid.random().toString()),
correlationId = correlationId,
causedBy = causedBy,
idempotency = idempotency,
)
A backend provider builds the service. InMemoryProvider needs no setup:
val accounts = InMemoryProvider().aggregateService(AccountDefinition)
accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1"))
accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1"))
val result = accounts.handle(AccountCommand.Withdraw(30).forAccount("acc-1"))
Handling a command for an ID with no stream creates the aggregate through decideFirst. A stream's first event has version 0, so after these three commands the account is at version 2 with a balance of 70.
10 November 2026