You have a batch job that reads thousands of CSV shards, joins them against a small dimension table, and writes partitioned output. It works fine locally. Then someone asks for the same logic on a cluster, then for a streaming version fed by Kafka, then for a version that also runs on a managed service. Reimplementing the logic three times is how teams end up with three subtly different answers to the same business question.
Apache Beam’s answer is unusual: you do not write a job, you build a deferred graph of operations, and a runner decides where and how to execute it. The Python SDK is where that abstract model becomes concrete classes you can read. It is also where most of the confusion lives, because the names look simple and the behavior is not.
This tour stays inside sdks/python/apache_beam/, the Python half of a very large polyglot monorepo. The checkout reports version 2.79.0.dev in version.py, and the tree holds 1,418 Python files, of which 889 are not tests. That is still a lot of code, but the public model rests on a small spine: values, transforms, a graph container, coders, and runners.
The Python SDK at a glance: a thin public API feeds a graph container, which a runner executes using transforms, coders, and I/O connectors.
Reading the overview from left to right:
- PCollection, L141 is the immutable handle on a possibly unbounded collection; it carries a windowing strategy and a reference to the transform that produced it, not the data itself.
- PTransform, L342 is the base of every operation; subclasses implement
expand(), and the base supplies labels, type hints, and composition through the|operator. - ParDo, L1544 is the general workhorse: it applies a
DoFnto each element and can emit to multiple tagged outputs or read side inputs. - DoFn, L598 defines the user-code lifecycle — setup, bundle start, processing, bundle finish, teardown — which is what makes bundling and retries possible.
- CombinePerKey, L3093 aggregates all values under a key; when side inputs are present it transparently falls back to a ParDo-based implementation.
- GroupByKey, L3456 is the shuffle boundary: the point where every value for a key must physically meet, and therefore where the network cost lives.
- Coder, L141 is the byte-level contract with
encode,decode, and anis_deterministic()flag that grouping correctness depends on. - TypeConstraint, L118 is the root of Beam’s own type algebra, used to infer which coder fits a user function’s input and output.
- BundleBasedDirectRunner, L546 is the local executor that makes tests fast by running bundles in process.
The detail view: how the API classes, transform library, combiner contracts, windowing, and execution backends connect.
The API Surface Is Deliberately Thin
Open apache_beam/__init__.py and you find almost no logic. It re-exports coders, io, metrics, typehints, and version, then pulls PCollection, Row, and TaggedOutput from pvalue.py and star-imports the transforms package before defining __version__ at line 106. The intent is that a first program needs one import, while the real implementation stays in modules that can be tested independently.
The value hierarchy is the clearest example of restraint. PValue at line 72 of pvalue.py is the abstract base for anything a transform can consume or produce. PCollection at line 141 extends it with a windowing strategy that is computed lazily from the producing transform, plus a DoOutputsTuple at line 234 for multi-output ParDo results. There is no row storage here, no executor, no batching — just the identity of a distributed value.
PTransform is equally small at the base. At line 342 of transforms/ptransform.py it documents the one rule that matters: subclasses define expand(), and applying a transform calls that method to record how inputs map to outputs. Composition is operator overload — PCollection.__or__ calls the graph container’s apply() — which is why Beam code reads as a chain of | steps rather than nested function calls. PTransformWithSideInputs at line 868 adds the argument scanning that rejects a raw PCollection argument and extracts explicit AsSideInput wrappers into a separate side-input list.
That thinness is a deliberate trade. It means the SDK can support several runners without forking user code, but it also means almost every convenience is a wrapper: Map at line 2104 and FlatMap at line 2067 of transforms/core.py are thin sugar that eventually constructs a ParDo around a wrapped callable. Reading those wrappers is the fastest way to understand what the framework actually executes.
From Apply to Execution: How the Graph Becomes Work
The DAG container is the piece people underestimate. Its module is 1,772 lines; the class is defined at line 116, its apply() method at line 686, and its run() method at line 562. When you call apply(), the container calls the transform’s expand(), records the resulting applied-transform objects (the class at line 1274), and returns new PCollection handles. Nothing computes yet. The graph is a data structure, and the container is its only owner.
run() is where the deferred model collapses into reality. It freezes the graph, runs a visitor over it, asks a runner to execute it, and returns a result handle. The runner interface in runners/runner.py is at line 103, and the result base is at line 268. The base runner’s job is small on purpose: take the recorded graph, hand each bundle of work to the backend, and expose state and metrics through the result object.
The local path is instructive. BundleBasedDirectRunner at line 546 of runners/direct/direct_runner.py executes bundles in process. Its _GroupByKey transform at line 343 does the shuffle by sorting keys in memory — a real shuffle algorithm, just without a network. That is why the direct runner is excellent for unit tests and a poor choice for production volume: the algorithm is honest, but every key’s values must fit on one machine.
The remote path is different in kind. PortableRunner at line 252 of runners/portability/portable_runner.py stages artifacts, submits a job description to a job service, and polls it. The same user graph can therefore target Flink or Spark through their portable runners, which is the architectural payoff of keeping the API thin. If you have read our Flink source tour or Spark internals walkthrough, the runner boundary is exactly where those engines take over.
Coders, Types, and the Determinism Contract
coders/coders.py is 1,943 lines, and it deserves that size. Coder at line 141 defines encode, decode, and is_deterministic(). That last method is not decoration: a key coder in a group-by-key must be deterministic, or two equal keys could land on different workers and produce inconsistent aggregates. The base class’s own docstring frames determinism as a correctness requirement, not an optimization.
Concrete coders specialize for speed. FastPrimitivesCoder at line 1086 handles common primitives in a compact format and falls back to PickleCoder for unknown types. TupleCoder at line 1322 composes element coders, which is how a PCollection of tuples gets an efficient representation without a user writing anything. The registry at line 78 of coders/typecoders.py maps type hints and runtime types to coder instances and caches the decision.
Type hints are Beam’s own small type system rather than Python’s typing objects alone. TypeConstraint at line 118 of typehints/typehints.py supports consistency checks, type-variable binding, and inference over composite types. A ParDo with annotated inputs and outputs can therefore get coders without an explicit with_output_types call. When annotations are inconsistent, the type-checking layer raises a TypeCheckError instead of silently guessing a coder, which is far cheaper than a serialization failure on a worker at 3 a.m.
The practical rule that falls out of this layer: if graph-adjacent code passes custom classes between stages, give them a deterministic coder or expect pickling costs and non-determinism warnings. The framework will run, but the shuffle quality depends on the coder you gave it.
Runners, Windowing, and the Long Tail
Windowing is first-class in the class hierarchy, not a bolt-on. WindowFn at line 124 of transforms/window.py maps a timestamp to one or more finite windows; FixedWindows at line 419 is the simplest bounded strategy, and Sessions at line 561 merges windows based on gaps. Triggers live separately: TriggerFn at line 190 of transforms/trigger.py, with AfterWatermark at line 547 and AfterCount at line 679 deciding when a window’s result is emitted before or after the watermark.
This separation is why the same graph can run in batch and streaming modes. In batch, every element arrives and the watermark advances to the end; in streaming, triggers decide how often partial results appear. The aggregation contract is the same CombineFn at line 1062 of transforms/core.py, whose four methods — create accumulator, add input, merge accumulators, extract output — make reduction associative and therefore splittable. The built-in MeanCombineFn at line 108 of transforms/combiners.py is the best small example: it accumulates count and sum and divides only at extraction.
The runner ecosystem follows the same pattern of interfaces plus implementations. The Python tree includes a Dask runner directory, plus portable Flink and Spark runners, and the direct runner for local iteration. Our Dask internals article is useful background here, because the Dask runner illustrates the general recipe: translate the Beam graph into the backend’s own task graph, then let that scheduler own execution.
Honest Limits
Beam’s abstraction is powerful and the Python SDK is readable, but the reading rewards patience. The star-import surface means IDE navigation often lands in core.py, a 4,370-line module where DoFn, ParDo, CombineFn, and GroupByKey all live; that is convenient for imports and annoying for discovery. The graph container is similarly central and similarly large, so expect to jump between three or four files to follow one operation.
Performance has sharp edges. The direct runner is honest but single-machine, and cross-language transforms add serialization hops. Custom coders are a common source of slow shuffles, and a non-deterministic key coder can produce wrong answers rather than slow ones. Finally, the portable runner model depends on a job service and artifact staging, so local debugging of a remote runner is a different skill from debugging the direct runner.
None of these are reasons to avoid the SDK; they are reasons to read it before you scale it. The spine is genuinely small — values, transforms, a graph container, coders, runners — and once you can trace one element from a source through a ParDo to a sink, the rest of the tree is variations on that path. Enjoyed this post? Never miss out on future posts by following us