Streaming, Stop Signals, and Safe Recovery in an LLM Agent Pipeline
System DesignModel answerLast updated
Design end-to-end token streaming, user-initiated cancellation, and failure recovery for a multi-turn agent system where tools may have irreversible side effects.
Streaming, Stop Signals, and Safe Recovery in an LLM Agent Pipeline
You are building the backend for a multi-turn conversational agent. Each turn can involve a language model, a vector retrieval step, and one or more external tools — some of which write data or trigger billable operations. Responses are streamed token-by-token to the client.
Users can click a Stop button at any point. The system must halt token delivery as quickly as possible, attempt to interrupt upstream generation, and avoid duplicating any side effects if the turn is later retried.
Constraints
- Tokens may already be in flight to the client when a stop or failure occurs.
- Closing the browser tab does not guarantee the remote model stopped generating or that billing was reversed.
- Providers offer no universal cancellation, request-lookup, or billing-refund API.
- Some tools are read-only, some are idempotent, and some are irreversible (sending an email, charging a card).
- Retrying an entire failed turn without safeguards can duplicate tool effects.
What to Address
Part 1 — Protocol and Stop Flow
Compare SSE (Server-Sent Events) and WebSockets for this use case. Then trace what happens from the moment a user clicks Stop: how the signal travels from the browser through the server, the orchestrator, the model call, and any pending tool invocations.
Cover:
- How to choose a protocol based on traffic direction and operational requirements.
- What the server can stop immediately versus what requires provider cooperation.
- The billing uncertainty that remains even after a well-formed cancellation request.
Part 2 — Failure Recovery and Attempt Safety
Describe how the system should handle timeouts and crashes in each layer of the agent chain. Specifically:
- How should retries differ between a retrieval step and a side-effecting tool?
- How do you prevent a retried turn from re-running a tool that already completed?
- What state should be recorded for each attempt, and how is it used to fence stale responses?
A strong answer is structured, uses concrete trade-offs, and is honest about what the system cannot guarantee.
Hints
Hint 1
SSE is unidirectional by design. Think about whether the stop signal needs to travel on the same connection as the token stream, or whether a separate channel is cleaner and what that implies for auth.
Hint 2
A model call you abandon locally is not the same as a model call the provider stopped. Consider what you record about billing state and how you surface that uncertainty to the user or an ops team.
Hint 3
Give each tool invocation a stable, deterministic ID derived from the turn and attempt. Before executing, check whether that ID already completed successfully. This is the core of idempotency fencing.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Protocol Choice
SSE vs WebSocket comes down to traffic direction. Token streaming is server-to-client only; the stop signal travels client-to-server. Those are two independent communication paths, and nothing forces them onto the same connection.
SSE is the simpler choice for the stream itself: it runs over plain HTTP/2, reconnects automatically, passes through standard proxies and CDNs, and needs no special infrastructure. The stop signal goes over a separate authenticated REST or HTTP/2 endpoint. This separation is actually an advantage — you can authorize the stop request independently and it works even if the stream connection has dropped.
WebSocket makes sense if you need true bidirectional interaction on one connection — for example, a UI that lets the user interject mid-generation with a clarifying message that the model must incorporate. For a Stop button alone, that complexity is not justified.
Practical choice: SSE for the stream, a separate POST /sessions/{id}/turns/{turn}/cancel for stop.
Part 1 — Tracing a Stop Request
What the server can do immediately
When the cancel endpoint is hit, the server should:
- Mark the turn's state as
cancelingin durable storage. - Close the SSE response body so no more tokens reach the client.
- Signal the orchestrator coroutine (via a cancellation token, channel close, or context cancellation) to stop reading from the model stream.
- If any tool invocation has not yet been dispatched, do not dispatch it.
All of this is local and happens in milliseconds.
What requires provider cooperation
Dropping the HTTP connection to the provider does not stop generation on their side. Most providers accept an abort at the TCP/HTTP level and will stop processing, but there is no contractual guarantee and no standard cancellation API. The model may have already generated the full response by the time your abort arrives.
Billing uncertainty is real and must be acknowledged. The typical provider contract bills by tokens generated, not tokens delivered. A well-timed abort might save cost; it might not. The system should log the cancellation timestamp alongside the provider request ID so that an ops team can correlate against provider billing exports if needed. Do not promise the user that stopping will prevent a charge.
Tools in flight
If a tool has been dispatched and has not yet returned:
- Read-only tools (vector retrieval, database reads): let them finish or abandon — no consequences either way.
- Idempotent tools (most REST GET/PUT with stable keys): safe to abandon; a retry will produce the same result.
- Irreversible tools (send email, charge payment, post to external API): if dispatch already happened, the effect is done. Record the outcome as
uncertainand surface it. Do not silently retry.
Part 2 — Failure Recovery and Attempt Safety
Turn and attempt identity
Every turn gets a stable turn_id. Every execution attempt within a turn gets an attempt_id (monotonically increasing). These are assigned before any work starts and persisted immediately.
Each tool invocation gets a deterministic operation key derived from (turn_id, attempt_id, tool_name, input_hash). Before executing a tool, the system checks whether that key already has a terminal outcome in storage. If it does, skip execution and use the stored result. This is the idempotency fence.
Retry rules by component
| Component | Retry policy |
|---|---|
| Vector retrieval | Retry freely with backoff; read-only, no side effects |
| LLM call (no tool) | Retry on transient errors; treat timeout as uncertain |
| Idempotent tool | Retry up to a configured limit |
| Irreversible tool | Do not retry automatically; require explicit operator decision |
Attempt fencing
Each attempt operates within a deadline. When an attempt exceeds its deadline:
- The attempt is marked
timed_out. - Any in-progress tool calls are marked
uncertainif they were dispatched,abandonedif they were not. - A new attempt can be created, but it starts from the last known safe checkpoint — completed tool results are reused from storage, not re-executed.
Stale goroutines or lambdas from the timed-out attempt may still be running. They should check the attempt state before writing any result and discard their output if the attempt is no longer active.
Outcome states to record
Each turn attempt lands in exactly one terminal state:
complete— full response delivered.canceled— user-initiated stop; partial tokens may have been delivered.failed— unrecoverable error.uncertain— at least one tool was dispatched and did not return a confirmed result; human review may be needed.
uncertain is the honest answer when you cannot prove what happened. Surface it rather than hiding it behind a generic error.
What partial history to keep
A canceled or failed turn should be stored with whatever partial text and tool outcomes were recorded. This lets a subsequent turn or retry start with accurate context rather than a fabricated or blank history. Whether to show partial text in the UI is a product decision, but the data should be preserved.
Common Mistakes
- Treating connection close as cancellation confirmation. It is not. Log it; do not bill against it.
- Retrying the entire agent turn as a unit. This re-runs already-completed tools. Use checkpoints and idempotency keys.
- No attempt ID on tool calls. Without a stable key, you cannot safely deduplicate on retry.
- Promising billing cancellation to the user. Only promise local stop; be honest about provider billing uncertainty.
- Ignoring the
uncertainoutcome. Silent failures in side-effecting tools become support incidents later.