Response Window
View as MarkdownA 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.
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
Executeruns. Its RPC returns success, thenExecuteexpires 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:
- 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, 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. - The
ExecuteofAwaitOfferResponselocks the same Attribute and closes the window on every branch. Dex takes the lock before it handsExecuteto a Worker, and reads the state after that. - When the Timer won, a response that committed before the lock is already in its Channel.
Executesees it through the Channel size and moves toRouteResponseBeforeExpiry, 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.
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 is at or past it. If the Timer wins, the size check still picks up the single response already admitted to the Channel.
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
Executeonly.WaitForstays unlocked. - The locked
Executesets 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
Executea short retry budget. A failingExecutekeeps the lock through its retries, so waiting responses can reach their lock wait limit. See 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.
- The response RPC may also record the admitted response as the outcome under the lock.
Executestill 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
409and a Flow not found to404. - To wait again, reopen the window under the same lock, in the
Executethat 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.
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
Executeruns, is taken through the size check. - With a hard cutoff, a response at or past the stored deadline gets "window closed".
Core implementation
The example is the Decision with Deadline 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.
# 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.
Example: examples/python/dex_examples/patterns/deferred-choice/offer_response_flow.py
// 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"
)
// 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
)
func (flow *OfferResponseFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.AcceptCustomerOffer, &dex.RPCOptions{LockAttributes: responseWindowLock}),
dex.DefineRPC(flow.RejectCustomerOffer, &dex.RPCOptions{LockAttributes: responseWindowLock}),
dex.DefineRPC(flow.GetDexSummary, nil),
// 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";
/** 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.
*
* @return {@link #OFFER_RESPONSE_WINDOW_CLOSED} after the first response or the decision
*/
@RPC(lockAttributes = {"offerResponseWindow"})
public RPCResult<String> acceptCustomerOffer(final Context context, final String note) {
return publishWhileWindowOpen(context, offerAccepted, note);
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/deferredchoice/OfferResponseFlow.java
/** 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";
/** 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.
*/
export function publishWhileWindowOpen(
context: Context,
response: Channel<string>,
note: string,
): RPCResult<string> {
Example: examples/typescript/src/patterns/deferred-choice/offer-response-flow.ts
/// 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";
/// Locked by both response RPCs and by `AwaitOfferResponse::execute`.
pub static OFFER_RESPONSE_WINDOW: LazyLock<Attribute<String>> =
LazyLock::new(|| Attribute::new("offerResponseWindow"));
/// Publishes the first response and closes the window; later responses get the closed result.
/// The check, the publish, and the close commit together, because the RPC holds the window lock.
fn publish_while_window_open(
context: &mut Context,
response: &Channel<String>,
note: String,
) -> HandlerResult<RpcResult<String>> {
let window = OFFER_RESPONSE_WINDOW.get(context)?;
if window.as_deref() == Some(RESPONSE_WINDOW_CLOSED) {
return Ok(RpcResult::new(OFFER_RESPONSE_WINDOW_CLOSED.to_string()));
}
response.publish(context, note)?;
Example: examples/rust/src/control_patterns/deferred_choice/flow.rs