Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Concurrency and Futures

Scala Actors, Pekko, cats-effect and ZIO

Tour the main Scala concurrency models beyond Future: actors with Apache Pekko, lazy effects with cats-effect IO and ZIO, plus streams, and how to choose between them.

Future and raw threads are the foundation, but large Scala systems usually add a library that makes concurrency easier to reason about. Three families dominate:

  1. Actors (Apache Pekko, the open-source continuation of Akka 2.6): isolated objects that communicate only by sending messages.
  2. Effect systems (cats-effect and ZIO): immutable descriptions of programs that are run later, with built-in cancellation, resource safety and structured concurrency.
  3. Streams (fs2, Pekko Streams): processing data flows with back-pressure.

None of these ship with Scala itself, and the runner on this site cannot run them, so the Scala snippets here are read-only. They show the style so you can recognize it in real code and pick a library. The runnable examples at the end are Java and Kotlin stand-ins for the underlying ideas.

Three concurrency models

Actors Private state. Talk only by messages.
Effects Programs as lazy values. Run at the edge.
Streams Data flows with back-pressure.
1 / 2

Actors

An actor owns private state and processes one message at a time from its mailbox. Because only the actor touches its state and messages are handled sequentially, no locks are needed. Other code sends a message with ! (tell) and continues without waiting.

A counter actor in Pekko Typed (read-only, needs the pekko-actor-typed dependency):

SCALA
import org.apache.pekko.actor.typed.{ActorRef, ActorSystem, Behavior}
import org.apache.pekko.actor.typed.scaladsl.Behaviors

object Counter:
  sealed trait Command
  case object Increment extends Command
  final case class GetValue(replyTo: ActorRef[Int]) extends Command

  def apply(count: Int = 0): Behavior[Command] =
    Behaviors.receiveMessage:
      case Increment =>
        apply(count + 1)               // new behavior with new state
      case GetValue(replyTo) =>
        replyTo ! count                // answer by sending a message
        Behaviors.same

@main def demo(): Unit =
  val system = ActorSystem(Counter(), "counter")
  system ! Counter.Increment
  system ! Counter.Increment

Notice how everything you have learned fits: the commands are a sealed ADT (Enums and Sealed ADTs), the handler is a pattern match, and state is immutable: each message returns the next behavior, which carries the new count. There is no var.

Strengths of actors: natural fit for stateful entities (a user session, a shopping cart, a device), location transparency (actors can live on other machines in a cluster), and supervision: a parent decides what to do when a child fails (restart, stop, escalate). Weaknesses: the message protocol replaces ordinary method calls and static typing of request/response needs care (the "ask" pattern with a replyTo reference).

Effect systems: cats-effect and ZIO

A Future runs the moment it is created. An effect such as IO (cats-effect) or ZIO is just a value that describes a computation. Nothing happens until the program is run at the "end of the world", usually the main method. That makes effects easy to compose, retry, time out and test, and keeps side effects out of pure code (see Immutability and Pure Functions).

A cats-effect program (read-only, needs cats-effect):

SCALA
import cats.effect.{IO, IOApp}
import cats.syntax.all.*
import scala.concurrent.duration.*

object Main extends IOApp.Simple:
  def fetch(name: String, delay: FiniteDuration): IO[String] =
    IO.sleep(delay) *> IO.pure(s"data from $name")

  val run: IO[Unit] =
    for
      _ <- IO.println("starting")
      (a, b) <- (fetch("A", 1.second), fetch("B", 1.second)).parTupled
      _ <- IO.println(s"$a and $b after about one second")
    yield ()

This uses the very same for-comprehension syntax from For-Comprehensions. parTupled runs both effects concurrently on lightweight fibers (green threads managed by the library, not OS threads), and cancels the other if one fails.

The equivalent in ZIO (read-only):

SCALA
import zio.*

