Retryable Async Request in YTsaurus Flow (Python)
This extends the AsyncRequest example: the request handler supports automatic retries using timers. If a request fails, it’s saved in the internal state and retried after a fixed interval, up to MAX_RETRIES attempts.
Structure
The pipeline includes two computations:
-
state(StateKeeperFunction) — a stateful computation: it routes events into requests and accumulates the total response length in the external state (similar toasync_request). -
processor(RequestProcessorFunction) — a stateful computation with retry logic:- On the first attempt, it saves the request in the internal state and tries to process it.
- If processing fails, it increments the failure counter, saves the state, and sets a timer (
DELAY_SECONDS = 5). - It retries the attempt after the timer fires (up to
MAX_RETRIES = 3). - If successful, it sends the response and clears the state.
request_processor_function.py
This is the key example file: it implements retry logic via on_timer and the helper method _try_or_retry.
class RequestProcessorFunction(RowFunction):
"""Retries requests up to MAX_RETRIES times; emits response on success."""
def on_message(self, message, output, ctx):
request_id = message.payload["request_id"]
data = {
"request_id": request_id,
"key": message.payload["key"],
"request": message.payload["request"],
"failed_attempts": 0,
}
state = ctx.state("request-state", message)
self._try_or_retry(state, data, output, ctx)
def on_timer(self, timer, output, ctx):
state = ctx.state("request-state", timer)
data = state.get_or_default(None)
if data is not None:
self._try_or_retry(state, data, output, ctx)
def _try_or_retry(self, state, data, output, ctx):
request_id = data["request_id"]
failed_attempts = data["failed_attempts"]
if not _is_request_successful(request_id, failed_attempts):
data["failed_attempts"] += 1
state.set(data)
output.add_timer(int(time.time()) + DELAY_SECONDS)
log.debug(
"Failed request (RequestId: %s, FailedAttempts: %s)",
request_id,
data["failed_attempts"],
)
else:
key = data["key"]
length = len(data["request"])
builder = ctx.message_builder("response")
builder.set("request_id", request_id)
builder.set("key", key)
builder.set("length", length)
output.add_message(builder.finish())
state.clear()
log.debug(
"Processed request (RequestId: %s, FailedAttempts: %s)",
request_id,
failed_attempts,
)
state_keeper_function.py
It handles stream routing and accumulates results in the external state (the same as in async_request).
class StateKeeperFunction(RowFunction):
"""Routes event messages to requests and accumulates response lengths in external state."""
def on_message(self, message, output, ctx):
stream_id = message.stream_id
if stream_id == "event":
key = message.payload["key"]
data = message.payload["data"]
request_id = random.getrandbits(64)
builder = ctx.message_builder("request")
builder.set("request_id", request_id)
builder.set("key", key)
builder.set("request", data)
output.add_message(builder.finish())
log.debug("Send request (RequestId: %s)", request_id)
elif stream_id == "response":
request_id = message.payload["request_id"]
length = message.payload["length"]
log.debug("Received response (RequestId: %s)", request_id)
state = ctx.external_state("/state", message)
current = state.get("total_length")
total_length = current if current is not None else 0
total_length += length
builder = state.to_builder()
builder.set("total_length", total_length)
state.set(builder.finish())
else:
raise ValueError(f"Unexpected stream_id: {stream_id}")
__main__.py
This is the entry point: its structure matches async_request, but it imports different classes.
def main():
log.info("Starting companion execution")
pipeline = Pipeline()
pipeline.add("state", StateKeeperFunction())
pipeline.add("processor", RequestProcessorFunction())
log.info("Starting pipeline...")
pipeline.run()
log.info("Pipeline completed")
Key patterns
- Retry via timers:
output.add_timer(int(time.time()) + DELAY_SECONDS)delays the next retry;on_timerreads the state and runs_try_or_retryagain. This is the standard pattern for implementing retries in Flow without external queues. - Retry counter in state: the
failed_attemptsfield is stored with the request data inctx.state("request-state", message), which ensures correctness after a restart. - Deterministic failure simulation:
_is_request_succeed(request_id, failed_attempts)simulates an unstable external service; in real code, you replace this with an HTTP client call. - Clearing state on success:
state.clear()after successful processing prevents the timer from triggering again on outdated data. - Separation of concerns:
StateKeeperFunctiondoesn’t know about retries — all retry logic is encapsulated inRequestProcessorFunction, which makes it easier to swap retry strategies.