Scala
Completed
-
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
192: CQRS Pattern Implementation in Scala
I've spent the last few hours wrestling with a legacy Order Management system, and it’s a classic example of what happens when you let your read and write models evolve into a single, bloated entity. We have this one massive Order case class that handles everything from database persistence to the JSON response sent to the frontend. It's a nightmare. Every time I want to add a field for the reporting dashboard, I'm risking a regression in the checkout logic.
The CRUD Wall
Initially, I tried to just optimize the queries. I thought, "I'll just add some indexes or a few more optional fields to the Order class." But look at what happens when we try to implement a simple 'Order Summary' view for a customer dashboard. In a standard CRUD approach, it looks something like this:
case class Order(id: UUID, customerId: UUID, items: List[Item], status: Status, shippingAddress: Address, metadata: Map[String, String])
def getCustomerOrderSummary(customerId: UUID): OrderSummary = {
val orders = repository.findByCustomerId(customerId)
// We're loading huge objects just to sum up the totals and count statuses
OrderSummary(
totalSpent = orders.map(_.items.map(_.price).sum).sum,
activeOrders = orders.count(_.status == Status.Pending)
)
}
It works, but it's inefficient. I'm pulling the shippingAddress and metadata for every single order from the database just to calculate a sum. As the data grows, this is going to crawl. I'm hitting a wall because my "Write Model" (the Order class optimized for updates) is being forced to serve as my "Read Model."
Splitting the Intent from the View
I decided to stop fighting the single model and instead separate the intent to change state from the request for information. This is the core of CQRS. First, I'll define my Commands. These aren't just "update" calls; they are explicit business intentions.
sealed trait OrderCommand
case class PlaceOrder(orderId: UUID, items: List[Item]) extends OrderCommand
case class UpdateShipping(orderId: UUID, newAddress: Address) extends OrderCommand
case class CancelOrder(orderId: UUID, reason: String) extends OrderCommand
Now, instead of updating a row in a table, I'm thinking in terms of events. If I PlaceOrder, the result isn't just a saved row; it's an OrderPlaced event. This is a subtle but huge shift. It means the "Write Side" only cares about whether the command is valid and then emitting the fact that something happened.
Wiring the Projection
Here is where it gets interesting. If the write side only emits events, how do I actually see my order summary? I need a "Projection." I'm essentially going to build a separate data structure—a Read Model—that is specifically shaped for my UI. I don't want a generic Order object; I want a CustomerDashboardView.
I tried implementing this with a simple fold over the event stream. Let's see if this logic holds up:
case class CustomerDashboardView(customerId: UUID, totalSpent: BigDecimal, activeOrderCount: Int)
def project(view: CustomerDashboardView, event: OrderEvent): CustomerDashboardView = event match {
case OrderPlaced(customerId, total) =>
view.copy(totalSpent = view.totalSpent + total, activeOrderCount = view.activeOrderCount + 1)
case OrderCancelled(customerId, total) =>
view.copy(totalSpent = view.totalSpent - total, activeOrderCount = view.activeOrderCount - 1)
case _ => view // Shipping updates don't affect the dashboard summary
}
Wait, I noticed a bug here. If I cancel an order, I shouldn't necessarily subtract the totalSpent if the customer was already charged. My Read Model logic is now decoupled from my Write Model, which means I can fix this business logic in the projection without touching the code that actually cancels the order in the database. That's the "aha!" moment for me. I can rebuild my entire read-side state just by replaying the events.
Testing the Segregation
To wrap this up, I've separated my services into a CommandService and a QueryService. The CommandService handles the validation and event sourcing, while the QueryService simply reads from a pre-computed table (the projection). There is zero contention between the two. The write side is fast because it's just appending events, and the read side is fast because it's reading a flat, optimized view. It's more boilerplate, sure, but the mental overhead of "will this change break the dashboard?" has completely vanished.
📋 Practical Task
Implementing a Flight Booking Seat Reservation Read-Model
You are tasked with implementing a CQRS-style projection for a flight booking system. You have a stream of events, but the frontend needs a specific "Seat Map View" that shows only which seats are occupied and the total number of available seats, without loading the full Passenger details.
Requirements:
- Define a sealed trait
BookingEventwith three cases:SeatReserved(flightId: String, seatNumber: String),SeatReleased(flightId: String, seatNumber: String), andFlightCancelled(flightId: String). - Create a case class
SeatMapViewthat contains theflightId, aSet[String]of occupied seats, and atotalCapacity: Int. - Implement a function
applyEvent(view: SeatMapView, event: BookingEvent): SeatMapViewthat updates the view based on the event.SeatReservedshould add the seat to the occupied set.SeatReleasedshould remove the seat from the occupied set.FlightCancelledshould clear all occupied seats.
- Write a small test case that folds a list of these events over an initial
SeatMapViewand asserts that the final occupied seat count is correct.
There are no comments for now.