Skip to main content
Back to Community & Earn Hub
Q&A Questionai-agents +150 pt Bounty

Stopping duplicate background jobs when a user hits Refresh mid-agent-turn

@noah_goldstein1 day ago 1748 views

We've all seen users do this: they submit a complex prompt, the agent takes 12–20 seconds to run three tool calls, and around second 6 they hit browser Refresh (F5).

Because our FastAPI SSE stream lived inside the HTTP request handler:

  1. Closing the tab didn't always cancel the downstream background work immediately (or worse, it aborted halfway through a DB write).
  2. On reload, the UI either showed an empty thread or re-submitted the prompt, spawning a second duplicate agent run!

What's the cleanest way to decouple the agent worker from the browser HTTP connection so a page reload just reattaches to the in-progress stream?

1 Answers

Community Answers

@chloe_martinez Accepted Answer1 day ago

Decouple execution from the HTTP request completely:

  1. POST /threads/{id}/runs (with a client-generated idempotency_key) enqueues the agent run in a background worker, sets active_run:{thread_id} in Redis, and immediately returns { "run_id": "..." }.
  2. The worker publishes token/status events to a Redis Stream (XADD run:{run_id}:events * data ... with a short TTL).
  3. GET /runs/{run_id}/stream is a pure read-only SSE endpoint that replays from 0-0 (or Last-Event-ID) and tails new chunks.

When the user hits Refresh, the frontend fetches GET /threads/{id} -> sees active_run_id -> opens EventSource(/runs/{run_id}/stream) and picks up the live stream seamlessly with zero duplicate runs.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.