Skip to main content
Version: 2.x

Build a Concurrent Job Processor with Fibers, Queue and Ref

Welcome! In this tutorial we build a small job processor: a program that receives jobs from producers, hands them to a fixed number of workers, counts how the jobs went, tells us when everything is done, and stops cleanly when it is interrupted.

You should know basic Scala and have read Basic Concurrency, which introduces fibers, ZIO#fork, Fiber#join and Fiber#interrupt. We use those without explaining them again.

Learning Objectivesโ€‹

By the end of this tutorial, you will understand:

  • How worker fibers take jobs from a Queue and run side by side
  • What a bounded queue does when it is full, and why that is useful
  • How a Ref counts results safely from many fibers
  • How a Promise tells the main program that all work is done
  • What happens to a running job when its worker is interrupted, and how to shut the processor down cleanly

We learn these through:

  1. One Worker Fiber and a Queue
  2. A Pool of Workers
  3. A Bounded Queue and Back-Pressure
  4. Producers and a Ref That Counts Results
  5. Signalling Completion with a Promise
  6. Shutting Down Cleanly
  7. Putting It Together

We recommend reading from top to bottom. Each section builds on the one before.

Backgroundโ€‹

A job processor has three roles. Producers create jobs. Workers do them. Between the two sits a queue, a waiting line that lets producers and workers run at different speeds without knowing about each other.

In ZIO each worker is a fiber, and the queue is a Queue. Fibers are cheap, so a worker needs no thread of its own. A fiber that waits for a job does not block a thread; it is suspended until a job arrives.

Setupโ€‹

The code needs only ZIO core:

// ZIO core
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"

Every snippet below assumes import zio._. Our jobs are small case classes, and a job takes 100 milliseconds so that we can watch the workers at work:

1. One Worker Fiber and a Queueโ€‹

We start with the smallest processor: one queue and one worker. The worker takes a job, processes it, and repeats forever.

final case class Job(id: Int)

def process(job: Job): UIO[Unit] =
ZIO.sleep(100.millis) *> ZIO.debug(s"processed job ${job.id}")

val program: UIO[Unit] =
for {
queue <- Queue.unbounded[Job]
worker <- queue.take.flatMap(process).forever.fork
_ <- queue.offerAll(List(Job(1), Job(2), Job(3)))
_ <- ZIO.sleep(500.millis)
_ <- worker.interrupt
_ <- ZIO.debug("worker stopped")
} yield ()

The code above:

  • Queue.unbounded[Job] โ€” creates a queue that can hold any number of jobs
  • queue.take.flatMap(process).forever.fork โ€” starts one fiber that takes a job, processes it, and loops. Queue#take suspends the fiber while the queue is empty
  • queue.offerAll(...) โ€” puts three jobs on the queue
  • ZIO.sleep(500.millis) โ€” gives the worker time to finish. This is a crude wait that we replace in Section 5
  • worker.interrupt โ€” stops the worker, which would otherwise wait for more jobs forever

Running it prints:

processed job 1
processed job 2
processed job 3
worker stopped

One worker handles the jobs one at a time, in the order they were offered.

2. A Pool of Workersโ€‹

To process jobs side by side, we start several workers that all take from the same queue. Each job goes to exactly one worker, whichever is free first.

final case class Job(id: Int)

def process(workerId: Int, job: Job): UIO[Unit] =
ZIO.sleep(100.millis) *> ZIO.debug(s"worker $workerId processed job ${job.id}")

def worker(workerId: Int, queue: Queue[Job]): UIO[Nothing] =
queue.take.flatMap(job => process(workerId, job)).forever

val program: UIO[Unit] =
for {
queue <- Queue.unbounded[Job]
workers <- ZIO.foreach(1 to 3)(id => worker(id, queue).fork)
_ <- queue.offerAll((1 to 6).map(Job(_)))
_ <- ZIO.sleep(500.millis)
_ <- Fiber.interruptAll(workers)
_ <- ZIO.debug("all workers stopped")
} yield ()

The code above:

  • worker(id, queue) โ€” the worker loop from Section 1, now with an id so that we can see who did what. Its result type is UIO[Nothing] because a loop that never ends never produces a value
  • ZIO.foreach(1 to 3)(id => worker(id, queue).fork) โ€” forks three workers and returns the three fibers
  • Fiber.interruptAll(workers) โ€” interrupts all the workers together and waits until each one has stopped

One run printed:

worker 3 processed job 3
worker 2 processed job 2
worker 1 processed job 1
worker 2 processed job 5
worker 1 processed job 6
worker 3 processed job 4
all workers stopped