object Main extends ZIOAppDefault:
  def fetch(name: String): ZIO[Any, Nothing, String] =
    ZIO.sleep(1.second) *> ZIO.succeed(s"data from $name")

  def run =
    for
      _ <- Console.printLine("starting")
      both <- fetch("A").zipPar(fetch("B"))
      _ <- Console.printLine(s"$both")
    yield ()

A ZIO[R, E, A] has three type parameters: the environment it needs, the error it may fail with and the success value. Typed errors and dependency injection are part of the type, in the spirit of Option, Either and Try.

What effect systems add over Future:

Feature Future IO / ZIO
Starts when created (eager) run (lazy)
Can be retried or repeated no, needs a new Future yes, the same value runs again
Cancellation none built in built in (fibers)
Resource safety manual Resource / acquireRelease / scopes
Referential transparency no yes

Streams

For continuous data (files, sockets, Kafka topics, events), streams process elements incrementally and apply back-pressure: a slow consumer automatically slows the producer, so memory stays bounded. fs2 (with cats-effect) example (read-only):

SCALA
import fs2.Stream
import cats.effect.IO

val pipeline: Stream[IO, Int] =
  Stream.range(1, 1_000_000)
    .filter(_ % 2 == 0)
    .map(_ * 3)
    .take(5)

// pipeline.compile.toList : IO[List[Int]]  gives List(6, 12, 18, 24, 30)

fs2 streams are lazy: nothing happens until you compile and run them. Pekko Streams offers the same idea with Source, Flow and Sink pieces.

Choosing

flowchart TD
    Q["What are you building?"] --> A["Small app, few async calls"]
    Q --> B["Many stateful entities or a cluster"]
    Q --> C["Typed, resource-safe services"]
    Q --> D["Continuous data flows"]
    A --> FA["scala.concurrent.Future"]
    B --> AC["Pekko actors"]
    C --> EF["cats-effect or ZIO"]
    D --> ST["fs2 or Pekko Streams"]

A rough guide, not a rule. Many projects combine them, for example Pekko HTTP with Futures, or http4s with cats-effect. The ecosystem choices matter more for hiring and libraries than for performance, so start with the stack your team or framework already uses. Build tooling for these libraries is covered in sbt and Project Setup.

Message passing in Java and Kotlin

Two non-Scala stand-ins demonstrate the core mechanics: an actor-like mailbox on a virtual thread (Java) and a channel-based worker (Kotlin coroutines).

Java Java: a tiny actor with a mailbox (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: producer, channel and consumer with back-pressure (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

(The "sent" lines may interleave differently from machine to machine, but the sum is always 91.)

Common mistakes

  • Mixing models carelessly, for example blocking an actor's thread with Await.result.
  • Mutable state shared between an actor and outside code: pass immutable messages only.
  • Running an IO or ZIO in the middle of your program (unsafeRunSync) instead of composing it up to main.
  • Using effect libraries for a tiny script. A plain Future or a loop may be enough.
  • Unbounded mailboxes or buffers that grow until memory runs out; prefer bounded queues and streams with back-pressure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main property that makes actors safe without locks?

    Because only the actor touches its state and its mailbox is processed sequentially, no two threads change that state at once.
  2. 2. What is the key difference between Future and IO (cats-effect)?

    IO values describe programs and do nothing until run, so they can be reused, retried and composed safely.
  3. 3. What does the E in ZIO[R, E, A] stand for?

    R is the required environment, E the error type and A the success type.
  4. 4. Why do streams use back-pressure?

    Back-pressure signals demand upstream so producers never flood consumers.

Summary

  • Beyond Future, Scala projects use actors (Pekko), effect systems (cats-effect, ZIO) and streams (fs2, Pekko Streams).
  • Actors isolate mutable state behind message passing; messages should be immutable sealed ADTs.
  • Effects are lazy, composable, cancellable descriptions of programs; they use the same for-comprehension syntax.
  • Streams add back-pressure for continuous data.
  • Choose the simplest tool that fits your problem and follow your framework's conventions.

Next: sbt and Project Setup