---
title: "Control Long-Running Work"
description: "Control Long-Running Work, formerly Stop Long-Running Work and Interruptible execution, changes or stops a loop while it runs."
canonical_url: "https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work/"
source: "docs/content/design-patterns/external-interaction/control-long-running-work.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Control Long-Running Work

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work.go.md) · [Java](https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work.rust.md)

Control Long-Running Work, formerly Stop Long-Running Work and Interruptible execution, changes or stops a loop while it runs.

Use this pattern for work that loops for a long time, such as a backfill or batch processing. A caller can change how the loop works, such as how many items each iteration loads. A caller can also ask the loop to stop. To wait for an external system, use [Polling with WaitFor Timer](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.md) or [Polling with Long-Running Step Heartbeat](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md) instead.

**Flow graph: RecordBackfillFlow**

**Steps**

1. `StartRecordBackfill` (start Step): Start the backfill at the first record. Next: `ProcessRecordBatch`.
2. `ProcessRecordBatch`: Read the controls, then process one batch of records or stop. Next: the Flow completes, or `ProcessRecordBatch` again. Reads `batchSize`, `stopRequested`.

**RPCs**

- `request_stop`: Writes `stopRequested`.
- `set_batch_size`: Writes `batchSize`.

Example: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

<a id="control-a-running-loop"></a>

## Control a running loop

1. An RPC writes control Attributes, such as a batch size and a stop request.
2. The loop Step waits between iterations, for example on a Timer.
3. Each iteration reads the control Attributes at the start of `Execute`.
4. When a stop is requested, `Execute` completes. Otherwise it processes one unit with the current controls.
5. `Execute` moves back to the same Step with the next position as its input.

<a id="rules"></a>

## Rules

- Keep the loop position in the Step input. Keep the controls in Attributes.
- A new control value applies from the next iteration. The running iteration keeps the values it read.
- The RPC validates each value before it writes it. The loop then reads only valid controls.
- Apply the default when a control is unset, at read time. A default that the start Step writes could overwrite an RPC that arrives first.

<a id="attribute-or-channel"></a>

## Choose an Attribute or a Channel

| Control                                                    | Primitive | Why                                                                                                                                |
| ---------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| A parameter, such as a batch size, a rate, or a pause flag | Attribute | The latest value wins. The loop needs only the current value.                                                                      |
| A command for one item, such as skip or retry              | Channel   | Accepted commands queue in FIFO order, and one consumer takes them in that order. A later command does not replace an earlier one. |

To take commands from a Channel, the loop waits on the Timer and the Channel together with `AnyOf`. `AnyOf` consumes messages only for the Channel branch that wins. `Execute` checks which branch won: it handles the consumed commands when the Channel won, and processes the next batch when the Timer won. Commands that arrive later stay queued for a later iteration.

