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

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

An extension of the [Async Request](https://ytsaurus.tech/docs/en/flow/go/examples/async_request.md) example: the request handler retries every failed attempt through [timers](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#timer). The whole request is stored in the internal [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state) and retried with a fixed delay until the external service answers it.

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

## Structure {#structure}

The pipeline consists of three [computations](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation):

- `injector` — a native source (`TSwiftPassthroughOrderedSourceComputation`) declared directly in the [spec](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec): it reads the queue and publishes the events to the `event` [stream](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation). It has no Go code.
- `state` (`stateKeeper`) — a transform computation grouped by `key`: for every event it opens a request in the `request` stream, and it adds the response that arrives in the `response` stream to the total response length of the key in the external state `/state`.
- `processor` (`requestProcessor`) — a transform computation grouped by `request_id`: it makes the attempts to call the external service and publishes the response to the `response` stream.

The two computations are grouped by different keys for a reason: `processor` is partitioned by request identifier, so the requests of one key are retried independently of each other. The `delay` timer stream is declared in the spec with `allow_timer_self_dependency = %true` — the computation sets timers for itself.

## `main.go` {#main-go}

The entry point: creating the pipeline and registering both computations of the companion.

[Source code: `main.go`](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/retryable_async_request/main.go)
```go
type eventMessage struct {
	flow.YSONMessage
	Key  uint64 `yson:"key"`
	Data string `yson:"data"`
}

type requestMessage struct {
	flow.YSONMessage
	RequestID uint64 `yson:"request_id"`
	Key       uint64 `yson:"key"`
	Request   string `yson:"request"`
}

type responseMessage struct {
	flow.YSONMessage
	RequestID uint64 `yson:"request_id"`
	Key       uint64 `yson:"key"`
	Length    int64  `yson:"length"`
}

func main() {
	pipeline := flow.NewPipeline()
	pipeline.AddStreams(
		flow.NewYSONStream[eventMessage](eventStreamID),
		flow.NewYSONStream[requestMessage](requestStreamID),
		flow.NewYSONStream[responseMessage](responseStreamID),
	)
	pipeline.Add(
		flow.NewRowComputation("state", &stateKeeper{}),
		flow.NewRowComputation("processor", &requestProcessor{}),
	)

	if err := pipeline.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "retryable_async_request: %v\n", err)
		os.Exit(1)
	}
}
```

## `state_keeper.go` {#state-keeper-go}

Stream routing and accumulation of the results in the external state: the branch on `msg.StreamID` sends the event and the response to two different handlers.

```go

type totalLengthState struct {
	TotalLength int64 `yson:"total_length"`
}

type stateKeeper struct{}

var _ flow.RowFunction = (*stateKeeper)(nil)

func (s *stateKeeper) OnMessage(
	ctx context.Context,
	rt flow.Runtime,
	msg flow.ExtendedMessage,
	out flow.OutputCollector,
) error {
	switch msg.StreamID {
	case eventStreamID:
		return s.sendRequest(rt, msg, out)
	case responseStreamID:
		return s.bookResponse(rt, msg)
	default:
		return fmt.Errorf("unhandled stream %q", msg.StreamID)
	}
}

func (s *stateKeeper) sendRequest(rt flow.Runtime, msg flow.ExtendedMessage, out flow.OutputCollector) error {
	var event eventMessage
	if err := msg.ConvertTo(&event); err != nil {
		return err
	}

	request := flow.NewYSONMessage[requestMessage](requestStreamID)
	request.RequestID = rand.Uint64()
	request.Key = event.Key
	request.Request = event.Data
	encoded, err := flow.ConvertFrom(rt, request)
	if err != nil {
		return err
	}
	out.AddMessage(encoded)
	return nil
}

func (s *stateKeeper) bookResponse(rt flow.Runtime, msg flow.ExtendedMessage) error {
	var response responseMessage
	if err := msg.ConvertTo(&response); err != nil {
		return err
	}

	state, err := flow.OpenExternalState(rt, totalStateName, msg)
	if err != nil {
		return err
	}
	var total totalLengthState
	if _, err := state.ConvertTo(&total); err != nil {
		return err
	}
	total.TotalLength += response.Length
	return state.ConvertFrom(&total)
}
```

## `request_processor.go` {#request-processor-go}

The state value is an ordinary Go structure with YSON tags. It holds everything a retry needs, including the counter of failed attempts, so the retry no longer needs the original message:

```go

type requestState struct {
	RequestID      uint64 `yson:"request_id"`
	Key            uint64 `yson:"key"`
	Request        string `yson:"request"`
	FailedAttempts int64  `yson:"failed_attempts"`
}
```

The retry logic: `OnMessage` opens the request and makes the first attempt, `OnTimer` reads the request from the state and repeats it. The `attempt` method shared by both handlers either sets a timer for the next attempt or publishes the response and clears the state:

```go

type requestProcessor struct{}

var (
	_ flow.RowFunction      = (*requestProcessor)(nil)
	_ flow.RowTimerFunction = (*requestProcessor)(nil)
)

func (p *requestProcessor) OnMessage(
	ctx context.Context,
	rt flow.Runtime,
	msg flow.ExtendedMessage,
	out flow.OutputCollector,
) error {
	state, err := flow.OpenYSONState[requestState](rt, requestStateName, msg)
	if err != nil {
		return err
	}

	var input requestMessage
	if err := msg.ConvertTo(&input); err != nil {
		return err
	}
	request := requestState{
		RequestID: input.RequestID,
		Key:       input.Key,
		Request:   input.Request,
	}
	return p.attempt(rt, state, request, out)
}

func (p *requestProcessor) OnTimer(
	ctx context.Context,
	rt flow.Runtime,
	timer flow.Timer,
	out flow.OutputCollector,
) error {
	state, err := flow.OpenYSONState[requestState](rt, requestStateName, timer)
	if err != nil {
		return err
	}

	if state.Empty() {
		return nil
	}
	return p.attempt(rt, state, *state.Value(), out)
}

func (p *requestProcessor) attempt(
	rt flow.Runtime,
	state *flow.YSONState[requestState],
	request requestState,
	out flow.OutputCollector,
) error {
	if !succeeds(request) {
		request.FailedAttempts++
		*state.Value() = request
		out.AddTimer(flow.TimerRequest{TriggerTimestamp: uint64(time.Now().Add(retryDelay).Unix())})
		return nil
	}

	response := flow.NewYSONMessage[responseMessage](responseStreamID)
	response.RequestID = request.RequestID
	response.Key = request.Key
	response.Length = int64(len(request.Request))
	encoded, err := flow.ConvertFrom(rt, response)
	if err != nil {
		return err
	}
	out.AddMessage(encoded)

	state.Clear()
	return nil
}

func succeeds(request requestState) bool {
	return (request.RequestID+uint64(request.FailedAttempts))%attemptsToSucceed == 0
}
```

## Key patterns {#key-patterns}

- Retries through timers: `out.AddTimer(flow.TimerRequest{TriggerTimestamp: ...})` postpones the next attempt by `retryDelay`, and `OnTimer` performs it. This is the standard way to implement retries in Flow without external queues. An empty `StreamID` in `flow.TimerRequest` means the only timer stream of the computation.
- The attempt counter lives in the state together with the request data, so it survives a [worker](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#worker) restart: after a restart the retries continue from the same place.
- The input is converted into `requestMessage` once through `msg.ConvertTo(&input)`, while the retry logic works with a separate `requestState` structure that holds the counter of failed attempts.
- The same state is opened both by a message and by a timer: `flow.OpenYSONState[requestState](rt, requestStateName, msg)` and `flow.OpenYSONState[requestState](rt, requestStateName, timer)` — both inputs carry the grouping key that the state is addressed by.
- Clearing the state on success: after `state.Clear()`, a timer that fires later finds `state.Empty()` and returns without doing anything — a stale firing is harmless.
- Separation of responsibilities: `stateKeeper` knows nothing about retries, the whole logic is encapsulated in `requestProcessor`, so you can change the retry strategy without touching the accounting of the results.
- Deterministic failure simulation: `succeeds(request)` stands in for a real client of the external service — in production code there would be an HTTP call here.
<!-- endsource: en/_includes/flow/go/examples/retryable_async_request.md -->

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

- [Getting started (Go)](https://ytsaurus.tech/docs/en/flow/go/getting-started.md)
- [Async Request (Go)](https://ytsaurus.tech/docs/en/flow/go/examples/async_request.md)
- [Working with states (Go)](https://ytsaurus.tech/docs/en/flow/go/state.md)
- [Timers](https://ytsaurus.tech/docs/en/flow/concepts/timers.md)
- [Similar example in C++](https://ytsaurus.tech/docs/en/flow/cpp/examples/retryable_async_request.md)
<!-- endsource: en/_includes/flow/go/examples/retryable_async_request_also.md -->
