whoami
Lucas Jenß
cat /etc/motd
The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.
ls -la ~/languages/
- drwxr-xr-x
- ▶ PHP
- ▶ Ruby
- ▶ Scala
- ▶ C#
- ▶ JavaScript
- ▶ Objective-C
- ▶ Shell Scripting
ls -la ~/toolchain/
- drwxr-xr-x
- ▶ Typo3
- ▶ Akka
- ▶ Capistrano
- ▶ Git
- ▶ MAMP
- ▶ Adobe Illustrator
- ▶ NSTrackingArea (Cocoa)
uname -a
- drwxr-xr-x
- ▶ Mac OS X
- ▶ Unix
Writing a Scala Akka Stream That Transforms CSV Files on the Fly
CSV processing looks simple until the input grows beyond the size that comfortably fits in memory. A small script can read every line, split it on commas, modify a few fields and write the result. A production service handling exports, uploads or scheduled reports needs a different approach.
Akka Streams provides a useful model for this work. It reads bytes incrementally, applies transformations while data is flowing, and writes the output without waiting for the entire file to arrive. Back-pressure also prevents a fast file reader from overwhelming a slower parser, database or network destination.
This pattern is suitable for Scala applications that receive files through an HTTP endpoint, consume objects from cloud storage or process daily exports from an Australian business system. It can handle a Melbourne customer export during business hours just as reliably as a nightly batch from a Brisbane warehouse.
The important details are boundary management, CSV correctness and failure handling. A newline is not always a record boundary, and a comma is not always a field boundary. The stream must account for quoted values, escaped quotes, character encoding and malformed rows before applying business rules.
Model the pipeline as small stages
An Akka Stream is easiest to maintain when each stage has one clear responsibility. A typical CSV transformation pipeline looks like this:
import akka.stream.scaladsl.{FileIO, Framing, Flow, Sink}
import akka.util.ByteString
val lines =
FileIO.fromPath(inputPath)
.via(Framing.delimiter(ByteString("\n"), maximumFrameLength = 1024 * 1024))
.map(_.utf8String.stripSuffix("\r"))
val transformed =
lines
.drop(1) // skip the header when it is handled separately
.map(transformRow)
transformed
.map(row => ByteString(row + "\n"))
.runWith(FileIO.toPath(outputPath))
The source emits chunks of bytes rather than complete records. Framing.delimiter turns those chunks into newline-delimited frames, even when one physical read contains half a line or several lines. The maximum frame length should be chosen deliberately. A one-megabyte limit may be sensible for ordinary exports, while a data set containing long JSON fields requires a larger value.
A real application will usually preserve the header and attach a materialised completion value to the stream. runWith returns a Future[IOResult], which should be observed by the calling service. A successful stream means the output sink completed; it does not automatically mean every record matched the desired business rules.
Parse CSV instead of splitting strings
Calling line.split(",") is a common source of subtle data corruption. Consider a field such as "Sydney, NSW" or a description containing a quotation mark. A plain split cannot distinguish the comma inside the quoted field from a separator between columns.
Use a CSV parser that understands RFC 4180-style quoting, escaped double quotes and optional headers. Libraries such as kantan.csv or commons-csv can be placed behind a small adapter. That keeps parsing concerns out of the stream stages that perform validation and enrichment.
case class Customer(id: String, suburb: String, spend: BigDecimal)
def parseCustomer(line: String): Either[String, Customer] =
CsvParser.parse(line) match {
case Right(fields) =>
for {
id <- fields.get("id").toRight("missing id")
suburb <- fields.get("suburb").toRight("missing suburb")
spend <- fields.get("spend").flatMap(toDecimal)
} yield Customer(id, suburb, spend)
case Left(error) =>
Left(error.message)
}
Keeping parsing as an Either makes malformed input explicit. It also prevents a single bad row from unexpectedly terminating a long-running import. Depending on the application, invalid rows can be sent to a dead-letter file, counted in metrics or returned in a validation report.
Preserve back-pressure during transformation
A synchronous map stage is sufficient when the transformation is CPU-bound and quick. Normalising a postcode, trimming whitespace or calculating a derived amount generally fits this model. The stream remains lazy, and downstream demand controls how quickly rows are processed.
External lookups require more care. If each record must be checked against a database or remote API, use mapAsync with a bounded parallelism value:
val enriched =
parsed.mapAsync(parallelism = 8) { customer =>
customerService.lookupRegion(customer.suburb)
.map(region => customer.copy(suburb = s"${customer.suburb} ($region)"))
}
The parallelism value is a limit, not a guarantee that eight requests are always safe. It should reflect connection-pool capacity, service limits and the amount of memory available for in-flight rows. For a small Australian retailer importing a file from Perth, eight concurrent lookups may be appropriate; a national catalogue import may need a different design based on batching or bulk queries.
Avoid converting the stream into a collection with runFold or toVector simply to make transformation easier. That defeats streaming and can cause an out-of-memory failure when a customer export reaches several gigabytes.
Choose an error strategy before production
There are two broad categories of failure. A malformed record is usually a data-quality issue, while an unavailable database or failed output write is an operational failure. Treating both in the same way makes recovery difficult.
One practical approach is to keep valid and invalid rows in separate flows:
val parsed = lines.map(parseCustomer)
val validRows = parsed.collect { case Right(customer) => customer }
val invalidRows = parsed.collect { case Left(reason) => reason }
This simple split is useful for demonstrations, but production code often needs the original line number and raw content as well. A wrapper such as ParsedRow(lineNumber, raw, result) allows support staff to locate the problem in a source file without guessing.
recoverWithRetries can help with temporary failures, but it should not conceal deterministic parser errors. Retrying a malformed CSV row will produce the same result and may duplicate side effects. For external services, combine bounded retries with timeouts and idempotent operations. Log enough context to diagnose an incident without writing personal information or payment data into application logs.
Compare common CSV stream designs
The right implementation depends on the shape of the input and the destination. A line-oriented design is compact, while a record-aware parser is safer for data containing embedded newlines.
| Design | Strengths | Risks | Suitable use |
|---|---|---|---|
Framing.delimiter plus a CSV parser |
Simple, fast and easy to compose | Does not support quoted fields containing newlines unless the parser receives complete logical records | Controlled exports with one record per physical line |
| Whole-file parsing | Convenient for small files and complex CSV grammar | Uses memory proportional to file size | Small uploads and administrative tools |
| Streaming CSV library | Handles quoting and record boundaries correctly | Adds a dependency and requires library-specific integration | Large, messy or externally supplied files |
Line parsing with mapAsync enrichment |
Clear separation between parsing and business work | Poorly bounded concurrency can overload services | Imports requiring database or HTTP lookups |
A useful compromise is to use a streaming CSV parser as a GraphStage or library-provided Flow[ByteString, CsvRecord, _]. This preserves Akka back-pressure while allowing quoted line breaks. If the application already has a shared platform, the parser can live in a reusable module, much like the shared codebase approach described in TYPO3 multisite configuration.
The output format deserves equal attention. Serialise fields with the same care used during parsing. A value containing commas, quotes or line breaks must be escaped and quoted consistently. Do not build output rows by interpolating strings unless the escaping function is guaranteed to cover every field.
Test boundaries, encoding and file semantics
Unit tests should include commas inside quoted values, escaped quotes, empty fields, trailing columns and Windows-style \r\n line endings. Test a delimiter split across byte chunks too. Akka Streams test utilities can feed controlled ByteString fragments into the parser and verify that records emerge in the expected order.
Use explicit character encoding where possible. UTF-8 is a sensible default for modern systems, but older exports may contain Windows-1252 characters such as curly apostrophes or the euro symbol. An Australian organisation may receive files from a legacy finance package in one encoding and send them to a cloud service expecting another, so encoding conversion should be a visible stage rather than an accidental platform default.
Temporary output files also need a safe lifecycle. Write to a temporary path, close the stream successfully, and then move the completed file into its final location. This prevents another process from reading a partially written export. On shared Linux hosts, include permissions and cleanup rules in the deployment configuration.
Make observability part of the stream
A file transformation is much easier to operate when it reports counts and timing. Track records read, records written, rejected rows, parser failures and downstream retries. wireTap can observe a flow for metrics without changing the elements moving through it, while alsoTo can send a copy to a diagnostic sink when that behaviour is genuinely required.
Keep the materialised result visible to the application boundary:
val result: Future[IOResult] =
output.runWith(FileIO.toPath(finalPath))
result.onComplete {
case Success(io) if io.wasSuccessful =>
logger.info("CSV transformation completed: {} bytes", io.count)
case Success(io) =>
logger.error("CSV output stopped after {} bytes", io.count)
case Failure(error) =>
logger.error("CSV transformation failed", error)
}
For HTTP uploads, connect cancellation to the request lifecycle. If a user in Adelaide closes the browser while a large file is being processed, the stream should stop reading and release resources. For scheduled jobs, record a run identifier and retain the source filename, checksum and processing counts so an operator can distinguish a new import from a replay.
The same principles apply when generating fixtures for tests. Deterministic rows are best for parser tests, while varied numeric combinations can exercise validation and aggregation paths; a separate keno data reference can provide a domain-neutral example of combinations without using production records.
Keep configuration and deployment predictable
Akka Streams relies on an ActorSystem and materialiser, so lifecycle management matters. Create them at application scope, shut them down during service termination and avoid creating one per uploaded file. Configure dispatcher settings for blocking work rather than allowing file or database operations to run on the default dispatcher.
File paths, maximum record size, parser mode, concurrency and rejected-row policy should come from configuration. Hard-coded limits become awkward when the same service processes a small local export in Canberra and a much larger feed from a Sydney partner. Configuration also makes operational changes auditable.
Start with a narrow vertical slice: read a file, parse valid CSV, transform one field and write a new file. Add invalid-row handling, asynchronous enrichment, metrics and atomic publication as separate steps. This keeps failures easy to isolate and makes the resulting Scala Akka stream understandable months after the original troubleshooting session.
Use a small representative fixture, then test with large generated files before release. Measure memory, throughput and downstream request rates rather than assuming that a streaming design is automatically efficient. Once the pipeline has clear boundaries, explicit errors and observable completion, it becomes a dependable building block for imports, exports and file-based integrations.
Build the first version around a streaming source, a standards-aware CSV parser and a bounded transformation flow. Run it against real edge cases, capture rejected rows separately and verify that incomplete output can never be mistaken for a completed file. That practical discipline turns an on-the-fly CSV conversion into a maintainable part of a Scala application.
cat ~/interests.json
| Key | Value |
|---|---|
| editor | Terminal-first workflow |
| os | Mac OS X / Unix |
| vcs | Git, distributed version control |
| deploy | Capistrano, cron automation |
| graphics | SVG, Adobe Illustrator troubleshooting |
| networking | IP validation, SSH, VPN |
git log --oneline --reverse
Solving SVG import issues in Adobe Illustrator CS6 and CC
When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.
Solving NDK build issues on OS X
Troubleshooting native development kit compilation problems on Mac OS X.
Programmatically adding PHP generated TypoScript to the backend configuration
Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.
ArgumentError: Could not parse PKey: no start line
Debugging an SSH key parsing error encountered during deployment.
Validating IP-Addresses in PHP
Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.
Cocoa: Using NSTrackingArea
A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.
cat ~/contact.txt