Skip to Content
Course content

38: Building a Simple Actor-Based System

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

Think about a high-end professional kitchen during the dinner rush. You've got a head chef, a sauté chef, and a pastry chef. Now, imagine if the head chef tried to manage the kitchen by physically reaching over and moving the sauté chef's pan, or if the pastry chef tried to change the temperature on the sauté station while the other guy was using it. It would be absolute chaos—and probably a few fires.

Instead, they use a ticket rail. The waiter pins a ticket (a message) to the rail. The sauté chef looks at the rail, takes one ticket, and handles it. They don't care who wrote the ticket; they just care what it says. They don't let anyone touch their station, and if they need the pastry chef to do something, they don't shout across the room or grab their arm—they send a ticket over to the pastry station. This is exactly how the Actor Model works.

Mapping the Kitchen to the Code

In Scala, when we build an actor-based system, we're essentially implementing that kitchen logic to avoid the nightmare of shared mutable state. Here is how the analogy maps to the actual implementation:

  • The Chef is the Actor: An actor is an object that encapsulates state and behavior. No one can "call a method" on an actor to change its internal variables. You can't just reach into the actor's "pan."
  • The Ticket is the Message: Actors communicate exclusively through immutable messages. If you want an actor to do something, you send it a message.
  • The Ticket Rail is the Mailbox: Every actor has a mailbox. Messages queue up there and are processed one by one. This is the magic part: because the actor only processes one message at a time, you don't need locks or synchronized blocks.

Designing a Simple Order Pipeline

Let's build a small system to handle a coffee shop order. I want to avoid the typical "everything in one class" approach. Instead, we'll have a CoffeeMachine actor that handles the brewing and an OrderManager that tracks the status.

case class BrewCoffee(orderId: String, roast: String)
case class CoffeeReady(orderId: String)
case class OrderStatus(orderId: String)

class CoffeeMachine extends Actor {
  def receive = {
    case BrewCoffee(id, roast) =>
      println(s"Brewing $roast for order $id...")
      // Simulate brewing time
      Thread.sleep(1000) 
      sender() ! CoffeeReady(id)
  }
}

class OrderManager(machine: ActorRef) extends Actor {
  var activeOrders = Map.empty[String, String]

  def receive = {
    case BrewCoffee(id, roast) =>
      activeOrders += (id -> "Brewing")
      machine ! BrewCoffee(id, roast)

    case CoffeeReady(id) =>
      activeOrders += (id -> "Ready")
      println(s"Order $id is now ready for pickup!")

    case OrderStatus(id) =>
      val status = activeOrders.getOrElse(id, "Unknown")
      sender() ! s"Order $id is $status"
  }
}

Why This Beats Traditional OOP

If you wrote this using standard objects, you'd probably have a List[Order] that both the OrderManager and the CoffeeMachine were trying to update. You'd be staring at ConcurrentModificationException or fighting with AtomicReference for hours.

I've found that the biggest mental shift here is accepting that you don't "get a return value" immediately. You don't call machine.brew() and wait for it to finish. You send a message and you trust that the actor will respond when it's done. It's a "fire and forget" mentality that allows your system to scale horizontally across multiple CPU cores—or even multiple servers—without changing a single line of business logic.

Handling the "Ask" Pattern

Sometimes, you actually do need a response right now—like when a user is staring at a loading spinner on a website. In these cases, we use the "ask" pattern, which creates a temporary actor just to wait for a single reply. It returns a Future, which we've already covered. Just remember: use "ask" sparingly. If your system is 90% "asks," you've basically just built a slow, complicated version of synchronous programming.




📋 Practical Task

Implementing a Distributed Logistics Tracker

Your task is to build a simplified logistics system using the Actor model. You need to create a system that tracks a package as it moves from a warehouse to a delivery truck.

Requirements:

  • Messages: Define immutable case classes for DispatchPackage(id: String, destination: String), PackageArrived(id: String), and RequestLocation(id: String).
  • The Warehouse Actor: This actor should maintain a list of packages currently in the warehouse. When it receives a DispatchPackage message, it should remove the package from its internal list and send it to the Delivery Actor.
  • The Delivery Actor: This actor should track packages currently on the truck. When it receives a package from the Warehouse, it should simulate a delivery delay (using Thread.sleep) and then send a PackageArrived message back to the Warehouse (or a separate Tracker actor) to mark it as delivered.
  • State Management: Ensure that no shared mutable variables are used between the two actors. All communication must happen via ! (tell).

Goal: Demonstrate a full lifecycle: Warehouse $\rightarrow$ Delivery $\rightarrow$ Delivered status update.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.