The Complete Production SOP: How to Deploy and Run Redis Streams Consumer Groups & Event Pipelines in Autonomous AI Agents
Deploy Redis Streams Consumer Groups in Codex, Claude Code, and Cursor. Master XREADGROUP, pending entry tracking, dead letter queues, and SOP guardrails.
Technical Overview & Architectural Context
Distributed messaging with Redis Streams presents subtle concurrency, delivery guarantee, and state tracking traps that autonomous AI agents consistently mishandle. Common pitfalls include attempting to re-create existing consumer groups without checking for BUSYGROUP exceptions, failing to track the Pending Entries List (PEL) via XPENDING, reading the stream using '$' instead of '>' in worker poll loops, and omitting approximate stream trimming (MAXLEN ~) which leads to unconstrained RAM exhaustion. Agents also regularly forget to implement XAUTOCLAIM or XCLAIM for orphaned messages during consumer process crashes. The 'redis-streams-consumer-groups' skill establishes deterministic guardrails for AI coding agents across Codex, Claude Code, Cursor, and Windsurf. By enforcing strict command construction sequences (e.g., verifying stream existence with MKSTREAM, managing ack cycles via XACK, and implementing dead-letter recovery protocols), this skill eliminates infinite re-processing loops and memory leaks in production streaming architectures.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the skill manifest into your project's agent rules directory to enable deterministic parsing.
Autonomous runtimes parse directory-level rules to expand their procedural capabilities. For Claude Code, skills can be mounted into the project-level .claude/skills/ directory. In Cursor or Windsurf, point your agent instructions (.cursorrules or .windsurfrules) to include the SKILL.md manifest, allowing the LLM engine to invoke the predefined command templates whenever stream ingestion tasks are requested.
mkdir -p .agents/skills/redis-streams-consumer-groups && curl -fsSL https://askills.dev/api/skills/redis-streams-consumer-groups/raw -o .agents/skills/redis-streams-consumer-groups/SKILL.md---
name: "redis-streams-consumer-groups"
description: "Implement resilient, horizontally scalable message distribution pipelines using Redis Streams."
metadata:
author: "Redis"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "create redis consumer group"
- "read from redis stream xreadgroup"
- "handle ack redis streams"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Redis Streams Consumer Groups & Event Pipelines
Builds event-driven architectures with Redis Streams: XADD event publishing, consumer groups with XREADGROUP, pending entry tracking (XPENDING), message claiming (XCLAIM), and auto-trimming (MAXLEN).
## When to Invoke
Invoke this skill whenever you need to:
- create redis consumer group
- read from redis stream xreadgroup
- handle ack redis streams
## Execution SOP & Rules
1. Publish stream entry: XADD telemetry:events MAXLEN ~ 100000 * event_type 'click' payload '{...}'.
2. Create consumer group: XGROUP CREATE telemetry:events analytics_group $ MKSTREAM.
3. Consume batch: XREADGROUP GROUP analytics_group worker_1 COUNT 10 BLOCK 2000 STREAMS telemetry:events >.
4. Acknowledge processed entries: XACK telemetry:events analytics_group message_id.
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.In Claude Code, keep SKILL.md under 150 lines to conserve contextual attention for dynamic message processing logic and large schema types.
The frontmatter specifies 'shell_exec: false'. The agent should generate the pipeline script within the workspace rather than trying to execute shell commands directly on external Redis instances without explicit user permission.
Environment Secrets & Dependency Validation
Inject Redis connection strings and initialize driver dependencies safely.
Provide the agent with Redis connection schemas without exposing plaintext credentials. Provide standard environment configuration files (.env.example and .env.local) and install the native client library (e.g., ioredis or redis-py).
npm install ioredis && echo 'REDIS_URL="redis://127.0.0.1:6379"' > .env.local && echo '.env.local' >> .gitignoreimport Redis from 'ioredis';
export const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
export async function initConsumerGroup(streamKey: string, groupName: string): Promise<void> {
try {
// MKSTREAM ensures the stream is created if it does not already exist
await redis.xgroup('CREATE', streamKey, groupName, '$', 'MKSTREAM');
} catch (err: any) {
if (!err.message.includes('BUSYGROUP')) {
throw err;
}
}
}Instruct the agent to look for REDIS_URL in process.env so it never hardcodes local passwords or staging Redis endpoints in generated TypeScript/Python code.
Never execute raw XGROUP CREATE without catching BUSYGROUP. Node and Python runtimes will crash on cold starts if a secondary container tries to re-register the existing group.
Intent Matching & Trigger Invocation
Trigger the agent to scaffold end-to-end consumer loops and dead-letter reclamation.
Prompt the agent using explicit SKILL triggers like 'create redis consumer group' and 'read from redis stream xreadgroup'. The agent will invoke the skill SOP, generating a resilient consumer pipeline that includes XREADGROUP, XACK, and an XAUTOCLAIM background worker for stale consumer recovery.
import { redis, initConsumerGroup } from './streamConsumer';
const STREAM_KEY = 'telemetry:events';
const GROUP_NAME = 'analytics_group';
const CONSUMER_NAME = `worker_${process.pid}`;
export async function startWorker() {
await initConsumerGroup(STREAM_KEY, GROUP_NAME);
while (true) {
try {
// Read only new messages targeting this group using special ID '>'
const response = await redis.xreadgroup(
'GROUP', GROUP_NAME, CONSUMER_NAME,
'COUNT', 10,
'BLOCK', 2000,
'STREAMS', STREAM_KEY,
'>'
) as [string, [string, string[]][]][];
if (!response || response.length === 0) continue;
const [_, messages] = response[0];
for (const [id, fields] of messages) {
await processRecord(id, fields);
await redis.xack(STREAM_KEY, GROUP_NAME, id);
}
} catch (error) {
console.error('Consumer error in stream loop:', error);
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
}
async function processRecord(id: string, rawFields: string[]) {
// Ingestion parsing logic
}Always pair '>' reads for new records with an asynchronous XAUTOCLAIM routine to process entries that crashed workers left pending in the PEL.
Using '0' instead of '>' in XREADGROUP reads the consumer's pending messages rather than new entries. This causes infinite looping if not deliberately routed into recovery logic.
Verification, Linting & Output Quality Gate
Execute automated integration tests and check for uncommitted memory retention.
Run type-checks and execute integration tests mocking or querying a local Redis test container to verify stream ingestion, acknowledge receipts, and check stream entry trimming behavior.
npx tsc --noEmit && npm testEnsure the test suite verifies that MAXLEN ~ <count> trims stream size properly without blocking Redis performance.
Never omit the tilde (~) in MAXLEN. Exact trimming (MAXLEN without ~) forces Redis to evaluate exact tree bounds, degrading ingestion throughput from O(1) amortized to O(N).
Real-World Scenario: Horizontally Scalable Payment Webhook Ingestion Engine
“Build an event ingestion pipeline using redis-streams-consumer-groups. Create a consumer group named 'payment_processors' on stream 'orders:webhooks'. Read batches of 20 with a 2-second block, acknowledge upon database write, and implement an auto-claim mechanism to reassign messages stuck in pending for more than 60 seconds.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent attempted to invoke XGROUP CREATE on an already initialized stream without trapping the existing group exception or checking group lists.
try { await redis.xgroup('CREATE', streamKey, groupName, '$', 'MKSTREAM'); } catch (err: any) { if (!err.message.includes('BUSYGROUP')) throw err; }Root Cause: The worker attempted to read from a stream that had not been created or where XGROUP CREATE failed prior to worker boot.
Ensure XGROUP CREATE includes the 'MKSTREAM' argument at initialization, guaranteeing that the target stream key is allocated in Redis before reading.Frequently Asked Questions (Redis Streams Consumer Groups & Event Pipelines SOP)
Q:Can I use Redis Streams Consumer Groups & Event Pipelines across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. Whether mounted in .claude/skills/, referenced in .cursorrules, or injected into Codex runtimes, all agents parse the identical triggers and execution SOP.
Q:How does Redis Streams Consumer Groups & Event Pipelines prevent context window overflow during long agent sessions?
By establishing concise procedural boundaries and deterministic validation gates rather than polluting system prompts with redundant rules, the agent retains maximum context for your application logic.
Q:Does this skill require escalated root or container permissions?
No. It is audited with a security score of 98/100 and runs safely within workspace-scoped sandboxes without requiring shell exec privileges or system root access.
Ready to equip your autonomous agent with Redis Streams Consumer Groups & Event Pipelines?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.