When every accepted command must be handled before the loop stops, drain the Channel before the Flow closes. When outside callers can publish at the same time, close with an atomic complete-if-empty decision, as in [Drain External Channels](https://docs.superdurable.io/design-patterns/draining-channel-for-external-publishing.md).

<a id="choose-how-to-stop"></a>

## Choose how to stop

Dex has three built-in ways to stop work. Choose by what must stop and what must still run.

| Way                 | What stops                                                                                      | Use it when                                                    |
| ------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| StopFlow            | The whole run, at once                                                                          | The run must end now, and no Step needs to report or clean up. |
| Graceful completion | Steps that wait on the graceful completion Condition; the Flow completes once no Step is active | The Flow should finish its current work and then complete.     |
| Step cancellation   | Chosen running Steps                                                                            | One branch must stop while the rest of the Flow keeps running. |

<a id="finish-the-current-unit-then-stop"></a>

The example below keeps its stop request in a control Attribute, next to its other controls. The loop reads it and stops before its next unit. Graceful completion also stops such a loop when its wait includes the graceful completion Condition, and then no stop Attribute is needed.

<a id="stopflow"></a>

### Stop the whole run with StopFlow

A client calls `StopFlow` to cancel, fail, or terminate the run. Each type records a different terminal status. The run closes as soon as the stop commits.

After the stop commits, only handlers that were already running can still run. No later Step decision, failure route, or cleanup runs. Running Steps get a cancellation signal. A handler that ignores it keeps running, and its calls to external systems still take effect. Dex discards its uncommitted result. Whoever waits for the stopped Flow reads its terminal state instead of waiting for a report.

Use StopFlow when nothing in the Flow needs to finish its work or run cleanup. See [Stop a Flow](https://docs.superdurable.io/reference/server/runtime-client.md#stop-a-flow) for every stop type.

<a id="graceful-completion"></a>

### Ask the Flow to complete gracefully

The Flow is asked to complete gracefully: a client calls `StopFlow` with graceful complete, or a Step returns `GracefulComplete`. Active Steps keep running, and their decisions still apply. The Flow completes once no Step is active.

A waiting Step that includes the graceful completion Condition stops waiting when the request arrives. Its `Execute` handles any message it consumed first. Otherwise it ends its branch. Steps whose wait lacks the Condition keep running and keep the Flow open. A loop that moves to its next unit through a Timer and `GoTo` keeps looping until it checks for the request itself.

Use graceful completion when each branch should finish its current unit and then stop. Add the Condition to every wait that would otherwise keep a branch alive. Every SDK has the graceful completion Condition: Go, Python, Java, TypeScript, and Rust. See [Wait for a completion request](https://docs.superdurable.io/reference/server/step-and-flow-close.md#graceful-completion-condition).

<a id="cancel-running-steps"></a>

### Cancel running Steps

A Step decision or an RPC cancels chosen active Steps, for example by Step type. The rest of the Flow keeps running. The SDK passes a cancellation signal to each canceled handler. The handler checks the signal and returns. Dex discards the canceled Step's later result.

Use Step cancellation to stop one branch, such as one job that the user no longer needs. Keep each handler idempotent, because a canceled Step's consumed messages normally return to their Channels. See [Step cancellation](https://docs.superdurable.io/reference/server/step-and-flow-close.md#step-cancellation).

<a id="example"></a>

## Example

<a id="core-implementation"></a>

`RecordBackfillFlow` processes 1000 records in batches. `StartRecordBackfill` moves to `ProcessRecordBatch` at the first record. `ProcessRecordBatch` waits one second between batches. Each `Execute` reads the `stopRequested` and `batchSize` Attributes first. The batch size is 10 until the batch size RPC sets it.

The example prints each batch to simulate processing. Each committed `GoTo` moves the position past the processed range, so a new batch size never skips or repeats a range. A retried `Execute` can process the same range again. Real processing must therefore be idempotent by each record's business ID.

The batch size RPC rejects a size below 1 or above 1000. The stop RPC sets `stopRequested`. The loop then completes gracefully before its next batch. The Flow completes once the loop has stopped.

The RPCs write the controls:

**Python**

```python
@rpc
def set_batch_size(self, context: Context, size: int) -> None:
    """Changes how many records each later batch processes."""
    if size < 1 or size > MAX_BATCH_SIZE:
        raise ValueError(f"batch size must be between 1 and {MAX_BATCH_SIZE}")
    BATCH_SIZE.set(context, size)

@rpc
def request_stop(self, context: Context) -> None:
    """Asks the loop to stop before its next batch."""
    STOP_REQUESTED.set(context, True)
```

Example: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

The loop Step reads the controls at the start of each `Execute`:

**Python**

```python
class ProcessRecordBatch(Step[BackfillProgress]):
    def wait_for(self, context: Context, progress: BackfillProgress) -> Wait:
        return Wait.until(Timer.by_duration(BATCH_INTERVAL))

    def execute(self, context: Context, progress: BackfillProgress) -> StepDecision:
        if STOP_REQUESTED.get(context):
            return graceful_complete(f"stopped before record {progress.next_record}")
        # An unset int Attribute reads as 0, and a set batch size is at least 1.
        size = BATCH_SIZE.get(context) or DEFAULT_BATCH_SIZE
        last = min(progress.next_record + size - 1, progress.last_record)
        print(f"processing records {progress.next_record} to {last}")
        if last == progress.last_record:
            return graceful_complete(f"processed {last} records")
        return go_to(ProcessRecordBatch, BackfillProgress(last + 1, progress.last_record))
```

Example: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

The start Step, the HTTP controller, and the tests are in the example folders. Run the HTTP sample from the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).

## Next

- [Responsive Update](https://docs.superdurable.io/design-patterns/responsive-update.md)
- [Durable Timer](https://docs.superdurable.io/design-patterns/durable-timer.md)
