Retryable Async Request in YTsaurus Flow (Java)

The pipeline extends AsyncRequest: the request handler now supports retry attempts with a delay. If a failure occurs, RequestProcessorFunction saves the request state in the internal state and sets a timer for 5 seconds; success is determined by the predicate (requestId + failedAttempts) % 3 == 0.

Source code (Java)

Source code (Kotlin)

Components

RequestProcessorFunction

This implements the retry logic using an internal YSON state and timers. When you receive a request, you save it to the state and call tryRequest. When the timer fires, you load the state and retry the attempt:

    @Override
    public void onMessage(ExtendedMessage message, OutputCollector output, RuntimeContext ctx) {
        long requestId = message.get("request_id", Long.class);
        long key = message.get("key", Long.class);
        String request = message.get("request", String.class);

        log.debug("Received request message (requestId={}, key={})", requestId, key);

        StateAccessor<RequestState> accessor =
                ctx.getState(REQUEST_STATE, message);

        RequestState state = new RequestState(requestId, key, request, 0);
        accessor.set(state);

        tryRequest(state, accessor, output, ctx);
    }
    override fun onMessage(message: ExtendedMessage, output: OutputCollector, ctx: RuntimeContext) {
        val requestId = message.get("request_id", Long::class.java)!!
        val key = message.get("key", Long::class.java)!!
        val request = message.get("request", String::class.java)

        log.debug("Received request message (requestId={}, key={})", requestId, key)

        val accessor: StateAccessor<RequestState> =
            ctx.getState(REQUEST_STATE, message)

        val state = RequestState(requestId, key, request, 0)
        accessor.set(state)

        tryRequest(state, accessor, output, ctx)
    }
    @Override
    public void onTimer(Timer timer, OutputCollector output, RuntimeContext ctx) {
        log.debug("Timer fired, retrying request");

        StateAccessor<RequestState> accessor =
                ctx.getState(REQUEST_STATE, timer);

        RequestState state = accessor.get();
        if (state == null) {
            throw new IllegalStateException("No request state found on timer fire");
        }

        tryRequest(state, accessor, output, ctx);
    }
    override fun onTimer(timer: Timer, output: OutputCollector, ctx: RuntimeContext) {
        log.debug("Timer fired, retrying request")

        val accessor: StateAccessor<RequestState> =
            ctx.getState(REQUEST_STATE, timer)

        val state = accessor.get()
            ?: throw IllegalStateException("No request state found on timer fire")

        tryRequest(state, accessor, output, ctx)
    }

The helper method tryRequest checks the success predicate. If the attempt fails, it increments the attempt counter, saves the state, and schedules the next attempt.

RequestState

This is a YSON-serializable model of the request state. It stores requestId, key, the request text request, and the counter failedAttempts:

@Entity
public class RequestState {
    @Column(name = "request_id")
    private long requestId;

    private long key;

    private String request;

    @Column(name = "failed_attempts")
    private int failedAttempts;

    public RequestState() {
    }

    public RequestState(long requestId, long key, String request, int failedAttempts) {
        this.requestId = requestId;
        this.key = key;
        this.request = request;
        this.failedAttempts = failedAttempts;
    }

    public long getRequestId() {
        return requestId;
    }

    public void setRequestId(long requestId) {
        this.requestId = requestId;
    }

    public long getKey() {
        return key;
    }

    public void setKey(long key) {
        this.key = key;
    }

    public String getRequest() {
        return request;
    }

    public void setRequest(String request) {
        this.request = request;
    }

    public int getFailedAttempts() {
        return failedAttempts;
    }

    public void setFailedAttempts(int failedAttempts) {
        this.failedAttempts = failedAttempts;
    }

    @Override
    public String toString() {
        return "RequestState{" +
                "requestId=" + requestId +
                ", key=" + key +
                ", request='" + request + '\'' +
                ", failedAttempts=" + failedAttempts +
                '}';
    }
}
@Entity
class RequestState {
    @Column(name = "request_id")
    var requestId: Long = 0

    var key: Long = 0

    var request: String? = null

    @Column(name = "failed_attempts")
    var failedAttempts: Int = 0

    constructor()

    constructor(requestId: Long, key: Long, request: String?, failedAttempts: Int) {
        this.requestId = requestId
        this.key = key
        this.request = request
        this.failedAttempts = failedAttempts
    }

    override fun toString(): String {
        return "RequestState{" +
            "requestId=" + requestId +
            ", key=" + key +
            ", request='" + request + '\'' +
            ", failedAttempts=" + failedAttempts +
            '}'
    }
}

StateKeeperFunction

This is identical to the StateKeeperFunction from AsyncRequest: it processes the event and response streams and accumulates total_length in the external state. The retry logic is fully encapsulated in RequestProcessorFunction.

    @Override
    public void onMessage(ExtendedMessage message, OutputCollector output, RuntimeContext ctx) {
        String streamId = message.getStreamId();

        if ("event".equals(streamId)) {
            handleEvent(message, output, ctx);
        } else if ("response".equals(streamId)) {
            handleResponse(message, ctx);
        } else {
            throw new IllegalArgumentException("Unknown streamId: " + streamId);
        }
    }
    override fun onMessage(message: ExtendedMessage, output: OutputCollector, ctx: RuntimeContext) {
        val streamId = message.streamId

        when (streamId) {
            "event" -> handleEvent(message, output, ctx)
            "response" -> handleResponse(message, ctx)
            else -> throw IllegalArgumentException("Unknown streamId: $streamId")
        }
    }

Registering computations

You register the state and processor computations with the @FlowComputation annotation on the classes of their process functions:

@FlowComputation(id = "state")
@FlowComputation(id = "processor")
@FlowComputation(id = "state")
@FlowComputation(id = "processor")

PipelineMain

This single entry point starts the pipeline or serves as its companion, depending on YT_FLOW_MODE.

    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder(PipelineMain.class).run(args);
    }
@SpringBootApplication
open class PipelineMain {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            SpringApplicationBuilder(PipelineMain::class.java)
                .run(*args)
        }
    }
}

Key patterns

  • Retries via timers: if a failure occurs, output.addTimer(now + 5, 0L) schedules a repeated call to onTimer; the state between attempts is stored in YsonStateAccessor.
  • Success predicate: (requestId + failedAttempts) % 3 == 0 simulates an unstable external service; in real tasks, you replace this with a check of the HTTP status or another indicator.
  • Clearing the state after success: accessor.clear() is called only on a successful response, preventing reprocessing.
  • Separation of concerns: the session state logic (StateKeeperFunction) is separated from the retry logic (RequestProcessorFunction), which makes it easier to test each part independently.

Differences from AsyncRequest

Aspect AsyncRequest RetryableAsyncRequest
RequestProcessorFunction Stateless, responds immediately Has internal state and timers
Failure handling Not provided Retry with a 5-second delay
Request state Absent RequestState in YSON

See also