Every data team eventually writes the same script twice: once to compute something, and once to figure out whether it already ran. Nightly jobs spawn dependencies, a retry silently recomputes a week of output, and the only source of truth is a folder of timestamps. Luigi was built at Spotify to make that reasoning explicit, and years later its model — a Task that declares its requirements and its outputs — still reads cleanly in source.

You do not have to adopt a heavyweight platform to learn from it. The library is small enough to read end to end: the Task contract lives in one module, typed parameters in another, and a central scheduler coordinates workers through a compact RPC surface. That makes Luigi an unusually good object of study if you want to understand how task orchestration actually works beneath the API.

This tour walks the real master branch — version 3.8.1 at the time of writing — and follows one task from the command line to completion. We will look at how a Task declares dependencies and outputs, how parameters round-trip through strings, how the scheduler keeps a mutable status graph, and how a worker pulls work back out of it. Each claim is tied to a file and line in the current tree.

Luigi overview architecture: entry points, Task model, parameters, scheduler, worker and targets

Luigi's main components: the entry points, the Task model, typed parameters, the central scheduler, the worker loop and the Target layer.

Reading the overview from left to right:

  • Task, L158 — the metaclass-registered base class every unit of work subclasses.
  • requires(), L690 — declares upstream tasks, and defaults to an empty list.
  • output(), L672 — returns the Target or Targets that define completion.
  • complete(), L648 — returns true only when every output already exists.
  • Parameter.parse, L340 — the identity default that typed parameters override.
  • add_task, L807 — the scheduler entry point for registering tasks, dependencies and status.
  • run, L1293 — the worker pull loop that drives execution to completion.
  • Event, L21 — the string constants used for lifecycle callbacks.
Luigi detail architecture: Task lifecycle, parameter subclasses, target hierarchy, scheduler internals, worker and RPC

The detail view: Task lifecycle methods, parameter subclasses, the Target hierarchy, scheduler internals and the worker/RPC boundary.

The Task Contract: requires, output, complete, run

The heart of Luigi is a four-method contract, and Task ships deliberately empty defaults for each. run() is a pass at line 744, so a subclass that forgets to implement work simply does nothing. output() returns [] at line 688, which means the base class has no notion of where results live. requires() also returns [] at line 702, so a leaf task needs no dependency declaration at all. Only complete() carries logic out of the box: it flattens the outputs, warns when there are none, and returns all(output.exists()) at line 660. Completion is therefore a property of the filesystem or store, not of a bookkeeping table.

That inversion is the design insight worth copying. A task is considered done when its declared outputs exist, not when a runner recorded that it finished. The scheduler can crash, the worker can be replaced, and the next run still knows the truth by asking the targets. input() follows the same philosophy: rather than caching upstream results, it calls getpaths(self.requires()) at line 733 and derives its inputs from the requirements graph.

Identity is equally deliberate. task_id_str() at line 127 serializes parameters to canonical JSON, hashes it with MD5, and builds an id from the family name, a truncated parameter summary and a hash prefix at line 143. Two Task instances with equal class and task id compare equal at line 646, which lets the scheduler deduplicate work submitted by many workers. A Register metaclass in task_register.py records families by name so a worker can reload a task it never imported by class reference. DynamicRequirements at line 836 and the WrapperTask/ExternalTask subclasses extend the same contract without breaking it.

Parameters That Survive a Round Trip

Luigi passes task identity across process and network boundaries as strings. That only works because parameters implement a small, strict protocol. The base Parameter.parse() is the identity function at line 340, serialize() calls str(x) at line 377, and normalize() clamps or validates the parsed value at line 397. Every concrete parameter changes one or more of those, which is why IntParameter can turn a CLI token into an integer while DateParameter can reconstruct a calendar date.

Dates show the pattern clearly. _DateParameterBase.parse() at line 538 calls strptime with a per-subclass date_format and returns a date, while serialize() at line 544 formats it back. DateParameter at line 553 fixes the format to YYYY-MM-DD, and MonthParameter and YearParameter narrow it further. DictParameter at line 1188 takes the JSON route, using a custom JSONEncoder so nested values survive serialization. ListParameter, TupleParameter and EnumParameter round out a family that now spans dozens of classes in a 1,391-line module.

The reason this matters is command-line ergonomics. Because each parameter knows both directions of the conversion, the same declaration powers argparse, config-file loading, task-id hashing and RPC payloads. You write year = luigi.IntParameter() once and the framework derives validation, help text and wire format. It is a quiet piece of metaprogramming that saves an enormous amount of boilerplate in real job code.

Inside the Scheduler: add_task and the Status Machine

