---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.2
alternate:
  - https://ytsaurus.tech/docs/en/flow/python/examples/retryable_async_request.md
  - https://ytsaurus.tech/docs/ru/flow/python/examples/retryable_async_request.md
  - href: https://ytsaurus.tech/docs/en/flow/python/examples/retryable_async_request.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/en/llms.txt?revision=0987aa47985046d89a7b7ec44c4bbc08e6a3b783
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/en/llms.txt?revision=0987aa47985046d89a7b7ec44c4bbc08e6a3b783

<!-- source: en/_includes/flow/python/examples/retryable_async_request.md -->
# Retryable Async Request in YTsaurus Flow (Python)

This extends the [AsyncRequest](https://ytsaurus.tech/docs/en/flow/python/examples/async_request.md) example: the request handler supports automatic retries using [timers](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#timer). If a request fails, it’s saved in the internal [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state) and retried after a fixed interval, up to `MAX_RETRIES` attempts.

[Source code](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/python/retryable_async_request)

## Structure

The pipeline includes two computations:

1. **`state`** (`StateKeeperFunction`) — a stateful computation: it routes events into requests and accumulates the total response length in the external state (similar to `async_request`).

2. **`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`.

```python
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`).

```python
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.

```python
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_timer` reads the state and runs `_try_or_retry` again. This is the standard pattern for implementing retries in Flow without external queues.
- **Retry counter in state**: the `failed_attempts` field is stored with the request data in `ctx.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**: `StateKeeperFunction` doesn’t know about retries — all retry logic is encapsulated in `RequestProcessorFunction`, which makes it easier to swap retry strategies.
<!-- endsource: en/_includes/flow/python/examples/retryable_async_request.md -->

<!-- source: en/_includes/flow/python/examples/retryable_async_request_also.md -->
## See also

- [Quick start (Python)](https://ytsaurus.tech/docs/en/flow/python/getting-started.md)
- [Computation (Python)](https://ytsaurus.tech/docs/en/flow/python/computation.md)
- [Timers](https://ytsaurus.tech/docs/en/flow/concepts/timers.md)
- [Stateful processing](https://ytsaurus.tech/docs/en/flow/concepts/stateful.md)
- [AsyncRequest (Python)](https://ytsaurus.tech/docs/en/flow/python/examples/async_request.md)
- [Similar example in C++](https://ytsaurus.tech/docs/en/flow/cpp/examples/retryable_async_request.md)
- [Similar example in Java](https://ytsaurus.tech/docs/en/flow/java/examples/retryable_async_request.md)
<!-- endsource: en/_includes/flow/python/examples/retryable_async_request_also.md -->
