Skip to Content
Course content

192: CQRS Pattern Implementation in Scala

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

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 BookingEvent with three cases: SeatReserved(flightId: String, seatNumber: String), SeatReleased(flightId: String, seatNumber: String), and FlightCancelled(flightId: String).
  • Create a case class SeatMapView that contains the flightId, a Set[String] of occupied seats, and a totalCapacity: Int.
  • Implement a function applyEvent(view: SeatMapView, event: BookingEvent): SeatMapView that updates the view based on the event.
    • SeatReserved should add the seat to the occupied set.
    • SeatReleased should remove the seat from the occupied set.
    • FlightCancelled should clear all occupied seats.
  • Write a small test case that folds a list of these events over an initial SeatMapView and asserts that the final occupied seat count is correct.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.