---
title: "Decision with Deadline"
description: "Wait for one of several outside decisions, or a deadline, and let the first one decide what happens next (also known as Deferred Choice)."
canonical_url: "https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline/"
source: "docs/content/design-patterns/external-interaction/decision-with-deadline.mdx"
locale: "en"
language: "python"
---

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

# Decision with Deadline

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

Wait for one of several outside decisions, or a deadline, and let the first one decide what happens next (also known as Deferred Choice).

The events come from outside the Flow. The Flow cannot pick a branch in advance.

An example is an offer to a customer. The customer can accept it or reject it. If the customer does neither within 3 days, the offer expires. Whichever happens first wins. The other two no longer change the chosen branch.

**Flow graph: OfferResponseFlow**

**Steps**

1. `AwaitOfferResponse` (start Step): Waits for an acceptance, a rejection, or the 3-day deadline, closes the response window, and routes on the winner. Next: `RouteResponseBeforeExpiry`, `ExpireOffer`, `FulfillOffer`, or `CloseRejectedOffer`. Reads `offerAccepted`, `offerRejected`; locks `offerResponseWindow`; writes `offerResponseWindow`.
2. `CloseRejectedOffer`: Completes the Flow with the rejected offer. Next: the Flow completes.
3. `ExpireOffer`: Completes the Flow with the expired offer. Next: the Flow completes.
4. `FulfillOffer`: Completes the Flow with the fulfilled offer. Next: the Flow completes.
5. `RouteResponseBeforeExpiry`: Takes the response that the customer sent before the window closed and routes on it. Next: `FulfillOffer`, or `CloseRejectedOffer`. Reads `offerAccepted`.

**RPCs**

- `accept_customer_offer`: Locks `offerResponseWindow`.
- `reject_customer_offer`: Locks `offerResponseWindow`.

Example: [examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py)

## How it works

One Step waits for every event at once. Its `WaitFor` returns `AnyOf` with one Condition per event. Each customer response is a Channel Condition. The deadline is a Timer.

When the first Condition is satisfied, the Step's `Execute` runs. It checks which Condition won and moves to the matching branch.

1. The customer accepts or rejects through an RPC. The first response publishes the customer's note to its own Channel and closes the response window. Every later response gets "window closed".
2. `AwaitOfferResponse` waits for an acceptance, a rejection, or the 3-day deadline, whichever comes first.
3. Its `Execute` closes the response window, if no response closed it yet.
4. When the acceptance Channel won, it moves to `FulfillOffer`. When the rejection Channel won, it moves to `CloseRejectedOffer`.
5. When the Timer won (`HasTimerFired`), it moves to `ExpireOffer`. If a response is still queued, it moves to `RouteResponseBeforeExpiry` instead, which takes that response.

Only one Condition wins, so only one branch ever starts.

## Rules

