Skip to Content
Course content

245: Practice Exercise: Building a Simple Event Sourcing System

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually represent the events so they stay type-safe?

When you're building an event sourcing system, you aren't saving the current state of an object—you're saving the history of what happened to it. In Kotlin, the absolute best way to do this is with a sealed class. Why? Because it forces you to handle every possible event type when you're reconstructing your state, and the compiler will scream at you if you forget one.

Let's use a Digital Wallet as our example. We don't just store the balance; we store every single transaction that ever occurred.

sealed class WalletEvent {
    data class AccountOpened(val accountId: String, val owner: String) : WalletEvent()
    data class MoneyDeposited(val amount: Double) : WalletEvent()
    data class MoneyWithdrawn(val amount: Double) : WalletEvent()
    data class AccountClosed(val reason: String) : WalletEvent()
}

By using a sealed class, we've created a closed hierarchy. I've found that this prevents the "mystery event" bug where some developer adds a new event type in a different package and the state-reconstruction logic just silently ignores it.

How do I "replay" these events to get the current state without a mess of if-else blocks?

This is where the magic happens. To get the current state, you take your initial state and "fold" the list of events over it. Think of it like a snowball rolling down a hill; each event adds a layer of data to the state.

I highly recommend creating a separate WalletState data class to hold the current snapshot. Then, use a reduce or fold operation. It keeps the logic clean and functional.

data class WalletState(
    val accountId: String = "",
    val balance: Double = 0.0,
    val isOpen: Boolean = false
)

fun applyEvents(events: List<WalletEvent>): WalletState {
    return events.fold(WalletState()) { currentState, event ->
        when (event) {
            is WalletEvent.AccountOpened -> currentState.copy(
                accountId = event.accountId, 
                isOpen = true
            )
            is WalletEvent.MoneyDeposited -> currentState.copy(
                balance = currentState.balance + event.amount
            )
            is WalletEvent.MoneyWithdrawn -> currentState.copy(
                balance = currentState.balance - event.amount
            )
            is WalletEvent.AccountClosed -> currentState.copy(
                isOpen = false
            )
        }
    }
}

Notice how I used .copy()? Since WalletState is a data class, we treat it as immutable. Never mutate the state directly during a replay; it makes debugging a nightmare when you're trying to trace exactly which event caused a balance to go negative.

Where should the validation logic live? In the event or the aggregate?

This is a common trap. A huge rule of thumb in event sourcing: Events are facts.

An event is something that has already happened. You cannot "validate" a fact. If you have a MoneyWithdrawn event in your store, it means the money was already taken. You shouldn't be checking if the balance is sufficient inside the applyEvents function. If you do that, and your business rules change later, you might find that you can no longer "replay" your old history because the old events now fail the new validation.

Put your validation in a "Command" layer. Check the balance, ensure the account is open, and then emit the event. Once the event is created and saved to the store, the replay logic should be "dumb"—it just applies the change and moves on. This separation is what allows you to change your business rules without corrupting your historical data.




📋 Practical Task

Exercise: Building a Library Book Tracking System

Your goal is to implement a mini event-sourcing system to track the status of a library book. Instead of just marking a book as "checked out," you need to track the entire lifecycle of the book via events.

  • Create a sealed class BookEvent with the following types: BookAdded (containing title and ISBN), BookCheckedOut (containing memberId), and BookReturned.
  • Create a BookState data class that tracks the title, the ISBN, whether it is currently available, and who currently holds the book (if anyone).
  • Write a function reconstructBookState(events: List<BookEvent>): BookState that uses fold to process the events and return the final state of the book.
  • Test your implementation by creating a list of events (Add -> Checkout -> Return -> Checkout) and verifying that the final state shows the book is checked out to the last member who took it.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.