Six jobs of 100 milliseconds finished in about 200 milliseconds, because three workers ran at once. Notice that the order of the lines is not fixed: which worker takes which job, and which line prints first, can differ from run to run.

3. A Bounded Queue and Back-Pressureโ€‹

An unbounded queue accepts jobs without limit. If producers are faster than workers, it keeps growing until the program runs out of memory. A bounded queue has a fixed capacity, and what offer does when the queue is full is the key point of this section.

val backPressure: UIO[Unit] =
for {
queue <- Queue.bounded[Int](2)
producer <- ZIO.foreachDiscard(1 to 4)(n => queue.offer(n) *> ZIO.debug(s"offered $n")).fork
_ <- ZIO.sleep(200.millis)
size <- queue.size
_ <- ZIO.debug(s"queue size: $size, producer is suspended")
taken <- queue.take
_ <- ZIO.debug(s"took $taken")
_ <- ZIO.sleep(200.millis)
_ <- producer.interrupt
} yield ()

The code above:

  • Queue.bounded[Int](2) โ€” a queue that holds at most two elements
  • producer โ€” a fiber that offers 1, 2, 3 and 4, printing a line after each offer completes
  • queue.take โ€” makes room by removing the oldest element

The output is:

offered 1
offered 2
queue size: 3, producer is suspended
took 1
offered 3

The third offer did not complete. On a bounded queue, Queue#offer suspends the producer fiber until there is room. This is called back-pressure: a slow consumer slows down the producers instead of letting work pile up. As soon as we took one element, the suspended offer finished and printed offered 3. The producer then suspended again on the fourth offer, and we interrupted it.

note

The size is 3, not 2, because Queue#size also counts the fibers that are suspended in offer. The queue holds two elements and one producer is waiting to add a third.

Queue has two more bounded variants that never suspend a producer. They differ in which element they give up when the queue is full:

val otherStrategies: UIO[Unit] =
for {
dropping <- Queue.dropping[Int](1)
first <- dropping.offer(1)
second <- dropping.offer(2)
kept <- dropping.take
_ <- ZIO.debug(s"dropping: offer(1) = $first, offer(2) = $second, queue keeps $kept")
sliding <- Queue.sliding[Int](1)
first2 <- sliding.offer(1)
second2 <- sliding.offer(2)
kept2 <- sliding.take
_ <- ZIO.debug(s"sliding: offer(1) = $first2, offer(2) = $second2, queue keeps $kept2")
} yield ()
dropping: offer(1) = true, offer(2) = false, queue keeps 1
sliding: offer(1) = true, offer(2) = true, queue keeps 2

A dropping queue throws away the new element and offer returns false. A sliding queue throws away the oldest element and makes room for the new one. Both lose jobs, so for a job processor we use Queue.bounded and let back-pressure do its work.

4. Producers and a Ref That Counts Resultsโ€‹

Now we put the pieces together. We add producers that fill a bounded queue, and make some jobs fail, because real jobs do. We also want to know how many jobs succeeded and how many failed. All workers must update these counts, so we keep them in a Ref, ZIO's mutable reference that can be updated safely from many fibers.

final case class Job(id: Int)

final case class Stats(succeeded: Int, failed: Int)

// Every fourth job fails
def process(job: Job): IO[String, Unit] =
ZIO.sleep(100.millis) *> ZIO.fail(s"job ${job.id} failed").when(job.id % 4 == 0).unit

def worker(queue: Queue[Job], stats: Ref[Stats]): UIO[Nothing] =
queue.take.flatMap { job =>
process(job).foldZIO(
_ => stats.update(s => s.copy(failed = s.failed + 1)),
_ => stats.update(s => s.copy(succeeded = s.succeeded + 1))
)
}.forever

val program: UIO[Unit] =
for {
queue <- Queue.bounded[Job](5)
stats <- Ref.make(Stats(succeeded = 0, failed = 0))
workers <- ZIO.foreach(1 to 3)(_ => worker(queue, stats).fork)
batches = List((1 to 6).map(Job(_)), (7 to 12).map(Job(_)))
_ <- ZIO.foreachParDiscard(batches)(batch => ZIO.foreachDiscard(batch)(queue.offer))
_ <- ZIO.sleep(1.second)
result <- stats.get
_ <- ZIO.debug(s"result: $result")
_ <- Fiber.interruptAll(workers)
} yield ()

