Skip to content

Pipe-and-Filter Architecture ​

"Among the important invariants of the style, filters must be independent entities: in particular, they should not share state with other filters." — David Garlan and Mary Shaw, An Introduction to Software Architecture, CMU-CS-94-166, January 1994

Summary: Pipe-and-filter builds a system as a chain of small independent steps (filters) joined by connectors that carry data (pipes); because filters share no state and do not know their neighbours, you can reuse, reorder, replace, parallelise and observe each step on its own. Focus: The style (Garlan and Shaw, Unix, EIP), the four filter roles, push versus pull, batch versus streaming, bounded pipes and backpressure, fan-out and fan-in, ordering, error handling (retries, dead letters, poison data), typed pipelines, where it appears (compilers, ETL, middleware, CI, Kafka), Go (channels, io.Reader, a generic Stage) and Laravel (Pipeline, middleware, LazyCollection, job chains and batches), and one order-import pipeline with tests, failure injection and a measured lab. Learning goal: Decide when a problem is a pipeline, draw it with the right filter types and pipe capacities, build it in Go and Laravel so that a slow stage slows the producer instead of exhausting memory, and say what changes when the pipes become a network and a log.

This chapter is the pipe-and-filter entry of the architecture styles group. It sits next to the layered monolith, the microkernel, client-server, SOA and microservices. The messaging mechanics that become the pipes at service scale live in Messaging Fundamentals, Backpressure & Flow Control, Dead Letter Queue, Message Transformation, Advanced Routing and Stream Processing.

Page map ​

If you are looking forGo to
The whole page in a few tablesEverything in one minute
Why chains of small steps win (and when they lose)Why it exists
McIlroy 1964, Unix, Garlan and Shaw, POSA, EIP, BeamWhere it comes from
The style and its invariantsThe style
Producer, transformer, tester, consumerFilter types
What a pipe is and what it guaranteesPipes
Push or pull, batch or streamPush vs pull, Batch vs streaming
Real shell pipelinesUnix pipes
Reuse, parallelism, ordering, observabilityProperties
Bounded buffers, backpressureBounded pipes
Parallel stagesFan-out and fan-in
Retries, dead letters, poison dataError handling
Typed versus untypedTyped pipes
Compilers, ETL, middleware, CI, data engineeringWhere it shows up
Kafka topics as pipesAt service scale
Go codeGo
Laravel codeLaravel
One pipeline end to end, with failure injectionWorked example
Classic problems and their fixesSolving the classic problems
When to choose itChoosing
Monolith to distributed systemIn architecture
Measure it yourselfLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
FilterA step that reads items, does one job, writes itemsgrep errorA big function nobody can reuse or test in pieces
PipeThe connector that carries items between two filters| in the shell, a channel in Go, a Kafka topicFilters call each other directly and become coupled
Producer (source)A filter with no input pipecat access.log, a file reader, a Kafka consumerNothing enters the system
TransformerOne input pipe, one output pipe, changes the itemparse, enrich, priceParsing and pricing tangled in one place
Tester (filter)Passes or drops items by a rulegrep, ValidateBad data reaches the database
Consumer (sink)A filter with no output pipe> out.txt, INSERTResults never leave memory
Bounded pipeA pipe with a fixed capacity; a full pipe blocks the writerGo make(chan T, 8)A fast producer fills memory
BackpressureThe slow stage slows everything upstreamBlocking sendOut-of-memory under load
Fan-out / fan-inSeveral workers read one pipe / write one pipe4 workers in a stageOne slow filter caps the whole pipeline
Dead letterA side pipe for items that cannot be processedimport_dead_letters tableOne bad row stops a million good ones
Poison dataAn item that fails every timeqty=abcInfinite retry loop

The four filter types (Richards and Ford name them in Fundamentals of Software Architecture):

TypeInputsOutputsDecides about the item?Example
Producer / source01NoRead lines of a CSV
Transformer11Changes itParse a line into an Order
Tester / filter11 (or 2)Keep, drop or rejectQuantity must be 1..1000
Consumer / sink10Stores or emits itUpsert into PostgreSQL

Pipeline styles compared:

QuestionBatch sequentialStreaming pipelineService pipeline (log between services)
When does filter 2 start?After filter 1 finished all inputAs soon as the first item arrivesWhenever a record appears in its topic
MemoryWhole data set between filtersA few items per pipeDisk (the log)
Latency to first outputWhole runMillisecondsMilliseconds to seconds
Typical toolNightly ETL, sortUnix pipe, Go channels, LazyCollectionKafka Streams, Kafka + consumer groups
Failure unitThe whole runThe item, or the runThe record, replayable from an offset

Why it exists ​

Most data-processing programs are the same story: read something, clean it, change it, enrich it, write it. A single function that does all five is fast to write and slow to change: the validation depends on the parser's variables, nobody can test pricing without a database, and the only way to go faster is to rewrite the whole thing. Pipe-and-filter replaces the one big function with small steps that agree only on the shape of the data between them.

Single big procedurePipe-and-filter
Fast to write the first versionSlightly more ceremony: a type per pipe, a wire-up function
Steps share local variablesSteps share nothing; only the item crosses
To test pricing, run everythingTest each filter with a hand-made item
Change the order = rewriteChange the order = change the wiring
One thread, or locks around everythingEach filter can run in its own goroutine, process or service
Memory grows with the inputMemory is the sum of the pipe capacities
Good for: a 20-line scriptGood for: anything that streams, transforms and may grow

The analogy we reuse on this page: a car-wash tunnel. The car moves on a conveyor (the pipe); each station (filter) does one job: soap, brush, rinse, dry. No station knows what the others do; you can add a wax station or remove the dryer without touching the rest. If the brush station is slow, the cars queue up behind it and the entrance light turns red: that is backpressure. A car with a broken mirror is pulled aside (dead letter) rather than stopping the tunnel.

Three common misunderstandings, up front ​

  1. "Pipe-and-filter is the Unix shell." The shell is the best-known instance, not the definition. The style is about independent filters, connectors that carry data and no shared state; it exists in compilers, Go channels, Laravel middleware, Kafka Streams and CI systems.
  2. "A pipeline is always fast because it is parallel." A pipeline's throughput equals the throughput of its slowest stage. Parallelism only helps if you widen that stage, and it can break ordering.
  3. "If a step fails, retry it." Retrying poison data forever is the classic way to stall a pipeline. Retry transient errors a few times, send the rest to a dead letter.

Where it comes from ​

McIlroy, 1964. The idea of connecting programs like hose segments comes from a Bell Labs memo. The tenth page, dated October 11, 1964, ends its summary with:

"We should have some ways of connecting programs like garden hose--screw in another segment when it becomes when it becomes necessary to massage data in another way. This is the way of IO also." — M. D. McIlroy, Bell Labs internal memo, October 11, 1964 (the doubled "when it becomes" is in the typescript)

The page that reproduces the scanned memo explains that this point "provides the historical background for Doug's encouragement of the Unix pipe notation".

Unix, 1973. Wikipedia (a secondary source; the memo page above is primary for the idea) says the idea "was implemented in 1973 when ('in one feverish night', wrote McIlroy) Ken Thompson added the pipe() system call and pipes to the shell and several utilities in Version 3 Unix", and that McIlroy credits Thompson with the | notation. The 1978 Bell System Technical Journal foreword to the Unix issue (McIlroy, Pinson, Tague, July-August 1978) records the maxims that became the philosophy:

"Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new 'features.'" "Expect the output of every program to become the input to another, as yet unknown, program." — M. D. McIlroy, E. N. Pinson, B. A. Tague, UNIX Time-Sharing System: Foreword, Bell System Technical Journal 57(6), 1978

Garlan and Shaw, 1993-1994. An Introduction to Software Architecture (CMU-CS-94-166) gave the style its architectural definition, listed the specialisations ("pipelines, which restrict the topologies to linear sequences of filters; bounded pipes, which restrict the amount of data that can reside on a pipe; and typed pipes") and the weaknesses.

POSA and EIP. Pattern-Oriented Software Architecture, Volume 1 (Buschmann et al., 1996) lists Pipes and Filters as an architectural pattern; we could not retrieve the book text, so we cite it only as a pointer. Hohpe and Woolf's Enterprise Integration Patterns (2003) moved the idea to messaging: "Use the Pipes and Filters architectural style to divide a larger processing task into a sequence of smaller, independent processing steps (Filters) that are connected by channels (Pipes)."

