Process a Large File with ZIO Streams
Welcome! This tutorial is for people who know basic ZIO (ZIO, for comprehensions, Ref) and want to process a file that is too big to load into memory. You don't need any experience with ZIO Streams.
Learning Objectivesโ
By the end of this tutorial, you will understand:
- How to read a file as a stream of bytes, decode it, and split it into lines
- How to parse each line into a case class and handle the lines that do not parse
- How to total a stream of records with a sink
- How to process records with bounded parallelism, and what ordered and unordered mean
- How to group records into batches and write them to a file
- Why memory use stays constant however big the file is
We'll learn these concepts through:
- Creating the input file
- Reading lines
- Parsing records
- Totalling with a sink
- Processing in parallel
- Grouping into batches
- Writing the summary
- Why memory stays constant
We recommend reading from top to bottom.
Backgroundโ
Reading a whole file into a List[String] works until the file is bigger than the heap. A stream solves this by handing out the file in small pieces. It reads a piece, your code handles it, and only then does the stream read the next piece.
In ZIO Streams, three types fit together to make a pipeline. A ZStream produces elements. A ZPipeline transforms them. A ZSink consumes them and returns one final result. In this tutorial, we process a file of orders. Each line holds an order id, a customer and an amount in cents, and some lines are broken on purpose.
Installโ
The tutorial uses ZIO Streams, which is a separate artifact from ZIO core:
// ZIO core
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
// ZIO Streams: ZStream, ZPipeline and ZSink
libraryDependencies += "dev.zio" %% "zio-streams" % "2.1.27"
Every code block below builds on the ones before it. The full program is in Putting It Together.
1. Creating the Input Fileโ
We need a file to read. Instead of shipping a big data file, we write one with a stream. ZStream.range produces the numbers, map turns each number into a CSV line, and ZSink.fromPath writes the bytes to a file. Every thousandth line is broken on purpose, so that we can handle bad input later.
import zio._
import zio.stream._
import java.nio.file.Path
final case class Order(id: Long, customer: String, cents: Long)
def generate(path: Path, n: Int): Task[Long] =
ZStream
.range(1, n + 1)
.map { i =>
if (i % 1000 == 0) s"order-$i,oops\n"
else s"$i,customer-${i % 50},${(i * 37) % 10000}\n"
}
.via(ZPipeline.utf8Encode)
.run(ZSink.fromPath(path))
The code above:
ZStream.range(1, n + 1)โ a stream of the numbers 1 ton..map { ... }โ turns each number into one line of text that ends with a newline..via(ZPipeline.utf8Encode)โ passes the stream through a pipeline that turns eachStringinto bytes..run(ZSink.fromPath(path))โ feeds the bytes to a sink that writes them topath. The result is the number of bytes written.
The program in the examples folder calls generate(input, 5000), and the first thing it prints is:
1. wrote 107299 bytes to the input file
2. Reading Linesโ
Reading is the same pipeline the other way round. ZStream.fromPath produces the file's bytes. ZPipeline.utf8Decode turns bytes into strings. ZPipeline.splitLines cuts the strings at newlines, so each element is one line. The >>> operator joins two pipelines into one.
def lines(path: Path): ZStream[Any, Throwable, String] =
ZStream
.fromPath(path)
.via(ZPipeline.utf8Decode >>> ZPipeline.splitLines)
Nothing is read yet. A stream is a description, and the file is opened only when something runs it. We run it to look at the first three lines:
def firstLines(path: Path): Task[Chunk[String]] =
lines(path).take(3).runCollect
The take(3) stops the stream after three lines, so the rest of the file is never read. Output:
2. first lines: 1,customer-1,37 | 2,customer-2,74 | 3,customer-3,111
splitLines handles both \n and \r\n, and it works even when a line is split across two pieces of the file.
3. Parsing Recordsโ
A line is just text. We turn it into an Order, and when that is not possible we get the bad line back. parse returns an Either: Right for an order and Left for a bad line.
def parse(line: String): Either[String, Order] =
line.split(",") match {
case Array(id, customer, cents) =>
(id.toLongOption, cents.toLongOption) match {
case (Some(i), Some(c)) => Right(Order(i, customer, c))
case _ => Left(line)
}
case _ => Left(line)
}
Now we have a choice for bad lines. We could fail the whole stream on the first one. Here we skip them and count them, which is what most large files need. A Ref holds the count. mapZIO runs an effect for each line, and collectSome keeps only the Some values:
def orders(path: Path, bad: Ref[Long]): ZStream[Any, Throwable, Order] =
lines(path)
.mapZIO { line =>
parse(line) match {
case Right(order) => ZIO.some(order)
case Left(_) => bad.update(_ + 1).as(None)
}
}
.collectSome
The code above:
mapZIOโ runs one effect per line, in order.ZIO.some(order)โ a good line becomesSome(order).bad.update(_ + 1).as(None)โ a bad line adds one to the counter and becomesNone.collectSomeโ drops theNonevalues and unwraps theSomevalues, so the stream has typeZStream[Any, Throwable, Order].
If you want the stream to stop at the first bad line instead, replace the Left case with ZIO.fail(line) and add String to the error type.
4. Totalling with a Sinkโ
A sink consumes a stream and returns one value. ZSink.foldLeft is the stream version of foldLeft. It starts with a value and updates it for each element. We use it to count the orders and add up their amounts:
final case class Totals(count: Long, cents: Long)
def totals(path: Path, bad: Ref[Long]): Task[Totals] =
orders(path, bad).run(
ZSink.foldLeft(Totals(0, 0))((t, o) => Totals(t.count + 1, t.cents + o.cents))
)
run reads the whole file through the pipeline and returns the final Totals. At any moment only one Totals value and the current piece of the file are in memory. Reading the counter afterwards gives the skipped lines:
4. totals: Totals(4995,24637500), skipped bad lines: 5
The file has 5000 lines and every thousandth one is broken, so 4995 orders and 5 skipped lines add up.
ZSink.count counts elements, and ZSink.collectAllToMap builds a Map by key. They are shortcuts for common folds. See Creating Sinks for the full list.
5. Processing in Parallelโ
Real pipelines call other systems for each record. In the example, enrich stands in for such a call: it waits a few milliseconds and then adds a region to the order. One call at a time would be slow, so we run eight at a time with mapZIOPar(8):
final case class EnrichedOrder(order: Order, region: String)
def enrich(order: Order): UIO[EnrichedOrder] =
ZIO
.sleep((order.id % 5 + 1).millis)
.as(EnrichedOrder(order, if (order.customer.hashCode % 2 == 0) "north" else "south"))
def enriched(path: Path, bad: Ref[Long]): ZStream[Any, Throwable, EnrichedOrder] =
orders(path, bad).mapZIOPar(8)(enrich)
mapZIOPar(8) starts up to eight calls at once. It never starts a ninth until one finishes, so the other system sees at most eight requests at a time. The results come out in the same order as the input.
mapZIOParUnordered(8) also runs eight at a time, but it emits each result as soon as it is ready. Orders with a short delay can overtake orders with a long delay. Here are the first twelve ids from each:
5. mapZIOPar(8) order: 1,2,3,4,5,6,7,8,9,10,11,12
5. mapZIOParUnordered(8) order: 1,2,5,3,6,4,7,10,8,11,9,12
Notice that the unordered ids come out mixed up. The order can differ from run to run. Choose mapZIOPar when the order of results matters, and mapZIOParUnordered when it doesn't, because it never makes a fast element wait for a slow one.
6. Grouping into Batchesโ
Writing each record on its own is wasteful. We group them into batches instead. groupedWithin(500, 5.seconds) collects up to 500 elements, and it emits a smaller batch when five seconds have passed since the last one or when the stream ends:
def batches(path: Path, bad: Ref[Long]): ZStream[Any, Throwable, Chunk[EnrichedOrder]] =
enriched(path, bad).groupedWithin(500, 5.seconds)
Each element of this stream is a Chunk of up to 500 orders. A Chunk is ZIO's immutable array-like collection. grouped(500) does the same without the time limit. The time limit matters when records arrive slowly: without it, a batch of 500 could wait forever to fill up.
7. Writing the Summaryโ
The last step turns each batch into one summary line and writes the lines to a file. We reuse what we learned in section 1: encode with utf8Encode and finish with ZSink.fromPath. zipWithIndex numbers the batches:
def writeSummary(path: Path, summary: Path, bad: Ref[Long]): Task[Long] =
batches(path, bad)
.zipWithIndex
.map { case (batch, index) =>
s"batch-$index,${batch.size},${batch.map(_.order.cents).sum}\n"
}
.via(ZPipeline.utf8Encode)
.run(ZSink.fromPath(summary))
The whole job is one stream: read, decode, split, parse, enrich, batch, encode and write. Running it on the 5000-line file prints:
7. wrote 200 bytes to the summary file
7. summary has 10 rows, first: batch-0,500,2334250, last: batch-9,495,2432880
Ten rows is right: 4995 orders make nine batches of 500 and one of 495.
8. Why Memory Stays Constantโ
None of the steps above holds the file. Three facts explain this:
- Streams work on small chunks.
ZStream.fromPathreads the file 4096 bytes at a time, and the steps pull data in small pieces instead of loading the file. Some steps, such asmapZIOParandgroupedWithin, also keep a small fixed-size buffer. The Streams Are Chunked by Default page explains this in depth. - A slow step slows the whole pipeline. The stream is pulled from the end. The sink asks for more only when it is ready, so a slow
enrichstep makes the file reader wait instead of piling up data. This is called back-pressure. - The only state is small. The
Totalsvalue, the counter, one batch of 500 orders and the small fixed-size buffers of the parallel and batching steps are all we keep.
So the size of the file does not decide how much memory the job needs. To check this, we ran the totals step from section 4 on a generated file of 3 million lines (73 MB) with the Java heap limited to 48 MB with -Xmx48m. It finished and printed Totals(2997000,14985000000). The file was bigger than the whole heap, and the job did not run out of memory.
Putting It Togetherโ
The complete program joins the steps above. It differs from the sections in four ways. It creates a temporary directory for the input and the summary and deletes it at the end. It runs the pipeline several times on the same file, once for each section. It prints a labelled line after each stage, which is how the outputs in this tutorial were produced. And it counts bad lines in one Ref that is shared by all of those runs.
Runnable version, with a temporary directory and printed output: CompleteExample.scala
//> using scala 2.13.18
//> using dep dev.zio::zio:2.1.25
//> using dep dev.zio::zio-streams:2.1.25
// Run from this folder: scala-cli run CompleteExample.scala
// Or from zio-examples/streams-large-file: sbt "runMain streamslargefile.CompleteExample"
package streamslargefile
import zio._
import zio.stream._
import java.nio.file.{Files, Path}
/**
* Tutorial: Process a Large File with ZIO Streams
*
* Generates a CSV file of orders, then reads it back as a stream, parses it,
* totals it, enriches it with bounded parallelism, groups it into batches and
* writes a summary file. Memory use does not depend on the size of the file.
*/
object CompleteExample extends ZIOAppDefault {
final case class Order(id: Long, customer: String, cents: Long)
final case class EnrichedOrder(order: Order, region: String)
final case class Totals(count: Long, cents: Long)
val orderCount = 5000
// Writes `n` order lines (every 1000th one is malformed) with a sink
def generate(path: Path, n: Int): Task[Long] =
ZStream
.range(1, n + 1)
.map { i =>
if (i % 1000 == 0) s"order-$i,oops\n"
else s"$i,customer-${i % 50},${(i * 37) % 10000}\n"
}
.via(ZPipeline.utf8Encode)
.run(ZSink.fromPath(path))
// Turns one line into an Order, or hands the bad line back
def parse(line: String): Either[String, Order] =
line.split(",") match {
case Array(id, customer, cents) =>
(id.toLongOption, cents.toLongOption) match {
case (Some(i), Some(c)) => Right(Order(i, customer, c))
case _ => Left(line)
}
case _ => Left(line)
}
// Read bytes, decode them, split them into lines
def lines(path: Path): ZStream[Any, Throwable, String] =
ZStream
.fromPath(path)
.via(ZPipeline.utf8Decode >>> ZPipeline.splitLines)
// Parse every line; skip the bad ones and count them
def orders(path: Path, bad: Ref[Long]): ZStream[Any, Throwable, Order] =
lines(path).mapZIO { line =>
parse(line) match {
case Right(order) => ZIO.some(order)
case Left(_) => bad.update(_ + 1).as(None)
}
}.collectSome
// Stands in for a call to another service; the delay differs per order
def enrich(order: Order): UIO[EnrichedOrder] =
ZIO
.sleep((order.id % 5 + 1).millis)
.as(EnrichedOrder(order, if (order.customer.hashCode % 2 == 0) "north" else "south"))
def run =
ZIO.scoped {
for {
dir <- ZIO.acquireRelease(ZIO.attempt(Files.createTempDirectory("orders")))(d =>
ZIO.attempt {
Files.list(d).forEach(p => Files.delete(p))
Files.delete(d)
}.orDie
)
input = dir.resolve("orders.csv")
summary = dir.resolve("summary.csv")
// 1. Generate the input file
written <- generate(input, orderCount)
_ <- Console.printLine(s"1. wrote $written bytes to the input file")
// 2-3. Read, decode, split, parse; count bad lines
bad <- Ref.make(0L)
first <- lines(input).take(3).runCollect
_ <- Console.printLine(s"2. first lines: ${first.mkString(" | ")}")
// 4. Aggregate with a sink: only the Totals value stays in memory
totals <- orders(input, bad).run(ZSink.foldLeft(Totals(0, 0))((t, o) => Totals(t.count + 1, t.cents + o.cents)))
skipped <- bad.get
_ <- Console.printLine(s"4. totals: $totals, skipped bad lines: $skipped")
// 5. Bounded parallelism: ordered and unordered
ordered <- orders(input, bad).mapZIOPar(8)(enrich).map(_.order.id).take(12).runCollect
_ <- Console.printLine(s"5. mapZIOPar(8) order: ${ordered.mkString(",")}")
unordered <- orders(input, bad).mapZIOParUnordered(8)(enrich).map(_.order.id).take(12).runCollect
_ <- Console.printLine(s"5. mapZIOParUnordered(8) order: ${unordered.mkString(",")}")
// 6-7. Batch, summarise, write the summary file
bytes <- orders(input, bad)
.mapZIOPar(8)(enrich)
.groupedWithin(500, 5.seconds)
.zipWithIndex
.map { case (batch, index) =>
s"batch-$index,${batch.size},${batch.map(_.order.cents).sum}\n"
}
.via(ZPipeline.utf8Encode)
.run(ZSink.fromPath(summary))
_ <- Console.printLine(s"7. wrote $bytes bytes to the summary file")
rows <- ZIO.attempt(Files.readAllLines(summary))
_ <- Console.printLine(
s"7. summary has ${rows.size} rows, first: ${rows.get(0)}, last: ${rows.get(rows.size - 1)}"
)
} yield ()
}
}
Running the Examplesโ
All runnable code from this tutorial is in zio-examples/streams-large-file/. Run it with scala-cli run CompleteExample.scala from that folder, or from zio-examples/streams-large-file with sbt "runMain streamslargefile.CompleteExample".
What You've Learnedโ
In this tutorial, you learned:
- How to read a file with
ZStream.fromPath, and decode and split it withZPipeline.utf8Decode >>> ZPipeline.splitLines - How to parse lines into a case class and skip bad lines while counting them
- How to total a stream with a sink such as
ZSink.foldLeft - How to process records with
mapZIOParandmapZIOParUnordered, and when each is the right choice - How to batch with
groupedWithinand write results withZSink.fromPath - Why a pipeline of small chunks and back-pressure keeps memory constant
You now have a path you can reuse for any file that is too big to load whole.
Where to Go Nextโ
- Want the full API? Read the reference pages for
ZStream,ZPipelineandZSink. - Need to retry the calls in the parallel step? See Retry and Repeat Policies with Schedule.
- Want to handle errors in a stream? Read Error Handling in ZStream.