Skip to main content
Version: 2.x

Run Many Effects in Parallel with a Concurrency Limit

You have a list of items, such as 1,000 user ids, and a call to make for each one. You want the calls to run in parallel, but never more than a fixed number at a time. In this guide we pick the right tool for three situations: one batch of items (ZIO.foreachPar with ZIO#withParallelism), several places in a program that must share one limit (Semaphore), and items that arrive as a stream (ZStream#mapZIOPar).

Your situationUse
One list of items, one place in the codeZIO.foreachPar(...).withParallelism(n)
Several places must stay under one shared limitSemaphore.withPermit
The items come from a ZStreamZStream#mapZIOPar(n)

The Problemโ€‹

Calling a service once per item one after another is slow: 1,000 calls of 50 milliseconds take 50 seconds. Starting all of them at once is fast, but it opens 1,000 connections at the same moment. A remote service may reject that many calls, and your own process may run out of connections or memory.

ZIO.foreachPar has this second behavior. When no limit is set, it starts one fiber (a lightweight thread) for every element:

import zio._

def fetchUser(id: Int): UIO[String] = ZIO.succeed(s"user-$id")

// All 1,000 calls start together.
val allAtOnce: UIO[List[String]] =
ZIO.foreachPar((1 to 1000).toList)(fetchUser)

The rest of this guide shows how to put a ceiling on that number. Every program below uses a simulated service that sleeps for a short time and counts how many calls overlap, so no network is needed.

Prerequisitesโ€‹

Add ZIO to your build. The stream section also needs zio-streams:

// ZIO core: foreachPar, withParallelism and Semaphore
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
// ZIO Streams: mapZIOPar and mapZIOParUnordered
libraryDependencies += "dev.zio" %% "zio-streams" % "2.1.27"

We assume you know the basics of parallel operators. If not, read the Basic Concurrency overview first.

Limiting One Batch with withParallelismโ€‹

Wrap the foreachPar call with ZIO#withParallelism(n). At most n fibers run at the same time, and the rest wait for a free fiber.

import zio._

def fetchUser(id: Int): UIO[String] = ZIO.succeed(s"user-$id")

val limited: UIO[List[String]] =
ZIO.foreachPar((1 to 1000).toList)(fetchUser).withParallelism(5)

If you do not set a limit, or you call ZIO#withParallelismUnbounded, the operator runs one fiber per element. The limit also has no effect when it is larger than the number of elements.

The program below calls a simulated service for 100 ids, first with no limit and then with a limit of 5. A Probe (a small helper in the example project) records the highest number of calls that ran at the same moment.

BoundedBatchExample.scala
zio-examples/parallel-with-a-limit/src/main/scala/parallellimit/BoundedBatchExample.scala
package parallellimit

import zio._

/**
* Limits one batch of calls with `withParallelism`.
*/
object BoundedBatchExample extends ZIOAppDefault {

val ids: List[Int] = (1 to 100).toList

val run =
for {
unlimited <- Probe.make
_ <- ZIO.foreachPar(ids)(unlimited.fetchUser)
before <- unlimited.maxInFlight
_ <- Console.printLine(s"No limit: at most $before calls at once")

limited <- Probe.make
users <- ZIO.foreachPar(ids)(limited.fetchUser).withParallelism(5)
after <- limited.maxInFlight
_ <- Console.printLine(s"withParallelism(5): at most $after calls at once")
_ <- Console.printLine(s"Results keep the input order: ${users.take(3).mkString(", ")}, ...")

discarded <- Probe.make
_ <- ZIO.foreachParDiscard(ids)(discarded.fetchUser).withParallelism(5)
peak <- discarded.maxInFlight
_ <- Console.printLine(s"foreachParDiscard: at most $peak calls at once, no results kept")
} yield ()
}

Output:

No limit: at most 99 calls at once
withParallelism(5): at most 5 calls at once
Results keep the input order: user-1, user-2, user-3, ...
foreachParDiscard: at most 5 calls at once, no results kept

Without a limit, nearly all 100 calls ran together (the exact number can vary by one or two between runs). With the limit, never more than 5 did.

Keeping Results or Discarding Themโ€‹

ZIO.foreachPar returns the results in the same order as the input, however long each call took. That is the third line of the output above.

If you only care about the side effects, such as sending 1,000 emails, use ZIO.foreachParDiscard. It returns Unit and does not collect the results, and it obeys withParallelism in the same way (the last line of the output).

import zio._

def sendEmail(id: Int): UIO[Unit] = ZIO.unit

val sent: UIO[Unit] =
ZIO.foreachParDiscard(1 to 1000)(sendEmail).withParallelism(10)

What Happens When One Call Failsโ€‹

If any call fails, foreachPar fails with that error and interrupts the calls that are still running. Calls that have not started yet never start.

The next program makes call number 6 fail quickly while the others are slow, with a limit of 4. It counts how many calls started and how many were interrupted. It then repeats the run with .either on each call, which turns a failure into a value so that every call runs.

FirstFailureExample.scala
zio-examples/parallel-with-a-limit/src/main/scala/parallellimit/FirstFailureExample.scala
package parallellimit

import zio._

/**
* Shows what happens to the other calls when one call fails.
*/
object FirstFailureExample extends ZIOAppDefault {

val ids: List[Int] = (1 to 20).toList

/** Call 6 fails after a short delay. All other calls take longer. */
def call(started: Ref[Int], interrupted: Ref[Int])(id: Int): IO[String, Int] =
(started.update(_ + 1) *>
(if (id == 6) ZIO.sleep(20.millis) *> ZIO.fail(s"call $id failed")
else ZIO.sleep(200.millis).as(id)))
.onInterrupt(interrupted.update(_ + 1))

val run =
for {
started <- Ref.make(0)
interrupted <- Ref.make(0)
result <- ZIO.foreachPar(ids)(call(started, interrupted)).withParallelism(4).either
s <- started.get
i <- interrupted.get
_ <- Console.printLine(s"Result: $result")
_ <- Console.printLine(s"Started: $s of ${ids.size} calls")
_ <- Console.printLine(s"Interrupted: $i calls")

// To keep going after a failure, turn each failure into a value first.
all <- ZIO.foreachPar(ids)(id => call(started, interrupted)(id).either).withParallelism(4)
_ <- Console.printLine(s"With .either: ${all.count(_.isRight)} succeeded, ${all.count(_.isLeft)} failed")
} yield ()
}

Output:

Result: Left(call 6 failed)
Started: 8 of 20 calls
Interrupted: 3 calls
With .either: 19 succeeded, 1 failed

Only 8 of the 20 calls started, and 3 of them were interrupted when call 6 failed. Use .either (or .option) on each call when you want every item processed and a report of which ones failed.

Sharing One Limit Across Call Sitesโ€‹

withParallelism limits one foreachPar call. If two parts of your program each start their own batch, each batch gets its own limit, and together they can reach twice the number you wanted. When the limit belongs to the remote service, not to one batch, share a Semaphore.

A Semaphore holds a fixed number of permits. Semaphore#withPermit waits for a free permit, runs the effect, and gives the permit back when the effect succeeds, fails, or is interrupted. Create the semaphore once and pass it to every place that calls the service.

import zio._

def fetchUser(id: Int): UIO[String] = ZIO.succeed(s"user-$id")

val shared: UIO[List[String]] =
for {
limit <- Semaphore.make(4)
users <- ZIO.foreachPar((1 to 1000).toList)(id => limit.withPermit(fetchUser(id)))
} yield users

Here foreachPar still starts one fiber per element, but each fiber waits for a permit before it calls the service, so no more than 4 calls run. The program below loads users and orders from two parts of the program at the same time and compares two separate withParallelism(4) limits with one shared Semaphore.

SharedLimitExample.scala
zio-examples/parallel-with-a-limit/src/main/scala/parallellimit/SharedLimitExample.scala
package parallellimit

import zio._

/**
* Shares one limit between two call sites with a `Semaphore`.
*/
object SharedLimitExample extends ZIOAppDefault {

/**
* Two separate batches, each started from a different part of the program.
*/
def loadUsers(probe: Probe, limit: Semaphore): UIO[List[String]] =
ZIO.foreachPar((1 to 30).toList)(id => limit.withPermit(probe.fetchUser(id)))

def loadOrders(probe: Probe, limit: Semaphore): UIO[List[String]] =
ZIO.foreachPar((101 to 130).toList)(id => limit.withPermit(probe.fetchUser(id)))

val run =
for {
// Each batch has its own limit of 4, so together they reach 8.
separate <- Probe.make
_ <- ZIO.foreachPar(List(1 to 30, 101 to 130)) { ids =>
ZIO.foreachPar(ids.toList)(separate.fetchUser).withParallelism(4)
}
separatePeak <- separate.maxInFlight
_ <- Console.printLine(s"Two withParallelism(4) batches: at most $separatePeak calls at once")

// One Semaphore with 4 permits is shared by both batches.
shared <- Probe.make
limit <- Semaphore.make(4)
_ <- loadUsers(shared, limit).zipPar(loadOrders(shared, limit))
peak <- shared.maxInFlight
_ <- Console.printLine(s"One shared Semaphore(4): at most $peak calls at once")
} yield ()
}

Output:

Two withParallelism(4) batches: at most 8 calls at once
One shared Semaphore(4): at most 4 calls at once
tip

Put withPermit around the call to the service only, not around the whole batch. A permit held while waiting for other work blocks other fibers for no reason.

See the Semaphore reference for withPermits, which takes several permits at once, and withPermitsScoped.

Limiting Items That Arrive as a Streamโ€‹

When items come from a ZStream, such as lines read from a file or messages from a queue, use ZStream#mapZIOPar(n). It runs up to n calls at the same time, and it emits the results in the original order. If the order does not matter, ZStream#mapZIOParUnordered(n) may emit results as soon as they finish.

import zio._
import zio.stream._

def fetchUser(id: Int): UIO[String] = ZIO.succeed(s"user-$id")

val users: UIO[Chunk[String]] =
ZStream.fromIterable(1 to 1000).mapZIOPar(5)(fetchUser).runCollect

The stream does not read all the items up front. It reads ahead only as far as a small buffer (16 by default, set with the bufferSize parameter), so it does not need to hold all the items in memory.

StreamExample.scala
zio-examples/parallel-with-a-limit/src/main/scala/parallellimit/StreamExample.scala
package parallellimit

import zio._
import zio.stream._

/**
* Limits concurrency for items that arrive as a stream.
*/
object StreamExample extends ZIOAppDefault {

val ids: List[Int] = (1 to 100).toList

val run =
for {
ordered <- Probe.make
users <- ZStream.fromIterable(ids).mapZIOPar(5)(ordered.fetchUser).runCollect
peak1 <- ordered.maxInFlight
_ <- Console.printLine(s"mapZIOPar(5): at most $peak1 calls at once")
_ <- Console.printLine(s" first results: ${users.take(5).mkString(", ")}")

unordered <- Probe.make
users2 <- ZStream.fromIterable(ids).mapZIOParUnordered(5)(unordered.fetchUser).runCollect
peak2 <- unordered.maxInFlight
_ <- Console.printLine(s"mapZIOParUnordered(5): at most $peak2 calls at once")
_ <- Console.printLine(s" first results: ${users2.take(5).mkString(", ")}")
} yield ()
}

Output:

mapZIOPar(5): at most 5 calls at once
first results: user-1, user-2, user-3, user-4, user-5
mapZIOParUnordered(5): at most 5 calls at once
first results: user-5, user-1, user-6, user-2, user-3

The ordered version keeps the input order. The unordered version returned results in the order the calls finished, which is why user-5 came first.

Choosing Between Themโ€‹

ToolLimit applies toResult orderUse it when
foreachPar + withParallelism(n)One batchSame as inputYou have a list and one place that processes it
foreachParDiscard + withParallelism(n)One batchNone (returns Unit)You only need the side effects
Semaphore#withPermitEvery call that shares the semaphoreSame as the surrounding operatorSeveral call sites must stay under one limit
ZStream#mapZIOPar(n)One streamSame as inputItems arrive over time or are too many to hold
ZStream#mapZIOParUnordered(n)One streamOrder of completionAs above, and order does not matter

Running the Examplesโ€‹

The companion source files for this guide live in the zio-examples/parallel-with-a-limit directory of the ZIO repository. Clone the repository and run any program with sbt:

git clone https://github.com/zio/zio.git
cd zio/zio-examples/parallel-with-a-limit
sbt "runMain parallellimit.BoundedBatchExample"

The other programs are FirstFailureExample, SharedLimitExample and StreamExample. All of them live in the parallellimit package.

Going Furtherโ€‹

ZIO Chat

Hi there! ๐Ÿ‘‹ I'm ZIO Chat, your friendly neighborhood ZIO expert. I'm here to help you navigate the world of ZIO. Whether you're a seasoned pro or just starting out, fire away with your ZIO questions. I will hit you back with the best insights I've got. Let's dive into the world of ZIO together!