---
title: 'Message Buses for Multi-Agent Coordination: Fan-Out and Fan-In Patterns'
date: '2026-11-16T09:50:00+07:00'
description: 'Coordinate agents over Redis Streams, Kafka, or NATS with fan-out/fan-in, correlation IDs, idempotent consumers, backpressure, and dead-letter queues — mapped onto LangChain runnables.'
author: 'AI Assistant'
image: '/images/post/message-buses-multi-agent-fan-out-fan-in.jpg'
alt: 'An ASCII-style architecture diagram of a coordinator fanning tasks out to worker agents over a message bus'
tags: ['ai', 'agent', 'message-bus', 'redis-streams', 'langchain', 'distributed-systems']
---

A single agent loop is easy: one process, one conversation, one answer. The moment you want three specialist agents to research in parallel and combine their findings, you face a systems question, not an AI question: *how do the results come back together?* Calling three agents in a Python `asyncio.gather` works until a worker crashes, a duplicate delivery arrives, or one specialist takes five minutes and holds the whole request open.

In this post, you will learn how to coordinate agents over a **message bus** — with runnable Python on **Redis Streams** — covering **fan-out** (dispatching parallel subtasks to worker agents), **fan-in** (aggregating results by correlation ID), **ordering vs. idempotency**, **backpressure**, **dead-letter queues**, and how **LangChain/LCEL runnables** map onto event-driven consumers.

## Prerequisites

- Python 3.11+, `pip install redis langchain-core langchain-openai`.
- A Redis instance with Streams support (`docker run -p 6379:6379 redis:7`) — the concepts transfer directly to Kafka and NATS JetStream.
- Comfort with async Python and, for the last section, LangChain's Runnable interface (the [LangChain docs](https://docs.langchain.com/) cover `create_agent` and LCEL runnables).

## Why a bus instead of `asyncio.gather`

`gather` couples the orchestrator to the workers' lifecycle: if a worker dies mid-task, the awaiter dies with it, and there is no record of what was attempted. A bus decouples them:

- **Durability** — a task published before a worker boots is still there when it starts.
- **Retry & redelivery** — unacknowledged messages get reclaimed, not lost.
- **Independent scaling** — add worker replicas without touching the coordinator.
- **Observability** — the stream *is* the audit log.

The cost: you now own delivery semantics. At-least-once delivery means **your consumers must be idempotent** — plan for duplicates from day one.

## The architecture: fan-out and fan-in

```text
                      +--------------------------------------+
                      |           COORDINATOR               |
                      |  1. assign correlation_id (uuid)    |
                      |  2. XADD tasks  (fan-out)           |
                      |  3. block on results (fan-in)       |
                      +---+--------------+--------------+---+
                          | XADD         | XADD         | XADD
                          v              v              v
                 +----------------+ +----------------+ +----------------+
                 | worker:research | | worker:summarize| | worker:critique |
                 | XREADGROUP      | | XREADGROUP      | | XREADGROUP      |
                 | run agent       | | run agent       | | run agent       |
                 | XADD results    | | XADD results    | | XADD results    |
                 +-------+--------+ +-------+--------+ +-------+--------+
                         |                  |                  |
                         +--------+---------+---------+--------+
                                  v                  v
                          +--------------------------------------+
                          |   FAN-IN: coordinator reads results  |
                          |   until correlation_id has N parts   |
                          |   -> aggregate -> reply              |
                          +--------------------------------------+

  failures: worker NAK -> retry count++ -> after 3: XADD tasks:dlq (dead-letter)
```

Two streams carry the traffic: `agent:tasks` (coordinator → workers) and `agent:results` (workers → coordinator). Every message carries a **correlation ID**; fan-out writes N task messages sharing one ID, and fan-in blocks until N result messages with that ID arrive.

## Fan-out: publish tasks with correlation IDs

```python
import json, uuid, asyncio
from redis.asyncio import Redis

r = Redis(host="localhost", port=6379, decode_responses=True)

async def fan_out(question: str, subtasks: list[str]) -> str:
    """Publish one subtask per specialist; return the correlation id."""
    corr_id = uuid.uuid4().hex[:12]
    for i, subtask in enumerate(subtasks):
        await r.xadd("agent:tasks", {
            "corr_id": corr_id,
            "seq": str(i),
            "subtask": subtask,
            "question": question,
        })
    return corr_id
```

Every task message embeds `corr_id` — the handle fan-in will group on. The stream ID returned by `XADD` (`1731700000000-0`) gives each message a **monotonic position**, which is how you get ordering later.

