Skip to Content
Course content

191: Event Sourcing Patterns with Akka Persistence Revisited

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

When I first started working with Akka Persistence, I fell into a trap that I see almost every developer hit. I thought of the event store as just a "more detailed database table." I figured that if I needed to know the current balance of a bank account, I could just run a query against the event log to sum up all the deposits and withdrawals. It seemed intuitive—after all, the events are where the data lives.

The Event Log is Just a History Table

Here is why that mindset will kill your performance and your sanity. If you treat your event store like a relational table that you query for current state, you aren't actually doing event sourcing; you're just doing slow logging. Imagine a bank account that has been active for ten years with thousands of transactions. If every single "withdraw" request triggers a SELECT SUM(amount) FROM events WHERE account_id = 'XYZ', your database will choke as your system scales.

Even worse, the "history table" mindset leads people to try and "fix" data by editing an event in the database. In a real event-sourced system, the log is immutable. If you accidentally deposited $100 instead of $10, you don't UPDATE the event. You emit a CorrectionEvent. If you start editing the log, you lose the one thing that makes event sourcing valuable: the absolute, audit-able truth of what happened and when.

State is a Derivation, Not the Source

The correct way to think about this is that the Event Log is the Source of Truth, but the Actor's State is the Source of Performance. In Akka Persistence, the actor doesn't query the database to make decisions; it carries the current state in its memory. When the actor starts up (or recovers after a crash), it "replays" the events to rebuild that state. Once the state is rebuilt, the database is no longer touched for read operations.

Let's look at a concrete example of a BankAccount actor. Instead of calculating the balance on the fly, we define a state class and a way to apply events to that state.

case class AccountState(balance: BigDecimal, closed: Boolean = false)

sealed trait AccountEvent
case class MoneyDeposited(amount: BigDecimal) extends AccountEvent
case class MoneyWithdrawn(amount: BigDecimal) extends AccountEvent
case object AccountClosed extends AccountEvent

// This is the "pure" part of the logic. No Side Effects.
def applyEvent(state: AccountState, event: AccountEvent): AccountState = event match {
  case MoneyDeposited(amount) => state.copy(balance = state.balance + amount)
  case MoneyWithdrawn(amount) => state.copy(balance = state.balance - amount)
  case AccountClosed          => state.copy(closed = true)
}

I always tell my juniors: if your applyEvent function does anything other than transform a state object based on an event, you're doing it wrong. No API calls, no logging to files, no database lookups. It must be a pure function.

Bridging the Gap with EventSourcing Behavior

In modern Akka (Typed), we use EventSourcedBehavior to glue this together. The magic happens in the commandHandler and the eventHandler. The commandHandler is where you validate the business logic (e.g., "Do I have enough money to withdraw?"). If the validation passes, you don't change the state immediately—you return an Effect.persist.

The sequence is critical:

  • Command: "I want to withdraw $50."
  • Validation: "Current state says balance is $100. Valid."
  • Persistence: "Store MoneyWithdrawn(50) to the journal."
  • Application: "Now that it's safely stored, update the internal state to $50."

By separating the intent (the command) from the fact (the event), you ensure that your actor's memory is always a perfect reflection of the persistent log. If you need to query these accounts from a UI—say, a list of all accounts with a balance over $1,000—you don't query the actor or the event log. You use a Projection to pipe those events into a separate read-optimized database (CQRS). That's the only way to stay sane at scale.




📋 Practical Task

Implement a Transactional Limit Guard for the BankAccount Actor

You are tasked with enhancing the BankAccount actor to support a "Daily Withdrawal Limit." You need to ensure that the actor doesn't just check the balance, but also tracks how much has been withdrawn in the current 24-hour window.

Requirements:

  • Modify the AccountState to track the total amount withdrawn today and the timestamp of the last withdrawal.
  • Create a new event DailyLimitReset that is triggered when a withdrawal is attempted on a new calendar day.
  • Update the commandHandler to reject a WithdrawMoney command if the amount exceeds a hardcoded limit of $1,000 for the day.
  • Ensure that the eventHandler (the applyEvent logic) correctly handles the DailyLimitReset by zeroing out the daily counter.

Your solution should demonstrate that the limit check happens against the in-memory state, while the reset and the withdrawal are persisted as immutable events.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.