With plain pub/sub, any event sent while a consumer is restarting for a deploy is lost. Redis Streams keeps every event in a log until a worker confirms it. This tutorial builds a Redis Streams event processor in Node.js with the official node-redis client: a producer, a consumer group that acknowledges each message, and a recovery loop that picks up messages left behind by a crashed worker.
Quick answer: Append events with XADD, create a consumer group once with XGROUP CREATE ... MKSTREAM, and have each worker read with XREADGROUP using the ID >. Acknowledge each message with XACK only after it is processed, and periodically claim messages that sat unacknowledged too long.
- Install
redisanddotenv, and start Redis. - Publish events with
xAdd(stream, '*', fields). - Create the consumer group and read new messages with
xReadGroup. - Call
xAckafter successful processing; failed messages stay pending. - Every few seconds, list pending messages with
xPendingRangeand take over idle ones withxClaim.
In this guide
- Before You Start
- What You Will Build
- Why Choose Redis Streams Over Pub/Sub
- Step 1: Set Up the Project and Redis
- Step 2: Produce Events to the Stream
- Step 3: Build a Consumer Group That Acknowledges Messages
- Test It: Process the Events and Find the Failed One
- Step 4: Claim Messages Stuck After a Crash
- Step 5: Scale Out with Multiple Consumers
- Common Problems in Production
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps
- Official resources
Unlike pub/sub, a stream is an append-only log: it keeps your data until you trim it, and it tracks which messages each consumer group has acknowledged.

