Module 5 · Streaming & production

Concurrency, queues and double-texting

6 min read

A customer sends "Where is my order?", then, impatient, "ORD-1002" two seconds later, before the answer to the first message. An operator double-clicks "Approve". Two server instances receive messages for the same conversation at the same time. These concurrency situations are routine in production, and a graph that isn't prepared for them silently corrupts its conversations. This lesson explains the problem and the strategies to solve it.

The problem: two runs, one state

A thread has a single state. If two runs start at the same time on the same thread:

  1. both read the same starting checkpoint;
  2. each appends its message and continues its own run;
  3. each writes its checkpoints in turn.

Result: the history contains two interleaved branches, one of the answers ignores the other's message, and on the next turn the model may receive an inconsistent history (a tool call without a result, for example), which will make the API call fail. The rule is therefore absolute: only one run at a time per thread.

Double-texting: four strategies

The most frequent case is double-texting: a new message arrives while a run is in progress on the same thread. Four strategies exist (they are also those of LangChain's managed platform):

StrategyBehaviorWhen to use it
rejectThe new message is refused (HTTP 409); the client will retryThe simplest and safest; the interface disables sending during the answer
enqueueThe new message waits for the current run to end, then runsMessages that complement each other ("ORD-1002" after "where is my order?")
interruptThe current run is stopped and the new message processed, on the state already producedThe customer corrects their request; we keep the work done
rollbackThe current run is cancelled and erased, then the new message processedThe customer rephrases completely; the work in progress is worthless

interrupt and rollback are the trickiest: stopping a run midway assumes its side effects so far are acceptable, and that no tool call is left without a result in the history.

Relay's implementation: one lock per thread

Relay's server implements reject (default) and enqueue, with one asyncio.Lock per thread:

def _lock(thread_id: str) -> asyncio.Lock:
    return app.state.locks.setdefault(thread_id, asyncio.Lock())


@app.post("/threads/{thread_id}/messages")
async def post_message(thread_id: str, body: MessageIn) -> StreamingResponse:
    lock = _lock(thread_id)
    if body.multitask == "reject" and lock.locked():
        raise HTTPException(409, "Une réponse est déjà en cours pour cette conversation.")
    if await _pending(thread_id):
        raise HTTPException(409, "Cette conversation attend une validation : utilisez /resume.")
    graph_input = {"messages": [HumanMessage(body.text)]}
    return StreamingResponse(_locked_stream(thread_id, lock, graph_input, Context(body.customer_id)),
                             media_type="text/event-stream")
  • With reject, if the lock is taken, the request is refused immediately.
  • With enqueue, the request waits for the lock (async with lock in _locked_stream): messages are processed in order of arrival.
  • Resuming an approval (/resume) takes the same lock: a double-click on "Approve" produces only one resume; the second finds the approval already handled and is refused (409).

The second check is just as important: a thread waiting for approval doesn't accept a new message. Otherwise, the new message would restart the graph from the beginning while an interrupt is waiting for an answer. The test_refund_approval_flow test checks this refusal.

Beyond one instance: distributed locks

An asyncio.Lock only protects a single process. As soon as you run several server instances (several workers, several containers), two requests for the same thread can land on two different instances. You then need a shared lock:

  • PostgreSQL advisory lock: pg_try_advisory_lock(hashtext(thread_id)). You already have Postgres for checkpoints: it's the simplest solution. The lock is held by the connection, and released automatically if it drops.
  • Redis lock with expiration (SET key value NX PX 30000), if Redis is already part of your infrastructure. Expiration prevents a dead process from blocking the thread forever, but requires renewing it for long runs.
  • Routing by thread: a load balancer that always sends the same thread_id to the same instance (sticky routing) makes the local lock sufficient… as long as no instance restarts. It's an optimization, not a guarantee.

Long runs: decoupling request and execution

A run waiting for a slow tool, or chaining dozens of steps, shouldn't depend on an open HTTP connection. The classic architecture separates the API from the work:

Client ──POST──► API ──► task queue (Postgres, Redis, SQS…) ──► workers ──► graph + checkpointer
   ▲                                                                   │
   └──────────── events (SSE / WebSocket / webhook) ◄──────────────────┘
  1. The API records the request in a queue and replies immediately with a run id.
  2. Workers consume the queue, take the thread's lock and run the graph.
  3. The client follows progress through an event stream, or receives a webhook at the end.

The queue solves several problems at once: it absorbs load peaks, it naturally implements the enqueue strategy, it survives API restarts, and it lets you cap the number of simultaneous runs to respect the model API's quotas.

The model's rate limits

Concurrency isn't only about threads. A hundred simultaneous conversations means potentially hundreds of model calls per minute, plus each run's parallel tasks (Send). Beyond your account's quotas, the API returns 429 errors. Protect yourself at several levels:

  • the model SDK's automatic retries (max_retries), for transient peaks;
  • a global semaphore (or the number of workers) capping simultaneous runs;
  • a cap on parallel tasks in your Send routers (lesson 2.3);
  • different models for different tasks: Relay's triage and item assessment use a fast model, whose quotas are often larger.

Client-side idempotency

Clients retry too: a mobile network drops, and the same message is sent again. To avoid processing the same message twice, have each request carry a client-generated message id. The server ignores an id it has already processed. With LangGraph, just give that id to the HumanMessage (HumanMessage(content=..., id=client_message_id)): the add_messages reducer replaces a message with the same id instead of appending it, which avoids duplicates in the history — what remains is not restarting the run.

Key takeaways

  • Only one run at a time per thread: two simultaneous runs corrupt the history.
  • Double-texting: reject (safest), enqueue (complementary messages), interrupt and rollback (trickier).
  • A thread waiting for approval must accept only the resume, not a new message.
  • An asyncio.Lock only protects one process: with several instances, use a Postgres or Redis lock.
  • For long runs: a task queue and workers; for quotas: retries, a semaphore, parallelism caps.

Practice

  1. Send two simultaneous requests on the same thread, one with multitask="enqueue": check in the history that both messages were processed in order.
  2. Replace Relay's lock with a PostgreSQL advisory lock and test it with two uvicorn processes on different ports.
  3. Add a message_id field to MessageIn and make sure an already received message doesn't restart a run.

Resources