---
title: "Response Window"
description: "A response window tells each caller that gets a business result whether its response decides. Add it to Decision with Deadline when a caller must learn whether its response made the deadline, such as a customer who accepts an offer just as it expires."
canonical_url: "https://docs.superdurable.io/design-patterns/external-interaction/response-window/"
source: "docs/content/design-patterns/external-interaction/response-window.mdx"
locale: "en"
language: "python"
---

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

# Response Window

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

A response window tells each caller that gets a business result whether its response decides. Add it to [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md) when a caller must learn whether its response made the deadline, such as a customer who accepts an offer just as it expires.

**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)

<a id="how-it-works"></a>

## How it works

When the business accepts that a response arriving just after the deadline is ignored, skip the window: the response RPC only publishes and takes no lock. Otherwise a caller can be told a response was recorded that never decides. This happens in two ways:

- A response commits after the Timer won but before `Execute` runs. Its RPC returns success, then `Execute` expires the offer and ignores the response.
- 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 leaves these gaps open, because a response can still commit after it. `ForceCompleteIfChannelsEmpty` can route a queued response before closing the Flow. Use a response window when only one response may be admitted.

The example closes the gaps with an Attribute lock:

1. The `offerResponseWindow` Attribute starts open: an unset value reads as open.
2. 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, closes the window, and returns "recorded". While the Flow is active, a later response publishes nothing and returns "window closed". At most one response is ever queued.
3. The `Execute` of `AwaitOfferResponse` locks the same Attribute and closes the window on every branch. Dex takes the lock before it hands `Execute` to a Worker, and reads the state after that.
4. When the Timer won, a response that committed before the lock is already in its Channel. `Execute` sees it through the Channel size and moves to `RouteResponseBeforeExpiry`, whose wait takes that response at once.

This is a soft cutoff. The deadline is the moment the locked `Execute` takes the lock, not the instant the Timer fires. A first response that commits in between is accepted and decides the offer. Once that `Execute` commits, the window stays closed. A later response waits for the lock, then finds the window closed. Every business result from a returned handler is truthful.

<a id="hard-cutoff"></a>

### Hard cutoff

For a hard business cutoff, store the deadline in the Flow before the wait starts. Under the window lock, the response RPC answers "window closed" when the [trusted receive time](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#decision-windows-and-rounds) is at or past it. If the Timer wins, the size check still picks up the single response already admitted to the Channel.

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

## Rules

- Every RPC that writes a response Channel declares the same lock. Prefer one entry RPC per response Channel.
- Every RPC that can decide checks and closes the same window.
- Lock `Execute` only. `WaitFor` stays unlocked.
- The locked `Execute` sets the window, checks the winner and the size, and routes. External calls go in the next Step, because the response RPCs wait for this lock.
- Give the locked `Execute` a short retry budget. A failing `Execute` keeps the lock through its retries, so waiting responses can reach their lock wait limit. See [Lock holding](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#lock-holding).
- Callers retry a lock conflict with a bounded backoff, and get an error when it runs out. Make each response idempotent, such as with a business reply ID. See [Decision windows and rounds](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#decision-windows-and-rounds).
- The response RPC may also record the admitted response as the outcome under the lock. `Execute` still checks which Condition fired, and learns about the Timer only from the Timer result.
- A business result comes only from a call whose handler returned. After the Flow closes, Dex rejects the RPC before its handler runs. The example's HTTP route maps a retained closed Flow to `409` and a Flow not found to `404`.
- To wait again, reopen the window under the same lock, in the `Execute` that starts the next wait.
- A response left pending after the window closed stays in its Channel, and the next wait on that Channel consumes it. Delete it, or key responses by round, before you wait again.

<a id="test"></a>

## Test it

Cover these scenarios:

- A response before the deadline decides.
- Two responses sent back to back get one "recorded" and one "window closed".
- A response to an active Flow after the window closed gets "window closed".
- A response that commits after the Timer won, but before the locked `Execute` runs, is taken through the size check.
- With a hard cutoff, a response at or past the stored deadline gets "window closed".

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

## Core implementation

The example is the [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md) sample. This excerpt shows the window: the response RPC, the window check, and the lock of the deciding `Execute`. The HTTP routes, with the lock conflict retry and the closed-Flow check, are in the example folders. Try them in the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).

**Python**

```python
# 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"

# 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,
        )


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)

<a id="next"></a>

## Next

- [Locked Decision Rounds](https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds.md)
- [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md)
- [Attribute locks](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#attribute-locks)
