Decision with Deadline
View as MarkdownWait 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.
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.
- 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".
AwaitOfferResponsewaits for an acceptance, a rejection, or the 3-day deadline, whichever comes first.- Its
Executecloses the response window, if no response closed it yet. - When the acceptance Channel won, it moves to
FulfillOffer. When the rejection Channel won, it moves toCloseRejectedOffer. - When the Timer won (
HasTimerFired), it moves toExpireOffer. If a response is still queued, it moves toRouteResponseBeforeExpiryinstead, which takes that response.
Only one Condition wins, so only one branch ever starts.
Rules
AnyOfconsumes 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.
- 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:HasTimerFiredfor 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.
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
Executeruns. Its RPC returns success.Executethen 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
offerResponseWindowAttribute 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".
ExecuteofAwaitOfferResponselocks the same Attribute and sets it to closed. Dex takes the lock before it handsExecuteto a Worker, and reads the state after that.- A response that committed before the lock is in the Channel.
Executesees it through the Channel size and moves toRouteResponseBeforeExpiry. That Step waits on both Channels, and the queued response wins at once. - While
Executeholds 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 answers409. See 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, notWaitFor. - The response RPCs take this lock, so the locked
Executemakes no external call. Put side effects, such as an expiry notice, in the next Step. A failingExecutekeeps the lock through its retries, and responses get lock conflicts meanwhile. - Give the locked
Executean 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. - Make the response idempotent, so a retried call is safe.
- To wait again, reopen the window under the same lock, in the
Executethat starts the next wait.
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
AnyOfthat are ready together, the first declared wins, andExecuteuses 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.
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. 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, Idle Timer, and Idle Timer with Resolution also wait on
AnyOfof a Timer and a Channel. They loop back to the same Step. This pattern decides once and moves on. - First-Win Parallel Steps 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.
# 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
Example: examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py
// OfferExpiry is how long the customer has to respond.
const OfferExpiry = 3 * 24 * time.Hour
// The response window is open until the first reply or AwaitOfferResponse closes it. Unset reads as open.
const (
ResponseWindowOpen = "open"
ResponseWindowClosed = "closed"
)
// The outcomes of a customer response RPC.
const (
OfferResponseRecorded = "recorded"
OfferResponseWindowClosed = "window closed"
)
var (
OfferAccepted = dex.DefineChannel[string]("offerAccepted")
OfferRejected = dex.DefineChannel[string]("offerRejected")
// OfferResponseWindow is locked by both response RPCs and by AwaitOfferResponse.Execute.
OfferResponseWindow = dex.DefineAttribute[string]("offerResponseWindow")
)
var responseWindowLock = []dex.AttributeLock{dex.LockAttribute(OfferResponseWindow)}
// A failing locked Execute holds the window lock through its retries, so keep the budget short.
const (
awaitOfferResponseRetryInterval = time.Second
awaitOfferResponseMaxAttempts = 3
awaitOfferResponseRetryBudget = time.Minute
awaitOfferResponseMethodTimeout = 10 * time.Second
/** How long the customer has to respond. */
public static final Duration OFFER_EXPIRY = Duration.ofDays(3);
// The locked execute holds the window lock through its retries, so keep the budget short.
private static final RetryPolicy WINDOW_EXECUTE_RETRY = RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.maximumAttempts(3)
.totalDuration(Duration.ofMinutes(1))
.build();
private static final Duration WINDOW_EXECUTE_TIMEOUT = Duration.ofSeconds(10);
/** The first response or AwaitOfferResponse closes the window. Unset reads as open. */
public static final String RESPONSE_WINDOW_OPEN = "open";
public static final String RESPONSE_WINDOW_CLOSED = "closed";
/** The outcomes of a customer response RPC. */
public static final String OFFER_RESPONSE_RECORDED = "recorded";
public static final String OFFER_RESPONSE_WINDOW_CLOSED = "window closed";
public static final Channel<String> offerAccepted =
Channel.define("offerAccepted", String.class);
public static final Channel<String> offerRejected =
Channel.define("offerRejected", String.class);
/** Locked by both response RPCs and by AwaitOfferResponse's execute. */
public static final Attribute<String> offerResponseWindow =
Attribute.define("offerResponseWindow", String.class);
/**
* Records that the customer accepted the offer.
*
Example: examples/java/src/main/java/io/superdurable/dex/patterns/deferredchoice/OfferResponseFlow.java
/** How long the customer has to respond. */
export const OFFER_EXPIRY_MS = 3 * 24 * 60 * 60 * 1000;
/** The first reply or AwaitOfferResponse closes the response window. Unset reads as open. */
export const RESPONSE_WINDOW_OPEN = "open";
export const RESPONSE_WINDOW_CLOSED = "closed";
/** The outcomes of a customer response RPC. */
export const OFFER_RESPONSE_RECORDED = "recorded";
export const OFFER_RESPONSE_WINDOW_CLOSED = "window closed";
export const offerAccepted = new Channel("offerAccepted", stringCodec);
export const offerRejected = new Channel("offerRejected", stringCodec);
/** Locked by both response RPCs and by AwaitOfferResponse.execute. */
export const offerResponseWindow = new Attribute(
"offerResponseWindow",
stringCodec,
);
/** Responses get lock conflicts while the locked execute retries, so its retry budget stays short. */
export const AWAIT_OFFER_RESPONSE_EXECUTE_RETRY: RetryPolicy = {
initialIntervalMs: 1000,
maximumAttempts: 3,
totalDurationMs: 60 * 1000,
};
export const AWAIT_OFFER_RESPONSE_EXECUTE_TIMEOUT_MS = 10 * 1000;
/**
* Publishes the first response and closes the window. The RPC lock commits both with the check.
*/
Example: examples/typescript/src/patterns/deferred-choice/offer-response-flow.ts
/// How long the customer has to respond.
pub const OFFER_EXPIRY: Duration = Duration::from_secs(3 * 24 * 60 * 60);
/// The response window is open until the first reply or `AwaitOfferResponse` closes it. Unset reads as open.
pub const RESPONSE_WINDOW_OPEN: &str = "open";
pub const RESPONSE_WINDOW_CLOSED: &str = "closed";
/// The retry budget of the locked `AwaitOfferResponse` Execute.
pub const DECIDE_RETRY_INITIAL_INTERVAL: Duration = Duration::from_secs(1);
pub const DECIDE_RETRY_MAXIMUM_ATTEMPTS: u32 = 3;
pub const DECIDE_RETRY_TOTAL_DURATION: Duration = Duration::from_secs(60);
pub const DECIDE_EXECUTE_TIMEOUT: Duration = Duration::from_secs(10);
/// The outcomes of a customer response RPC.
pub const OFFER_RESPONSE_RECORDED: &str = "recorded";
pub const OFFER_RESPONSE_WINDOW_CLOSED: &str = "window closed";
pub static OFFER_ACCEPTED: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("offerAccepted"));
pub static OFFER_REJECTED: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("offerRejected"));
/// Locked by both response RPCs and by `AwaitOfferResponse::execute`.
pub static OFFER_RESPONSE_WINDOW: LazyLock<Attribute<String>> =
LazyLock::new(|| Attribute::new("offerResponseWindow"));
pub const ACCEPT_CUSTOMER_OFFER: Rpc<String, String> = Rpc::new("accept_customer_offer");
pub const REJECT_CUSTOMER_OFFER: Rpc<String, String> = Rpc::new("reject_customer_offer");
impl OfferResponseFlow {
/// Records that the customer accepted the offer.
Example: examples/rust/src/control_patterns/deferred_choice/flow.rs