Apache Pekko Streams (Scala / Java)
The Apache-licensed fork of Akka Streams. A stream is an immutable blueprint (Source, Flow, Sink, RunnableGraph) that does nothing until a Materializer turns it into running GraphStageLogic state machines, fused into actors, wired by Reactive Streams demand. Each run() also returns a typed materialized value.
| Field | Value |
|---|---|
| Language | Scala 2.13 / 3 with a parallel Java DSL; Java 17+ (releases-2.0.md) |
| License | Apache-2.0 (LICENSE) |
| Repository | apache/pekko, module stream/ (+ stream-testkit/, stream-typed/) |
| Documentation | pekko.apache.org/docs/pekko/current/stream/, sources in docs/src/main/paradox/stream/ |
| Category | Pull-demand (Reactive Streams) dataflow graphs with explicit materialization, run by an actor-hosted graph interpreter |
| Versions surveyed | main at df133f7de2d5 (2026-11-23). The newest upstream tag is v2.0.0-RC1, and the tree already carries the 2.0.0 release notes. Version numbers come from @since tags and the release notes |
| Core abstraction | Graph[S <: Shape, +M], specialised as Source[+Out, +Mat], Flow[-In, +Out, +Mat], Sink[-In, +Mat] and RunnableGraph[+Mat]; user operators are GraphStage + GraphStageLogic with InHandler/OutHandler callbacks |
NOTE
Why Pekko rather than Akka. On September 7, 2022 Lightbend announced that "The new license for Akka is the Business Source License (BSL) v1.1". Under it each release becomes Apache 2.0 only after three years (Bonér, "Why we are changing the license for Akka"). Pekko's README says it "is a fork of [Akka] 2.6.x, prior to the Akka project's adoption of the Business Source License. Pekko 2.x now contains most of the features up to and including Akka 2.9.0 (Apache 2.0 Licensed now)" (README.md). This survey cites the code we can freely read and copy from. Apart from the additions noted below (switchMap, doOnCancel, Sink.source), the Streams design is the same as Akka's.
Overview
What it solves
Pekko Streams handles bounded-memory processing of possibly infinite sequences across asynchronous boundaries: sockets, files, actors, other Reactive Streams libraries. Back-pressure is guaranteed end to end. It is the transport layer under Pekko HTTP, Pekko Connectors and Artery remoting. The model is one where the same pipeline description is built in one place, shared freely, and run many times elsewhere (stream-flows-and-basics.md):
"no data will flow through it until it is materialized. Materialization is the process of allocating all resources needed to run the computation described by a Graph (in Pekko Streams this will often involve starting up Actors). Thanks to Flows being a description of the processing pipeline they are immutable, thread-safe, and freely shareable"
Design philosophy
The design-principles page is unusually explicit (general/stream/stream-design.md):
"Pekko is built upon a conscious decision to offer APIs that are minimal and consistent—as opposed to easy or intuitive. The credo is that we favor explicitness over magic, and if we provide a feature then it must work always, no exceptions."
It then states the consequence that drives the whole API:
"The representation of these pieces must therefore be an immutable blueprint that is materialized in an explicit step in order to start the stream processing. … The process of materialization will often create specific objects that are useful to interact with the processing engine once it is running, for example for shutting it down or for extracting metrics. This means that the materialization function produces a result termed the materialized value of a graph."
Two further principles matter for sparkles. First, Reactive Streams is treated as an SPI, not an API. Source/Sink/Flow deliberately do not extend Publisher/Subscriber, so that "Pekko Streams to perform optimizations like fusing and dispatcher configuration during the materialization step". Second, libraries must return blueprints, not run them. "compositionality would be destroyed if different libraries only accepted operators and expected to materialize them … materialization can only happen once" (stream-design.md).
How it works
Blueprint layer. Every piece is a Graph[S, M]: a Shape (its typed Inlets/Outlets) plus a traversal builder, and a materialized-value type M. Source has one outlet, Sink one inlet, Flow one of each, and BidiFlow two of each (stream-design.md). Attaching both ends gives a RunnableGraph[Mat]. Linear composition is via/to; non-linear composition is GraphDSL (below). Graphs are values: "since operators are immutable, connecting them returns a new operator" (stream-flows-and-basics.md).
Materialization. run(), runWith(sink) and sugar such as runForeach are the "terminal operations". "Materialization is performed synchronously on the materializing thread by an ActorSystem global Materializer" (stream-flows-and-basics.md). For each GraphStage the materializer calls createLogic(attributes), producing a fresh GraphStageLogic per run: "All mutable state needs to be confined to the GraphStageLogic that is created for every materialization" (stream-customize.md).
Fusion and islands. By default all operators are fused into one GraphInterpreter hosted by one actor (ActorGraphInterpreter). Elements are passed by direct method calls, and "fused stream operators do not run in parallel to each other, meaning that only up to one CPU core is used for each fused part" (stream-flows-and-basics.md). .async adds an Attributes.asyncBoundary that closes an island: "attributes always work by adding information to the flow graph that has been constructed up to this point". Each island is a separate actor, and islands exchange batched Reactive Streams demand with input buffers between them (initial-input-buffer-size = 4, max-input-buffer-size = 16 in reference.conf).
The interpreter. GraphInterpreter.scala keeps a table of Connections, one per outlet→inlet edge. Each holds a portState bitfield (InReady, Pulling, Pushing, OutReady, InClosed, OutClosed, InFailed), a slot for the in-flight element, failure or cancellation cause, and the two handlers. "there can be only one event in flight for a given Connection". A pull/push flips the bits and enqueues the connection on a circular event queue. execute(eventLimit) drains it by calling the target handler's onPull/onPush. The sync-processing-limit = 1000 setting interrupts long synchronous runs so the actor stays responsive (reference.conf).
// The three linear building blocks and what each type parameter means.
val src: Source[Int, NotUsed] = Source(1 to 10) // Out = Int, Mat = NotUsed
val dbl: Flow[Int, Int, NotUsed] = Flow[Int].map(_ * 2) // In, Out, Mat
val sum: Sink[Int, Future[Int]] = Sink.fold(0)(_ + _) // In, Mat = the result
val g: RunnableGraph[Future[Int]] = src.via(dbl).toMat(sum)(Keep.right)
val r1: Future[Int] = g.run() // run #1
val r2: Future[Int] = g.run() // run #2: new actors, new FutureEvaluation model
Pull-demand with push delivery ("dynamic push/pull"). Between islands, Reactive Streams request(n) bounds what a publisher may send. The docs call the result "'dynamic push / pull mode', since it will switch between push and pull based back-pressure models depending on the downstream being able to cope" (stream-flows-and-basics.md). Inside a fused island the same rule holds at granularity 1. An outlet may be pushed only after onPull, and pull twice before a push throws: "There can only be one outstanding request at any given time" (GraphStage.scala pull).
Lazy and cold. A blueprint is inert; each materialization is an independent running instance with fresh state and a fresh materialized value. Hot sources such as Source.queue, Source.actorRef and MergeHub.source are hot per materialization. Their "handle" exists only as a materialized value.
Not a value-propagation model. There are no derived cells, so glitch-freedom does not apply. zipLatest/mergeLatest/combineLatest-style operators emit on every input, and the 2.0 notes list "MergeLatest does not backpressure upstreams and buffers without bound" as a known issue (releases-2.0.md). Propagation inside an island is synchronous and depth-first through the event queue. Across islands it is batched by demand windows.
Composition
Linear composition uses methods on Source/Flow (map, filter, mapAsync, via, to). Fan-in/fan-out and cycles use GraphDSL, a mutable builder that is sealed into an immutable graph:
val g = RunnableGraph.fromGraph(GraphDSL.createGraph(Sink.seq[Int]) { implicit b => out =>
import GraphDSL.Implicits._
val bcast = b.add(Broadcast[Int](2)) // fan-out: every element to every output
val merge = b.add(Merge[Int](2)) // fan-in: first-come
Source(1 to 3) ~> bcast ~> Flow[Int].map(_ + 1) ~> merge ~> out
bcast ~> Flow[Int].map(_ * 10) ~> merge
ClosedShape
})The junctions in scaladsl/Graph.scala are Merge, MergePreferred, MergePrioritized, Interleave, MergeSorted, Concat, OrElse, MergeSequence, Zip/ZipWith/ZipLatest/ZipN (fan-in), and Broadcast, Balance, Partition, WireTap, Unzip/UnzipWith (fan-out). ~> is defined on port ops for an inlet, a Flow, a uniform fan-in or a fan-out shape (Graph.scala#L1849). GraphDSL.create has an arity-N overload family generated from GraphApply.scala.template; it exists only to thread the N materialized values in.
Operator surface. The operator index lists 231 rows in 17 categories (row counts at this SHA; an operator offered on Source and Flow is one row):
| Category | Rows | Examples |
|---|---|---|
| Source operators | 37 | single, tick, queue, unfold, lazySource, future |
| Sink operators | 35 | foreach, fold, seq, last, queue, source |
| Additional Sink and Source converters | 8 | asInputStream, fromJavaStream |
| File IO Sinks and Sources | 2 | FileIO.fromPath, toPath |
| Simple operators | 51 | map, filter, scan, statefulMap, throttle, take |
| Flow operators composed of Sinks and Sources | 2 | Flow.fromSinkAndSource, …Coupled |
| Asynchronous operators | 4 | mapAsync, mapAsyncUnordered, mapAsyncPartitioned{,Unordered} |
| Timer driven operators | 7 | delay, delayWith, initialDelay, groupedWithin, takeWithin |
| Backpressure aware operators | 8 | conflate, conflateWithSeed, batch, batchWeighted, expand, buffer |
| Nesting and flattening operators | 9 | flatMapConcat, flatMapMerge, switchMap, flatMapPrefix, groupBy |
| Time aware operators | 5 | idleTimeout, completionTimeout, keepAlive |
| Fan-in operators | 21 | merge, zip, zipLatest, mergeLatest, concat, orElse |
| Fan-out operators | 4 | Broadcast, Balance, Partition, Unzip |
| Watching status operators | 2 | watchTermination, monitor |
| Actor interop operators | 16 | ActorFlow.ask, ActorSource.actorRef |
| Compression operators | 6 | gzip, deflate, zstd |
| Error handling | 14 | recover, recoverWithRetries, onErrorResume, RestartSource.withBackoff |
Each operator page carries a fixed "Reactive Streams semantics" callout: emits when / backpressures when / completes when / cancels when. The same four lines appear in every Scaladoc (switchMap.md). It is the most transferable documentation convention in this survey.
API structure and naming
Source / transform / sink are three types, separated by shape. The separation is static (a Shape with one outlet, one inlet+outlet, or one inlet), not a separate API layer. Transforms are written once in the FlowOps[+Out, +Mat] trait and shared by Source, Flow, SubFlow and SubSource through an abstract type member: type Repr[+O] <: FlowOps[O, Mat], and type Closed ("result of closing a Source is RunnableGraph, closing a Flow is Sink") (Flow.scala#L853). So source.map(f) returns a Source and flow.map(f) returns a Flow from one method body. That is the Scala equivalent of our "operator returns a concrete struct" rule. FlowOpsMat adds the ReprMat[+O, +M]/ClosedMat[+M] members for operators that change Mat (Flow.scala#L4097). Sources are factories on the Source companion; sinks are factories on Sink. Running is on the blueprint (run, runWith, runFold, runForeach are Sink.xxx sugar).
Type parameters. In is the element type consumed and Out the type produced (contravariant / covariant in scaladsl). Mat is the value run() hands back for this piece, NotUsed when there is none. NotUsed is a sealed singleton type rather than Unit, so Java has a nameable value (NotUsed.scala).
The Mat plumbing family. Every combinator that joins two graphs comes in two forms. The plain one keeps the left value; the …Mat twin takes a combine function (Mat, Mat2) => Mat3, usually Keep.left, Keep.right, Keep.both or Keep.none (Materialization.scala). scaladsl/Flow.scala alone has 27 such twins: viaMat, toMat, zipMat, zipWithMat, zipLatestMat, zipLatestWithMat, zipAllMat, mergeMat, mergeLatestMat, mergePreferredMat, mergePrioritizedMat, mergeSortedMat, interleaveMat, concatMat, concatLazyMat, prependMat, prependLazyMat, orElseMat, alsoToMat, wireTapMat, divertToMat, monitorMat, flatMapPrefixMat, joinMat, fromSinkAndSourceMat, fromSinkAndSourceCoupledMat and fromProcessorMat. The viaMat doc even asks users to prefer Keep.left/Keep.right as "internally optimized" (Flow.scala#L4097).
That is the ergonomic cost. Three hot sources merged give ((Q1, Q2), Q3) nested tuples. Escape hatches have kept arriving to avoid threading a value to the top: preMaterialize (obtain a Source's value before wiring it), mapMaterializedValue, and in 2.0 Sink.source/materializeIntoSource (releases-2.0.md). MergeHub.source has type Source[T, Sink[T, NotUsed]], a source whose materialized value is a sink, and BroadcastHub.sink is the mirror (Hub.scala#L77, #L487). The model is coherent, but a reader must type-check two parallel pipelines (elements and materialized values) in every expression.
NOTE
The "ergonomic complaint" is inferred from the API's own shape: the twin count, the escape hatches added over time, and the nested Keep.both tuples in the project's own tests (FlowSwitchSpec.scala). No upstream design document conceding it was found at this SHA.
Variant naming families (all from scaladsl/Flow.scala):
| Suffix / prefix | Meaning | Examples |
|---|---|---|
xxxMat | also combine materialized values | viaMat, zipMat, alsoToMat |
flatMapXxx | flattening strategy named in the suffix | flatMapConcat, flatMapMerge, flatMapPrefix; latest-wins is switchMap |
flattenXxx | the same, for an already-nested stream | flattenMerge |
xxxUnordered | drop order preservation | mapAsyncUnordered, mapAsyncPartitionedUnordered |
xxxWithin | bounded by a time window | groupedWithin, takeWithin, dropWithin |
xxxWeighted | bounded by a cost function rather than a count | batchWeighted, groupedWeighted, groupedWeightedWithin, limitWeighted |
xxxWith | the "user function" variant of a fixed one | zipWith, zipLatestWith, delayWith, conflateWithSeed |
xxxLatest | combine the latest value of each side | zipLatest, mergeLatest |
xxxLazy / lazyXxx | defer the other side's materialization until needed | concatLazy, prependLazy; Source.lazySource, lazyFuture, lazySingle |
xxxAll | n-ary form taking a sequence | mergeAll, interleaveAll, concatAllLazy, alsoToAll |
onErrorXxx / recoverXxx | failure handling | onErrorComplete, onErrorResume, onErrorContinue, recoverWithRetries |
doOnXxx | side-effect taps | doOnFirst, doOnCancel |
A user-defined operator is either a composition (def debounced[T](d: FiniteDuration): Flow[T, T, NotUsed] = Flow[T].switchMap(…), returned as a reusable blueprint, per the library rule) or a GraphStage. The GraphStage is the one place where Pekko's contract resembles our Step next(ref FiberContext, ref T), so it is analysed in detail here:
final class TakeWhileLatest[T](p: T => Boolean) extends GraphStage[FlowShape[T, T]] {
val in = Inlet[T]("in"); val out = Outlet[T]("out")
override val shape = FlowShape(in, out)
override def createLogic(attrs: Attributes) = new GraphStageLogic(shape) with InHandler with OutHandler {
override def onPull(): Unit = pull(in) // demand flows up
override def onPush(): Unit = { // an element arrived
val x = grab(in)
if (p(x)) push(out, x) else completeStage()
}
// inherited defaults: onUpstreamFinish = completeStage(); onUpstreamFailure(ex) = failStage(ex);
// onDownstreamFinish(cause) = cancelStage(cause)
setHandlers(in, out, this)
}
}- Inverted control. The stage never asks "give me the next value". It receives
onPull(downstream wants one), callspull(in), and later receivesonPushand callsgrab/push. Onenext()call in our design is split into a request half and a reply half. That split is what lets one interpreter thread multiplex many stages without fibers. In our design the fiber stack does that job, sonextcan simply block. - Termination is three distinct callbacks, matching our
Steparms:onUpstreamFinish()corresponds todone,onUpstreamFailure(ex)to an error value, andonDownstreamFinish(cause: Throwable)tocancelled, with a cause (GraphStage.scala#L2115). The defaults complete, fail or cancel the whole stage. Cancellation is upstream-flowing, distinct from completion, and carries a reason (SubscriptionWithCancelException.NoMoreElementsNeededversusStageWasCompletedversus a real error;GraphStage.scala#L735). - Port state machines are enforced at run time.
pushbeforeonPull, orpulltwice, throwsIllegalArgumentException(#L872). The docs draw the legal transitions as state diagrams (stream-customize.md). OurStepreturn type encodes the same protocol in the type, so it cannot be violated. - Teardown is
postStop, not the handlers. "This is the only tear down callback that is guaranteed to happen, if the actor system or the materializer is terminated the handlers may never see any callbacks" (GraphStage.scala#L550). This matches scope-exit cleanup in a structured design. - Foreign threads enter through
getAsyncCallback, which marshals a value back onto the interpreter: "the passed handler will be invoked eventually in a thread-safe way by the execution environment" (#L1433). Timers come fromTimerGraphStageLogic.scheduleOnce(key, delay), whoseafterPostStopcancels every outstanding timer (#L1952). The concurrency guarantee is actor-like: "The callbacks exposed by all of these classes are never called concurrently" (stream-customize.md).
The Scala/Java split. javadsl is a parallel set of wrapper classes. javadsl.Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) is invariant and forwards each method by hand, for example def switchMap(…) = new Flow(delegate.switchMap(o => sourceGraph(f(o)))) (javadsl/Flow.scala#L381, #L3053). The wrappers are large: javadsl/Flow.scala 4,725 lines and javadsl/Source.scala 5,152, against 4,574 and 1,152 for scaladsl. Every operator is written twice, and the docs show every signature twice (@apidoc[…] { scala="…" java="…" }). 2.0 spent a release cleaning the Java side: "Java APIs no longer leak Scala types", wildcard bounds added "without casts or upcast", and pekko.japi.function types used throughout (releases-2.0.md).
Regrets, renames and removals. 2.0 removed "the Future based operators, stream converters, OverflowStrategy.dropNew, SubstreamCancelStrategy, the old splitWhen/splitAfter overloads, GraphStage.onDownstreamFinish() and the stream testkit probe methods" (releases-2.0.md#L384). The cause-less onDownstreamFinish() was replaced by onDownstreamFinish(cause), so cancellation now always carries a reason. TestSource.probe became TestSource(). gunzip was replaced by gzipDecompress (#L269). The Source.queue(bufferSize, overflowStrategy) overloads are deprecated because their "asynchronous offer can hang indefinitely under OverflowStrategy.backpressure". The replacement Source.queue(bufferSize) gives a BoundedSourceQueue with synchronous feedback (Source.scala#L1014, migration-guide-1.x-2.x.md). switchMap itself was only added in 1.2.0 (releases-1.2.md#L74), so for about a decade the Akka/Pekko line had no latest-wins flatten.
Time and scheduling
All time comes from the ActorSystem scheduler. TimerGraphStageLogic.scheduleOnce calls interpreter.materializer.scheduleOnce, which calls system.scheduler.scheduleOnce (PhasedFusingActorMaterializer.scala#L472). Timer callbacks re-enter the stage as async events. Operators run on the actor's dispatcher, which can be selected per island with ActorAttributes.dispatcher(...) or .async(dispatcher). There is no frame clock.
There is no debounce. git grep -i debounce over the whole tree returns nothing. The time operators are delay, delayWith, initialDelay, groupedWithin, throttle, idleTimeout and keepAlive, plus the rate adapters conflate/batch/expand. None of these restarts a timer on every input. A trailing restart-on-input debounce is written with the latest-wins flatten:
def debounce[T](d: => FiniteDuration): Flow[T, T, NotUsed] =
Flow[T].switchMap(x => Source.single(x).initialDelay(d)) // `d` re-read per elementinitialDelay is a TimerGraphStageLogic that calls scheduleOnce(GraphStageLogicTimer, delay) in preStart and pulls only after onTimer (Timers.scala#L210). Each element materializes a fresh substream, so the duration can change at runtime: d is evaluated when the substream is built. The old substream's timer dies in afterPostStop when switchMap cancels it. delayWith(() => DelayStrategy[T], …) is the built-in per-element dynamic delay (delayWith.md), but it delays every element rather than dropping superseded ones. throttle (token bucket over TimerGraphStageLogic, impl/Throttle.scala) and conflate are rate limiters, not debouncers.
Concurrency and cancellation
Latest-wins: switchMap (since 1.2.0). The doc: "the current (now previous) substream is cancelled while the Source resulting from the input element is subscribed to and flattened into the output stream … (which is why this operator is sometimes also called 'flatMapLatest')". Its callout says backpressures: never (switchMap.md, Flow.scala#L2898). The implementation Switch.scala always tryPull(in)s after a push. On each new element, setupCurrentSource calls src.cancel() on the current SubSinkInlet, discards it, and immediately calls subFusingMaterializer.materialize(...) on the new source. Empty sources are not materialized at all (the 1.2.0 fix "Avoid materialize an empty source in switchMap", releases-1.2.md). The test suite states the contract: "not wait for the previous / non-last substream to complete" and "cancel previous substream once a next substream arrives" (FlowSwitchSpec.scala).
Cancel does not wait. Cancellation is a signal: the cancelled substream's stages get onDownstreamFinish(cause) and then postStop, while the new substream is already running. Nothing joins the old one, and there is no "cancel and await" primitive anywhere in the stage API.
How cancellation reaches running work, and where it stops. Cancellation reaches every stage upstream, and timers and stage-owned resources are released in postStop. It does not reach a computation started by mapAsync. MapAsync registers future.onComplete(holder) and has no postStop cancellation (Ops.scala#L1355), and Scala's Future has no cancel at all. The work runs to completion, and its result is posted to a stopped stage and dropped. CPU-bound work therefore runs as mapAsync(parallelism)(x => Future(work(x))(blockingEc)), where parallelism is the in-flight bound. Making it cancellable means passing a token yourself. doOnCancel((cause, wasNormal) => …), added in 1.3.0, is the hook to flip that token (Flow.scala#L1634). The alternative, .async plus a dedicated dispatcher, moves a fused island to other threads, but a running map callback still cannot be interrupted.
External cancellation: kill switches. KillSwitches.single[T] is a pass-through Flow whose materialized value is a UniqueKillSwitch. It "always controls that graph and operator which yielded the materialized value". KillSwitches.shared(name) is created before materialization and controls every flow it is placed in. Both expose shutdown() (complete downstream, cancel upstream) and abort(ex) (fail downstream) (KillSwitch.scala). The kill switch is how a UI toggle kills a whole running graph from outside.
Errors and completion
The design separates errors (data elements) from failures (onError, the stream collapsing). "data elements emitted before a failure can still be lost if the onError overtakes them", because failure must be able to tear down a back-pressured stream (stream-design.md). Recovery operators act as "a bulkhead that confines a stream collapse to a given region of the stream topology": recover, recoverWithRetries, mapError, onErrorComplete/Resume/Continue.
Supervision (Supervision.Stop / Resume / Restart, Supervision.scala) is set as an attribute, but each operator must implement it: "if there is nothing in the documentation of an operator saying that it adheres to the supervision strategy it means it fails rather than applies supervision" (stream-error.md). 2.0 is still adding support to batch, expand and groupedWeightedWithin (releases-2.0.md). Restart means "accumulated state is cleared". RestartSource.withBackoff(settings)(() => source) / onFailuresWithBackoff re-materializes a source factory with exponential backoff (RestartSource.scala#L46). Completion of a running graph is observed through a materialized value (Sink.seq's Future, watchTermination's Future[Done]).
State and sharing
There is no value cell and no "current value" concept. Values live inside stages (scan, statefulMap) or outside the stream. Conflation is an operator: conflate((_, b) => b) keeps the latest element while downstream is slow, batch/batchWeighted bound the summary, and expand/extrapolate repeat the last element for a faster downstream (operator index).
Fan-out within one graph is explicit (Broadcast, Balance, Partition). Every materialized processor accepts a single subscriber, and "all fan-out is done using explicit elements like Broadcast[T]" (stream-design.md). Dynamic multicast across independently materialized graphs uses hubs: BroadcastHub.sink (materializes a Source that consumers attach to), MergeHub.source (materializes a Sink that producers attach to) and PartitionHub (Hub.scala).
Lifetime and ownership
A running graph is owned by its island actors, which are children of the materializer's supervisor. Its lifetime is the graph's: it ends when every stage has stopped. A stage stops when all its ports are closed (unless setKeepGoing(true)), and postStop is the guaranteed cleanup hook (GraphStage.scala#L550). A materializer created inside an actor (Materializer(context)) ties all its streams to that actor and stops them when the actor stops (stream-flows-and-basics.md). That is the nearest thing to a structured scope, and it is per-materializer, not lexical.
Leaks happen in three ways: a never-terminated infinite stream with no kill switch, a materialized value (BoundedSourceQueue, UniqueKillSwitch) dropped on the floor, and in-flight Futures that outlive cancellation. The 2.0 notes include memory-retention fixes ("Release references to completed stage logics and to the initial interpreter shell", releases-2.0.md).
Testing
stream-testkit provides TestSource[T]() and TestSink[T]() (TestSource.scala, TestSink.scala). They materialize to TestPublisher.Probe/TestSubscriber.Probe, which script demand and signals (request, sendNext, sendError, expectNext, expectRequest, expectCancellation). These are themselves an instance of the materialized-value pattern. The switchMap suite uses them to observe cancellation directly:
val (mainPub, probe) =
TestSource[Source[Int, NotUsed]]().switchMap(identity).toMat(TestSink())(Keep.both).run()
val subPub = TestPublisher.probe[Int]()
probe.request(1)
mainPub.sendNext(Source.fromPublisher(subPub))
subPub.expectRequest()
mainPub.sendError(new Exception("buh"))
subPub.expectCancellation()Virtual time is a process-wide scheduler swap. Setting pekko.scheduler.implementation = "org.apache.pekko.testkit.ExplicitlyTriggeredScheduler" replaces the ActorSystem scheduler. timePasses(d) then runs due tasks on the calling thread (ExplicitlyTriggeredScheduler.scala). The typed testkit wraps the swap as ManualTime.config and ManualTime().timePasses(d) (ManualTime.scala). Stream timers ride on the system scheduler, so a debounce is testable deterministically. stream-tests does this for aggregateWithBoundary, with a telling caveat: "To run multiple tests in parallel using simulated timer, the tests must be in separate Specs with different instances of the ActorSystem" (AggregateWithBoundarySpec.scala#L173). The clock is global to the system, not scoped to the test. Pekko's stream testkit page (stream-testkit.md) does not mention virtual time.
The worked pipeline
One BoundedSourceQueue carries tagged UI events. statefulMap folds them into commands, and switchMap gives the debounce, the latest-wins hash and the toggle in one operator, because emitting Source.empty cancels whatever is running.
sealed trait Ev
final case class Query(q: String) extends Ev
final case class Interval(n: FiniteDuration) extends Ev
final case class Enabled(on: Boolean) extends Ev
sealed trait Cmd
final case class Run(q: String, n: FiniteDuration) extends Cmd
case object Stop extends Cmd
final case class St(n: FiniteDuration, on: Boolean, last: Option[String])
val hashEc: ExecutionContext = system.dispatchers.lookup("hash-dispatcher") // CPU pool
val latest = new AtomicReference[Option[Digest]](None) // read by the UI each frame
val (ui, done) =
Source.queue[Ev](bufferSize = 64) // Mat: BoundedSourceQueue[Ev]
.statefulMap(() => St(250.millis, on = true, last = None))(
(s, ev) => ev match {
case Query(q) => val s2 = s.copy(last = Some(q)); (s2, if (s.on) Some(Run(q, s.n)) else None)
case Interval(n) => (s.copy(n = n), None) // affects the *next* debounce
case Enabled(b) => (s.copy(on = b),
if (!b) Some(Stop) else s.last.map(Run(_, s.n)))
},
_ => None)
.collect { case Some(c) => c }
.switchMap {
case Stop => Source.empty // cancels debounce + hash
case Run(q, n) =>
val cancelled = new AtomicBoolean(false) // per-query token
Source.single(q)
.initialDelay(n) // the debounce
.mapAsync(parallelism = 1)(q => Future(hashFileSet(q, cancelled))(hashEc))
.doOnCancel((_, _) => cancelled.set(true)) // cancel -> token
}
.toMat(Sink.foreach(d => { latest.set(Some(d)); wakeUi() }))(Keep.both)
.run()
ui.offer(Query("ab")) // from the UI thread; returns QueueOfferResult synchronouslyTrace.
- Keystroke during debounce.
ui.offer(Query("abc"))returnsEnqueuedat once. On the stream actor,statefulMapemitsRun("abc", n)andSwitch.onPushcallscancelCurrentSource(). The old substream getsonDownstreamFinish(NoMoreElementsNeeded)throughdoOnCancel(which sets a token nobody is using yet) andmapAsync, then reachesinitialDelay. ItspostStop→afterPostStopcancels the pending timer. A new substream is materialized with a freshntimer. The input is dropped and nothing is hashed. - Keystroke during hash. Same path, but the old
mapAsyncholds a runningFuture.doOnCancelsetscancelled, and the stage stops at once without waiting. The worker keeps hashing untilhashFileSetnext polls the flag. Meanwhile the new substream's debounce timer is already running, so for a while two hashes can occupyhashEc. The old result, if it arrives, goes to a stoppedAsyncCallbackand is discarded. Latest-wins holds for output, but not for resources. - Interval change.
statefulMapstoresnand emits nothing, so a pending debounce keeps its old deadline and the next query uses the newn. Restarting the pending timer with the new duration would mean emittingRun(last, n)instead. That also restarts an in-flight hash, becauseswitchMapcannot tell "same query, new delay" apart from a new query. - Toggle off.
StopreachesswitchMap, which cancels the current substream (debounce timer or hash token, as above). It then seesSource.emptyviaTraversalBuilder.isEmptySourceand materializes nothing. Queries while off only updatelast. Toggle on re-runs the last query. A heavier alternative wraps the graph inKillSwitches.singleand re-materializes on enable, which loses all stage state.
Fit with a per-frame UI. The fit is reasonable but indirect. The stream runs on actor threads, so the UI must cross threads twice. Input goes in through BoundedSourceQueue.offer, which is synchronous and frame-friendly. Output comes back through an AtomicReference plus a wake, or through Sink.queue's pull(): Future[Option[T]]. Every handle the UI needs (ui, done, a kill switch) exists only as a materialized value of one run(). A widget tree rebuilt every frame must store them across frames and must never re-run the blueprint. There is no frame clock and no conflating "current value" sink built in, and the debounce and the cancellation token are both user code.
Strengths
- Blueprint/run separation is total and principled. Graphs are immutable values that can be shared and run many times. Libraries return blueprints, and resources are acquired only at materialization. This is the cleanest statement of "description versus running" in the survey.
- One trait, many shapes.
FlowOpswithtype Repr[+O]writes each operator once forSource,FlowandSubFlow, each returning its own concrete type. GraphStageis a well-specified, documented operator SPI. It has explicit port state machines, three distinct termination callbacks, cancellation with a cause, a guaranteedpostStop, actor-like non-concurrency and an async-callback door.- Operator documentation discipline. A categorised index of about 230 entries, plus fixed emits/backpressures/completes/cancels callouts on every operator.
- Bounded by construction. Demand bounds every hop, every buffer is explicit (
buffer,conflate,batch), and fusion makes the common case free of per-element messages.
Weaknesses
- The materialized-value channel doubles the type-level surface. There are 27
xxxMattwins,Keep.*tuples, arity-generatedGraphDSL.create, and a stream of escape hatches (preMaterialize,Sink.source). - There is no structured cancellation of user work.
Futures are not cancellable,mapAsynccannot stop them,switchMapdoes not wait for the cancelled substream, and resources overlap after a switch. - There is no debounce and no value cell. Latest-wins arrived only in 1.2.0. UI-shaped streams are assembled from
switchMap,initialDelayand an outsideAtomicReference. - The Java DSL is a hand-maintained mirror. About 10,000 lines of forwarding code, two signatures per operator in the docs, and a major version spent fixing leaked Scala types.
- Supervision is opt-in per operator, and absence means "fails"; users must check each operator's page.
- Virtual time is per
ActorSystem: tests that use it cannot share a system or run in parallel inside one.
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
| Immutable blueprints, explicit materialization | Reuse, shareability, library composability; optimisation at materialize time | Handles to a running stream exist only as materialized values |
A typed Mat channel on every graph | Expose control objects (queues, kill switches, results) type-safely | xxxMat twins, Keep combinators, nested tuples; a second pipeline to type-check |
| Reactive Streams as hidden SPI | Freedom to fuse and swap java.util.concurrent.Flow; hard-to-implement SPI hidden | Interop needs explicit asPublisher/fromSubscriber adapters |
Fuse by default, .async to split | No per-element messaging; one actor per island | One core per island; boundaries are coarse attributes, not per-operator |
Callback stages (onPull/onPush) on a shared interpreter | Thousands of stages per thread without stacks | Inverted control; protocol violations are runtime exceptions |
| Cancellation as a signal with a cause, no join | Fast teardown of back-pressured graphs | Cancelled work overlaps new work; Futures are never interrupted |
| Supervision implemented per operator | Only meaningful where state can be dropped/reset | Inconsistent coverage; users read each operator page |
Parallel scaladsl/javadsl wrappers | Idiomatic types (variance, CompletionStage, Optional) per language | Double maintenance; Java API lagged and leaked Scala types until 2.0 |
Sources
- apache/pekko at
df133f7de2d535c138a2ed6c943995ef93ac529d:README.md,LICENSE. - Design and guide pages:
stream-design.md,stream-flows-and-basics.md,stream-customize.md,stream-error.md,stream-testkit.md,operators/index.md,switchMap.md,delayWith.md. - Release notes and migration:
releases-1.2.md,releases-2.0.md,migration-guide-1.x-2.x.md. - Source:
scaladsl/Flow.scala,scaladsl/Materialization.scala,scaladsl/Graph.scala,GraphApply.scala.template,scaladsl/Hub.scala,scaladsl/RestartSource.scala,scaladsl/Source.scala,javadsl/Flow.scala,stage/GraphStage.scala,impl/fusing/GraphInterpreter.scala,impl/fusing/Switch.scala,impl/fusing/Ops.scala,impl/Timers.scala,impl/Throttle.scala,impl/PhasedFusingActorMaterializer.scala,KillSwitch.scala,Supervision.scala,reference.conf,NotUsed.scala. - Testing:
TestSource.scala,TestSink.scala,ExplicitlyTriggeredScheduler.scala,ManualTime.scala,FlowSwitchSpec.scala,AggregateWithBoundarySpec.scala. - External: Pekko Streams documentation; Jonas Bonér, Why we are changing the license for Akka (September 7, 2022).
- Related deep-dives: RxJS, Rx.NET, Kotlin Flow, fs2, Rust streams, Swift Async Algorithms, Effect-TS, Cats Effect; umbrella index, concepts, comparison; async I/O survey.