Skip to content

Checkpointing long jobs

A long job saves its input position and state at intervals, so a crash costs the work since the last save, not the whole run. A strong design names what is saved, where, how often, and what is redone.

On this page

What it is

A checkpoint is a snapshot of a running job's state, copied to reliable storage so that after a failure the job reads the latest snapshot and continues from there instead of starting over. The simplest form pauses the job, copies what it needs from memory to durable storage, and carries on. The idea is old: batch programs that worked through hundreds of thousands of records took a checkpoint after a set number of transactions, together with the last place in the input where a transaction had finished, and a failed run was restarted with that checkpoint as its input.

For a job that works through an input, two things usually go into it. The position says how far through the input the job has come. In Kafka 3.9.2 that is the committed offset: the last offset stored securely, which the consumer uses as its position after a failure. The state is whatever has been derived from the input so far that would be expensive to rebuild. PyTorch's tutorial for a checkpoint meant for resuming training saves more than the model's weights: it stores the model's state_dict, the optimizer's state_dict (which holds the optimizer's own state and its hyperparameters), the epoch reached and the latest loss, by convention in a .tar file. A job that reads a stream and keeps running aggregates has the same two parts: Spark 3.5.9 Structured Streaming uses checkpointing and write-ahead logs to record the offset range being processed in each trigger, and assumes each source has offsets so the read position can be tracked.

Kind of jobPositionStateWhere it is kept

Kafka consumer (3.9.2)

Committed offset per partition

Whatever the application keeps; the offset can be saved in the same store as that state

Kafka, or your own store with seek on restart

Training run (PyTorch)

The epoch reached

Model and optimizer state_dict, latest loss

A checkpoint file on durable storage

Structured Streaming query (Spark 3.5.9)

Offset range of each trigger

Aggregation and window state

The checkpoint location, through a write-ahead log

Temporal workflow

Implicit: replaying the event history brings the code back to where it stopped

Rebuilt by re-running deterministic code

The event history held by the Temporal service

What gets redone. Resuming from a checkpoint repeats whatever happened between that checkpoint and the crash, so the order of "do the work" and "record the position" decides the delivery semantics. The Kafka 3.9.2 consumer documentation spells this out: automatic offset commits give at-least-once delivery, provided you process everything a poll returned before the next poll or before closing; break that rule and the committed offset can run ahead of what you processed, so records go missing. Manual commits give you direct control over the moment a record counts as consumed. Spark 3.5.9's guide draws the other half of the picture: its sinks are designed to be idempotent so that reprocessing is harmless, and it describes end-to-end exactly-once as the combination of replayable sources and idempotent sinks. In your own design that means the output is keyed so a redone write overwrites its earlier copy, or the output and the position update are committed together. See Delivery semantics and Idempotency keys.

How often. Taking a checkpoint costs time and I/O, so it was not done per record even in the batch era; the compromise then was somewhere between 25 and 200 records per checkpoint, depending on the cost of a checkpoint against the value of the computer time needed to redo a batch. Our advice is to start from the other end: decide how many minutes of rework a crash may cost, set the interval from that, and then confirm that writing one checkpoint takes a small fraction of the interval. If it doesn't, you have two levers: save less (drop state you can recompute cheaply on restart), or save less often and accept a longer recovery window.

Several workers. When a job is spread over processes that send each other messages, each one saving on its own timer is not enough for a consistent whole. A restored set of snapshots can have one process that remembers receiving a message another does not remember sending; fixing that can force the second process back to an earlier snapshot, which can push a third back further, and in the worst case the start of the run is the first consistent point (the domino effect). Coordinated checkpointing avoids this by having processes agree on their snapshots, usually with a two-phase commit style protocol. Our advice: either partition the work so that each worker's input, state and output are independent of the others', which per-partition offsets support on the input side, or let one coordinator trigger each snapshot.

A different shape: replaying a history. Durable workflow engines keep a log of what each step returned instead of a snapshot of variables. Temporal's documentation describes workflow code that must be deterministic: on replay, the commands the code emits are compared with the recorded event history, and where a matching event already exists the execution moves on without redoing that step. Calls to external systems, which are not deterministic, go into Activities that run outside the replay path and are retried for you, and worker process failures are handled by the platform rather than by your code. The price is a strict rule set: reordering, adding or removing steps that produce commands in code that a running execution depends on produces a non-deterministic error unless you use its versioning tools. This is a close cousin of Event sourcing and ledgers.

When to use it

Reach for checkpoints when the work a crash would throw away is measured in hours: a backfill across a large table, a training run that holds weights and optimizer state in memory, a stream processor keeping windows and aggregates, or a multi-step workflow that calls other services and waits on timers. The common thread is state that took real time to build and an input you can re-read from a known position.

Restarts are not all crashes. A deploy, a node drain or a preempted machine ends a job the same way, so a job that can resume is also a job you can move on purpose. When you describe the design, name the trigger that writes a checkpoint (every N records, every T seconds, or on a shutdown signal), where the checkpoint lives, and what the restarted worker reads first.

When not to

Skip the machinery when a rerun is cheap. A job that finishes in minutes and writes its output in one final step loses little by starting over, and the checkpoint code is one more thing that can be wrong. The same holds when the state is enormous relative to the work between saves: if a snapshot takes longer to write than the work it protects, you are spending more time saving than computing, and a less frequent save or a smaller state is the first fix.

Often the output can serve as the progress record. If each unit of work writes a result under its own key, a restarted job can list what exists and skip it, and no separate checkpoint is needed. Likewise, if the work already splits into small independent tasks on a queue, the queue usually tracks which tasks are done and retries and dead-letter queues handle failure; a checkpoint on top helps mainly when a single task runs long enough to be worth resuming partway. Save a snapshot when there is state the next task depends on, not just a list of tasks left to run.

Compared

ApproachWhat is savedRight whenCost

Rerun from the start

Nothing

The job is short, or a rerun is cheaper than the extra code

The full run is lost on each failure

Position only (offset, cursor)

Where you are in the input

Each record is processed on its own and the output is idempotent, as with a Kafka consumer committing offsets

Records since the commit are redone, or skipped if committed too early

Position plus state snapshot

Offset or epoch and the accumulated state

State is built from all input so far: model weights and optimizer state, windows, aggregates

Snapshot size and the pause to write it; consistency across workers

Event history replay

An event history of what the workflow scheduled and what came back

A multi-step workflow calling external services, where each step is slow or costly to repeat

Deterministic code rules; history grows with the number of steps

Output as the record

Each unit's result under its key

Work splits into units whose results are cheap to list and check

A startup scan; no help for state shared between units

In a picture

snapshotcrashrestoreresultsredoInput logWorker ACheckpoint storeWorker BKeyed sink
Worker A snapshots position and state to a store that outlives it. After the crash, Worker B restores the snapshot, re-reads the input from that position and redoes the tail; keyed writes make the redo overwrite rather than duplicate.

How to say it in an interview

The common mistake

Quiz

A consumer commits its offset as soon as a poll returns, then processes the records. It crashes halfway through the batch. What happens to the unprocessed records after the restart?
A training job saves the model weights at the end of each epoch and nothing else. It crashes and resumes from the file. What is missing?
You move a job from a checkpoint every 10,000 records to one every 100. What changes?
Three workers exchange messages and each saves a snapshot on its own timer. After a crash all three restore their latest snapshots. What is the risk?

Related

Sources

  1. Wikipedia: Application checkpointing
  2. Apache Kafka 3.9.2 API: KafkaConsumer (offsets and consumer position)
  3. Spark 3.5.9: Structured Streaming Programming Guide
  4. PyTorch Tutorials 2.15: Saving and Loading Models
  5. Temporal documentation: Workflow Definition
Sign in to report a mistake