---
title: "Critical Section"
description: "Use a Critical Section when parallel branches of one Flow must take turns on a sequence of Steps. Only one branch may be inside the sequence at a time."
canonical_url: "https://docs.superdurable.io/design-patterns/parallel/critical-section/"
source: "docs/content/design-patterns/parallel/critical-section.mdx"
locale: "en"
language: "python"
---

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

# Critical Section

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/parallel/critical-section.go.md) · [Java](https://docs.superdurable.io/design-patterns/parallel/critical-section.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/parallel/critical-section.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/parallel/critical-section.rust.md)

Use a Critical Section when parallel branches of one Flow must take turns on a sequence of Steps. Only one branch may be inside the sequence at a time.

An example is several reviewers who edit the same contract. Each edit takes three Steps. The first takes the turn. The second makes the change. The third saves it and hands the turn on. Two edits must never interleave.

**Flow graph: ContractEditFlow**

**Steps**

1. `StartContractEdits` (start Step): Start one edit path per contract edit and the Step that awaits them. Next: `EnterContractEdit`, or `FinishContractEdits`. Publishes to `contractEditToken`.
2. `EditContract`: Apply the edit while holding the token. Next: this branch ends, `SaveContractEdit`, or `ReleaseContractEditToken` if it keeps failing. Publishes to `contractEditFinished`, `contractEditToken`.
3. `EnterContractEdit`: Wait for the contract edit token to enter the section. Next: `EditContract`, or `ReleaseContractEditToken` if it keeps failing.
4. `FinishContractEdits`: Wait for every edit to report, then complete with the results. Next: the Flow completes. Reads `contractEditFinished`.
5. `ReleaseContractEditToken`: Report the failed edit and release the token. Next: this branch ends. Publishes to `contractEditFinished`, `contractEditToken`.
6. `SaveContractEdit`: Save the edit, report it, and release the token. Next: this branch ends, or `ReleaseContractEditToken` if it keeps failing. Publishes to `contractEditFinished`, `contractEditToken`.

Example: [examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py)

## How it works

A dedicated Channel holds exactly one message. That message is the token.

- One Step publishes the token once, before any branch enters.
- A handoff Step waits for the token with `ForOne`. One message satisfies one wait, so only one branch gets it. The other branches keep waiting.
- The handoff Step does no protected work. Its `Execute` only moves to the first Step that does.
- The last Step of the section publishes the token back. One waiting branch consumes it and enters.

In the example:

1. `StartContractEdits` puts the token in the Channel. Then it starts one branch for each edit, plus `FinishContractEdits`, which waits for every edit to finish.
2. Each branch waits in `EnterContractEdit` for the token. It enters only once it holds the token.
3. `EditContract` changes the contract and moves to `SaveContractEdit`, which records the saved edit and puts the token back. When the reviewer withdraws, `EditContract` records the withdrawal and puts the token back instead.
4. When the `Execute` of `EnterContractEdit`, `EditContract`, or `SaveContractEdit` runs out of retries, `ExecuteFailure` routes it to `ReleaseContractEditToken`. That Step records the failed edit and puts the token back.

Any waiting branch can get the token next, in no fixed order.

<a id="why-not-an-attribute-lock"></a>

## Token or Attribute lock

An Attribute lock, such as `ExecuteLockAttributes`, covers one Step method. It does not cover a `WaitFor`, and it does not span several Steps. Use a lock when the protected work fits in one `Execute`. Use a token when the section spans Steps.

## Every exit returns the token

The token is an ordinary message. A branch that leaves the section without publishing it back blocks every other branch forever. List each way out of the section, and publish the token on each one.

- **Normal exit.** The last Step of the section publishes the token.
- **Execute failure.** Route it with `ExecuteFailure` to a Step that publishes the token. Configure that route on every Step of the section. In the example, `EnterContractEdit`, `EditContract`, and `SaveContractEdit` all move to `ReleaseContractEditToken`.
- **WaitFor failure.** When a later Step of the section has its own `WaitFor`, set its `WaitForFailure` policy to proceed to its `Execute`. That `Execute` sees the failure and publishes the token.
- **Early exit.** An `Execute` that leaves the section with a business decision publishes the token in the same `Execute`.
- **Cancellation of the handoff.** Canceling the handoff Step is safe, because it does no protected work. If Dex cancels it after its wait consumed the token but before Dex saved its `Execute` result, Dex returns the token to the front of the Channel. Another branch enters.
- **Cancellation inside the section.** Never cancel a Step that does protected
  work. A canceled Step does not publish the token; see
  [Canceling a Step that publishes](https://docs.superdurable.io/correctness-and-expressiveness/step-guarantees.md#cancellation-completion-order).
  To stop a branch early, send it a stop request that its Steps check, such as
  an Attribute that an RPC sets. The Step that sees the request leaves through
  an early exit that publishes the token.
- **Closing the Flow.** `ForceComplete`, `ForceFail`, a Flow timeout, and a Client `StopFlow` end every branch. No branch waits for the token any more.

Dex saves a method's Channel publications together with its result, or not at all. A failed attempt publishes nothing, so a retry cannot create a second token.

A canceled `Execute` can keep running and writing to external systems after Dex has returned its token. This is another reason never to cancel a Step that does protected work.

## Rules

- Publish exactly one token, in the Step that starts the branches or before. A second token lets two branches into the section at once.
- Use the token Channel for the token only.
- Keep the section short. Every other branch waits while one branch is inside.
- Keep the protected state in Attributes; the token's value carries no meaning.

## Example

`ContractEditFlow` starts with a list of edits, one per reviewer. `StartContractEdits` publishes the token and starts one `EnterContractEdit` per edit, plus the join `FinishContractEdits`. `EnterContractEdit` hands off to `EditContract`, which records when the edit started. The join completes the Flow with every edit's record. The edit intervals never overlap.

Flags on an edit simulate the other exits. A failed handoff and an edit whose `SaveContractEdit` fails twice both go to `ReleaseContractEditToken`. A withdrawn edit leaves early from `EditContract`. Each of these returns the token, and the other reviewers still get their turn.

**Python**

```python
CONTRACT_EDIT_TOKEN = Channel("contractEditToken", str)
CONTRACT_EDIT_FINISHED = Channel("contractEditFinished", ContractEditRecord)
CONTRACT_EDIT_RETRY = RetryPolicy(
    initial_interval=timedelta(seconds=1), maximum_attempts=2
)


class EnterContractEdit(Step[ContractEdit]):
    """Takes the token and hands off; it does no protected work, so canceling it is safe."""

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
            ReleaseContractEditToken
        )

    def wait_for(self, context: Context, edit: ContractEdit) -> Wait:
        return Wait.until(CONTRACT_EDIT_TOKEN.for_one())

    def execute(self, context: Context, edit: ContractEdit) -> StepDecision:
        if edit.should_fail_handoff:
            raise ContractEditError("contract handoff failed")
        return go_to(EditContract, edit)


class EditContract(Step[ContractEdit]):
    """The first Step that works on the contract. Never cancel it."""

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
            ReleaseContractEditToken
        )

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, edit: ContractEdit
    ) -> StepDecision:
        started_edit = replace(edit, started_at_millis=current_time_millis())
        if started_edit.should_withdraw:
            CONTRACT_EDIT_FINISHED.publish(
                context, finish_contract_edit(started_edit, "withdrawn")
            )
            CONTRACT_EDIT_TOKEN.publish(context, "contract")
            return dead_end()
        await asyncio.sleep(CONTRACT_EDIT_SECONDS)
        return go_to(SaveContractEdit, started_edit)


class SaveContractEdit(Step[ContractEdit]):
    """The last Step of the section; it records the edit and publishes the token back."""

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
            ReleaseContractEditToken
        )

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, edit: ContractEdit
    ) -> StepDecision:
        await asyncio.sleep(CONTRACT_EDIT_SECONDS)
        if edit.should_fail_edit:
            raise ContractEditError("contract edit failed")
        CONTRACT_EDIT_FINISHED.publish(context, finish_contract_edit(edit, "saved"))
        CONTRACT_EDIT_TOKEN.publish(context, "contract")
        return dead_end()


class ReleaseContractEditToken(Step[ContractEdit]):
    """The failure exit of the section."""

    def execute(self, context: Context, edit: ContractEdit) -> StepDecision:
        CONTRACT_EDIT_FINISHED.publish(context, finish_contract_edit(edit, "failed"))
        CONTRACT_EDIT_TOKEN.publish(context, "contract")
        return dead_end()
```

Example: [examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py)

## Next

- [SubFlows](https://docs.superdurable.io/design-patterns/subflows.md)
- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
- [Step](https://docs.superdurable.io/concepts/step.md)
- [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md)
- [Workflow Patterns evaluation: WCP-39 Critical Section](https://docs.superdurable.io/correctness-and-expressiveness/workflow-patterns.md#wcp-39)
