Back to Community & Earn Hub
Q&A Questiondatabases +150 pt Bounty

Redis Streams for Multi-Agent Event Buses: How to prevent XREADGROUP consumer lag and PEL memory bloat when tool workers crash mid-trajectory?

@ishaan_malhotra11 hours ago 1455 views

We coordinate our asynchronous multi-agent tool workers using Redis Streams (XADD / XREADGROUP / XACK).

Worker Loop

python
entries = await redis.xreadgroup(
    groupname="agent-workers",
    consumername=pod_id,
    streams={"agent:tasks": ">"},
    count=5,
    block=2000,
)
for stream, messages in entries:
    for msg_id, fields in messages:
        await execute_agent_tool(fields)
        await redis.xack("agent:tasks", "agent-workers", msg_id)

The Production Failure Mode

When a Kubernetes worker pod is killed mid-execution (spot preemption or OOM during a heavy Playwright/Python tool run):

  1. XACK is never called, leaving the message orphaned in that dead pod's Pending Entries List (PEL).
  2. Because pod_id is ephemeral (e.g. worker-7f8b9c), the replacement pod boots with a new consumername and never sees the orphaned task!
  3. Even worse, because PEL entries prevent Redis from freeing stream memory, XPENDING grows to tens of thousands of stale entries and XTRIM won't reclaim them cleanly.

What is the recommended pattern using XAUTOCLAIM in Redis 7+ to rescue stalled tasks, cap retries into a Dead Letter Stream (DLQ), and keep stream RAM bounded?

1 Answers

Community Answers

@rohan_mehta Accepted Answer10 hours ago

Orphaned PEL entries from ephemeral Kubernetes pod names are the #1 gotcha with Redis Streams. You should never rely solely on > (new messages) in XREADGROUP—every worker needs a periodic XAUTOCLAIM reaper loop paired with a delivery-count Dead Letter Queue (DLQ).

Here is the production-hardened pattern for Redis 7+ in Python (redis.asyncio):


1. Rescue Stalled Tasks with XAUTOCLAIM & Route Poison Pills to DLQ

Run a background reaper (or check on every Nth poll) that claims any message idle in the PEL for longer than your tool timeout (e.g., 60,000 ms):

python
STREAM_KEY = "agent:tasks"
DLQ_KEY = "agent:tasks:dlq"
GROUP = "agent-workers"
IDLE_TIMEOUT_MS = 60_000
MAX_DELIVERIES = 3

async def reclaim_stalled_tasks(redis, consumer_name: str):
    # XAUTOCLAIM returns (next_start_id, [(msg_id, fields), ...], deleted_ids)
    _, claimed, _ = await redis.xautoclaim(
        name=STREAM_KEY,
        groupname=GROUP,
        consumername=consumer_name,
        min_idle_time=IDLE_TIMEOUT_MS,
        start_id="0-0",
        count=10,
    )
    if not claimed:
        return

    for msg_id, fields in claimed:
        # Check how many times this message has been delivered across crashes
        pending_info = await redis.xpending_range(
            STREAM_KEY, GROUP, min=msg_id, max=msg_id, count=1
        )
        deliveries = pending_info[0]["times_delivered"] if pending_info else 1

        if deliveries > MAX_DELIVERIES:
            # Poison pill: move to DLQ and ACK so it leaves the PEL
            await redis.xadd(DLQ_KEY, {**fields, "original_id": msg_id, "reason": "max_retries_exceeded"}, maxlen=10000, approximate=True)
            await redis.xack(STREAM_KEY, GROUP, msg_id)
        else:
            # Retry execution on the healthy worker
            try:
                await execute_agent_tool(fields)
                await redis.xack(STREAM_KEY, GROUP, msg_id)
            except Exception:
                pass  # Remains in PEL for next backoff cycle

2. Prevent Unbounded RAM Growth & Clean Dead Consumers

  1. Approximate Trimming on Every XADD: Always pass MAXLEN ~ 50000 (maxlen=50000, approximate=True) when publishing tasks so Redis evicts old acknowledged entries in O(1) radix-tree macro-nodes.
  2. Prune Ephemeral Consumer Names: Use a Kubernetes StatefulSet ordinal (worker-0, worker-1) instead of random Deployment hashes if possible, or run XGROUP DELCONSUMER on shutdown hooks (SIGTERM) after draining in-flight tasks.

With XAUTOCLAIM + MAX_DELIVERIES DLQ routing + MAXLEN ~, crashed worker pods recover cleanly within 60 seconds and Redis PEL memory stays flat.

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.