The code above:

  • process โ€” now has the type IO[String, Unit], and fails for every job whose id is divisible by four
  • process(job).foldZIO(onFailure, onSuccess) โ€” handles both outcomes inside the worker, so a failed job is counted and the worker carries on. Without it, the first failure would end the worker fiber
  • stats.update(...) โ€” changes the counts atomically. Two workers that update at the same moment never overwrite each other's change
  • ZIO.foreachParDiscard(batches)(...) โ€” runs two producers in parallel, each offering its own batch of six jobs. With a capacity of five, the producers are suspended now and then until the workers catch up

The output is:

result: Stats(9,3)

Jobs 4, 8 and 12 failed and the other nine succeeded.

5. Signalling Completion with a Promiseโ€‹

Waiting a fixed second and hoping that everything is done is not good enough. The program should continue exactly when the last job has finished. A Promise is made for this: it starts empty, one fiber completes it, and any fiber that calls Promise#await is suspended until then.

The worker that finishes the last job completes the promise. It knows it was the last one when the counts add up to the total number of jobs:

final case class Job(id: Int)

final case class Stats(succeeded: Int, failed: Int) {
def finished: Int = succeeded + failed
}

// Every fourth job fails
def process(job: Job): IO[String, Unit] =
ZIO.sleep(100.millis) *> ZIO.fail(s"job ${job.id} failed").when(job.id % 4 == 0).unit

def worker(
queue: Queue[Job],
stats: Ref[Stats],
done: Promise[Nothing, Unit],
total: Int
): UIO[Nothing] = {
def record(update: Stats => Stats): UIO[Unit] =
stats.updateAndGet(update).flatMap(s => done.succeed(()).when(s.finished == total).unit)

queue.take.flatMap { job =>
process(job).foldZIO(
_ => record(s => s.copy(failed = s.failed + 1)),
_ => record(s => s.copy(succeeded = s.succeeded + 1))
)
}.forever
}

val program: UIO[Unit] = {
val total = 12
for {
queue <- Queue.bounded[Job](5)
stats <- Ref.make(Stats(succeeded = 0, failed = 0))
done <- Promise.make[Nothing, Unit]
workers <- ZIO.foreach(1 to 3)(_ => worker(queue, stats, done, total).fork)
batches = List((1 to 6).map(Job(_)), (7 to 12).map(Job(_)))
_ <- ZIO.foreachParDiscard(batches)(batch => ZIO.foreachDiscard(batch)(queue.offer))
_ <- done.await
result <- stats.get
_ <- ZIO.debug(s"all $total jobs finished: $result")
_ <- Fiber.interruptAll(workers)
} yield ()
}

The code above:

  • Promise.make[Nothing, Unit] โ€” a promise that can only succeed, and carries no value. We use it as a plain signal
  • stats.updateAndGet(update) โ€” updates the counts and returns the new value in one atomic step. Exactly one worker sees finished == total, so exactly one worker completes the promise
  • done.succeed(()).when(s.finished == total) โ€” completes the promise only for that last job
  • done.await โ€” replaces the one-second sleep. The main fiber resumes the moment the promise is completed

The output is:

all 12 jobs finished: Stats(9,3)

6. Shutting Down Cleanlyโ€‹

So far we stopped the workers with Fiber.interruptAll once everything was done. A real processor must also stop when it is interrupted halfway, for example when the user presses Ctrl-C. The question is what happens to the job a worker is running at that moment.

By default, interrupting a fiber stops it wherever it is, even in the middle of a job. Let's see that with six jobs of 200 milliseconds and two workers, and shut down after 300 milliseconds. We compare two worker loops:

final case class Job(id: Int)

def process(job: Job): UIO[Unit] =
ZIO.debug(s"started job ${job.id}") *>
ZIO.sleep(200.millis) *>
ZIO.debug(s"finished job ${job.id}")

// Interruptible: a job that is running when the worker is interrupted is cut short
def abruptWorker(queue: Queue[Job]): UIO[Nothing] =
queue.take.flatMap(job => process(job).onInterrupt(ZIO.debug(s"job ${job.id} lost"))).forever

// Waiting for a job can be interrupted; once a job is taken, it runs to the end
def carefulWorker(queue: Queue[Job]): UIO[Nothing] =
ZIO.uninterruptibleMask { restore =>
restore(queue.take).flatMap(process)
}.forever