Richards and Ford. Fundamentals of Software Architecture (O'Reilly, 2020) presents the pipeline architecture style with exactly four filter types: producer, transformer, tester, consumer. We could not retrieve the book text (paywalled), so we use the four names as a citation and phrase every explanation ourselves.

Streaming systems. The Go blog's Go Concurrency Patterns: Pipelines and cancellation (Sameer Ajmani, 13 March 2014) defines "a pipeline is a series of stages connected by channels". Apache Beam and Kafka Streams scale the same model to clusters: Beam's PCollection flows through PTransform steps; Kafka Streams runs "a graph of stream processors (nodes) that are connected by streams (edges)".

text
     Year   Event                                          What it added
1    1964   McIlroy memo: "garden hose" programs            The idea of composable data connectors
2    1973   Unix pipe `|`                                    A notation and a kernel mechanism
3    1978   BSTJ foreword: one thing well, output = input   The philosophy
4    1994   Garlan and Shaw                                 The style, its invariants, its weaknesses
5    1996   POSA vol. 1 Pipes and Filters                   Pattern with a solution structure
6    2003   Enterprise Integration Patterns                 Pipes and Filters over message channels
7    2014   Go blog on pipelines and cancellation           Channel pipelines with explicit shutdown
8    2020   Richards and Ford pipeline style                Four filter roles for architects

The concepts, one by one ​

The style Must-know ​

In plain words: a system made of filters that each read a stream, do one local job and write a stream, connected by pipes that only carry data.

Common misunderstanding: "Any chain of function calls is pipe-and-filter." If step 2 calls step 3 by name, or they share a struct they both mutate, you have a procedure with helpers. The style needs independence: no shared state and no knowledge of neighbours.

Definition: Garlan and Shaw: "each component has a set of inputs and a set of outputs. A component reads streams of data on its inputs and produces streams of data on its outputs, delivering a complete instance of the result in a standard order. This is usually accomplished by applying a local transformation to the input streams and computing incrementally so output begins before input is consumed." Two invariants: filters "should not share state with other filters" and "do not know the identity of their upstream and downstream filters"; the output "should not depend on the order in which the filters perform their incremental processing".

text
     Producer ──pipe──▶ Transformer ──pipe──▶ Tester ──pipe──▶ Consumer
1    emits items        item in, item out      keep / drop      stores
2    knows: nothing     knows: its own rule    knows: its rule  knows: its target
3    never: "who reads me?" for any filter

Real scenario: a log shipper (read file, parse, drop health checks, add host label, send to Elasticsearch); an image service (decode, resize, watermark, encode, upload); an order import (this page's example).

What provides it:

ContextThe pipeThe filter
Unix shellKernel pipe (byte stream)A process
GoChannel, io.Pipe, io.Reader wrappingA goroutine or a Read wrapper
LaravelThe $next closure chainA pipe class, a middleware
Laravel queuesA queue (Redis, SQS, database)A job
KafkaA topic (a partitioned log)A consumer-group member or a Kafka Streams processor
Apache BeamA PCollectionA PTransform

Fix / how to use it: write the filter as a function from an item to an item (or to an error) and put the wiring in one place; see Go and Laravel.

Filter types Must-know ​

In plain words: four roles: the one that starts the flow, the ones that change items, the ones that say yes or no, and the one that finishes the flow.

Common misunderstanding: "Every filter transforms." A tester never changes the item; it only decides. Keeping the two roles apart keeps decisions (rules) separate from conversions (formats), and the tester can be placed anywhere, usually as early as possible.

Definition: Richards and Ford's four types, in our words: a producer (source) is the starting point and has only an outbound pipe; a transformer accepts input, optionally transforms some or all of it, then forwards it; a tester examines the input and passes it on or not, depending on a criterion; a consumer (sink) is the termination point and persists or shows the result.

Producer(source)Transformerparse / mapTester(filter) keep or dropTransformerenrich / priceConsumer(sink) storeDead letterspipepipepipepipe0 inputs1 output pipe1 in, 1 out1 in, 1 out1 input pipe0 outputsrejected items leave the main flowEvery filter only knows its own input pipe and output pipe
text
     Filter        Input                 Output                  Fails by...
1    Producer      file, socket, topic   Item                    source unreachable: fatal
2    Transformer   Item                  Item (other type)       bad item: reject; slow call: retry
3    Tester        Item                  Item or nothing         never fails; may reject to dead letter
4    Consumer      Item                  side effect             target down: fatal; duplicate: idempotent

Real scenario: in the order import, Read lines is the producer, Parse and Enrich and Price are transformers, Validate is the tester, Persist is the consumer. A CI pipeline: checkout (producer), build and compile (transformers), tests and lint (testers), deploy (consumer).

What provides it:

ProductProducerTransformerTesterConsumer
Unixcat, curl, findsed, cut, tr, jqgrep, head, uniq> file, tee, wc
Go (this page)stage.FromFuncstage.Mapstage.Filterstage.Drain
Laravel CollectionsLazyCollection::makemapfiltereach, reduce
Kafka StreamsSource processormapValues, flatMapfilterSink processor
Apache BeamRead, CreateParDo, MapFilterWrite
EIPMessage source / channel adapterMessage Translator, Content EnricherMessage FilterMessage sink endpoint

Fix / how to use it: name the role in the code (ParseLine, ValidateOrder), keep a tester free of side effects, and put cheap testers before expensive transformers so rejected items cost nothing.

Pipes Must-know ​

In plain words: the thing between two filters that holds items in transit and defines what "next" means.

Common misunderstanding: "A pipe is just a function call." A pipe is a buffer with a capacity, an order and a close signal. Those three properties decide memory use, ordering and shutdown behaviour.

Definition: a pipe carries a sequence of items from one output port to one input port. Its design choices: capacity (unbounded, bounded, zero), delivery (in-process, byte stream, durable log), ordering (FIFO per pipe), and end-of-stream (close or EOF).

text
     Pipe kind            Capacity           Ordering          Survives a crash?
1    Unix pipe            64 KiB (Linux)     FIFO bytes        No
2    Go chan T            you choose         FIFO              No
3    io.Pipe              0 (synchronous)    FIFO bytes        No
4    Laravel $next        1 item (call stack) call order        No
5    Queue job            queue length       FIFO per queue    Yes (driver dependent)
6    Kafka topic          retention (days)   FIFO per partition Yes

The pipe(7) Linux manual says: "A pipe has a limited capacity. If the pipe is full, then a write(2) will block or fail", and "Since Linux 2.6.11, the pipe capacity is 16 pages (i.e., 65,536 bytes in a system with a page size of 4096 bytes)". It also says the channel "is a byte stream: there is no concept of message boundaries", which is why Unix pipelines are untyped (see Typed pipes).

Real scenario: a Go make(chan Order, 8) between parse and validate keeps at most eight parsed orders in flight; an io.Pipe between a gzip writer and an HTTP upload has no buffer at all, so the writer only advances when the uploader reads.

What provides it:

NeedPipe to pick
Lowest latency, same processUnbuffered or small buffered channel
Smooth bursts, same processBuffered channel (size = burst)
Byte streams between librariesio.Reader / io.Writer, io.Pipe
Survive restarts, retry laterQueue (RabbitMQ, SQS, Redis, database)
Replay and many independent readersKafka topic
Request/response chainMiddleware ($next)

Fix / how to use it: give every pipe an explicit capacity and a reason; "unbounded" is a memory leak with a delay.

Push versus pull Important ​

In plain words: in a push pipeline the producer sends items as they appear; in a pull pipeline the consumer asks for the next item.

Common misunderstanding: "Push is for streaming and pull is for batch." Both can stream. The real difference is who controls the speed: pull gives backpressure for free (nothing moves until asked), push needs a bounded buffer or a credit scheme.

Definition: push: upstream calls downstream (out <- v, consumer.accept(v), a webhook). Pull: downstream calls upstream (Read(p), iterator.next(), PHP generator foreach). Unix pipes are push at the process level but behave as pull because a full pipe blocks the writer.

text
     Style   Who drives     Example                      Backpressure
1    Pull    consumer       io.Reader chain, PHP yield   free: no request, no data
2    Push    producer       Go channel send, webhook     needs a bounded buffer or blocking send
3    Hybrid  both           Kafka consumer poll()        consumer polls at its own pace, log holds the rest
4    Hybrid  both           Reactive Streams request(n)  consumer grants credits

Real scenario: a PHP LazyCollection over fgets is pull: the file advances one line per foreach step. A webhook receiver is push: the sender decides the rate, so you queue first and process at your own speed.

What provides it:

ProductModel
Go io.ReaderPull (Read is called by the consumer)
Go channelsPush with blocking send (bounded = backpressure)
PHP generators, LazyCollectionPull
Laravel PipelinePush (each pipe calls $next)
Kafka consumerPull (poll)
RabbitMQ consumerPush with prefetch credits
Redis Streams XREADPull

Fix / how to use it: if the source pushes (HTTP, webhooks), put a bounded queue at the edge and pull from it inside; see Backpressure & Flow Control.

Batch versus streaming pipelines Must-know ​

In plain words: a batch pipeline finishes each step for all the data before the next step starts; a streaming pipeline lets the first item reach the end while the last one is still being read.

Common misunderstanding: "Batch means big, streaming means real-time." Both can be big. A streaming pipeline can process a 1 GB file in constant memory; a batch pipeline can run every second on tiny data. What differs is whether data sits between steps.

Definition: Garlan and Shaw call the degenerate case, where each filter processes all of its input as a single entity, "batch sequential": "pipes no longer serve the function of providing a stream of data, and therefore are largely vestigial". Apache Beam makes the data-set distinction explicit: a PCollection "can be bounded, meaning it comes from a fixed source like a file, or unbounded, meaning it comes from a continuously updating source via a subscription or other mechanism."

text
     Time   Batch sequential                    Streaming
1    t0     parse all 1M lines (RAM: 1M)        parse line 1
2    t1     validate all 1M                      parse line 2, validate line 1
3    t2     price all 1M                         parse 3, validate 2, price 1
4    t3     persist all 1M                       parse 4, validate 3, price 2, persist 1
5    end    first row stored at the very end    first row stored at t3, memory = pipe capacities

Real scenario: a nightly CSV import written as "read the file into an array, map, filter, insert" works at 10 MB and kills the worker at 10 GB. The same logic as a pipeline over a generator runs in a few MB.

What provides it:

NeedChoiceProduct
Bounded data, simple, restartable per runBatch sequentialcron + SQL, Spark batch, Laravel Collection
Bounded data, largeStreaming over a fileGo channels, LazyCollection, awk
Unbounded dataStreaming with windowsKafka Streams, Apache Beam, Flink
Both with one code baseUnified modelApache Beam (batch and streaming use the same transforms)

Fix / how to use it: default to streaming inside one run (items flow) and to batch at the run level (one input file, one result); windows and watermarks are in Stream Processing.

Unix pipes, the archetype Must-know ​

In plain words: a | b | c starts three processes and connects the standard output of each to the standard input of the next.

Common misunderstanding: "a | b runs a to the end, then b." Both run at the same time. If b is slow, the kernel pipe fills up and a blocks on write.

Definition: the shell creates a kernel pipe per |; the writer blocks when it is full and the reader blocks when it is empty. When the last reader exits, the writer gets SIGPIPE; when the last writer exits, the reader sees end-of-file. man 7 pipe documents these rules: "If a process attempts to read from an empty pipe, then read(2) will block until data is available", and reading after all writers closed returns end-of-file.

bash
# Orders per customer, ignoring rows with a non-numeric quantity
tail -n +2 orders.csv \
  | awk -F, '$4 ~ /^[0-9]+$/' \
  | cut -d, -f2 \
  | sort | uniq -c | sort -rn
#  2 c1
#  1 c2

# Count error lines in a compressed log without ever writing the decompressed file
gzip -dc access.log.gz | grep -c ' 500 '

# First 3 matches only: head exits, SIGPIPE stops the producers early
gzip -dc big.log.gz | grep ERROR | head -n 3

# A pipeline hides failures by default: the exit code is the LAST command's
bash -c 'false | true; echo "default rc=$?"'                  # default rc=0
bash -c 'set -o pipefail; false | true; echo "rc=$?"'         # rc=1
text
     Step   Process      State                       Pipe
1    t0     cat          writes 64 KiB               full: cat blocks in write(2)
2    t1     grep         reads, matches 3 lines      16 KiB free
3    t2     cat          wakes, writes more          fills again
4    t3     head -n 3    prints 3 lines, exits       no reader left
5    t4     grep         write(2) raises SIGPIPE     chain collapses, cat stops

Real scenario: log triage on a server (journalctl -u app \| grep ERROR \| sort \| uniq -c \| sort -rn \| head); building a release (git archive \| gzip \| aws s3 cp - s3://...); checking a deploy (kubectl get pods -o json \| jq ...).

What provides it:

Shell featureWhat it does
|Connect stdout to the next stdin
set -o pipefail (bash)Pipeline fails if any stage fails
teeCopy the stream to a file and onward (a wire tap)
mkfifoNamed pipe between unrelated processes
xargs -P NFan-out: run N workers
<( cmd )Process substitution: a pipe presented as a file

Fix / how to use it: in scripts always use set -o pipefail, and remember pipes carry bytes, not records; filters must agree on the text format.

Properties of the style Must-know ​

In plain words: what you get for the price of the ceremony: reuse, easy replacement, parallelism and per-step visibility; and what it costs: copies, format agreement and error plumbing.

Common misunderstanding: "Independent filters are automatically parallel and automatically ordered." Concurrency is possible, not automatic, and order is lost the moment a stage has more than one worker.

Definition: Garlan and Shaw list the nice properties: the designer can "understand the overall input/output behavior of a system as a simple composition of the behaviors of the individual filters", filters support reuse "provided they agree on the data that is being transmitted between them", systems "can be easily maintained and enhanced: new filters can be added to existing systems and old filters can be replaced by improved ones", they "permit certain kinds of specialized analysis, such as throughput and deadlock analysis", and "naturally support concurrent execution". The disadvantages they list: a tendency toward batch organisation, poor fit for interactive applications, trouble keeping two related streams in step, and a lowest-common-denominator data format that costs "parse and unparse" work in each filter.

text
     Property       Benefit                               Cost / trap
1    Reuse          Same Validate in import and API       Filters must agree on one item type
2    Replace        Swap the price filter, rest unchanged Behavioural contract still needed
3    Parallelism    Stages run concurrently               Order lost after fan-out
4    Throughput     Equals slowest stage                  Widen the bottleneck, not every stage
5    Backpressure   Bounded pipes stop fast producers     Deadlock if pipes form a cycle
6    Errors         Per-item rejection, dead letters      No transaction across filters
7    Observability  Count in/out/errors per stage         Needs deliberate taps (see Tap)

Real scenario: the ops team asks "where do orders get stuck?" With per-stage counters you read in=1000 out=993 err=7 at each filter and see the loss at Validate. In a single big function you would add logging by hand.

What provides it:

PropertyGoLaravelKafka
ReuseGeneric Stage[In, Out]Invokable pipe classTopology + Serdes
ConcurrencyWorkers per stageQueue workersPartitions and tasks
BackpressureBounded channelGenerator (pull)Consumer poll rate, max.poll.records
Per-stage metricsstage.Tap countersPipe-level logging, HorizonConsumer lag per group
OrderingResequence by SeqNatural (sequential)Per partition only

Fix / how to use it: add a counter tap to each stage from day one; it is a dozen lines and it is the first thing you will wish you had.

Bounded buffers and backpressure Must-know ​

In plain words: a pipe that can hold only N items forces a fast producer to wait when the pipe is full, so memory use is fixed.

Common misunderstanding: "Make the buffer bigger and the slowdown goes away." A bigger buffer only delays the moment the pipe fills; if the producer is faster on average, it fills anyway. Buffers absorb bursts, not a sustained rate difference.

Definition: backpressure is the signal that travels from a slow consumer to its producers, normally by blocking the write (or by an explicit credit such as Reactive Streams request(n) or RabbitMQ prefetch_count). With bounded pipes the system's memory is the sum of the pipe capacities plus the items being processed.

ProducerfastTransformerslow (remote call)Consumerfastpipe, capacity 3: FULLpipe, capacity 3: almost empty3 of 3 slots used1 of 3 slots usedthe send blocks: producer waits, memory stays boundedthroughput of the whole pipeline = throughput of the slowest stage; fix it with workers, not with bigger buffersBounded pipes turn "too fast" into "wait"
text
     Step   Producer (fast)        Pipe A (cap 3)   Transformer (slow)   Pipe B (cap 3)   Consumer
1    t0     send 1, 2, 3           [1 2 3] full     processing 0         []               idle
2    t1     send 4 BLOCKS          [1 2 3] full     finishes 0           [0]              takes 0
3    t2     send 4 succeeds        [2 3 4]          processing 1         []               idle
4    t3     send 5 BLOCKS          [2 3 4] full     ...                  ...              ...
5    rule   memory = 3 + 1 + 3 + 1 items, never more

Real scenario: a 20 GB CSV, a 5 ms remote enrichment call: without bounds, the reader loads millions of lines while the enrich stage handles 200 per second; with a pipe of 100, the reader never gets more than 100 lines ahead. In messaging terms the same idea is prefetch_count in RabbitMQ and max.poll.records in Kafka; see Backpressure & Flow Control.

What provides it:

LayerBounding mechanism
Unix pipeKernel buffer (64 KiB on Linux), blocking write
Gomake(chan T, n) plus a select on ctx.Done() for every send
PHPGenerators (pull) and chunk(n)
HTTPTCP window, HTTP/2 flow control
RabbitMQbasic.qos prefetch_count
KafkaConsumer max.poll.records, pausing partitions, lag alerts
Queue workersQueue length alarms, worker count

Fix / how to use it: bound every pipe, and when the system cannot slow its source (a webhook), shed load or queue durably at the edge; see Load Shedding and Bulkhead.

Fan-out, fan-in and parallel stages Must-know ​

In plain words: if one filter is the slowest, run several copies of it side by side that share the same input pipe and write to the same output pipe.

Common misunderstanding: "More workers always means more throughput, in order." Throughput grows until the next bottleneck (CPU cores, a database connection pool, a rate-limited API), and results come out in completion order, not input order.

Definition: the Go blog: "Multiple functions can read from the same channel until that channel is closed; this is called fan-out", and "A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that's closed when all the inputs are closed. This is called fan-in." Two different patterns share the name: same-input workers (a worker pool in one stage) and branching (an item goes to several different filters, which in EIP terms is a Recipient List or a Splitter).

Previousstageworker 1worker 2worker 3worker 4Resequenceorder by SeqNextstagefan-out: workers share one inbound pipefan-inholds early items,bounded memoryParallel stage
text
     Item   Seq   Worker   Duration   Completes   Output order without Resequence
1    A      0     w1       30 ms      t=30        3rd
2    B      1     w2       10 ms      t=10        1st
3    C      2     w3       20 ms      t=20        2nd
4    rule   Resequence holds B and C until A arrives, then emits A, B, C

Real scenario: an enrich stage calls a customer service at 2 ms per call; one worker gives about 440 items/s, eight workers give 3500 items/s (measured in the lab). A CPU-bound stage scales only to the number of cores.

What provides it:

ProductParallel stageOrder after the stage
Go stage.Map(workers, ...)Goroutines on one channelLost; use stage.Resequence
xargs -P 8ProcessesLost
Laravel queue workers (queue:work x N)Processes on one queueLost per queue
Laravel Bus::batchJobs in parallelLost; batch joins at then
Kafka consumer groupOne member per partitionPreserved per partition
Apache Beam ParDoBundles on workersNot guaranteed

Fix / how to use it: widen only the measured bottleneck; if later steps need order, resequence on a sequence number or partition by key (see Ordering & Partitioning and Competing Consumers); to split one item into many and join them back, see the Splitter and Aggregator in Advanced Routing.

Error handling: retries, dead letters, poison data Must-know ​

In plain words: when one item fails, decide whether to try again, to set it aside, or to stop everything; do not let one bad row decide for a million good ones.

Common misunderstanding: "A pipeline either succeeds or fails." Item-level and pipeline-level failures are different. A malformed row is item-level; a database that is down is pipeline-level.

Definition: three outcomes per failure. Retry (transient: timeout, 503, deadlock) with backoff and a limit; reject to a dead-letter stage with the reason (poison data: parse error, rule violation); stop (infrastructure: the sink is unreachable), cancel upstream and let the run be repeated. Because the run can be repeated, the consumer must be idempotent.

text
     Failure                       Kind              Action                         Where recorded
1    "qty=abc"                     poison            reject, continue               dead letter + reason
2    directory timeout (3 tries)   transient         retry with backoff             counter; then dead letter
3    directory down for 10 min     transient, long   retry budget spent: dead letter, or stop and replay    alert
4    database refuses connections  infrastructure    cancel pipeline, return error  alert; rerun the file
5    same file run twice           duplicate         upsert by primary key          none (idempotent)

Real scenario: a customer sends an export with 3 broken lines in 2 million. The pipeline stores 1 999 997 rows, writes 3 dead letters with line numbers and reasons, and finishes green; support reads the dead-letter table and asks the customer to resend 3 lines.

What provides it:

ConcernGo (this page)LaravelMessaging
Item error travelsItem.Err, skipped by later filtersPoisonRow exception caught by the driverDead letter exchange or topic
Retry transientstage.Retry with backoffretry() helper, job $tries and $backoffRetry topics, delayed queues
Stop the pipelineerrgroup cancels the contextUncaught exception, Bus::chain stops, catchConsumer crash, redelivery
Idempotent sinkUpsert on Order.IDDB::table()->upsert()Idempotent consumer
ReplayRun the file againRerun command or batchReset the consumer offset

Fix / how to use it: classify errors in one place (a sentinel such as ErrTransient, an exception such as PoisonRow), never retry what is not transient, and record the reason with the item; see Dead Letter Queue and Retry, Backoff & Delay, and for the system-level retry rules Timeouts, Retries & Jitter.

Typed pipes versus untyped streams Important ​

In plain words: either every pipe carries a known type that the compiler checks, or it carries bytes or text that every filter must parse.

Common misunderstanding: "Untyped is more flexible." It is more flexible to start and more expensive to keep: each filter re-parses and each format change breaks unknown readers, which is Garlan and Shaw's "lowest common denominator" cost.

Definition: a typed pipe requires "that the data passed between two filters have a well-defined type" (Garlan and Shaw). In Go that is chan Item[Order]; in Kafka it is a topic with a schema in a registry; in the shell it does not exist, and PowerShell passes objects for that reason.

text
     Aspect               Untyped (bytes/text)           Typed (objects/records)
1    Compile-time check   none                           yes (Go generics, PHP types)
2    Parse cost           every filter                   once at the edge
3    Evolution            silent breakage                versioned schema, compatibility rules
4    Interop              any language, any tool         needs a shared schema or codec
5    Debugging            `tee`, eyeball                 structured logs, schema tools

Real scenario: the order pipeline parses once (Parse: string to Order) and every later filter takes an Order; the day a column is added, one filter changes. In a text pipeline every cut -f index shifts.

What provides it:

ContextTyping
Unix shellNone (bytes)
Go channels / Stage[In, Out]Static, per pipe
Laravel PipelineThe passable object, checked by PHP types
KafkaAvro/Protobuf/JSON Schema with a registry
BeamCoders and schemas per PCollection

Fix / how to use it: parse at the edge into a type, keep internal pipes typed, and when pipes cross services version the schema; see Message Design & Schema Evolution.

Where the style shows up Important ​

In plain words: more places than you think, usually without anyone calling it by name.

Common misunderstanding: "It is old Unix stuff." Compilers, CI systems, ETL tools, HTTP stacks and stream processors are all pipelines.

Definition: the style appears wherever data is transformed in stages.

text
     Domain               Source            Filters                                         Sink
1    Compiler             source text       lexer, parser, semantic analysis, codegen       object code
2    ETL / ELT            databases, files  clean, join, aggregate, mask PII                warehouse
3    Image / video        upload            decode, scale, filter, encode, thumbnail        object storage
4    Log processing       app logs          parse, drop noise, enrich, redact               Elasticsearch
5    Web middleware       request           auth, rate limit, CORS, session, router         response
6    CI pipeline          git push          build, lint, test, scan, package                deploy
7    Data engineering     events            validate, dedupe, window, join, aggregate       feature store

Garlan and Shaw name compilers as the classic example: "The stages in the pipeline include lexical analysis, parsing, semantic analysis, code generation", with the remark that phases are often not incremental, which is why real compilers often behave closer to batch sequential.

Real scenario: GitLab CI or GitHub Actions: a pipeline file lists stages, each job is a filter, artifacts are the pipes, and a failed test stage stops the deploy stage. The same file may use needs: to describe a branching graph instead of a line.

What provides it:

SystemPipeline unit
GNU Compiler Collection, LLVMPasses over an intermediate representation
Apache Beam, Spark, FlinkTransforms on distributed collections
Logstash, Vector, Fluent BitInput, filter, output plugins
ffmpegFilter graph (-vf scale,fps)
GitHub Actions, GitLab CI, JenkinsStages and jobs
Laravel, Express, Go net/httpMiddleware chain

Fix / how to use it: when you are about to write a long function with sequential steps on a stream of data, ask whether each step could be a filter; the answer is yes more often than not.

At service scale: Kafka topics as pipes Important ​

In plain words: the same shape, but each filter is its own service and each pipe is a durable topic that stores items until the next filter reads them.

Common misunderstanding: "Services connected by topics are an event-driven architecture, not pipe-and-filter." They can be both. If each service reads one stream and writes one stream and knows nothing about its neighbours, it is a pipe-and-filter system on a log; see Event-Driven Architecture.

Definition: Kafka Streams documents the model directly: "A stream processor is a node in the processor topology; it represents a processing step to transform data in streams by receiving one input record at a time from its upstream processors in the topology, applying its operation to it, and may subsequently produce one or more output records to its downstream processors." A source processor has no upstream and a sink processor has no downstream. Parallelism comes from partitions: "Kafka Streams creates a fixed number of tasks based on the input stream partitions for the application". The EIP book calls the same shape Pipes and Filters over Message Channels.

OrdersserviceValidatorservicePricingservicePersisterserviceorders.raworders.validorders.pricedDatabaseorders.dead (DLQ)Filters = services (one consumer group each). Pipes = durable topics with partitions and retention.Same style, different pipe: a log instead of a channel
text
     Topic            Producer           Consumer group    Partitions   Key
1    orders.raw       Orders service     validator         12           order id
2    orders.valid     Validator          pricing           12           order id
3    orders.priced    Pricing            persister         12           order id
4    orders.dead      Validator          ops tooling       1            n/a
5    rule             Same key keeps one order on one partition, so order is kept per order

Real scenario: an e-commerce platform ingests orders from a web shop and a marketplace. A validator service rejects bad orders to orders.dead, a pricing service applies rules, a persister writes the database. When pricing is deployed with a bug, the team fixes it and resets that consumer group's offsets to replay orders.valid; the other services do not notice.

What provides it:

ConcernKafkaRabbitMQRedis Streams
PipeTopic with partitionsQueue (bound to an exchange)Stream
Filter instance scalingConsumer group members, max = partitionsCompeting consumers, prefetchConsumer group
ReplayReset offsetsClassic and quorum queues: none (a consumed message is gone); RabbitMQ Streams: yesRe-read from an ID
OrderingPer partitionPer queue, lost with competing consumersPer stream
Dead-letterConvention: dead topicDead letter exchangeConvention: dead stream
Product toolingKafka Streams, ksqlDB, FlinkShovel, FederationNone built in

Fix / how to use it: keep the filters stateless (state in Kafka Streams state stores or in the database), make each consumer idempotent, give each stage its own consumer group, and size partitions for the slowest stage; see Kafka in Depth, Message Transformation and Observability for Messaging.

Pipe-and-filter next to its neighbours Good to know ​

In plain words: it differs from layers (calls go down, not along a stream), from events (many independent subscribers, not a chain) and from microservices (a unit of deployment, not a way of connecting).

Common misunderstanding: "Layered, pipeline and microkernel are alternatives at the same level." Styles can combine: a layered monolith can contain a pipeline inside its service layer, and a microkernel can run plugins as filters.

Definition: compare on one axis each.

StyleConnectorData flowTypical couplingSee
Pipe-and-filterPipe (stream)One direction, item by itemItem type onlythis page
LayeredProcedure callRequest goes down, answer upInterface of the layer belowLayered Monolith
MicrokernelPlug-in contractCore calls plug-insPlug-in APIMicrokernel
Client-serverRequest/responseRound tripProtocol and APIClient-Server
Event-drivenEvent channelPublish to manyEvent schemaEvent-Driven Architecture
MicroservicesNetwork call or messageAnyContracts between servicesMicroservices
Big-data (Lambda/Kappa)Log and batch storeStream plus batchSchema and replayBig Data Architectures

Fix / how to use it: see Styles vs patterns for why a style is a way to organise the whole system while Pipes and Filters in POSA and EIP are also usable as patterns inside one subsystem.

Mechanics ​

Cancellation and shutdown Must-know ​

Every goroutine in a channel pipeline blocks on a send or a receive; if the consumer stops early, upstream senders block forever and leak. The Go blog explains why: "stages keep receiving values from inbound channels until those channels are closed or the senders are unblocked" and "Pipelines unblock senders either by ensuring there's enough buffer for all the values that are sent or by explicitly signalling senders when the receiver may abandon the channel." The fix that scales is a context.Context: every send is a select with ctx.Done(), and errgroup cancels the context when a stage returns an error. The errgroup doc says: "The first goroutine in the group that returns a non-nil error will cancel the associated Context, if any. The error will be returned by Wait."

text
     Step   Event                                    Effect on the pipeline
1    t0     sink returns an error                    errgroup cancels ctx
2    t1     Map workers wake in select               return without sending
3    t2     producer's emit returns false            generator returns
4    t3     all goroutines exit, Wait returns        the first error is reported
5    leak   (without ctx) workers block on send       goroutines and memory leak forever

Ordering Must-know ​

A single worker per stage and FIFO pipes preserve source order. A parallel stage does not. Options: do not care (idempotent upserts do not need order), resequence by a sequence number (stage.Resequence holds early items; memory is bounded by workers plus pipe capacity), or partition by key so that all items of one key use one worker (the Kafka model).

Batching inside a pipeline Important ​

Many sinks are cheaper in batches (one INSERT of 500 rows instead of 500 inserts). A batcher is a transformer that emits a slice when it has N items or T milliseconds passed, whichever comes first. Remember the trade-off: bigger batches raise throughput and latency, and a failure in a batch needs a per-row fallback or an idempotent retry. In Laravel, LazyCollection::chunk($n) is the batcher.

Error messages you will meet Good to know ​

WhereMessage or symptomMeaning
Gofatal error: all goroutines are asleep - deadlock!Every goroutine waits on a channel, usually a missing close or a sink that stopped reading
Gopanic: send on closed channelA stage closed its output while another writer was still sending (closing from the wrong side)
Gocontext canceled / context deadline exceededPipeline cancelled or timed out
Goio: read/write on closed pipeio.Pipe side closed early; use CloseWithError to carry the reason
ShellBroken pipe / exit 141Reader exited early (SIGPIPE), normal with head
PHPAllowed memory size of N bytes exhaustedSomething materialised the stream (all(), toArray(), Collection instead of LazyCollection)
Laravel queueMaxAttemptsExceededExceptionA job used up $tries or $maxExceptions
Laravel batchBatch marked cancelledA job failed and allowFailures() was not set
KafkaRecordTooLargeExceptionAn item exceeds max.message.bytes; pass a reference, not the payload
KafkaConsumer rebalance, lag growsThe slowest filter is under-provisioned

Go ​

All Go code is one module, academy/pipe-and-filter, under docs/snippets/architecture/pipe-and-filter/go. It passes gofmt -l, go vet ./... and go test -race ./....

A channel pipeline with context and errgroup ​

The Go blog's gen -> sq -> merge, rewritten with the cancellation tools of today: each stage is a goroutine in an errgroup.Group; every send is a select on ctx.Done(); an error in any stage cancels all of them. run(1, 2, 3, 4) prints 30 <nil>; run(1, 2, -3, 4) stops with negative input.

go
// Command channels shows the classic channel pipeline of the Go blog, with
// context cancellation and errgroup instead of a hand-made done channel.
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"sync"

	"golang.org/x/sync/errgroup"
)

// gen is the producer: it stops as soon as ctx is cancelled.
func gen(ctx context.Context, g *errgroup.Group, nums ...int) <-chan int {
	out := make(chan int)
	g.Go(func() error {
		defer close(out)
		for _, n := range nums {
			select {
			case out <- n:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
		return nil
	})
	return out
}

// sq is a transformer. It fails on poison input, which cancels the group.
func sq(ctx context.Context, g *errgroup.Group, in <-chan int) <-chan int {
	out := make(chan int)
	g.Go(func() error {
		defer close(out)
		for n := range in {
			if n < 0 {
				return errors.New("negative input")
			}
			select {
			case out <- n * n:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
		return nil
	})
	return out
}

// merge is fan-in: one goroutine per inbound pipe, one outbound pipe.
func merge(ctx context.Context, g *errgroup.Group, ins ...<-chan int) <-chan int {
	out := make(chan int)
	var wg sync.WaitGroup
	wg.Add(len(ins))
	for _, c := range ins {
		g.Go(func() error {
			defer wg.Done()
			for n := range c {
				select {
				case out <- n:
				case <-ctx.Done():
					return ctx.Err()
				}
			}
			return nil
		})
	}
	g.Go(func() error { wg.Wait(); close(out); return nil })
	return out
}

func run(nums ...int) (sum int, err error) {
	g, ctx := errgroup.WithContext(context.Background())
	src := gen(ctx, g, nums...)
	// fan-out: two sq workers read the same pipe
	out := merge(ctx, g, sq(ctx, g, src), sq(ctx, g, src))
	g.Go(func() error {
		for n := range out { // the sink
			sum += n
		}
		return nil
	})
	return sum, g.Wait()
}

func main() {
	fmt.Println(run(1, 2, 3, 4)) // 30 <nil>
	if _, err := run(1, 2, -3, 4); err != nil {
		fmt.Fprintln(os.Stderr, "pipeline stopped:", err)
	}
}

An io.Reader chain ​

Go's io.Reader is already a pull-based filter interface: a Read method that wraps another Reader. The standard library gives you decompression (gzip.NewReader), buffering (bufio), tees (io.TeeReader), limits (io.LimitReader) and a synchronous pipe (io.Pipe). The package comment of io says "its primary job is to wrap existing implementations of such primitives ... into shared public interfaces", and warns that "unless otherwise informed clients should not assume they are safe for parallel execution". The example is gzip source, an uppercasing transformer, a grep tester and a gzip consumer, with pw.CloseWithError(err) to propagate a failure to the reading side.

go
// Command readers shows pipe-and-filter at the io.Reader level:
// gzip -> lines -> decode -> transform -> gzip again, one buffer in memory.
package main

import (
	"bufio"
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"strings"
)

// upper is a transformer filter as an io.Reader: it wraps another Reader.
type upper struct{ r *bufio.Reader }

func (u upper) Read(p []byte) (int, error) {
	n, err := u.r.Read(p)
	copy(p[:n], bytes.ToUpper(p[:n]))
	return n, err
}

// grep is a tester filter over lines: it drops lines without the needle.
func grep(r io.Reader, needle string, w io.Writer) (kept int, err error) {
	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 64*1024), 1<<20) // lines up to 1 MiB
	bw := bufio.NewWriter(w)
	for sc.Scan() {
		if strings.Contains(sc.Text(), needle) {
			kept++
			if _, err = bw.WriteString(sc.Text() + "\n"); err != nil {
				return kept, err
			}
		}
	}
	if err = sc.Err(); err != nil {
		return kept, err
	}
	return kept, bw.Flush()
}

func main() {
	// producer: a gzip file in memory
	var src bytes.Buffer
	zw := gzip.NewWriter(&src)
	for i := 0; i < 1000; i++ {
		fmt.Fprintf(zw, "order=%d status=%s\n", i, map[bool]string{true: "ok", false: "bad"}[i%10 != 0])
	}
	_ = zw.Close()

	zr, err := gzip.NewReader(&src) // filter 1: decompress
	if err != nil {
		panic(err)
	}
	pr, pw := io.Pipe() // a synchronous, unbuffered pipe between two goroutines
	var out bytes.Buffer
	gz := gzip.NewWriter(&out) // consumer: compress again

	done := make(chan error, 1)
	go func() { // filter 2 + 3 in a goroutine, writing into the pipe
		_, err := grep(upper{bufio.NewReader(zr)}, "STATUS=BAD", pw)
		pw.CloseWithError(err) // propagates a failure to the reader side
		done <- err
	}()
	if _, err := io.Copy(gz, pr); err != nil { // consumer pulls the data
		panic(err)
	}
	if err := <-done; err != nil {
		panic(err)
	}
	_ = gz.Close()
	fmt.Println("compressed bytes:", out.Len())
}

A generic Stage[In, Out] ​

The toolkit used by the worked example. A Stage is a function from an inbound pipe to an outbound pipe; Compose joins two stages; Map is a transformer with a worker pool (fan-out and fan-in in one place); Filter is a tester; Resequence restores order; Retry retries only ErrTransient; Tap counts; Drain is the consumer. An Item carries a sequence number, a value and an error, so poison data flows to the end without stopping the pipeline.

go
// Package stage is a tiny pipe-and-filter toolkit built on channels.
// A pipe is a bounded channel, a filter is a Stage, a poison item is an Item
// that carries an error and flows to the end of the pipeline.
package stage

import (
	"context"
	"errors"
	"sort"
	"sync"
	"sync/atomic"
	"time"
)

// Item is the unit that travels through a pipe. Seq is the position in the
// source, Err marks poison data: downstream filters skip it and pass it on.
type Item[T any] struct {
	Seq int
	Val T
	Err error
}

// Stage is a filter: it reads items from the inbound pipe and returns the
// outbound pipe. It never closes the inbound pipe and always closes its own.
type Stage[In, Out any] func(ctx context.Context, in <-chan Item[In]) <-chan Item[Out]

// ErrTransient marks an error worth retrying (a timeout, a 503).
var ErrTransient = errors.New("transient")

// Compose connects two stages: the pipe between them is the channel the first
// stage returns, so its capacity is chosen by the first stage.
func Compose[A, B, C any](s1 Stage[A, B], s2 Stage[B, C]) Stage[A, C] {
	return func(ctx context.Context, in <-chan Item[A]) <-chan Item[C] {
		return s2(ctx, s1(ctx, in))
	}
}

// FromSlice is a producer filter: it numbers the values and emits them.
func FromSlice[T any](ctx context.Context, buf int, vals []T) <-chan Item[T] {
	out := make(chan Item[T], buf)
	go func() {
		defer close(out)
		for i, v := range vals {
			if !send(ctx, out, Item[T]{Seq: i, Val: v}) {
				return
			}
		}
	}()
	return out
}

// FromFunc is a producer filter driven by a generator. emit returns false once
// the pipeline is cancelled, so the generator must stop.
func FromFunc[T any](ctx context.Context, buf int, gen func(emit func(T) bool) error) (<-chan Item[T], func() error) {
	out := make(chan Item[T], buf)
	var genErr error
	done := make(chan struct{})
	go func() {
		defer close(done)
		defer close(out)
		seq := 0
		genErr = gen(func(v T) bool {
			ok := send(ctx, out, Item[T]{Seq: seq, Val: v})
			seq++
			return ok
		})
	}()
	return out, func() error { <-done; return genErr }
}

// Map is a transformer filter with a worker pool: workers goroutines read the
// same inbound pipe (fan-out) and write the same outbound pipe (fan-in).
// buf is the capacity of the outbound pipe, the backpressure budget.
// Order is NOT preserved when workers > 1: use Resequence.
func Map[In, Out any](workers, buf int, fn func(context.Context, In) (Out, error)) Stage[In, Out] {
	if workers < 1 {
		workers = 1
	}
	return func(ctx context.Context, in <-chan Item[In]) <-chan Item[Out] {
		out := make(chan Item[Out], buf)
		var wg sync.WaitGroup
		wg.Add(workers)
		for range workers {
			go func() {
				defer wg.Done()
				for {
					select {
					case <-ctx.Done():
						return
					case it, ok := <-in:
						if !ok {
							return
						}
						res := Item[Out]{Seq: it.Seq, Err: it.Err}
						if it.Err == nil {
							res.Val, res.Err = fn(ctx, it.Val)
						}
						if !send(ctx, out, res) {
							return
						}
					}
				}
			}()
		}
		go func() { wg.Wait(); close(out) }()
		return out
	}
}

// Filter is a tester filter: it drops values for which keep returns false.
// Dropping leaves gaps in Seq, so place Resequence before it, not after.
func Filter[T any](buf int, keep func(T) bool) Stage[T, T] {
	return func(ctx context.Context, in <-chan Item[T]) <-chan Item[T] {
		out := make(chan Item[T], buf)
		go func() {
			defer close(out)
			for {
				select {
				case <-ctx.Done():
					return
				case it, ok := <-in:
					if !ok {
						return
					}
					if it.Err == nil && !keep(it.Val) {
						continue
					}
					if !send(ctx, out, it) {
						return
					}
				}
			}
		}()
		return out
	}
}

// Resequence restores source order after a parallel stage. It holds at most
// the items that arrived early, so memory is bounded by the worker count plus
// the pipe capacities. Seq values must be dense (0, 1, 2, ...).
func Resequence[T any](buf int) Stage[T, T] {
	return func(ctx context.Context, in <-chan Item[T]) <-chan Item[T] {
		out := make(chan Item[T], buf)
		go func() {
			defer close(out)
			pending := map[int]Item[T]{}
			next := 0
			for {
				select {
				case <-ctx.Done():
					return
				case it, ok := <-in:
					if !ok {
						flush(ctx, out, pending)
						return
					}
					pending[it.Seq] = it
					for {
						p, found := pending[next]
						if !found {
							break
						}
						delete(pending, next)
						next++
						if !send(ctx, out, p) {
							return
						}
					}
				}
			}
		}()
		return out
	}
}

func flush[T any](ctx context.Context, out chan<- Item[T], pending map[int]Item[T]) {
	keys := make([]int, 0, len(pending))
	for k := range pending {
		keys = append(keys, k)
	}
	sort.Ints(keys)
	for _, k := range keys {
		if !send(ctx, out, pending[k]) {
			return
		}
	}
}

// Merge is fan-in for several pipes of the same type.
func Merge[T any](ctx context.Context, buf int, ins ...<-chan Item[T]) <-chan Item[T] {
	out := make(chan Item[T], buf)
	var wg sync.WaitGroup
	wg.Add(len(ins))
	for _, c := range ins {
		go func() {
			defer wg.Done()
			for it := range c {
				if !send(ctx, out, it) {
					return
				}
			}
		}()
	}
	go func() { wg.Wait(); close(out) }()
	return out
}

// Drain is the consumer filter: it calls fn for every item until the pipe is
// closed or fn fails. A non-nil error from fn is fatal for the pipeline; the
// caller cancels the context, which unblocks every upstream stage.
func Drain[T any](ctx context.Context, in <-chan Item[T], fn func(Item[T]) error) error {
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case it, ok := <-in:
			if !ok {
				return nil
			}
			if err := fn(it); err != nil {
				return err
			}
		}
	}
}

// Retry wraps fn so that ErrTransient failures are retried with exponential
// backoff. Anything else is returned at once: poison data must not be retried.
func Retry[In, Out any](attempts int, base time.Duration, fn func(context.Context, In) (Out, error)) func(context.Context, In) (Out, error) {
	return func(ctx context.Context, v In) (Out, error) {
		var zero Out
		delay := base
		for i := 1; ; i++ {
			out, err := fn(ctx, v)
			if err == nil || !errors.Is(err, ErrTransient) || i >= attempts {
				return out, err
			}
			select {
			case <-ctx.Done():
				return zero, ctx.Err()
			case <-time.After(delay):
				delay *= 2
			}
		}
	}
}

// Counter is a per-stage observability tap: in, out and errors.
type Counter struct{ In, Out, Errs atomic.Int64 }

// Tap counts items passing through without changing them.
func Tap[T any](c *Counter, buf int) Stage[T, T] {
	return func(ctx context.Context, in <-chan Item[T]) <-chan Item[T] {
		out := make(chan Item[T], buf)
		go func() {
			defer close(out)
			for {
				select {
				case <-ctx.Done():
					return
				case it, ok := <-in:
					if !ok {
						return
					}
					c.In.Add(1)
					if it.Err != nil {
						c.Errs.Add(1)
					}
					if !send(ctx, out, it) {
						return
					}
					c.Out.Add(1)
				}
			}
		}()
		return out
	}
}

// send is the only place that writes to a pipe: it gives up when cancelled.
func send[T any](ctx context.Context, out chan<- T, v T) bool {
	select {
	case out <- v:
		return true
	case <-ctx.Done():
		return false
	}
}

The tests check the properties this chapter promised: the set survives fan-out (but not the order), Resequence restores order, a poison item skips later filters, a cancelled pipeline leaks no goroutines, and a bounded pipe stops a producer.

go
package stage

import (
	"context"
	"errors"
	"fmt"
	"runtime"
	"sort"
	"testing"
	"time"
)

func collect[T any](t *testing.T, ctx context.Context, in <-chan Item[T]) []Item[T] {
	t.Helper()
	var got []Item[T]
	if err := Drain(ctx, in, func(it Item[T]) error { got = append(got, it); return nil }); err != nil {
		t.Fatalf("drain: %v", err)
	}
	return got
}

func TestMapFanOutKeepsEveryItemButNotOrder(t *testing.T) {
	ctx := context.Background()
	in := FromSlice(ctx, 4, []int{1, 2, 3, 4, 5, 6, 7, 8})
	sq := Map(4, 4, func(_ context.Context, n int) (int, error) { return n * n, nil })
	got := collect(t, ctx, sq(ctx, in))
	vals := make([]int, 0, len(got))
	for _, it := range got {
		vals = append(vals, it.Val)
	}
	sort.Ints(vals) // order is not guaranteed after fan-out, the set is
	want := []int{1, 4, 9, 16, 25, 36, 49, 64}
	if fmt.Sprint(vals) != fmt.Sprint(want) {
		t.Fatalf("got %v want %v", vals, want)
	}
}

func TestResequenceRestoresSourceOrder(t *testing.T) {
	ctx := context.Background()
	src := make([]int, 50)
	for i := range src {
		src[i] = i
	}
	slowFirst := func(_ context.Context, n int) (int, error) {
		if n%7 == 0 {
			time.Sleep(3 * time.Millisecond)
		}
		return n, nil
	}
	p := Compose(Map(8, 2, slowFirst), Resequence[int](2))
	got := collect(t, ctx, p(ctx, FromSlice(ctx, 2, src)))
	for i, it := range got {
		if it.Val != i {
			t.Fatalf("position %d holds %d", i, it.Val)
		}
	}
}

func TestPoisonItemFlowsToTheEndWithoutCallingLaterFilters(t *testing.T) {
	ctx := context.Background()
	calls := 0
	boom := Map(1, 1, func(_ context.Context, n int) (int, error) {
		if n == 2 {
			return 0, errors.New("poison")
		}
		return n, nil
	})
	next := Map(1, 1, func(_ context.Context, n int) (int, error) { calls++; return n, nil })
	got := collect(t, ctx, Compose(boom, next)(ctx, FromSlice(ctx, 1, []int{1, 2, 3})))
	if len(got) != 3 || got[1].Err == nil || calls != 2 {
		t.Fatalf("got %+v calls %d", got, calls)
	}
}

func TestFilterDropsAndKeepsPoison(t *testing.T) {
	ctx := context.Background()
	even := Filter[int](1, func(n int) bool { return n%2 == 0 })
	got := collect(t, ctx, even(ctx, FromSlice(ctx, 1, []int{1, 2, 3, 4})))
	if len(got) != 2 {
		t.Fatalf("got %+v", got)
	}
}

func TestRetryOnlyRetriesTransient(t *testing.T) {
	n := 0
	fn := Retry(3, time.Millisecond, func(context.Context, int) (int, error) {
		n++
		if n < 3 {
			return 0, fmt.Errorf("db: %w", ErrTransient)
		}
		return 7, nil
	})
	if v, err := fn(context.Background(), 0); err != nil || v != 7 || n != 3 {
		t.Fatalf("v=%d err=%v n=%d", v, err, n)
	}
	n = 0
	perm := Retry(3, time.Millisecond, func(context.Context, int) (int, error) { n++; return 0, errors.New("bad row") })
	if _, err := perm(context.Background(), 0); err == nil || n != 1 {
		t.Fatalf("err=%v n=%d", err, n)
	}
}

func TestCancelUnblocksEveryStageAndLeaksNoGoroutines(t *testing.T) {
	before := runtime.NumGoroutine()
	ctx, cancel := context.WithCancel(context.Background())
	src := make([]int, 10_000)
	slow := Map(4, 1, func(ctx context.Context, n int) (int, error) { return n, nil })
	out := Compose(slow, slow)(ctx, FromSlice(ctx, 1, src))
	<-out // take one item, then walk away with the pipeline full
	cancel()
	deadline := time.Now().Add(2 * time.Second)
	for runtime.NumGoroutine() > before+1 && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if g := runtime.NumGoroutine(); g > before+1 {
		t.Fatalf("goroutines before=%d after=%d", before, g)
	}
}

func TestBoundedPipeBlocksTheProducer(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	produced := make(chan int, 100)
	in, wait := FromFunc(ctx, 2, func(emit func(int) bool) error {
		for i := 0; i < 100; i++ {
			if !emit(i) {
				return nil
			}
			produced <- i
		}
		return nil
	})
	time.Sleep(50 * time.Millisecond) // nobody reads: the producer must stall
	if n := len(produced); n > 4 {
		t.Fatalf("producer ran ahead by %d items despite a pipe of 2", n)
	}
	cancel()
	_ = wait()
	_ = in
}

func TestTapCounts(t *testing.T) {
	ctx := context.Background()
	var c Counter
	_ = collect(t, ctx, Tap[int](&c, 1)(ctx, FromSlice(ctx, 1, []int{1, 2, 3})))
	if c.In.Load() != 3 || c.Out.Load() != 3 {
		t.Fatalf("in=%d out=%d", c.In.Load(), c.Out.Load())
	}
}

The Go angle ​

TopicGo answer
Pipechan T with a capacity you choose; io.Pipe for bytes
FilterA goroutine, or a Read wrapper
Shutdowncontext.Context plus errgroup.WithContext; never rely on "the consumer will drain"
ClosingThe sender closes its own channel; a receiver never closes
ParallelismMap(workers, ...); errgroup.SetLimit(n) bounds a group
OrderingSequence numbers and a resequencer, or one worker
Iteratorsiter.Seq (Go 1.23) is a pull pipeline without goroutines; use it when no concurrency is needed
Racesgo test -race; channels transfer ownership of the item
GenericsStage[In, Out] type-checks the wiring at compile time

Laravel ​

Laravel 13 has the style built in at three levels: the Pipeline helper (a synchronous chain), the HTTP middleware stack (a pipeline over a request), and queued jobs (an asynchronous pipeline). Large files are handled by LazyCollection. PHP was not run on the machine that wrote this page: the code is reviewed against the Laravel 13 docs and framework source, not executed.

The Pipeline helper ​

The helpers documentation says: "Laravel's Pipeline facade provides a convenient way to 'pipe' a given input through a series of invokable classes, closures, or callables, giving each class the opportunity to inspect or modify the input and invoke the next callable in the pipeline", and "As you may have noticed, this is very similar to middleware". "If a class name is provided, the class will be instantiated via Laravel's service container, allowing dependencies to be injected." The framework source shows the methods: send, through, pipe, via, then, thenReturn, finally and withinTransaction; the facade is declared with $cached = false, so each Pipeline::send(...) call returns a fresh pipeline. A pipe is any callable (passable, Closure $next); it calls $next($passable) to continue, or returns early (or throws) to stop the chain.

The order import uses one passable (OrderRow), five pipes and a PoisonRow exception for rejects.

php
<?php

declare(strict_types=1);

namespace App\Import;

/**
 * The passable of the pipeline: one CSV line that gains fields stage by stage.
 * Money is integer cents, never float.
 */
final class OrderRow
{
    public ?string $id = null;
    public ?string $customer = null;
    public ?string $sku = null;
    public ?int $qty = null;
    public ?string $tier = null;
    public ?int $unitCents = null;
    public ?int $totalCents = null;

    public function __construct(
        public readonly int $seq,
        public readonly string $line,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Import;

use RuntimeException;

/**
 * Thrown by a filter that decides the row can never be processed.
 * The driver catches it, writes the row to the dead-letter store and moves on.
 */
final class PoisonRow extends RuntimeException
{
    public function __construct(public readonly OrderRow $row, string $reason)
    {
        parent::__construct($reason);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Import\Pipes;

use App\Import\OrderRow;
use App\Import\PoisonRow;
use Closure;
use Illuminate\Support\Facades\DB;
use RuntimeException;

/** Filter 1, transformer: CSV line to fields. */
final class ParseLine
{
    public function __invoke(OrderRow $row, Closure $next): OrderRow
    {
        $f = str_getcsv($row->line);

        if (count($f) !== 4 || ! ctype_digit($f[3])) {
            throw new PoisonRow($row, "cannot parse line {$row->seq}");
        }

        [$row->id, $row->customer, $row->sku, $row->qty] = [$f[0], $f[1], $f[2], (int) $f[3]];

        return $next($row);
    }
}

/** Filter 2, tester: business rules. */
final class ValidateOrder
{
    public function __invoke(OrderRow $row, Closure $next): OrderRow
    {
        if ($row->id === '' || $row->qty < 1 || $row->qty > 1000) {
            throw new PoisonRow($row, "order {$row->id}: quantity {$row->qty} out of range");
        }

        return $next($row);
    }
}

/** Filter 3, transformer: asks another system, so it retries transient errors. */
final class EnrichCustomer
{
    public function __construct(private readonly CustomerDirectory $directory) {}

    public function __invoke(OrderRow $row, Closure $next): OrderRow
    {
        // retry(times, callback, sleepMilliseconds): the framework helper.
        try {
            $row->tier = retry(3, fn () => $this->directory->tier($row->customer), 50);
        } catch (RuntimeException $e) {
            // Retry budget spent: this row goes to the dead letters, the import goes on.
            throw new PoisonRow($row, "directory unavailable for {$row->customer}: {$e->getMessage()}");
        }

        return $next($row);
    }
}

/** Filter 4, transformer: integer-cent pricing. */
final class PriceOrder
{
    public function __invoke(OrderRow $row, Closure $next): OrderRow
    {
        /** @var array<string, int> $catalog sku => unit price in cents, from config/orders.php */
        $catalog = config('orders.catalog', []);
        $unit = $catalog[$row->sku] ?? throw new PoisonRow($row, "unknown sku {$row->sku}");
        $total = $unit * $row->qty;

        if ($row->tier === 'gold' && $total > 10_000) {
            $total -= intdiv($total, 10);
        }

        [$row->unitCents, $row->totalCents] = [$unit, $total];

        return $next($row);
    }
}

/** Filter 5, consumer: idempotent upsert on the primary key. */
final class PersistOrder
{
    public function __invoke(OrderRow $row, Closure $next): OrderRow
    {
        DB::table('orders')->upsert(
            [[
                'id' => $row->id,
                'customer' => $row->customer,
                'sku' => $row->sku,
                'qty' => $row->qty,
                'total_cents' => $row->totalCents,
            ]],
            ['id'],                              // unique key
            ['customer', 'sku', 'qty', 'total_cents'], // columns to update on conflict
        );

        return $next($row);
    }
}

/** Port of the enrichment filter, bound in a service provider. */
interface CustomerDirectory
{
    public function tier(string $customer): string;
}

withinTransaction() wraps the whole chain in one database transaction, which is the right choice when the pipes are all database writes of one item, and the wrong choice when a pipe calls another system. Our consumer is a single upsert, so we do not need it.

Middleware is a request pipeline ​

The framework's own HTTP kernel builds a Pipeline: sendRequestThroughRouter runs (new Pipeline($this->app))->send($request)->through($this->middleware)->then($this->dispatchToRouter()) (we read Illuminate/Foundation/Http/Kernel.php on the 13.x branch; the class used is Illuminate\Routing\Pipeline, a subclass tuned for requests). The middleware documentation shows how the list is edited: $middleware->append(...), prepend(...), insertBefore(...), insertAfter(...) and use([...]). A middleware is a filter with two halves, before and after $next: the filters run in order on the request and in reverse order on the response.

php
<?php

declare(strict_types=1);

// bootstrap/app.php: the global middleware list IS a pipeline definition.
// Illuminate\Foundation\Http\Kernel::sendRequestThroughRouter() runs
// (new Pipeline($app))->send($request)->through($middleware)->then($router).

use App\Http\Middleware\AddRequestId;
use App\Http\Middleware\EnsureTokenIsValid;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php', health: '/up')
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->prepend(AddRequestId::class);      // first filter in, last filter out
        $middleware->append(EnsureTokenIsValid::class); // last filter before the router
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
php
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/** A transformer filter with two halves: before and after $next. */
final class AddRequestId
{
    public function handle(Request $request, Closure $next): Response
    {
        // inbound half: acts on the request
        $id = $request->header('X-Request-Id') ?? (string) Str::uuid();
        $request->headers->set('X-Request-Id', $id);

        $response = $next($request);

        // outbound half: acts on the response on the way back
        $response->headers->set('X-Request-Id', $id);

        return $response;
    }
}

LazyCollection: streaming a 1 GB CSV ​

The Collections documentation: "the LazyCollection class leverages PHP's generators to allow you to work with very large datasets while keeping memory usage low." You build the producer with LazyCollection::make(function () { ... yield ... }); map, filter, chunk and tapEach are lazy filters; each is the consumer that pulls. The same page warns about the alternative: User::all()->filter(...) "must be loaded into memory at the same time", while User::cursor() "returns a LazyCollection instance" and keeps one model at a time. chunk(500) is a bounded buffer: at most 500 rows exist at once. ImportOrders below reads a file this way, runs each row through the Pipeline and writes poison rows to import_dead_letters.

php
<?php

declare(strict_types=1);

namespace App\Import;

use App\Import\Pipes\EnrichCustomer;
use App\Import\Pipes\ParseLine;
use App\Import\Pipes\PersistOrder;
use App\Import\Pipes\PriceOrder;
use App\Import\Pipes\ValidateOrder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Pipeline;
use Illuminate\Support\LazyCollection;

/**
 * Producer + pipeline + dead letters. The producer is a generator, so only
 * one chunk of lines is ever in memory, however big the file is.
 */
final class ImportOrders
{
    /** @return array{read:int, stored:int, dead:int} */
    public function handle(string $path, int $chunk = 500): array
    {
        $count = ['read' => 0, 'stored' => 0, 'dead' => 0];

        LazyCollection::make(function () use ($path) {
            $h = fopen($path, 'rb');
            fgets($h); // header
            $seq = 0;
            while (($line = fgets($h)) !== false) {
                yield new OrderRow($seq++, rtrim($line, "\r\n"));
            }
            fclose($h);
        })
            ->chunk($chunk)                       // a bounded buffer: 500 rows
            ->each(function (LazyCollection $rows) use (&$count) {
                foreach ($rows as $row) {
                    $count['read']++;
                    $this->one($row, $count);
                }
            });

        return $count;
    }

    private function one(OrderRow $row, array &$count): void
    {
        try {
            // A new Pipeline per row: the facade is not cached.
            Pipeline::send($row)
                ->through([
                    ParseLine::class,       // class names are resolved by the container,
                    ValidateOrder::class,   // so constructor dependencies are injected
                    EnrichCustomer::class,
                    PriceOrder::class,
                    PersistOrder::class,
                ])
                ->thenReturn();
            $count['stored']++;
        } catch (PoisonRow $e) {
            $this->deadLetter($e->row, $e->getMessage());
            $count['dead']++;
        }
        // Any other Throwable (database gone) is not caught on purpose: it
        // stops the import, and the replay is safe because persist is an upsert.
    }

    private function deadLetter(OrderRow $row, string $reason): void
    {
        DB::table('import_dead_letters')->insert([
            'seq' => $row->seq,
            'line' => $row->line,
            'reason' => $reason,
            'created_at' => now(),
        ]);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Import\ImportOrders;
use Illuminate\Console\Command;

final class ImportOrdersCommand extends Command
{
    protected $signature = 'orders:import {path} {--chunk=500}';
    protected $description = 'Stream a large orders CSV through the import pipeline';

    public function handle(ImportOrders $import): int
    {
        $start = hrtime(true);
        $r = $import->handle($this->argument('path'), (int) $this->option('chunk'));
        $seconds = (hrtime(true) - $start) / 1e9;

        $this->table(['read', 'stored', 'dead'], [[$r['read'], $r['stored'], $r['dead']]]);
        $this->info(sprintf(
            '%.1f s, %.0f rows/s, peak memory %.1f MB',
            $seconds,
            $r['read'] / max($seconds, 0.001),
            memory_get_peak_usage(true) / 1048576,
        ));

        return self::SUCCESS;
    }
}

The expected memory figure for a 1 GB file (about 20 million lines of 50 bytes) is a flat line near the PHP baseline plus 500 rows, roughly 20 to 40 MB, regardless of file size, while Collection over file() would try to hold the whole file and exhaust memory_limit. We did not run PHP on this machine, so treat the figure as the design target to verify in the lab.

Job chains and batches: the asynchronous pipeline ​

The queues documentation: "Job chaining allows you to specify a list of queued jobs that should be run in sequence after the primary job has executed successfully. If one job in the sequence fails, the rest of the jobs will not be run." Bus::chain([...])->catch(...)->dispatch() is a sequential pipeline for one unit of work whose pipes are queues. Bus::batch([...]) is fan-out with a join: "execute a group of jobs in parallel and then perform some action when the batch of jobs has completed executing"; callbacks are before, progress, then, catch and finally; "When a job within a batch fails, Laravel will automatically mark the batch as 'cancelled'" unless you call allowFailures(). Batchable jobs check $this->batch()->cancelled(). Batches need the table made by php artisan make:queue-batches-table. Internals of the queue drivers are in Laravel Queue Internals.

php
<?php

declare(strict_types=1);

namespace App\Jobs;

use Illuminate\Bus\Batch;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Bus;
use Throwable;

/**
 * Asynchronous pipe-and-filter: the queue is the pipe, a job is the filter.
 * A chain is a sequential pipeline for ONE unit of work; a batch is
 * fan-out of many independent units with a join at the end.
 */
final class SplitFile implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $path) {}

    public function handle(): void
    {
        // Producer: cut the file into byte ranges and fan out one batch.
        $ranges = [[0, 50_000_000], [50_000_000, 100_000_000]]; // computed from filesize()

        $jobs = array_map(fn (array $r) => new ImportRange($this->path, $r[0], $r[1]), $ranges);

        Bus::batch($jobs)
            ->name('orders-import')
            ->onQueue('import')
            ->allowFailures()                       // one bad range must not cancel the others
            ->then(fn (Batch $b) => logger()->info('all ranges done', ['id' => $b->id]))
            ->catch(fn (Batch $b, Throwable $e) => logger()->error('range failed', ['e' => $e->getMessage()]))
            ->finally(fn (Batch $b) => logger()->info('failed jobs', ['n' => $b->failedJobs]))
            ->dispatch();
    }
}

final class ImportRange implements ShouldQueue
{
    use Batchable, Queueable;

    public int $tries = 3;
    /** @var array<int, int> seconds between retries */
    public array $backoff = [10, 60, 300];

    public function __construct(public string $path, public int $from, public int $to) {}

    public function handle(): void
    {
        if ($this->batch()?->cancelled()) {
            return;
        }
        // read lines in [from, to), run each through the Pipeline (see ImportOrders)
    }
}

// One order, three asynchronous filters, strictly in order. If one fails,
// the rest of the chain does not run and catch() fires.
// Bus::chain([new ReserveStock($id), new ChargeCard($id), new SendReceipt($id)])
//     ->onQueue('orders')
//     ->catch(fn (Throwable $e) => report($e))
//     ->dispatch();

The Laravel angle ​

TopicLaravel answer
PipeThe $next closure (sync), a queue (async)
FilterInvokable class, middleware, job
Streaming a big fileLazyCollection::make over a generator; cursor() for Eloquent; lazyById() for chunked queries
Bounded bufferchunk($n), queue --max-jobs, --memory flags on queue:work
Poison dataThrow a domain exception, catch in the driver, write a dead-letter row; for jobs, failed_jobs table and $tries, $backoff
ParallelismMore queue:work processes (Horizon maxProcesses), Bus::batch
Cancellation$batch->cancel(), Bus::chain()->catch(), a signal for the worker
ObservabilityHorizon metrics, Bus::findBatch($id) progress, per-pipe logging
TestingFake the directory, assert dead letters and row counts (see below); Bus::fake() for jobs

Worked example: an order-import pipeline ​

Requirement. A partner sends orders.csv with a header and lines id,customer,sku,qty. Import it so that: bad lines never stop good ones and are kept with a reason; the customer tier comes from another service that sometimes times out; gold customers get 10% off above 100.00; the database is written idempotently so a failed run can be repeated; memory does not grow with the file.

text
     Stage     Role         Input          Output          Failure handling
1    Read      producer     file           line            file error: fatal
2    Parse     transformer  line           Order           poison -> dead letter
3    Validate  tester       Order          Order           rule broken -> dead letter
4    Enrich    transformer  Order          Enriched        timeout: retry x3; then dead letter
5    Price     transformer  Enriched       Priced          unknown sku -> dead letter
6    Persist   consumer     Priced         row             retry; then fatal, cancel, rerun

Go version ​

orders.Run wires the stages with stage.Compose, drains the result in one goroutine and treats an Item with an error as a dead letter. The errgroup has two members: the sink and the producer's wait. A store failure returns an error from the sink, the group cancels the context, every stage exits and Run returns the error. The filters are separate functions with a Config carrying the knobs: Workers, Buffer, Attempts, Backoff.

go
// Package orders is the worked example: an order-import pipeline
// parse -> validate -> enrich -> price -> persist, built from stage filters.
package orders

import (
	"bufio"
	"context"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"

	"academy/pipe-and-filter/stage"

	"golang.org/x/sync/errgroup"
)

// ErrInvalid marks poison data: retrying it can never help.
var ErrInvalid = errors.New("invalid order")

// Order is what a CSV line becomes.
type Order struct {
	ID, Customer, SKU string
	Qty               int
}

// Enriched adds data from another system (the customer tier).
type Enriched struct {
	Order
	Tier string
}

// Priced is the final shape that is persisted. Money is integer cents.
type Priced struct {
	Enriched
	UnitCents, TotalCents int64
}

// Directory and Catalog are the ports of the two enrichment filters.
type Directory interface {
	Tier(ctx context.Context, customer string) (string, error)
}

type Catalog interface {
	UnitCents(ctx context.Context, sku string) (int64, error)
}

// Store is the port of the consumer. Save MUST be idempotent on Order.ID,
// because a failed run is simply started again.
type Store interface {
	Save(ctx context.Context, p Priced) error
}

// Deps groups the ports so tests can inject failures.
type Deps struct {
	Directory Directory
	Catalog   Catalog
	Store     Store
}

// Config holds the knobs that decide throughput and memory.
type Config struct {
	Workers    int           // parallel workers in each transformer stage
	Buffer     int           // capacity of every pipe (the backpressure budget)
	Attempts   int           // tries per item for transient errors
	Backoff    time.Duration // first retry delay, doubled each time
	DeadLetter io.Writer     // poison items are written here, may be nil
}

// DeadLetter describes one rejected input line.
type DeadLetter struct {
	Seq    int
	Reason string
}

// Report is the outcome of one run.
type Report struct {
	Read, Stored int
	Dead         []DeadLetter
}

// Parse is a transformer: one CSV line to an Order.
func Parse(cfg Config) stage.Stage[string, Order] {
	return stage.Map(cfg.Workers, cfg.Buffer, func(_ context.Context, line string) (Order, error) {
		rec, err := csv.NewReader(strings.NewReader(line)).Read()
		if err != nil || len(rec) != 4 {
			return Order{}, fmt.Errorf("%w: cannot parse %q", ErrInvalid, line)
		}
		qty, err := strconv.Atoi(rec[3])
		if err != nil {
			return Order{}, fmt.Errorf("%w: quantity %q is not a number", ErrInvalid, rec[3])
		}
		return Order{ID: rec[0], Customer: rec[1], SKU: rec[2], Qty: qty}, nil
	})
}

// Validate is a tester: it rejects orders that break a business rule.
func Validate(cfg Config) stage.Stage[Order, Order] {
	return stage.Map(cfg.Workers, cfg.Buffer, func(_ context.Context, o Order) (Order, error) {
		switch {
		case o.ID == "" || o.Customer == "" || o.SKU == "":
			return o, fmt.Errorf("%w: %s has an empty field", ErrInvalid, o.ID)
		case o.Qty <= 0 || o.Qty > 1000:
			return o, fmt.Errorf("%w: %s quantity %d out of range", ErrInvalid, o.ID, o.Qty)
		}
		return o, nil
	})
}

// Enrich asks the directory for the tier; transient errors are retried.
func Enrich(cfg Config, d Directory) stage.Stage[Order, Enriched] {
	fn := func(ctx context.Context, o Order) (Enriched, error) {
		tier, err := d.Tier(ctx, o.Customer)
		if err != nil {
			return Enriched{}, err
		}
		return Enriched{Order: o, Tier: tier}, nil
	}
	return stage.Map(cfg.Workers, cfg.Buffer, stage.Retry(cfg.Attempts, cfg.Backoff, fn))
}

// Price applies the rule "gold customers get 10% off above 100.00".
func Price(cfg Config, c Catalog) stage.Stage[Enriched, Priced] {
	return stage.Map(cfg.Workers, cfg.Buffer, func(ctx context.Context, e Enriched) (Priced, error) {
		unit, err := c.UnitCents(ctx, e.SKU)
		if err != nil {
			return Priced{}, err
		}
		total := unit * int64(e.Qty)
		if e.Tier == "gold" && total > 10_000 {
			total -= total / 10
		}
		return Priced{Enriched: e, UnitCents: unit, TotalCents: total}, nil
	})
}

// Run wires the pipeline and drives it. Poison items end in the dead-letter
// list; an infrastructure failure of the store stops everything and is
// returned. Running the same input again is safe because Save is idempotent.
func Run(ctx context.Context, r io.Reader, deps Deps, cfg Config) (Report, error) {
	g, ctx := errgroup.WithContext(ctx)
	lines, srcWait := stage.FromFunc(ctx, cfg.Buffer, func(emit func(string) bool) error {
		sc := bufio.NewScanner(r)
		sc.Buffer(make([]byte, 64*1024), 1<<20)
		first := true
		for sc.Scan() {
			if first { // header line
				first = false
				continue
			}
			if !emit(sc.Text()) {
				return nil
			}
		}
		return sc.Err()
	})
	pipeline := stage.Compose(
		stage.Compose(
			stage.Compose(Parse(cfg), Validate(cfg)),
			Enrich(cfg, deps.Directory)),
		Price(cfg, deps.Catalog))
	save := stage.Retry(cfg.Attempts, cfg.Backoff, func(ctx context.Context, p Priced) (struct{}, error) {
		return struct{}{}, deps.Store.Save(ctx, p)
	})

	var rep Report
	g.Go(func() error {
		return stage.Drain(ctx, pipeline(ctx, lines), func(it stage.Item[Priced]) error {
			rep.Read++
			if it.Err != nil {
				return rep.reject(cfg, it)
			}
			if _, err := save(ctx, it.Val); err != nil {
				return fmt.Errorf("store: %w", err) // fatal: cancels the group
			}
			rep.Stored++
			return nil
		})
	})
	g.Go(srcWait)
	return rep, g.Wait()
}

func (rep *Report) reject(cfg Config, it stage.Item[Priced]) error {
	rep.Dead = append(rep.Dead, DeadLetter{Seq: it.Seq, Reason: it.Err.Error()})
	if cfg.DeadLetter != nil {
		_, err := fmt.Fprintf(cfg.DeadLetter, "%d\t%s\n", it.Seq, it.Err)
		return err
	}
	return nil
}

The in-memory adapters give the tests a way to inject faults: MemDirectory{FailFirst: 2} returns ErrTransient for the first two calls per customer, Down makes a customer permanently unavailable, and MemStore{FailAfter: 10} fails every Save after ten calls.

go
package orders

import (
	"context"
	"fmt"
	"sync"
	"sync/atomic"

	"academy/pipe-and-filter/stage"
)

// MemDirectory is an in-memory Directory. FailFirst makes the first N calls
// per customer fail with a transient error, to exercise the retry filter.
type MemDirectory struct {
	Tiers     map[string]string
	FailFirst int32
	Down      map[string]bool // customers whose lookup always fails
	mu        sync.Mutex
	calls     map[string]int32
}

func (d *MemDirectory) Tier(_ context.Context, customer string) (string, error) {
	d.mu.Lock()
	if d.calls == nil {
		d.calls = map[string]int32{}
	}
	d.calls[customer]++
	n := d.calls[customer]
	d.mu.Unlock()
	if d.Down[customer] || n <= d.FailFirst {
		return "", fmt.Errorf("directory timeout: %w", stage.ErrTransient)
	}
	return d.Tiers[customer], nil
}

// MemCatalog is an in-memory Catalog; an unknown SKU is poison data.
type MemCatalog map[string]int64

func (c MemCatalog) UnitCents(_ context.Context, sku string) (int64, error) {
	v, ok := c[sku]
	if !ok {
		return 0, fmt.Errorf("%w: unknown sku %q", ErrInvalid, sku)
	}
	return v, nil
}

// MemStore is an idempotent Store. FailAfter makes every Save after the first
// N calls fail, to simulate the database going away mid-run.
type MemStore struct {
	FailAfter int64 // 0 means never fail
	mu        sync.Mutex
	rows      map[string]Priced
	calls     atomic.Int64
}

func (s *MemStore) Save(_ context.Context, p Priced) error {
	if s.FailAfter > 0 && s.calls.Add(1) > s.FailAfter {
		return fmt.Errorf("store: connection refused")
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.rows == nil {
		s.rows = map[string]Priced{}
	}
	s.rows[p.ID] = p // upsert by primary key: replay-safe
	return nil
}

// Len returns the number of distinct orders stored.
func (s *MemStore) Len() int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return len(s.rows)
}

// Get returns one stored order.
func (s *MemStore) Get(id string) (Priced, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	p, ok := s.rows[id]
	return p, ok
}

The tests are the failure-injection run:

go
package orders

import (
	"bytes"
	"context"
	"fmt"
	"runtime"
	"strings"
	"testing"
	"time"
)

const header = "id,customer,sku,qty\n"

func deps() (Deps, *MemStore) {
	st := &MemStore{}
	return Deps{
		Directory: &MemDirectory{Tiers: map[string]string{"c1": "gold", "c2": "basic"}},
		Catalog:   MemCatalog{"pen": 250, "desk": 12_000},
		Store:     st,
	}, st
}

func cfg() Config {
	return Config{Workers: 4, Buffer: 8, Attempts: 3, Backoff: time.Millisecond}
}

func TestHappyPathAndPricing(t *testing.T) {
	d, st := deps()
	in := header + "o1,c1,desk,1\no2,c2,desk,1\no3,c1,pen,2\n"
	rep, err := Run(context.Background(), strings.NewReader(in), d, cfg())
	if err != nil || rep.Stored != 3 || len(rep.Dead) != 0 {
		t.Fatalf("rep=%+v err=%v", rep, err)
	}
	cases := map[string]int64{"o1": 10_800, "o2": 12_000, "o3": 500}
	for id, want := range cases {
		if p, _ := st.Get(id); p.TotalCents != want {
			t.Errorf("%s total %d want %d", id, p.TotalCents, want)
		}
	}
}

func TestPoisonLinesGoToTheDeadLetterAndTheRestContinues(t *testing.T) {
	d, st := deps()
	in := header + "o1,c1,pen,1\nbroken-line\no3,c1,pen,abc\no4,c1,ghost,1\no5,c2,pen,5000\no6,c2,pen,1\n"
	var dlq bytes.Buffer
	c := cfg()
	c.DeadLetter = &dlq
	rep, err := Run(context.Background(), strings.NewReader(in), d, c)
	if err != nil {
		t.Fatal(err)
	}
	if rep.Stored != 2 || len(rep.Dead) != 4 || st.Len() != 2 {
		t.Fatalf("rep=%+v", rep)
	}
	if got := strings.Count(dlq.String(), "\n"); got != 4 {
		t.Fatalf("dead-letter lines: %d\n%s", got, dlq.String())
	}
}

func TestTransientDirectoryErrorsAreRetried(t *testing.T) {
	d, st := deps()
	d.Directory = &MemDirectory{Tiers: map[string]string{"c1": "gold"}, FailFirst: 2}
	rep, err := Run(context.Background(), strings.NewReader(header+"o1,c1,pen,1\no2,c1,pen,1\n"), d, cfg())
	if err != nil || rep.Stored != 2 || len(rep.Dead) != 0 || st.Len() != 2 {
		t.Fatalf("rep=%+v err=%v", rep, err)
	}
}

func TestRetryBudgetExhaustedDeadLettersOnlyThatItem(t *testing.T) {
	d, _ := deps()
	d.Directory = &MemDirectory{Tiers: map[string]string{"c1": "gold"}, Down: map[string]bool{"c9": true}}
	rep, err := Run(context.Background(), strings.NewReader(header+"o1,c1,pen,1\no2,c9,pen,1\no3,c1,pen,1\n"), d, cfg())
	if err != nil || rep.Stored != 2 || len(rep.Dead) != 1 || rep.Dead[0].Seq != 1 {
		t.Fatalf("rep=%+v err=%v", rep, err)
	}
}

func lines(n int) string {
	var b strings.Builder
	b.WriteString(header)
	for i := 0; i < n; i++ {
		fmt.Fprintf(&b, "o%d,c1,pen,1\n", i)
	}
	return b.String()
}

func TestStoreFailureStopsThePipelineAndAReplayIsIdempotent(t *testing.T) {
	before := runtime.NumGoroutine()
	d, st := deps()
	st.FailAfter = 10
	in := lines(500)
	_, err := Run(context.Background(), strings.NewReader(in), d, cfg())
	if err == nil || !strings.Contains(err.Error(), "store") {
		t.Fatalf("want a store error, got %v", err)
	}
	deadline := time.Now().Add(2 * time.Second)
	for runtime.NumGoroutine() > before+1 && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if g := runtime.NumGoroutine(); g > before+1 {
		t.Fatalf("goroutine leak: before=%d after=%d", before, g)
	}
	if st.Len() != 10 {
		t.Fatalf("stored before failure: %d", st.Len())
	}
	// the store is back: run the same file again
	st.FailAfter = 0
	rep, err := Run(context.Background(), strings.NewReader(in), d, cfg())
	if err != nil || rep.Stored != 500 || st.Len() != 500 {
		t.Fatalf("rep.Stored=%d len=%d err=%v", rep.Stored, st.Len(), err)
	}
}

func TestCancellationReturnsPromptly(t *testing.T) {
	d, _ := deps()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
	defer cancel()
	d.Directory = &MemDirectory{Tiers: map[string]string{"c1": "gold"}, Down: map[string]bool{"c1": true}}
	c := cfg()
	c.Attempts, c.Backoff = 50, 50*time.Millisecond
	start := time.Now()
	_, _ = Run(ctx, strings.NewReader(lines(100)), d, c)
	if time.Since(start) > time.Second {
		t.Fatalf("pipeline ignored cancellation for %v", time.Since(start))
	}
}

Real output on the machine that wrote this page (go test -race -count=1 -v ./orders/):

text
--- PASS: TestHappyPathAndPricing (0.00s)
--- PASS: TestPoisonLinesGoToTheDeadLetterAndTheRestContinues (0.00s)
--- PASS: TestTransientDirectoryErrorsAreRetried (0.00s)
--- PASS: TestRetryBudgetExhaustedDeadLettersOnlyThatItem (0.00s)
--- PASS: TestStoreFailureStopsThePipelineAndAReplayIsIdempotent (0.01s)
--- PASS: TestCancellationReturnsPromptly (0.01s)
ok  	academy/pipe-and-filter/orders	1.387s

And the demo, which imports 1000 generated lines with seven bad ones, printing dead letters to stderr:

go
// Command demo imports a generated CSV with a few bad lines.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"academy/pipe-and-filter/orders"
)

func main() {
	var in strings.Builder
	in.WriteString("id,customer,sku,qty\n")
	for i := 0; i < 1000; i++ {
		switch {
		case i%250 == 7:
			fmt.Fprintf(&in, "o%d,c1,ghost,1\n", i) // unknown sku: poison
		case i%333 == 5:
			fmt.Fprintf(&in, "o%d,c2,pen,zero\n", i) // malformed quantity: poison
		default:
			fmt.Fprintf(&in, "o%d,c%d,pen,%d\n", i, i%2+1, i%5+1)
		}
	}
	store := &orders.MemStore{}
	deps := orders.Deps{
		Directory: &orders.MemDirectory{Tiers: map[string]string{"c1": "gold", "c2": "basic"}},
		Catalog:   orders.MemCatalog{"pen": 250},
		Store:     store,
	}
	cfg := orders.Config{Workers: 4, Buffer: 16, Attempts: 3, Backoff: time.Millisecond, DeadLetter: os.Stderr}
	rep, err := orders.Run(context.Background(), strings.NewReader(in.String()), deps, cfg)
	fmt.Printf("read=%d stored=%d dead=%d err=%v\n", rep.Read, rep.Stored, len(rep.Dead), err)
}
text
$ go run ./orders/cmd/demo
7	invalid order: unknown sku "ghost"
5	invalid order: quantity "zero" is not a number
257	invalid order: unknown sku "ghost"
...
read=1000 stored=993 dead=7 err=<nil>

What the failure-injection tests prove, one by one:

Injected faultExpected behaviourTest
Garbage line, quantity 0, unknown SKU, quantity 50004 dead letters, rest storedTestPoisonLines...
Directory times out twice per customerRetried; all stored; no dead lettersTestTransientDirectoryErrorsAreRetried
One customer permanently unreachableOnly that line dead-letteredTestRetryBudgetExhausted...
Store dies after 10 savesRun returns a store error; no goroutine leak; 10 rows storedTestStoreFailure...
Same file replayed with a healthy store500 rows, no duplicates (upsert)TestStoreFailure...
Context deadline during long retriesRun returns within a secondTestCancellationReturnsPromptly

Laravel version ​

The Laravel version uses the same stages as pipe classes (see Pipes), a generator-backed LazyCollection as the producer and a dead-letter table. The consumer is an idempotent upsert; PostgreSQL syntax shown, MySQL uses INSERT ... ON DUPLICATE KEY UPDATE, SQL Server MERGE, SQLite ON CONFLICT like PostgreSQL:

sql
CREATE TABLE orders (
  id           text PRIMARY KEY,
  customer     text   NOT NULL,
  sku          text   NOT NULL,
  qty          int    NOT NULL CHECK (qty BETWEEN 1 AND 1000),
  total_cents  bigint NOT NULL
);

CREATE TABLE import_dead_letters (
  id         bigserial PRIMARY KEY,
  seq        int         NOT NULL,   -- line number in the file
  line       text        NOT NULL,   -- the original input, for support
  reason     text        NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- What DB::table('orders')->upsert([...], ['id'], [...]) sends
INSERT INTO orders (id, customer, sku, qty, total_cents)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
   SET customer = EXCLUDED.customer, sku = EXCLUDED.sku,
       qty = EXCLUDED.qty, total_cents = EXCLUDED.total_cents;

The test file runs the three failure cases: poison rows to the dead-letter table, a directory that times out twice, and a replay that must not duplicate rows.

php
<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Import\ImportOrders;
use App\Import\Pipes\CustomerDirectory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

final class OrderImportTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        config(['orders.catalog' => ['pen' => 250]]);
    }

    private function csv(string ...$rows): string
    {
        $path = tempnam(sys_get_temp_dir(), 'orders');
        file_put_contents($path, "id,customer,sku,qty\n".implode("\n", $rows)."\n");

        return $path;
    }

    public function test_poison_rows_go_to_the_dead_letter_table_and_the_rest_continue(): void
    {
        $this->app->bind(CustomerDirectory::class, fn () => new class implements CustomerDirectory {
            public function tier(string $customer): string { return 'basic'; }
        });

        $r = $this->app->make(ImportOrders::class)
            ->handle($this->csv('o1,c1,pen,1', 'garbage', 'o3,c1,pen,0', 'o4,c1,pen,2'));

        $this->assertSame(['read' => 4, 'stored' => 2, 'dead' => 2], $r);
        $this->assertDatabaseCount('orders', 2);
        $this->assertDatabaseCount('import_dead_letters', 2);
    }

    public function test_transient_directory_error_is_retried(): void
    {
        $calls = new \ArrayObject(['n' => 0]);
        $this->app->bind(CustomerDirectory::class, fn () => new class($calls) implements CustomerDirectory {
            public function __construct(private \ArrayObject $calls) {}

            public function tier(string $customer): string
            {
                if (++$this->calls['n'] < 3) {
                    throw new \RuntimeException('timeout');
                }

                return 'gold';
            }
        });
        config(['orders.catalog' => ['pen' => 250]]);

        $r = $this->app->make(ImportOrders::class)->handle($this->csv('o1,c1,pen,1'));

        $this->assertSame(1, $r['stored']);
        $this->assertSame(3, $calls['n']);
    }

    public function test_replay_after_a_crash_does_not_duplicate_rows(): void
    {
        $this->app->bind(CustomerDirectory::class, fn () => new class implements CustomerDirectory {
            public function tier(string $customer): string { return 'basic'; }
        });
        $path = $this->csv('o1,c1,pen,1', 'o2,c1,pen,1');

        $import = $this->app->make(ImportOrders::class);
        $import->handle($path);
        $import->handle($path); // run the same file twice

        $this->assertSame(2, DB::table('orders')->count());
    }
}

For the asynchronous variant, SplitFile cuts the file into byte ranges and dispatches a Bus::batch of ImportRange jobs with allowFailures(), so one bad range does not cancel the others and finally reports the failed count.

Solving the classic problems ​

A slow stage caps the pipeline ​

SolutionHowAdvantageCost / limitation
Measure firstPer-stage in/out counters and queue depthYou widen the right stageNeeds taps from the start
Widen the stageMap(workers, ...), more consumersLinear gain for I/O-bound workOrder lost; downstream pressure
Batch the callschunk(500), bulk insert, bulk APIFewer round tripsHigher latency per item, partial failure
Cache the lookupIn-process LRU or Redis for the directoryRemoves the callStale data; see Caching
Move the workPre-compute upstream, join in SQLNo stage at allDifferent design

Memory grows with the input ​

SolutionHowAdvantageCost / limitation
Stream with bounded pipesGenerators, channels with capacityMemory is constantNeeds cancellation discipline
Use cursorscursor(), lazyById(), server-side cursors; see Cursors & StreamingRows arrive as neededHolds a connection or transaction
Chunkchunk(n)SimpleChunk size to tune
Spill to diskTemp files, a queueSurvives huge fan-inSlower, cleanup

One bad row blocks everything ​

SolutionHowAdvantageCost / limitation
Dead-letter stageItem with Err, write to table or topic with reasonPipeline continuesSomeone must read the dead letters
Retry classificationRetry only ErrTransientNo infinite loopsClassification must be right
Circuit breaker on a filterFail fast when the dependency is down; see Circuit BreakerProtects the dependencyItems must wait or be dead-lettered
Stop on thresholdAbort when dead letters exceed 5%Detects a wrong fileThreshold needs tuning

Retrying duplicates data ​

SolutionHowAdvantageCost / limitation
Idempotent sinkUpsert on a natural keyReplay is safeNeeds a stable key
Inbox tableRemember processed message IDs; see Idempotent ConsumersWorks for non-upsert sinksExtra table and cleanup
Transactional outboxWrite result and message in one transaction; see OutboxNo lost or duplicate publishesMore moving parts
Offset commit after writeCommit the Kafka offset only after the sink succeededAt-least-once, no lossDuplicates, so the sink must be idempotent

Order matters downstream ​

SolutionHowAdvantageCost / limitation
One workerworkers = 1Order for freeNo parallelism
ResequenceSequence number, hold early itemsParallel and orderedMemory for held items; gaps stall it
Partition by keySame key, same worker or partitionOrder per keyHot keys
Make order irrelevantCommutative updates, upserts with versionsSimplestNeeds design; see Ordering & Partitioning

Cycles deadlock ​

A pipeline with a feedback loop (stage C sends items back to stage A through bounded pipes) can fill every pipe and stop: A waits for room in A-to-B, which waits for B-to-C, which waits for C-to-A. Remedies: keep the graph acyclic, make the feedback pipe unbounded or lossy, or use a separate re-queue with a delay (a retry queue); see Retry, Backoff & Delay.

Choosing ​

SituationChooseExtra techniqueReason
File import, ETL, log processingStreaming pipeline in one processBounded pipes, dead letters, idempotent sinkConstant memory, easy to test per step
HTTP request handlingMiddleware chainOrder the filters, short-circuit earlyCross-cutting concerns without coupling
Heavy work per item with an external callPipeline with a parallel stageRetry, circuit breaker, resequence if neededHide latency with workers
Work must survive restartsQueue between stagesIdempotent jobs, Bus::chain, Bus::batchDurable pipes
Many independent readers or replayKafka topics between servicesConsumer groups, schema registryLog gives replay and fan-out
Interactive UI, many small state updatesNot pipe-and-filterEvent-driven or layeredGarlan and Shaw: poor for interactive applications
Steps need a shared transactionNot pipe-and-filter across filtersSaga (Saga Pattern) or one transaction in one filterFilters share no state, so no shared transaction
One 20-line scriptPlain functionExtract filters when a second use appearsThe style costs ceremony
text
     Question                                              Yes                      No
1    Is the data a stream of items (or can it be)?         continue                 not a pipeline
2    Are the steps independent and ordered?                continue                 consider events or layers
3    Does a bad item have to be isolated?                  add dead-letter stage    plain error return
4    Is one step much slower than the rest?               parallel stage + bound   single worker
5    Must the work survive a restart?                      durable pipes (queue)    in-process channels
6    Do many consumers need the same stream?               log (Kafka)              queue

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Example (everyday). A Laravel app's orders:import command reads a partner CSV through LazyCollection::chunk(500) and the Pipeline of five pipes, writes with upsert, and puts rejects in import_dead_letters. HTTP requests pass through the middleware pipeline. All pipes are in-process function calls, a retry is a PHP loop, and consistency is easy: the persist pipe writes in one local transaction. The risk is memory (materialising the file) and one worker that blocks the others, solved by the generator and a queue worker.

Modular monolith: boundaries and ownership ​

Each module owns its filters and exposes one entry point (for example Ordering\Import\ImportOrders), not its pipes; other modules call the entry point or consume its events. The shared things are the item types at the boundaries, which become the module's public contract. Pipes between modules should be queues or events (OrderImported), not calls into another module's filters, otherwise a refactoring of one pipe breaks a neighbour. See Modular Monolith.

Microservices: filters become services ​

Example (production). An order platform: orders.raw (Kafka) receives web and marketplace orders; the validator service reads it, writes valid orders to orders.valid and rejects to orders.dead; pricing reads orders.valid and writes orders.priced; the persister consumes it into PostgreSQL and emits OrderStored. Each service is a filter with one input topic and one output topic.

text
     Hop   From -> To                          Delivery            What must hold
1    1     orders.raw -> validator             at-least-once       validator idempotent
2    2     validator -> orders.valid           producer acks=all   key = order id (order per order)
3    3     orders.valid -> pricing             at-least-once       pricing deterministic
4    4     pricing -> orders.priced            transactional produce or outbox
5    5     orders.priced -> persister          at-least-once       upsert on order id
6    fail  poison in any hop                   -> orders.dead      reason + original offset

What survives the network and what does not: the style survives (independence, typed items, dead letters); shared state does not exist at all (good); a transaction across filters does not exist (use idempotency and sagas for multi-step business processes); backpressure becomes lag and partition counts instead of a blocked send; ordering shrinks to one partition; observability needs tracing across hops (Messaging Observability). The warning from Service Boundaries applies: do not split a three-line transformer into a service.

Distributed data: replicas, caches, multi-region ​

A pipeline's sink and enrichment sources are data stores with their own consistency. Enrichment from a read replica sees data that is a little old, so an order may be priced with yesterday's tier; accept it, or read from the primary, or put the tier in the event (event-carried state transfer). A cache in front of the directory lowers the retry rate and adds staleness. Across regions, each region runs its own pipeline over a local topic; mirrored topics (MirrorMaker, cluster linking) deliver duplicates and reorderings, so the sink needs idempotency and a version column, not order. For the database side see Replication & Failover, Eventual Consistency and Distributed SQL.

Scaling path: 1x, 10x, 100x ​

LoadShapeWhat changes
1x: thousands of lines a dayOne process, LazyCollection or one goroutine per stageNothing: a cron command
10x: millions of lines, nightlyParallel stage on the bottleneck, bounded pipes, batched insertsWorkers = measured bottleneck; add stage counters
100x: tens of millions, many partnersDurable pipes (queues), Bus::batch or Kafka topics, several worker hostsIdempotency everywhere; dead-letter dashboards; lag alerts
1000x: streaming platformKafka Streams, Flink or Beam; exactly-once semantics where supportedWindowing, state stores, schema registry; see Stream Processing and Big Data Architectures

Lab ​

Experiment 1: throughput with 1, 4 and 8 parallel transform stages (Go) ​

Run from docs/snippets/architecture/pipe-and-filter/go. The program pushes 2000 items through one Map stage with 1, 4 and 8 workers, for an I/O-bound transformer (a 2 ms sleep standing for a remote call) and a CPU-bound one (about 0.8 ms of SHA-256 hashing per item on this machine).

go
// Command bench measures pipeline throughput with 1, 4 and 8 parallel
// transform workers, for an I/O-bound and a CPU-bound transformer.
package main

import (
	"context"
	"crypto/sha256"
	"fmt"
	"runtime"
	"time"

	"academy/pipe-and-filter/stage"
)

const items = 2000

func ioBound(_ context.Context, n int) (int, error) {
	time.Sleep(2 * time.Millisecond) // stands for a 2 ms call to another service
	return n, nil
}

func cpuBound(_ context.Context, n int) (int, error) {
	h := sha256.Sum256([]byte{byte(n)})
	for range 20_000 { // about 0.8 ms of hashing on Apple silicon
		h = sha256.Sum256(h[:])
	}
	return int(h[0]), nil
}

func run(workers int, fn func(context.Context, int) (int, error)) time.Duration {
	ctx := context.Background()
	src := make([]int, items)
	start := time.Now()
	out := stage.Map(workers, workers*2, fn)(ctx, stage.FromSlice(ctx, workers*2, src))
	_ = stage.Drain(ctx, out, func(stage.Item[int]) error { return nil })
	return time.Since(start)
}

func main() {
	fmt.Printf("GOMAXPROCS=%d, %d items per run\n", runtime.GOMAXPROCS(0), items)
	fmt.Printf("%-10s %8s %12s %8s\n", "transform", "workers", "items/s", "speedup")
	for _, c := range []struct {
		name string
		fn   func(context.Context, int) (int, error)
	}{{"io-2ms", ioBound}, {"cpu-hash", cpuBound}} {
		var base float64
		for _, w := range []int{1, 4, 8} {
			d := run(w, c.fn)
			rate := float64(items) / d.Seconds()
			if w == 1 {
				base = rate
			}
			fmt.Printf("%-10s %8d %12.0f %7.1fx\n", c.name, w, rate, rate/base)
		}
	}
}
bash
cd docs/snippets/architecture/pipe-and-filter/go
go run ./bench

Measured on the machine that wrote this page (Apple silicon, GOMAXPROCS=10; your numbers will differ):

text
GOMAXPROCS=10, 2000 items per run
transform   workers      items/s  speedup
io-2ms            1          442     1.0x
io-2ms            4         1771     4.0x
io-2ms            8         3475     7.9x
cpu-hash          1         1249     1.0x
cpu-hash          4         4846     3.9x
cpu-hash          8         7746     6.2x

How to read it: the I/O-bound stage scales linearly because workers wait on sleeps, so eight workers overlap eight waits. The CPU-bound stage scales almost linearly to four workers and then bends (6.2x at eight) because the 10 logical cores are shared with the producer, the runtime and, on Apple silicon, a mix of performance and efficiency cores. Try workers = 32 for the I/O case (expect close to linear growth until another limit appears) and workers = 32 for the CPU case (expect no further gain). The single-worker rate of 1249 items/s means about 0.8 ms of hashing per item on this machine.

Experiment 2: order and the resequencer ​

Change bench to print the first ten output Seq values with 8 workers: they are out of order. Insert stage.Resequence[int](16) after Map and print again: they are 0..9. Then measure throughput again: the resequencer costs a little, and a slow item holds back at most (workers + pipe capacities) later items.

Experiment 3: a slow stage and backpressure ​

In stage_test.go the test TestBoundedPipeBlocksTheProducer asserts that a producer facing a pipe of capacity 2 and no reader gets at most four items ahead. Change the capacity to 1000 and run the test: it fails, because the producer runs far ahead. Use runtime.ReadMemStats in the demo to watch the heap with Buffer: 8 versus Buffer: 100000 on a 5-million-line input.

Experiment 4: the LazyCollection import, memory-bounded (Laravel) ​

Generate a 1 GB file and run the command (PHP and a Laravel 13 app are needed; they were not available on the machine that wrote this page, so the expected values are the design target, not measurements):

bash
# 20 million lines of about 50 bytes = roughly 1 GB
awk 'BEGIN { print "id,customer,sku,qty"; for (i = 0; i < 20000000; i++) printf "o%d,c%d,pen,%d\n", i, i % 1000, i % 5 + 1 }' > orders-big.csv
ls -lh orders-big.csv

php artisan orders:import orders-big.csv --chunk=500
# expected shape: table of read/stored/dead, then
#   "... s, ... rows/s, peak memory ~30 MB"      (flat, independent of file size)

php -d memory_limit=64M artisan orders:import orders-big.csv    # must still succeed

Then break it on purpose: replace the producer by collect(file('orders-big.csv')) and run with -d memory_limit=256M; PHP stops with Allowed memory size of 268435456 bytes exhausted. Put 1,2,3 lines (garbage) in the file and check import_dead_letters; kill the process half way and rerun: the row count in orders ends equal to the number of valid lines, with no duplicates.

Common misconceptions ​

BeliefReality
Pipe-and-filter means Unix pipesUnix is one instance; the style is independent filters plus data connectors, found in compilers, middleware, Kafka Streams
Filters run one after anotherIn a streaming pipeline they run at the same time on different items
More workers always speed up the pipelineOnly the bottleneck stage matters, and workers lose ordering
A bigger buffer fixes a slow stageIt only delays the block; it absorbs bursts, not rate differences
Retrying makes the pipeline reliableRetrying poison data stalls it; retry transient errors only, dead-letter the rest
Unbounded queues are safe because memory is cheapUnbounded means "out of memory later, at the worst time"
A failing filter should stop the pipelineItem failures should be isolated; only infrastructure failures stop the run
Pipes give you transactions across filtersFilters share no state; use idempotency and sagas
Middleware is something elseLaravel middleware is built on the same Pipeline class as the helper
Streaming means real timeStreaming means data flows incrementally; the latency can still be minutes
Typed pipelines are over-engineeringUntyped streams push parsing into every filter
Microservices connected by topics are not pipelinesIf each reads one stream and writes one stream without knowing neighbours, they are

Cheat sheet ​

TopicWhat to remember
StyleIndependent filters, data-only pipes, no shared state, no knowledge of neighbours
Filter rolesProducer, transformer, tester, consumer
ThroughputEquals the slowest stage; widen that stage only
MemorySum of pipe capacities; bound every pipe
BackpressureFull pipe blocks the writer; bursts need buffers, rate gaps need workers
CancellationContext on every send and receive; errgroup cancels on first error
OrderLost after fan-out; resequence, partition by key, or make it irrelevant
ErrorsTransient: retry with backoff and a limit. Poison: dead letter with reason. Infrastructure: stop and rerun
IdempotencyThe sink must tolerate replays: upsert or inbox
TypingParse once at the edge; type the internal pipes; version schemas across services
GoStage[In, Out], errgroup, io.Reader chains, go test -race
LaravelPipeline::send()->through()->thenReturn(), middleware, LazyCollection::make, Bus::chain, Bus::batch
Service scaleTopics are pipes, consumer groups are filters, partitions are parallelism, lag is backpressure
ObservabilityPer-stage in, out and error counters; consumer lag
Shellset -o pipefail; pipes carry bytes

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What two invariants make a set of components a pipe-and-filter system? Must-know ​

Answer

Answer: Filters are independent (they share no state) and they do not know the identity of their upstream and downstream filters. Garlan and Shaw add that the output should not depend on the order in which filters do their incremental work.

2 — Name the four filter types and say which one never changes an item. Important ​

Answer

Answer: Producer (source), transformer, tester (filter) and consumer (sink). The tester only decides whether to pass the item on.

3 — Why does a | b not run a to completion first? Important ​

Answer

Answer: Both processes run concurrently and are coupled by a bounded kernel pipe. A full pipe blocks the writer (write(2) blocks), an empty pipe blocks the reader. If the reader exits first the writer gets SIGPIPE.

4 — A producer is ten times faster than the slowest stage. What happens with an unbounded pipe, and with a pipe of capacity 100? Must-know ​

Answer

Answer: Unbounded: the pipe grows until memory is exhausted. Capacity 100: the producer blocks when the pipe is full, so it runs at the slowest stage's speed and memory stays bounded.

5 — After a four-worker Map stage the output order differs from the input order. Give two fixes. Important ​

Answer

Answer: Resequence on a dense sequence number (holding early items, bounded memory), or partition by key so all items of one key go to one worker; or make downstream processing order-independent (upserts with version).

6 — Which errors do you retry and which do you dead-letter? Must-know ​

Answer

Answer: Retry transient errors (timeouts, 503, deadlocks) a limited number of times with backoff. Dead-letter poison data (parse errors, rule violations) with the reason. Infrastructure failures of the sink stop the pipeline and are fixed by rerunning an idempotent run.

7 — Why must every channel send in a Go pipeline be a select with ctx.Done()? Must-know ​

Answer

Answer: If the consumer stops early, a plain send blocks forever and the goroutine leaks. The select lets cancellation unblock every upstream stage.

8 — Why does LazyCollection keep memory flat on a 1 GB file, and what breaks it? Important ​

Answer

Answer: It is built on a PHP generator, so items are pulled one at a time and chunk(n) keeps at most n rows. Calling all(), toArray(), collect(file(...)) or using Collection materialises the whole file.

9 — How is Laravel middleware related to the Pipeline helper? Good to know ​

Answer

Answer: The HTTP kernel builds (new Pipeline($app))->send($request)->through($middleware)->then($router). Middleware are pipes with a before and an after half around $next.

10 — What is the difference between Bus::chain and Bus::batch? Must-know ​

Answer

Answer: A chain runs jobs one after another and stops at the first failure (a sequential pipeline). A batch runs jobs in parallel (fan-out) and joins with then, catch and finally; a failure cancels the batch unless allowFailures() is set.

11 — When is pipe-and-filter a poor choice? Must-know ​

Answer

Answer: For interactive applications and anything needing shared state or a transaction across steps. Garlan and Shaw say such systems are "typically not good at handling interactive applications".

12 — What replaces the bounded channel when the pipe becomes a Kafka topic, and how do you scale a filter? Important ​

Answer

Answer: Consumer lag and retention replace the blocked send; backpressure is consumer pace. You scale a filter with consumer-group members up to the partition count, and keep order per partition by keying on the order id.

Glossary ​

TermMeaning
Pipe-and-filterStyle of independent filters connected by data-carrying pipes
FilterComponent that reads from input pipes, processes locally, writes to output pipes
PipeConnector that carries a stream of items between two filters
Producer (source)Filter with no input pipe; starts the flow
TransformerFilter that changes items
TesterFilter that decides whether an item continues
Consumer (sink)Filter with no output pipe; ends the flow
PipelinePipe-and-filter restricted to a linear sequence of filters
Batch sequentialDegenerate form where each filter finishes all input before the next starts
StreamingItems flow through the stages as they arrive
Bounded pipePipe with a fixed capacity
BackpressureSignal from a slow consumer that slows its producers
Fan-outSeveral workers read the same pipe
Fan-inSeveral pipes merge into one
ResequencerStage that restores source order using sequence numbers
Dead letterItem set aside with a reason because it cannot be processed
Poison dataItem that fails every time it is processed
Transient errorFailure that may succeed on retry (timeout, 503)
Idempotent sinkConsumer that can receive the same item twice with the same result
SIGPIPESignal sent to a writer when no reader is left on a pipe
io.ReaderGo interface for pull-based byte streams
errgroupGo package that runs goroutines, returns the first error and cancels the context
Pipeline (Laravel)Helper that passes an object through callables with $next
MiddlewareA filter on the HTTP request pipeline
LazyCollectionLaravel collection backed by a generator; processes items one at a time
Job chainQueued jobs run in sequence, stopped by the first failure
Job batchQueued jobs run in parallel with join callbacks
Kafka Streams topologyGraph of stream processors connected by streams
Apache Beam PCollectionBounded or unbounded dataset flowing between transforms
Consumer groupSet of Kafka consumers sharing the partitions of a topic
LagHow far a consumer is behind the end of a Kafka partition

References ​

Built by Morteza Negahi