-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
191: Event Sourcing Patterns with Akka Persistence Revisited
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
AccountStateto track the total amount withdrawn today and the timestamp of the last withdrawal. - Create a new event
DailyLimitResetthat is triggered when a withdrawal is attempted on a new calendar day. - Update the
commandHandlerto reject aWithdrawMoneycommand if the amount exceeds a hardcoded limit of $1,000 for the day. - Ensure that the
eventHandler(theapplyEventlogic) correctly handles theDailyLimitResetby 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.
There are no comments for now.