def scenario(name: String, worker: Queue[Job] => UIO[Nothing]): UIO[Unit] =
for {
_ <- ZIO.debug(s"--- $name ---")
queue <- Queue.bounded[Job](10)
workers <- ZIO.foreach(1 to 2)(_ => worker(queue).fork)
_ <- queue.offerAll((1 to 6).map(Job(_)))
_ <- ZIO.sleep(300.millis)
_ <- ZIO.debug("shutting down")
_ <- Fiber.interruptAll(workers)
waiting <- queue.size
_ <- queue.shutdown
_ <- ZIO.debug(s"workers stopped, $waiting jobs still waiting in the queue")
offer <- queue.offer(Job(99)).exit
_ <- ZIO.debug(s"offer after shutdown was interrupted: ${offer.isInterrupted}")
} yield ()

val program: UIO[Unit] =
scenario("abrupt", abruptWorker) *> scenario("careful", carefulWorker)

The code above:

  • abruptWorker โ€” an ordinary loop. ZIO#onInterrupt prints a line if the job is cut short
  • carefulWorker โ€” ZIO.uninterruptibleMask makes the whole loop body uninterruptible, and restore makes only the take interruptible again. A worker that waits for a job can be stopped at once. A worker that has taken a job is not stopped until the job has finished. The reference page on interruptible regions explains restore in detail
  • queue.size โ€” counts the jobs nobody has taken
  • queue.shutdown โ€” shuts the queue down. Fibers suspended in offer or take are interrupted, and later calls to offer and take are interrupted immediately
  • queue.offer(Job(99)).exit โ€” shows that last point. We use ZIO#exit so that the interruption becomes a value that we can print, instead of interrupting our own program

The output is:

--- abrupt ---
started job 2
started job 1
finished job 1
finished job 2
started job 3
started job 4
shutting down
job 4 lost
job 3 lost
workers stopped, 2 jobs still waiting in the queue
offer after shutdown was interrupted: true
--- careful ---
started job 1
started job 2
finished job 1
started job 3
finished job 2
started job 4
shutting down
finished job 3
finished job 4
workers stopped, 2 jobs still waiting in the queue
offer after shutdown was interrupted: true

With the abrupt workers, jobs 3 and 4 were running at the shutdown and were lost. With the careful workers, the same two jobs ran to the end, and only then did the workers stop. In both cases jobs 5 and 6 never left the queue. The order of the lines that belong to the two workers can differ from run to run.

caution

ZIO#fork gives the new fiber the interruptibility of the place where it was forked. A worker forked from the acquire step of ZIO.acquireRelease, or from any other uninterruptible region, cannot be interrupted at all, not even while it waits in take, because restore returns to the region it was called in. Fork workers from an interruptible region, as the program above does. The reference page has the details.

Jobs that are still in the queue at shutdown are not processed. A processor that must not lose them would first stop its producers, wait for the queue to empty, and only then shut down. We keep to the simple version here.

7. Putting It Togetherโ€‹

The complete program packages the processor as a JobProcessor that lives inside a Scope. Closing the scope is what shuts the processor down, so it stops cleanly whether the program finishes normally or is interrupted. It differs from the sections in four ways:

  • The queue, the Ref and the Promise are hidden inside JobProcessor. The outside world sees only submit, awaitDone and snapshot
  • Shutdown is registered with ZIO.addFinalizer and forkScoped instead of calling Fiber.interruptAll by hand. Finalizers run in reverse order, so the program first prints shutting down, then stops the workers, and last shuts the queue down and prints the final counts
  • All workers run under one supervising fiber, started with ZIO.foreachParDiscard(...).withParallelism(workerCount), so that one interrupt reaches all of them
  • It runs twice: once until all 12 jobs are done, and once with 40 jobs and ZIO#timeout(350.millis), which interrupts the program early
zio-examples/job-processor/src/main/scala/jobprocessor/CompleteExample.scala
package jobprocessor

import zio._

