Video in progress

If you need to write logs, send metrics or call an external system inside a stream pipeline, how do you design that?

I try to keep the pipeline itself pure: the transformation separate, with side effects at the end, in the terminal operation or after the pipeline. For metrics, an aggregate result (how many processed, how many failed) is enough. External calls must be idempotent, bounded and ready to be retried, because a stream doesn't store a state like "where did it stop".

📖 Answer

The problem is that the stream API allows side effects but gives no guarantees for them: peek may be skipped, in parallel there is no order, and short-circuiting means some elements are never seen at all. And if an error occurs in the middle, it's unknown which elements the side effect has already reached.

The three things I separate:

1. Logs. A log.info per element inside the stream is a log volume and cost problem in prod. A summary is usually enough:

var result = invoices.stream()
        .map(validator::check)
        .collect(partitioningBy(Check::ok, counting()));
log.info("invoices checked: ok={}, failed={}", result.get(true), result.get(false));

For the failed elements, only them, with their IDs, at debug or in a separate audit channel.

2. Metrics. Incrementing a Micrometer counter inside a lambda technically works (the counter is thread-safe), but writing the aggregate value at the end is cheaper and easier to check in a test. For timing, use Timer.record(...) around the whole pipeline, not per element.

3. External side effects (DB writes, sending messages, HTTP):

List<Notification> toSend = users.stream()
        .filter(User::wantsEmail)
        .map(notificationFactory::create)
        .toList();                        // the pure part is done

for (List<Notification> batch : partition(toSend, 100)) {
    mailClient.sendBatch(batch);          // retry, rate limit, idempotency key
    outboxRepo.markSent(batch);
}

Why I separated this from the stream: batching, retry and recording partial success are awkward and unclear to do inside forEach. If every message has an idempotency key, a restart doesn't produce duplicates.

In a larger system this becomes the outbox pattern: the pipeline only computes "what needs to be sent" and writes it to the DB, and a separate process delivers it reliably. Then the stream code stays a testable pure function, and the side effects sit in a place that's observable and recoverable.

A practical sign: if there's try/catch, retry and logging inside forEach, it's time to move that code out of the pipeline.