Pub/Sub, Fluxos e Limitação de Taxa com Redis
Transmita eventos, crie Redis Streams duráveis e implemente limitadores de taxa por balde de tokens atomicamente.
Pub/Sub, Fluxos e Limitação de Taxa com Redis é uma aula grátis de Node.js Backend Development Bootcamp no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Node.js Backend Development Bootcamp, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Node.js Backend Development Bootcamp inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Three Messaging Primitives in One Server
Redis is more than a key/value cache. In a Node.js backend it doubles as a lightweight message broker and a coordination engine. In this lesson you will learn three production patterns that ship with every Redis install:
- Pub/Sub — fire-and-forget broadcast to all connected listeners.
- Streams — an append-only, durable log with consumer groups and replay.
- Rate limiting — atomic counters that throttle abusive clients.
The key idea that ties them together: a single round-trip to Redis can do work that would otherwise need a database, a queue server, and a lock service. We will use the ioredis client throughout, which is the de-facto standard for Node backends because it supports pipelining, Lua scripting, and cluster mode.
Pub/Sub: Broadcast to Every Subscriber
Redis Pub/Sub lets one process PUBLISH a message to a channel and have every SUBSCRIBEd client receive it instantly. It is perfect for cache-invalidation fan-out or pushing live updates to WebSocket servers.
The critical gotcha: a connection in subscribe mode cannot run normal commands. You must create a dedicated subscriber connection separate from the one you use for GET/SET. Below, sub only listens; a second client would be used to publish.
const Redis = require('ioredis');
const sub = new Redis(); // dedicated subscriber connection
const pub = new Redis(); // separate connection for publishing
sub.subscribe('cache:invalidate', (err, count) => {
if (err) throw err;
console.log('Subscribed to ' + count + ' channel(s)');
});
sub.on('message', (channel, message) => {
console.log('[' + channel + '] ' + message);
});
// Another part of the app publishes an event
pub.publish('cache:invalidate', JSON.stringify({ key: 'user:42' }));Pattern Subscriptions and the Fire-and-Forget Caveat
Beyond exact channels, Redis supports PSUBSCRIBE with glob patterns. Subscribing to order:* receives messages from order:created, order:shipped, and so on. The callback is pmessage and includes the matched pattern.
The crucial limitation to internalize: Pub/Sub has no persistence. If no subscriber is connected when you publish, the message is gone forever — there is no buffering, no acknowledgement, no replay. If a subscriber crashes and reconnects, it misses everything that happened while it was down.
- Use Pub/Sub for ephemeral events where a missed message is acceptable.
- For events that must not be lost, you need Streams (next section).
const Redis = require('ioredis');
const sub = new Redis();
sub.psubscribe('order:*', (err, count) => {
console.log('Pattern subscriptions: ' + count);
});
sub.on('pmessage', (pattern, channel, message) => {
console.log('matched ' + pattern + ' on ' + channel + ': ' + message);
});Streams: A Durable, Replayable Log
A Redis Stream is an append-only log. Each entry gets a monotonically increasing ID like 1718000000000-0 (milliseconds-sequence). Unlike Pub/Sub, entries are stored until you trim them, so late or restarted consumers can replay history.
You append with XADD. The special ID * tells Redis to auto-generate the next ID. After the ID you pass field/value pairs, exactly like a hash.
const Redis = require('ioredis');
const redis = new Redis();
async function publishOrder() {
// XADD key * field value field value ...
const id = await redis.xadd(
'stream:orders', '*',
'orderId', '42',
'amount', '99.90',
'status', 'created'
);
console.log('Appended entry with ID ' + id);
// Read the latest 5 entries (newest last)
const entries = await redis.xrange('stream:orders', '-', '+', 'COUNT', 5);
console.log(JSON.stringify(entries, null, 2));
}
publishOrder();Consumer Groups: Scale Out Without Double-Processing
The real power of Streams is consumer groups. A group lets multiple worker processes share the load of one stream: each entry is delivered to exactly one consumer in the group, enabling horizontal scaling.
Create the group once with XGROUP CREATE. The MKSTREAM option creates the stream if it does not exist yet. The start ID $ means 'only deliver entries added after the group was created'; use 0 to consume from the very beginning.
const Redis = require('ioredis');
const redis = new Redis();
async function setup() {
try {
await redis.xgroup(
'CREATE', 'stream:orders', 'order-workers', '$', 'MKSTREAM'
);
console.log('Group created');
} catch (e) {
if (e.message.includes('BUSYGROUP')) {
console.log('Group already exists, continuing');
} else {
throw e;
}
}
}
setup();Reading and Acknowledging Stream Entries
Each worker reads with XREADGROUP, passing its group name and a unique consumer name. The special ID > means 'give me entries never delivered to any consumer in this group'.
An unacknowledged entry stays in the group's Pending Entries List (PEL). After you finish processing, you call XACK so Redis knows it is safely handled. If your worker crashes before XACK, the entry remains pending and can be reclaimed — this is what makes Streams at-least-once and durable.
const Redis = require('ioredis');
const redis = new Redis();
async function consume() {
const res = await redis.xreadgroup(
'GROUP', 'order-workers', 'worker-1',
'COUNT', 10, 'BLOCK', 5000,
'STREAMS', 'stream:orders', '>'
);
if (!res) return; // BLOCK timed out with no new entries
for (const [, entries] of res) {
for (const [id, fields] of entries) {
console.log('processing ' + id, fields);
// ... do real work here ...
await redis.xack('stream:orders', 'order-workers', id);
}
}
}
consume();Reclaiming Stuck Messages and Trimming
What if worker-1 dies mid-processing? Its entries stay in the PEL forever unless reclaimed. Use XAUTOCLAIM (Redis 6.2+) to transfer entries idle longer than a threshold to a healthy consumer:
XAUTOCLAIM stream group consumer min-idle-time start— grabs entries idle pastmin-idle-timems.- Inspect outstanding work with
XPENDINGbefore reclaiming.
Streams grow forever, so cap memory with capped XADD: XADD key MAXLEN ~ 10000 * .... The ~ means 'approximately', which lets Redis trim efficiently in whole macro-nodes instead of exact counts.
const Redis = require('ioredis');
const redis = new Redis();
async function recover() {
// Reclaim entries idle > 30s, hand them to worker-2
const [cursor, claimed] = await redis.xautoclaim(
'stream:orders', 'order-workers', 'worker-2',
30000, '0', 'COUNT', 25
);
console.log('Reclaimed ' + claimed.length + ' entries; next cursor ' + cursor);
// Append with an approximate cap to bound memory
await redis.xadd('stream:orders', 'MAXLEN', '~', 10000, '*', 'orderId', '99');
}
recover();Why Naive Rate Limiting Breaks
Switching gears to throttling. A first instinct is to GET a counter, check it in Node, then SET it back. This is a classic race condition: between your GET and SET, another concurrent request reads the same stale value, and both think they are under the limit. Under load you let through far more requests than allowed.
The fix is atomicity. Redis runs each command (and each Lua script) single-threaded and indivisibly. A simple fixed-window limiter uses INCR plus EXPIRE so the read-modify-write happens server-side with no gap. The pure-JS demo below shows the race conceptually before we move it into Redis.
// Demonstrates WHY check-then-set races. Two 'requests' interleave.
let counter = 0;
const LIMIT = 3;
function tryRequest(name) {
const current = counter; // read
if (current < LIMIT) {
// imagine an await here: another request runs before we write
counter = current + 1; // write (stale!)
return name + ': allowed (' + counter + ')';
}
return name + ': blocked';
}
// Both read 0 before either writes -> over-admission
const a = tryRequest('reqA');
const b = tryRequest('reqB');
console.log(a);
console.log(b);
console.log('Final counter: ' + counter);Fixed-Window Limiter with INCR + EXPIRE
The simplest correct limiter: key the counter by client + time window, INCR it, and set a TTL the first time the window opens. Because INCR returns the new value atomically, there is no race.
The weakness of fixed windows is boundary bursting: a client can send the full quota at 0:59 and again at 1:00, briefly doubling the rate. Acceptable for many APIs, but token buckets (next) smooth this out.
const Redis = require('ioredis');
const redis = new Redis();
async function allow(userId, limit = 100, windowSec = 60) {
const key = 'rl:' + userId + ':' + Math.floor(Date.now() / 1000 / windowSec);
const count = await redis.incr(key);
if (count === 1) {
await redis.expire(key, windowSec); // set TTL only on first hit
}
return count <= limit;
}
allow('user:42').then((ok) => {
console.log(ok ? 'request allowed' : '429 Too Many Requests');
});Atomic Token Bucket with a Lua Script
A token bucket gives each client a bucket of capacity C that refills at R tokens/second. Each request costs one token; if the bucket is empty, the request is rejected. It allows controlled bursts while enforcing a steady average rate.
Refill and consume must be one atomic step, so we ship them as a Lua script via EVAL. Redis runs the whole script without interleaving other commands. We store two fields in a hash — current tokens and last refill ts — and lazily compute how many tokens regenerated since the last call.
const Redis = require('ioredis');
const redis = new Redis();
const LUA = [
"local cap = tonumber(ARGV[1])",
"local refill = tonumber(ARGV[2])",
"local now = tonumber(ARGV[3])",
"local cost = tonumber(ARGV[4])",
"local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')",
"local tokens = tonumber(b[1])",
"local ts = tonumber(b[2])",
"if tokens == nil then tokens = cap; ts = now end",
"local delta = math.max(0, now - ts)",
"tokens = math.min(cap, tokens + delta * refill)",
"local allowed = 0",
"if tokens >= cost then allowed = 1; tokens = tokens - cost end",
"redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)",
"redis.call('EXPIRE', KEYS[1], 3600)",
"return allowed"
].join('\n');
async function take(userId) {
const now = Date.now() / 1000;
// capacity 10, refill 1 token/sec, cost 1
const allowed = await redis.eval(LUA, 1, 'tb:' + userId, 10, 1, now, 1);
return allowed === 1;
}
take('user:42').then((ok) => console.log(ok ? 'allowed' : 'throttled'));Wiring the Limiter into Express Middleware
In a real Node backend the limiter lives in middleware so every route is protected. On rejection you return HTTP 429 and, as a courtesy, a Retry-After header telling the client when to try again.
Best practices to remember:
- Key by a stable identity (API key or authenticated user id), not just IP — IPs are shared behind NAT.
- Fail open or closed deliberately: if Redis is unreachable, decide whether to allow traffic (availability) or block it (protection). Make it an explicit choice, not an accident.
- Return rate-limit headers so well-behaved clients can self-throttle.
function rateLimit(redis, take) {
return async (req, res, next) => {
const id = req.user?.id || req.ip;
try {
if (await take(id)) return next();
res.set('Retry-After', '1');
return res.status(429).json({ error: 'Too Many Requests' });
} catch (err) {
// Redis down: fail OPEN here (prioritize availability)
console.error('rate limiter degraded', err.message);
return next();
}
};
}
module.exports = { rateLimit };Quick Check: Choosing the Right Primitive
You are building an order-processing pipeline. Worker processes can crash and restart, and no order event may ever be lost; each event must be processed by exactly one of several workers, with crashed work automatically retried. Which Redis feature fits?
Recap: Pick the Tool That Matches the Guarantee
You now have three Redis messaging and control patterns and, more importantly, the judgment to choose between them:
- Pub/Sub — instant fan-out, but ephemeral. Use a dedicated subscriber connection. Great for cache invalidation and live notifications where a missed message is harmless.
- Streams — durable, replayable log. Consumer groups give exactly-one-of-N delivery;
XACKplus the Pending Entries List andXAUTOCLAIMgive at-least-once processing with crash recovery. Cap growth withMAXLEN ~. - Rate limiting — never check-then-set in app code; that races. Use atomic
INCR+EXPIREfor fixed windows, or anEVALLua token bucket for smooth bursts. Wrap it in middleware, return429withRetry-After, and decide consciously whether to fail open or closed.
The unifying principle: let Redis do the atomic work in a single round-trip, and choose the primitive by the durability guarantee your use case actually requires.
Perguntas Frequentes
A aula “Pub/Sub, Fluxos e Limitação de Taxa com Redis” é grátis?
Sim — o texto completo de “Pub/Sub, Fluxos e Limitação de Taxa com Redis” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Node.js Backend Development Bootcamp, atualize para CoddyKit PRO. O curso de Node.js Backend Development Bootcamp inclui 4 aulas no total.
O que vou aprender em “Pub/Sub, Fluxos e Limitação de Taxa com Redis”?
Transmita eventos, crie Redis Streams duráveis e implemente limitadores de taxa por balde de tokens atomicamente. Você pratica Node.js Backend Development Bootcamp com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Node.js Backend Development Bootcamp?
Nenhuma experiência prévia é necessária. Node.js Backend Development Bootcamp no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Pub/Sub, Fluxos e Limitação de Taxa com Redis”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Node.js Backend Development Bootcamp?
Sim. Cada aula de Node.js Backend Development Bootcamp inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Estratégias Cache-Aside, Write-Through e TTL
- Bloqueios Distribuídos e o Algoritmo Redlock
- Pub/Sub, Fluxos e Limitação de Taxa com Redis
- Prevenção de Avalanches de Cache e Rebanhos Ensurdecedores