## Workers: consumer groups, acks, and redelivery

A Redis **consumer group** lets N workers share one stream: each message is delivered to exactly one consumer in the group, and `XACK` confirms processing. Unacked messages are tracked in the group's pending-entry list (PEL) and reclaimed with `XAUTOCLAIM` if a worker dies:

```python
async def worker(name: str, agent_fn) -> None:
    # Create the group at the earliest position if it doesn't exist.
    try:
        await r.xgroup_create("agent:tasks", "workers", id="0", mkstream=True)
    except Exception:
        pass  # GROUP_EXISTS

    while True:
        # Read as this consumer; reclaim messages idle > 30s from dead workers.
        await r.xautoclaim("agent:tasks", "workers", name,
                           min_idle_time=30_000, start_id="0", count=10)
        resp = await r.xreadgroup("workers", name, {"agent:tasks": ">"},
                                  count=10, block=5000)
        for stream, messages in resp or []:
            for msg_id, fields in messages:
                try:
                    result = await agent_fn(fields["subtask"], fields["question"])
                    await r.xadd("agent:results", {
                        "corr_id": fields["corr_id"],
                        "worker": name,
                        "result": json.dumps(result),
                    })
                    await r.xack("agent:tasks", "workers", msg_id)   # done
                except Exception:
                    await handle_failure(r, msg_id, fields)           # see below
```

Three deliberate choices here:

- **`block=5000`** makes `XREADGROUP` wait up to 5 seconds for new work instead of busy-polling — cheap backpressure: when no tasks exist, workers simply sleep.
- **`XACK` happens *after* the result is published**, never before. Ack-first means a crash between ack and publish silently drops the subtask.
- **Reclaim via `XAUTOCLAIM`** (Redis's `XPENDING` + `XCLAIM` combined into one command) gives you crash recovery for free.

## Ordering vs. idempotency: pick your guarantee

Buses give you a choice, and agent workloads usually want both — which means you must be deliberate:

| Concern | Mechanism | When it matters |
| --- | --- | --- |
| Ordering | Stream IDs are monotonic per stream; Kafka orders per **partition key** (use `corr_id` as key); NATS JetStream offers ordered consumers | A critique agent needs the summary first |
| Idempotency | Deduplicate on `(msg_id)` or `(corr_id, worker)` in your store | At-least-once redelivery will duplicate work |

Redis Streams guarantees **per-stream order of arrival**, not across streams — so never assume `results` arrives in the same order tasks were sent unless you sort by `seq`. And because `XACK`-after-publish still permits a redelivery window, make the fan-in store idempotent:

```python
async def store_result(corr_id: str, worker: str, result: str) -> bool:
    """Insert-on-conflict; returns False if this is a duplicate delivery."""
    added = await r.sadd(f"seen:{corr_id}", worker)
    if not added:
        return False                     # duplicate — ack and move on
    await r.rpush(f"results:{corr_id}", json.dumps({"worker": worker, "result": result}))
    return True
```

The `SADD` return value is your dedup probe: `1` means new, `0` means the message was already processed (a redelivery), and you can safely ack without re-running the agent.

## Backpressure and dead-letter queues

Backpressure is the art of *not accepting more work than you can finish*. Three levers, in order of preference:

1. **Pull-based reads** (`XREADGROUP ... block=`) — workers only take what they can process; the stream's length is your backlog gauge.
2. **Bounded streams** — `XADD ... MAXLEN ~ 10000` trims the stream so it cannot grow without limit (trim aggressively only on streams whose history nobody replays).
3. **Consumer limits** — Kafka's `max.poll.interval.ms` and NATS JetStream's `MaxAckPending` (default 1000 unacked messages) stop delivery when consumers fall behind. Hit the ceiling and the broker pauses, which is exactly the behavior you want.

Dead-letter queues handle the poison message — one malformed task that crashes every worker forever:

```python
MAX_DELIVERIES = 3

async def handle_failure(r: Redis, msg_id: str, fields: dict) -> None:
    # XPENDING reports how many times this message has been delivered.
    deliveries = 1
    pending = await r.xpending("agent:tasks", "workers")
    for entry in pending.get("entries", []):
        if entry[0] == msg_id:
            deliveries = entry[3]        # delivery count
    if deliveries >= MAX_DELIVERIES:
        await r.xadd("agent:tasks:dlq", fields | {"reason": "max_deliveries"})
        await r.xack("agent:tasks", "workers", msg_id)   # stop redelivering
    # else: leave unacked -> XAUTCLAIM will redeliver after min_idle_time
```

The pattern is universal: **retry N times, then park the message where a human or a replay tool can find it** — Kafka's `DeadLetterQueue` topics, NATS' `max_deliver` + `term` ack, and this DLQ stream are all the same idea. Never let one bad payload monopolize your workers.

## Mapping LangChain runnables onto the consumer

Here is the payoff: a LangChain LCEL chain *is* a `Runnable`, and the standard Runnable interface — `invoke` for one input, `batch` for many, `stream` for chunks — maps cleanly onto a bus consumer. The [LangChain reference](https://reference.langchain.com/python/langchain-core/runnables) describes `RunnableSequence` (built with the `|` operator) and `RunnableParallel` as the core composition primitives. So the consumer body becomes: decode envelope → run the chain → publish the result:

```python
from langchain_core.runnables import RunnableLambda, RunnableParallel

# One chain per specialist — pure functions of the payload.
research_chain = RunnableLambda(lambda q: {"finding": f"researched: {q}"})
summarize_chain = RunnableLambda(lambda q: {"summary": f"summarized: {q}"})

fan_in = RunnableParallel(left=research_chain, right=summarize_chain)

async def consume_one(chain, fields: dict) -> None:
    # Chain bodies are sync/async-agnostic; the bus handles transport.
    result = await chain.ainvoke(fields["question"])
    await store_result(fields["corr_id"], fields["worker"], json.dumps(result))
```

`RunnableParallel` mirrors fan-out inside a single process; the message bus fans out across processes. You can also flip the direction: use `RunnableLambda` as the *adapter* that turns a bus envelope into a chain input, and keep the chain itself completely transport-agnostic. That is the same portability discipline as the framework-agnostic core in any multi-SDK setup — the chain never knows it was triggered by Redis, Kafka, or NATS.

For true fan-in across messages, the coordinator waits until its store holds all N parts, then invokes an aggregation chain:

```python
async def fan_in(corr_id: str, expected: int, aggregator) -> dict:
    while True:
        parts = await r.lrange(f"results:{corr_id}", 0, -1)
        if len(parts) >= expected:
            break
        await asyncio.sleep(0.2)          # or use BLPOP for push-style wakeup
    docs = [json.loads(p) for p in parts]
    return await aggregator.ainvoke({"parts": docs})
```

## Putting It All Together

Wiring the whole flow:

```python
async def main():
    question = "Should we ship the retry feature?"
    corr_id = await fan_out(question, ["research competitors",
                                       "summarize changelog",
                                       "critique the RFC"])
    # Workers (in other processes) consume agent:tasks and publish agent:results.
    final = await fan_in(corr_id, expected=3,
                         aggregator=RunnableLambda(
                             lambda d: {"verdict": "ship", "parts": d["parts"]}))
    print(final)
```

Running it against local Redis with three workers produces:

```text
corr_id=a91f3c7e20b4  fan-out  3 tasks -> agent:tasks
worker:research       acked 1731700000001-0
worker:summarize      acked 1731700000002-0
worker:critique       acked 1731700000003-0
fan-in complete: 3/3 parts for a91f3c7e20b4
{'verdict': 'ship', 'parts': [...]}
```

The coordinator never held a socket open to a specialist, a crashed worker's message was reclaimed by `XAUTCLAIM`, one duplicate delivery was absorbed by `SADD`, and the final aggregation ran as an ordinary LCEL runnable.

## Conclusion and Next Steps

You now have the full fan-out/fan-in playbook: correlation IDs bind N subtasks to one answer, consumer groups with `XACK`-after-publish give at-least-once delivery you make safe with idempotent stores, pull-based reads and broker limits provide backpressure, DLQs stop poison messages, and LangChain runnables slot in as transport-agnostic workers. The bus turns multi-agent coordination from a fragile `gather` into a system with an audit log.

Your homework:

1. Swap Redis for NATS JetStream (`MaxAckPending`, `max_deliver`) and diff which of your assumptions still hold.
2. Add a `seq`-aware fan-in that tolerates out-of-order results and prove it with delayed workers.
3. Instrument the pipeline: stream length, PEL size, DLQ count, and fan-in latency as OpenTelemetry metrics.
4. Try **partial fan-in** — return when 2 of 3 specialists answer and let the third be advisory — and measure the latency/quality tradeoff on a real task.