Before You Start
- Node.js 18 or newer (a current LTS release is best).
- Docker to run Redis locally, or any Redis server you can reach.
- Two or three terminal windows for the producer and consumers. The tutorial takes about 30 minutes.
- A test Redis, not your production one: the examples create a stream called
user_eventsand leave a failing message in it on purpose.
What You Will Build
redisClient.js– one shared connection used by both scripts.producer.js– adds five test events to theuser_eventsstream.consumer.js– joins a consumer group, processes and acknowledges events, and runs the crash-recovery loop.
Why Choose Redis Streams Over Pub/Sub
The guide to building a Redis Pub/Sub event broker in Node.js shows that Pub/Sub is fire-and-forget. If your Node.js process restarts because of a crash or a routine deploy, events sent in the meantime are lost.
Redis Streams keeps a history of messages instead. Three ideas make that work:
- Append-only log: every event gets a unique, timestamp-based ID and is stored in order.
- Consumer groups: several workers can join a group to share the work. Each message goes to only one worker in the group.
- Pending Entries List (PEL): Redis records which messages were delivered to a worker but not yet acknowledged. If a worker dies, you can find those messages here and hand them to another worker.
The Redis Streams documentation covers every command in detail.
Step 1: Set Up the Project and Redis
Run these commands in your terminal to create the project and install the official Node Redis client:
mkdir redis-streams-processor
cd redis-streams-processor
npm init -y
npm install redis dotenvCreate a file named redisClient.js. It manages one connection that the producer and consumer both import, so neither opens duplicates:
const { createClient } = require('redis');
require('dotenv').config();
const client = createClient({
url: process.env.REDIS_URL || 'redis://localhost:6379'
});
client.on('error', (err) => console.error('Redis Client Error', err));
async function connectRedis() {
if (!client.isOpen) {
await client.connect();
}
return client;
}
module.exports = { connectRedis, client };If you do not have Redis running, start it with Docker:
docker run --name local-redis -p 127.0.0.1:6379:6379 -d redisStep 2: Produce Events to the Stream
You add messages to a stream with the XADD command. Each message is a set of field-value pairs.
Create a file named producer.js. It simulates incoming webhooks, such as user signups or payment confirmations, by adding five events half a second apart:
const { connectRedis } = require('./redisClient');
async function publishEvent(streamName, eventData) {
const redis = await connectRedis();
try {
// "*" tells Redis to automatically generate a unique timestamp-based ID
const messageId = await redis.xAdd(streamName, '*', eventData);
console.log(`[Producer] Published event to ${streamName} with ID: ${messageId}`);
return messageId;
} catch (error) {
console.error('[Producer] Failed to publish event:', error);
}
}
async function run() {
const streamName = 'user_events';
for (let i = 1; i <= 5; i++) {
// Stream field values must be strings
await publishEvent(streamName, {
userId: `user_100${i}`,
action: 'signup'
});
await new Promise((resolve) => setTimeout(resolve, 500));
}
process.exit(0);
}
run();Run the producer in your terminal:
node producer.jsIt prints five lines like [Producer] Published event to user_events with ID: …. Each ID has two parts, such as 1715639120481-0: a Unix timestamp in milliseconds, then a counter for messages created in that same millisecond.
Step 3: Build a Consumer Group That Acknowledges Messages
A consumer group lets you run several consumer processes on one stream, and Redis delivers each message to only one of them. You create the group once with XGROUP CREATE. If it already exists, Redis returns a BUSYGROUP error, which the code below treats as fine.
Create a file named consumer.js:
const { connectRedis } = require('./redisClient');
const STREAM_NAME = 'user_events';
const GROUP_NAME = 'user_processor_group';
const CONSUMER_NAME = `worker_${process.pid}`;
async function initializeConsumerGroup(redis) {
try {
// MKSTREAM automatically creates the stream if it does not exist yet
await redis.xGroupCreate(STREAM_NAME, GROUP_NAME, '0', { MKSTREAM: true });
console.log(`[Consumer] Created consumer group: ${GROUP_NAME}`);
} catch (error) {
if (error.message.includes('BUSYGROUP')) {
console.log(`[Consumer] Consumer group ${GROUP_NAME} already exists.`);
} else {
throw error;
}
}
}
async function processMessage(messageId, fields) {
console.log(`[${CONSUMER_NAME}] Processing message ${messageId}:`, fields);
// Simulate processing time (e.g., sending an email, updating database)
await new Promise((resolve) => setTimeout(resolve, 300));
// Simulate a processing failure for testing
if (fields.userId === 'user_1003') {
throw new Error('Database timeout while saving user_1003');
}
}
async function startConsumer() {
const redis = await connectRedis();
await initializeConsumerGroup(redis);
console.log(`[${CONSUMER_NAME}] Started listening for events...`);
while (true) {
try {
// Read new messages that have not been delivered to anyone else
// ">" means only new messages
const response = await redis.xReadGroup(GROUP_NAME, CONSUMER_NAME, { key: STREAM_NAME, id: '>' }, {
COUNT: 1,
BLOCK: 2000 // Block for up to 2 seconds if no messages are available
});
if (!response || response.length === 0) {
continue;
}
const { messages } = response[0];
for (const message of messages) {
const { id, message: fields } = message;
try {
await processMessage(id, fields);
// Acknowledge the message so it is removed from the Pending Entries List
await redis.xAck(STREAM_NAME, GROUP_NAME, id);
console.log(`[${CONSUMER_NAME}] Successfully acknowledged message ${id}`);
} catch (processError) {
console.error(`[${CONSUMER_NAME}] Failed to process message ${id}:`, processError.message);
// We DO NOT acknowledge the message here. It remains in the PEL.
}
}
} catch (error) {
console.error('[Consumer] Error reading from stream:', error);
await new Promise((resolve) => setTimeout(resolve, 5000)); // Cool down
}
}
}
startConsumer().catch((error) => {
console.error('[Consumer] Fatal error:', error);
process.exit(1);
});The consumer only calls xAck after processMessage succeeds. A message that fails is not acknowledged, so it stays in the Pending Entries List instead of disappearing. To show this, the code fails on purpose for user_1003.
Test It: Process the Events and Find the Failed One
Start the consumer in a terminal:
node consumer.jsIt logs Created consumer group: user_processor_group, then processes the five events the producer added earlier, because the group was created from the start of the stream (ID 0). Four messages log Successfully acknowledged. The user_1003 message logs Failed to process message … Database timeout while saving user_1003.
Check that the failed message is still pending. In another terminal, run:
docker exec local-redis redis-cli xpending user_events user_processor_groupThe summary shows 1 pending message and the name of the consumer that holds it. The consumer keeps running and waits for new events; stop it with Ctrl+C.
Step 4: Claim Messages Stuck After a Crash
If a worker reads a message and then crashes, that message stays in the PEL indefinitely. No other worker receives it unless one claims it.
The fix is a recovery routine that runs on a timer. It lists pending messages with XPENDING, picks those idle for longer than 10 seconds, and takes them over with XCLAIM.
Add this function to consumer.js, above startConsumer(), so it can use the same constants and processMessage:
async function claimStuckMessages(redis) {
const MIN_IDLE_TIME = 10000; // 10 seconds in milliseconds
const BATCH_SIZE = 10;
try {
// Get pending messages for our group
const pendingInfo = await redis.xPendingRange(STREAM_NAME, GROUP_NAME, '-', '+', BATCH_SIZE);
if (pendingInfo.length === 0) {
return;
}
const messageIdsToClaim = [];
for (const item of pendingInfo) {
// item.millisecondsSinceLastDelivery tells us how long the message has been idle
if (item.millisecondsSinceLastDelivery > MIN_IDLE_TIME) {
messageIdsToClaim.push(item.id);
console.log(`[Recovery] Found stuck message ${item.id} (Idle for ${item.millisecondsSinceLastDelivery}ms)`);
}
}
if (messageIdsToClaim.length > 0) {
// Claim ownership of these messages for our current consumer
const claimedMessages = await redis.xClaim(STREAM_NAME, GROUP_NAME, CONSUMER_NAME, MIN_IDLE_TIME, messageIdsToClaim);
for (const message of claimedMessages) {
if (!message) continue; // The entry was deleted from the stream
console.log(`[Recovery] Claimed message ${message.id}. Retrying processing...`);
try {
// In a real app, you might want to track retry counts to avoid infinite loops
await processMessage(message.id, message.message);
await redis.xAck(STREAM_NAME, GROUP_NAME, message.id);
console.log(`[Recovery] Successfully processed and acknowledged claimed message ${message.id}`);
} catch (retryError) {
console.error(`[Recovery] Failed retry for message ${message.id}:`, retryError.message);
}
}
}
} catch (error) {
console.error('[Recovery] Error running auto-claim routine:', error);
}
}Then start it from inside startConsumer(). Add these lines right after await initializeConsumerGroup(redis); and before the while (true) loop:
// Add this inside startConsumer() right before the main while(true) loop
// A separate connection, so recovery commands do not wait behind the blocking XREADGROUP call
const recoveryClient = redis.duplicate();
recoveryClient.on('error', (err) => console.error('Redis Recovery Client Error', err));
await recoveryClient.connect();
setInterval(() => claimStuckMessages(recoveryClient), 15000); // Check every 15 secondsRestart the consumer. After about 15 seconds it logs [Recovery] Found stuck message … and Claimed message … Retrying processing.... Because this demo always fails user_1003, the retry fails too, and it will be claimed again on later checks. That endless loop is the poison-pill problem covered below.
Step 5: Scale Out with Multiple Consumers
Every consumer process that joins the group reads from the same stream, and Redis hands each new message to exactly one of them. To start three consumers from one terminal, run:
node consumer.js & node consumer.js & node consumer.jsEach process names itself after its process ID. Run the producer again in another terminal and you will see the three worker_… names share the new events. Because the consumers read with XREADGROUP and the > ID, Redis does the distribution; your code needs no extra coordination. Stop them with Ctrl+C, and if any keep running in the background, end them with kill and their process IDs.
If those events lead to calls to third-party APIs with strict limits, see how to handle external API rate limits with BullMQ and Redis.
Common Problems in Production
1. The stream keeps growing
By default, a stream keeps every message. If you process millions of events a day, memory use climbs until the server runs out. Trim the stream as you write by passing the MAXLEN option to XADD. In producer.js, change the xAdd call in publishEvent to this form (use the streamName variable there):
// Trim the stream to keep roughly the latest 10,000 events
await redis.xAdd(STREAM_NAME, '*', eventData, {
TRIM: {
strategy: 'MAXLEN',
strategyModifier: '~',
threshold: 10000
}
});The tilde (~) makes the limit approximate, so Redis only trims when it can drop a whole internal node. The stream may briefly hold a few more than 10,000 entries, but trimming stays cheap on every write.
2. Poison-pill messages loop forever
A message with bad data fails every time, so the recovery loop claims it, fails and repeats indefinitely. Check the delivery count that XPENDING returns (deliveriesCounter in node-redis). If a message has been delivered more than 5 times, copy it to a dead-letter list and acknowledge it so it leaves the pending list. The webhook retry system tutorial shows a simple dead-letter list in Redis.
If It Still Doesn’t Work
ECONNREFUSED 127.0.0.1:6379: Redis is not running. Start it withdocker start local-redis. If the error shows::1, setREDIS_URL=redis://127.0.0.1:6379in a.envfile.- A second run of the consumer processes nothing: the group already received those messages, and
>only returns new ones. Runnode producer.jsagain to add fresh events. NOGROUPerror while the consumer runs: the stream or group was deleted, for example byFLUSHALL. Restart the consumer so it creates them again.- The recovery loop never finds anything: messages are only claimed after 10 seconds idle and the check runs every 15 seconds. Wait at least 25 seconds after a failure.
Frequently Asked Questions
How does Redis Streams compare to RabbitMQ or Kafka?
Redis Streams is lighter and easier to run than Kafka or RabbitMQ. If you already use Redis for caching, you get a durable event log without running a new service. Kafka is the better fit for very high throughput and long-term log retention measured in days or weeks.
Can several different apps read the same stream?
Yes, give each app its own consumer group. For example, a billing_group and an analytics_group on the same stream each receive every message independently, and each keeps its own record of what it has acknowledged. Within one group, messages are split between that group’s workers.
What is the difference between Redis Streams and BullMQ?
BullMQ is a job queue library; Redis Streams is a raw event log. BullMQ is built on Redis lists and sorted sets (it uses Streams only for its event notifications) and gives you retries, delays and job dependencies out of the box. Use raw Streams for simple event processing and BullMQ for complex job management.
Next Steps
You now have a producer, a consumer group that acknowledges messages and a recovery loop for crashed workers. Before production, add the MAXLEN trim, a delivery-count limit with a dead-letter list, and logging for every claimed message. To see how this fits with signature checks, retries and rate limits, read the API integrations and webhooks guide.