/*
* Tutorial: Build a Concurrent Job Processor with Fibers, Queue and Ref
* Section: Putting It Together
*
* sbt "runMain jobprocessor.CompleteExample"
*/
object CompleteExample extends ZIOAppDefault {

final case class Job(id: Int)

final case class Stats(succeeded: Int, failed: Int) {
def finished: Int = succeeded + failed
}

// Every fourth job fails
def process(job: Job): IO[String, Unit] =
ZIO.sleep(100.millis) *> ZIO.fail(s"job ${job.id} failed").when(job.id % 4 == 0).unit

final class JobProcessor private (
queue: Queue[Job],
stats: Ref[Stats],
done: Promise[Nothing, Unit]
) {
def submit(job: Job): UIO[Unit] = queue.offer(job).unit
def awaitDone: UIO[Unit] = done.await
def snapshot: UIO[Stats] = stats.get
}

object JobProcessor {

def make(workerCount: Int, capacity: Int, total: Int): ZIO[Scope, Nothing, JobProcessor] =
for {
queue <- Queue.bounded[Job](capacity)
stats <- Ref.make(Stats(succeeded = 0, failed = 0))
done <- Promise.make[Nothing, Unit]
// Finalizers run in reverse order: "shutting down" first, then the workers stop,
// then the queue shuts down and the final counts are printed.
// One supervising fiber runs all the workers, so interrupting it stops them together.
_ <- ZIO.addFinalizer(queue.shutdown *> stats.get.flatMap(s => ZIO.debug(s"final counts: $s")))
_ <- ZIO
.foreachParDiscard(1 to workerCount)(_ => worker(queue, stats, done, total))
.withParallelism(workerCount)
.forkScoped
_ <- ZIO.addFinalizer(ZIO.debug("shutting down"))
} yield new JobProcessor(queue, stats, done)

private def worker(
queue: Queue[Job],
stats: Ref[Stats],
done: Promise[Nothing, Unit],
total: Int
): UIO[Nothing] = {
def record(update: Stats => Stats): UIO[Unit] =
stats.updateAndGet(update).flatMap(s => done.succeed(()).when(s.finished == total).unit)

ZIO.uninterruptibleMask { restore =>
restore(queue.take).flatMap { job =>
process(job).foldZIO(
_ => record(s => s.copy(failed = s.failed + 1)),
_ => record(s => s.copy(succeeded = s.succeeded + 1))
)
}
}.forever
}
}

def produce(processor: JobProcessor, jobs: Seq[Job]): UIO[Unit] = {
val batches = jobs.grouped(6).toList
ZIO.foreachParDiscard(batches)(batch => ZIO.foreachDiscard(batch)(processor.submit))
}

// Run 1: all 12 jobs finish, then the scope closes
val runToCompletion: UIO[Unit] =
ZIO.scoped {
for {
processor <- JobProcessor.make(workerCount = 3, capacity = 5, total = 12)
_ <- produce(processor, (1 to 12).map(Job(_)))
_ <- processor.awaitDone
_ <- ZIO.debug("all jobs finished")
} yield ()
}

// Run 2: the program is interrupted after 350 ms, long before 40 jobs can finish
val interrupted: UIO[Unit] =
ZIO.scoped {
for {
processor <- JobProcessor.make(workerCount = 3, capacity = 5, total = 40)
_ <- produce(processor, (1 to 40).map(Job(_)))
_ <- processor.awaitDone
} yield ()
}
.timeout(350.millis)
.flatMap(result => ZIO.debug(s"finished before the timeout: ${result.isDefined}"))

def run: UIO[Unit] =
ZIO.debug("--- run to completion ---") *> runToCompletion *>
ZIO.debug("--- interrupted run ---") *> interrupted
}

The output is:

--- run to completion ---
all jobs finished
shutting down
final counts: Stats(9,3)
--- interrupted run ---
shutting down
final counts: Stats(10,2)
finished before the timeout: false

In the first run the processor finished all 12 jobs. In the second run the timeout interrupted the program after 350 milliseconds. The scope closed, the workers finished the jobs they were running, and the processor reported the counts. The final counts are the jobs that finished before the program stopped. Their exact numbers can differ from run to run.

Running the Examplesโ€‹

All runnable code from this tutorial is in zio-examples/job-processor/src/main/scala/jobprocessor/. From the zio-examples/job-processor folder, run any file with sbt "runMain jobprocessor.<ObjectName>", for example sbt "runMain jobprocessor.CompleteExample". There is one file for each of Sections 1 to 6, named Step1OneWorker to Step6CleanShutdown, and CompleteExample for Section 7.

What You've Learnedโ€‹

In this tutorial, you learned:

  • How worker fibers take jobs from a shared Queue, one job per worker, and run side by side
  • How a bounded queue suspends producers in Queue#offer when it is full, and how dropping and sliding queues differ
  • How workers update a Ref atomically to count results from many fibers
  • How a Promise signals that the last job is done, so the main program does not have to guess how long to wait
  • How ZIO.uninterruptibleMask with restore lets a worker stop while it waits but finish the job it has taken, and how a Scope and Queue#shutdown stop the processor cleanly

Where to Go Nextโ€‹

ZIO Chat

Hi, fellow coder! ๐ŸŒŸ Welcome to your ZIO adventure with the ZIO Chat Bot. ๐Ÿš€ Let's master functional Scala together. From referential transparency to concurrent prowess, I've got your back. Ready to dive in? Your questions, my insights โ€“ let's conquer ZIO! ๐Ÿ’ก๐Ÿค–