- `AnyOf` consumes a message only from the Condition that wins. A response that lost stays pending in its Channel.
- When the wait is evaluated, Dex selects one ready Condition. A ready Timer comes first. Otherwise Dex selects the first ready Channel in declaration order. When Conditions become ready at different times, the first event to satisfy the wait triggers the Step. See the [Waits reference](https://docs.superdurable.io/reference/go/waits.md).
- Declare the Channels in business priority order. The example's window admits at most one response. Without that window, an acceptance and a rejection that are both pending would select the acceptance.
- In `Execute`, check which Condition fired: `HasTimerFired` for the Timer, and the Channel results for the responses. A Channel that lost returns no results. Do not treat a missing response as expiry.
- The Timer starts when the Step starts waiting. It survives Worker and Server restarts. While the Step waits, it holds no Worker.
- Every response gets a clear answer. The first one is recorded and decides the offer. Every later one gets "window closed". After the Flow closes, Dex rejects the RPC before its handler runs, so the HTTP route reads the closed Flow and answers "window closed" too. A Flow that never existed gets `404`.
- To test the expiry branch, skip the Timer with the Client `SkipTimer`. Do not shorten the business deadline for tests.

<a id="close-the-response-window"></a>

## Close the response window

Without a window, a customer can be told a response was accepted that never decides the offer. This happens in two ways:

- A response commits after the Timer won but before `Execute` runs. Its RPC returns success. `Execute` then expires the offer, and the response is silently ignored.
- An acceptance and a rejection both commit before the wait takes one. Both RPCs return success, but the wait consumes only one.

A Channel size read in `Execute` alone does not close these gaps, because a response can still commit after it.

The example closes the gaps with an Attribute lock:

- The `offerResponseWindow` Attribute starts open. An unset value reads as open.
- Both response RPCs lock `offerResponseWindow`. A locked RPC is transactional, so its check, its publish, and its window write commit together. The first response publishes and closes the window. When the window is closed, the RPC publishes nothing and returns "window closed".
- So at most one response is ever queued, and only its caller hears "recorded".
- `Execute` of `AwaitOfferResponse` locks the same Attribute and sets it to closed. Dex takes the lock before it hands `Execute` to a Worker, and reads the state after that.
- A response that committed before the lock is in the Channel. `Execute` sees it through the Channel size and moves to `RouteResponseBeforeExpiry`. That Step waits on both Channels, and the queued response wins at once.
- While `Execute` holds the lock, a response RPC gets a lock conflict. Dex does not queue it. The HTTP route retries a few times with a short backoff. After the window closes, the retry returns "window closed", and the route answers `409`. See [RPC lock conflicts](https://docs.superdurable.io/reference/server/runtime-data.md#rpc-lock-conflicts).

The business deadline is the moment the locked `Execute` closes the window, not the instant the Timer fires. When no response came first, the admission boundary is the moment `Execute` takes the lock. A first response that commits after the Timer fired, but before that moment, is accepted and decides the offer. A response after that moment gets a lock conflict while `Execute` runs. When `Execute` commits, the closed state persists, and every later response gets "window closed". The pattern chooses this on purpose, so every caller gets a truthful answer. It is not a hard cutoff at the Timer instant.

Keep these rules when you use the window:

- Every RPC that writes a response Channel declares the same lock. Locks are cooperative. An RPC without the lock bypasses the window.
- Lock only `Execute`, not `WaitFor`.
- The response RPCs take this lock, so the locked `Execute` makes no external call. Put side effects, such as an expiry notice, in the next Step. A failing `Execute` keeps the lock through its retries, and responses get lock conflicts meanwhile.
- Give the locked `Execute` an explicit short retry budget: a total retry duration, a maximum attempt count, and a per-attempt timeout. The default total budget is long, and waiting for the lock before the first attempt does not consume it. The example uses an initial retry interval of 1 second, at most 3 attempts, a total budget of 1 minute, and 10 seconds for each attempt. See the [StepOptions reference](https://docs.superdurable.io/reference/go/step-options.md#defaults).
- Make the response idempotent, so a retried call is safe.
- To wait again, reopen the window under the same lock, in the `Execute` that starts the next wait.

<a id="arbitrate-by-business-priority"></a>

## Arbitrate by business priority

Some processes rank events against each other. For example, a withdrawal wins over a decision, or a confirmation wins over a decline that arrives at the same moment. Keep such a rule, and state which meaning of "the same moment" the design uses. Both meanings are valid:

- **Server commit order.** A response window or lock admits responses one commit at a time. The first committed response wins, so ties never occur. This is the response window above.
- **Competing Channels ready when the wait is evaluated.** Among the Channel Conditions of one `AnyOf` that are ready together, the first declared wins, and `Execute` uses the messages it consumed. This ranks Channels only. A Timer in the same wait that is also ready is selected first, and the messages stay queued.

When a Timer wins and `Execute` then checks the Channels again, it sees the responses committed in the first state snapshot of `Execute`. Retries reuse that snapshot. That is a later moment than the wait evaluation. In the example, `Execute` takes the shared window lock before Dex builds the snapshot. The example's `RouteResponseBeforeExpiry` branch relies on this: it takes a response that committed after the Timer won.

<a id="locked-round"></a>

### Rank every event in a locked round

To rank every event admitted before the decision, use a locked round. Its closed window decides which events are eligible. A response window can be combined with ranked responses this way. The runnable examples above show only the first-committed-response window; they have no rounds, ranking, recovery route, or reply Step.

Each round has a round ID that is never reused. Two AttributeMaps are keyed by it: the round's window and the round's candidates. Every RPC and Step that reads or changes that window or those candidates locks that round's instances of both maps.

A Step opens the round under its locks, then moves to the arbitration Step for that round.

Each event's RPC names its target round. Under the round's locks, it accepts only while that round's window is open. A late RPC for a closed round gets "closed" and never reaches a newer round. The RPC appends its candidate: a key of round ID, event type, and event ID, a payload reference, the rank, and the admission order. It answers "received". The receipt confirms admission only. The arbitration Step decides the outcome. A retried RPC finds its key already in the set and adds nothing.

When the round's candidate set goes from empty to non-empty, the same RPC commit publishes one wake-up. Later admissions only append. The wake-up carries no data, and its ChannelMap key is the round ID. Never read a wake-up to decide candidates or the outcome. When the Timer wins, one wake-up may stay pending. A long-running Flow that must reclaim state deletes it with the round's other state.

The arbitration Step waits on `AnyOf` of the deadline Timer and the round's wake-up. Start only one such wait per round. Its `Execute` takes the round's locks. If the round is closed or missing, it ends the branch normally with a dead end (`DeadEnd`), with no decision and no business route. Otherwise it closes the round, reads the candidates, and picks the highest rank. Admission order breaks a tie. In the same commit it records the decision and the answer for every candidate. It then moves to a Step that holds no lock and gets those answers as its input. That Step sends them through an idempotent path keyed by the candidate key, then routes on the decision. With no candidate, the decision is the deadline branch.

The decision derives only from the round's Attribute state, so a retried `Execute` reaches the same decision. `Execute` holds the locks through its retries and backoff, so no candidate joins meanwhile. The successful locked close is the cutoff, not the Timer. A candidate admitted before it is eligible, even after the Timer fired.

When `Execute` exhausts its retries, neither the close nor the decision commits. Give `Execute` a short retry budget and a failure route. The recovery Step takes the same locks and rechecks the window. A closed or missing round ends the branch with a dead end. Otherwise, in one commit, it either arbitrates again from the stored candidates, or closes the round and records the failure, together with the answer for every candidate. It then moves to the same unlocked answering Step with those answers as input. The RPCs take the round's locks, so neither path sends an answer while it holds them. Keep the `Execute` of the arbitration Step and the recovery Step SYNC, even when the Flow defaults to ASYNC. The decision and the answers are then stored before the answering Step runs; see [Durability](https://docs.superdurable.io/reference/go/step-options.md#durability). It never relies on the wake-up. Without a failure route, the Flow fails, and senders learn the outcome from its terminal state.

Losing candidates stay in the record. Lock order is commit order, not business priority, so a locked RPC never decides between ranked events.

## Related shapes

- [Reminder](https://docs.superdurable.io/design-patterns/durable-timer/reminder.md), [Idle Timer](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer.md), and [Idle Timer with Resolution](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution.md) also wait on `AnyOf` of a Timer and a Channel. They loop back to the same Step. This pattern decides once and moves on.
- [First-Win Parallel Steps](https://docs.superdurable.io/design-patterns/parallel/first-win.md) races work that the Flow started itself. This pattern races events from outside.

## Example

`OfferResponseFlow` starts with the offer ID. `AwaitOfferResponse` waits for the `acceptCustomerOffer` RPC, the `rejectCustomerOffer` RPC, or the 3-day Timer. It closes the response window and moves to `FulfillOffer`, `CloseRejectedOffer`, `RouteResponseBeforeExpiry`, or `ExpireOffer`. Each outcome Step completes the Flow with its outcome.

The HTTP routes, with the lock conflict retry and the closed-Flow check, and the tests are in the example folders. Try the routes in the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).

**Python**

```python
# How long the customer has to respond.
OFFER_EXPIRY = timedelta(days=3)

# The first response or AwaitOfferResponse closes the response window. Unset reads as open.
RESPONSE_WINDOW_OPEN = "open"
RESPONSE_WINDOW_CLOSED = "closed"

# The outcomes of a customer response RPC.
OFFER_RESPONSE_RECORDED = "recorded"
OFFER_RESPONSE_WINDOW_CLOSED = "window closed"

OFFER_ACCEPTED = Channel("offerAccepted", str)
OFFER_REJECTED = Channel("offerRejected", str)
# Locked by both response RPCs and by AwaitOfferResponse.execute.
OFFER_RESPONSE_WINDOW = Attribute("offerResponseWindow", str)

# A short retry budget for the execute that holds the window lock.
WINDOW_CLOSE_RETRY = RetryPolicy(
    initial_interval=timedelta(seconds=1),
    maximum_attempts=3,
    total_duration=timedelta(minutes=1),
)
WINDOW_CLOSE_ATTEMPT_TIMEOUT = timedelta(seconds=10)


def read_response_window(context: Context) -> str:
    """Returns RESPONSE_WINDOW_OPEN while the window was never closed."""
    return OFFER_RESPONSE_WINDOW.get(context) or RESPONSE_WINDOW_OPEN


def publish_while_window_open(
    context: Context, response: Channel[str], note: str
) -> RPCResult[str]:
    """Publishes the first response and closes the window; later responses get window closed.

    The check, the publish, and the close commit together, because the RPC holds the window lock.
    """
    if read_response_window(context) == RESPONSE_WINDOW_CLOSED:
        return RPCResult(OFFER_RESPONSE_WINDOW_CLOSED)
    response.publish(context, note)
    # The first reply closes the window, so a second reply cannot also be recorded.
    OFFER_RESPONSE_WINDOW.set(context, RESPONSE_WINDOW_CLOSED)
    return RPCResult(OFFER_RESPONSE_RECORDED)


class AwaitOfferResponse(Step[str]):
    def get_step_options(self) -> StepOptions:
        """Locks the response window in execute, the same lock as the response RPCs."""
        return StepOptions(
            execute_lock_attributes=(OFFER_RESPONSE_WINDOW.lock(),),
            # Responses get lock conflicts while this execute retries, so keep the budget short.
            execute_retry=WINDOW_CLOSE_RETRY,
            execute_method_timeout=WINDOW_CLOSE_ATTEMPT_TIMEOUT,
        )

    def wait_for(self, context: Context, offer_id: str) -> Wait:
        return Wait.any_of(
            OFFER_ACCEPTED.for_one(),
            OFFER_REJECTED.for_one(),
            Timer.by_duration(OFFER_EXPIRY),
        )

    def execute(self, context: Context, offer_id: str) -> StepDecision:
        # Every later response RPC now returns OFFER_RESPONSE_WINDOW_CLOSED.
        OFFER_RESPONSE_WINDOW.set(context, RESPONSE_WINDOW_CLOSED)
        if context.has_timer_fired():
            # A response committed after the Timer won but before this execute took the lock.
            if OFFER_ACCEPTED.size(context) + OFFER_REJECTED.size(context) > 0:
                return go_to(RouteResponseBeforeExpiry, offer_id)
            return go_to(ExpireOffer, offer_id)
        if OFFER_ACCEPTED.results(context):
            return go_to(FulfillOffer, offer_id)
        return go_to(CloseRejectedOffer, offer_id)


class RouteResponseBeforeExpiry(Step[str]):
    def wait_for(self, context: Context, offer_id: str) -> Wait:
        return Wait.any_of(OFFER_ACCEPTED.for_one(), OFFER_REJECTED.for_one())

    def execute(self, context: Context, offer_id: str) -> StepDecision:
        if OFFER_ACCEPTED.results(context):
            return go_to(FulfillOffer, offer_id)
        return go_to(CloseRejectedOffer, offer_id)


class OfferResponseFlow(Flow[str]):
    @rpc(lock_attributes=(OFFER_RESPONSE_WINDOW.lock(),))
    def accept_customer_offer(self, context: Context, note: str) -> RPCResult[str]:
        """Records that the customer accepted the offer.

        Returns OFFER_RESPONSE_WINDOW_CLOSED once a response was recorded or the offer decided.
        """
        return publish_while_window_open(context, OFFER_ACCEPTED, note)
```

Example: [examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py)

## Next

- [Idle Timer](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer.md)
- [Timer](https://docs.superdurable.io/concepts/primitives/timer.md)
- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
- [Durable Timer](https://docs.superdurable.io/design-patterns/durable-timer.md)
- [Workflow Patterns evaluation: WCP-16 Deferred Choice](https://docs.superdurable.io/correctness-and-expressiveness/workflow-patterns.md#wcp-16)