The Scheduler class at line 677 is an asynchronous coordinator that maintains the authoritative graph. Its add_task() method at line 807 is the busiest door in the system: it accepts a task_id, a status defaulting to PENDING, an optional dependency list, resources, priority, family, module, serialized params and a retry policy. If the task is new, it is inserted through SimpleTaskState; if it exists, the call merges the new facts — dependencies, running worker, tracking URL, explanation — without losing previous ones.

Status is a small, fixed vocabulary defined in task_status.py: PENDING, FAILED, DONE, RUNNING, BATCH_RUNNING, SUSPENDED, UNKNOWN and DISABLED. The scheduler maps each of those to an upstream-facing reason through STATUS_TO_UPSTREAM_MAP at line 61, so a dependent task can distinguish “waiting for input” from “upstream failed” before it ever runs. The severity ordering of those upstream states at line 53 gives the front end a deterministic way to summarise a whole subtree.

Persistence and transport are both pragmatic. SimpleTaskState at line 431 holds tasks and workers in memory and can pickle them to a configured state_path, which defaults to /var/lib/luigi-server/state.pickle at line 119. The rpc_method decorator at line 88 is the RPC boundary: it inspects a method signature, registers it in RPC_METHODS, and turns the call into an HTTP request against /api/<method_name> at line 107. That one decorator is why prune, add_task, mark_as_done and forgive_failures are all reachable from remote workers without hand-written routes.

The Worker Pull Loop and Remote RPC

Workers are pull-based. Worker.run() at line 1293 enters an outer loop that waits for free process slots, calls _get_work() at line 1063, and either executes a task or backs off when nothing is ready. _get_work() asks the scheduler for the next runnable task, or calls count_pending() when the worker has no process pool. The response carries a task id, the list of tasks currently running elsewhere, pending counts and the worker state.

Execution is isolated. _run_task() at line 1115 loads the task class, checks completion, and hands the work to TaskProcess, a multiprocessing.Process subclass at line 104 that runs the user code and reports success or failure through a queue. This is what prevents a segfault or a runaway loop in one job from taking down the whole worker. On completion, the worker reports status back to the scheduler, which updates the graph and wakes up anything that was waiting on it.

For multi-machine deployments the worker talks to RemoteScheduler in rpc.py at line 138, a thin HTTP client that mirrors the scheduler API. The same rpc_method-decorated functions serve both the in-process and remote cases, so local development and production share one code path. RemoteScheduler uses tenacity retries around its requests, which is a small detail with large operational consequences: transient restarts of the central process do not immediately fail every worker.

From a Class Definition to a Finished Task

The engineering story is easiest to see in numbers from the tree itself. scheduler.py is 1,410 lines, parameter.py is 1,391, worker.py is 1,151 and task.py is 849. The package keeps that logic apart on purpose: the Task module never imports the scheduler, the scheduler never imports user code, and the worker is the only component that does both. The split is what allows luigi.build() to run everything in a single process while the same code runs across a cluster.

Targets complete the picture. The abstract Target at line 36 only requires exists(), and FileSystemTarget at line 195 layers path handling on top. AtomicLocalFile at line 316 writes to a temporary path from generate_tmp_path() and moves it into place on close, so a crashed write cannot leave a half-finished file that later looks complete. LocalTarget at line 131 and the many contrib targets — S3, GCS, BigQuery, Postgres and more — all inherit that contract. Compression lives beside it: format.py defines a Format class at line 328 with GzipFormat and Bzip2Format wrappers.

execution_summary.py closes the loop. LuigiStatusCode at line 37 enumerates seven outcomes from SUCCESS to MISSING_EXT, and summary() at line 498 walks the worker’s task map to group results by status. The Event constants let user code hook into dependency discovery, success, failure and progress without modifying the core. The result is a system where the interesting decisions — what depends on what, and what counts as done — are visible in user code, while the coordination machinery stays in a handful of readable modules.

Honest Limits

Luigi is a classic, not a current default, and its limits show. The scheduler holds the graph in memory and is essentially a single coordinating service; very large deployments need care around state size and restart behaviour. There is no built-in notion of data versioning or lineage beyond task ids and optional task history, so reproducibility depends on how disciplined your targets are. Retries and timeouts exist, but sophisticated scheduling policies, dynamic backfills and rich observability are left to operators and add-ons.

The parameter system is powerful but string-centric, and complex values can become awkward in task ids. The visualiser is convenient for debugging but not a production dashboard. And because completion is defined by outputs, correctness hinges entirely on writing complete() and the targets consistently; a sloppy output() can make tasks rerun forever or never run at all.

None of that erases the value of the design. If you are building a workflow engine, reading Luigi’s Task contract, its two-way parameter protocol and its pull-based worker is still one of the fastest ways to learn why the hard parts are hard. For related reading, see the source tours of Celery for distributed task queues, Dask for parallel task graphs, and APScheduler for in-process scheduling.

Watch PyShine on YouTube

Contents