2026-09-03 · 11 min
Redis Pub/Sub in Microservices: Event-Driven Architecture That Actually Holds Up in Production
Most teams reach for Kafka the moment someone says “event-driven architecture.” Then they spend two weeks setting up brokers, configuring ZooKeeper replacements, tuning retention policies — and the three microservices that actually need to talk to each other are still blocked. Redis Pub/Sub is already running in your stack. For a large class of real problems, it is enough.
This is not a comparison post. It is a practical guide to wiring Redis Pub/Sub into a microservice architecture, handling the parts that tutorials skip — reconnection logic, channel design, and the production trade-offs you will hit once load arrives.
When Redis Pub/Sub fits the problem
The constraint is non-negotiable: if a subscriber is not connected when a message is published, that message is gone. No persistence, no replay, no dead letter queue. Accept this early and design around it.
Where Pub/Sub earns its place:
- Cache invalidation broadcasts. One service updates a product record; it publishes to
catalog.product_updated; every other service holding a cached copy of that product drops it. A missed message means a briefly stale cache, not a corrupted order. - Real-time dashboard fanout. Operational metrics from the payment gateway office in Serpong Tech Park get pushed to a monitoring dashboard. Dropped events cause a gap in the graph, not a lost transaction.
- Saga coordination signals (with an idempotent design). One service signals completion; downstream services react. As long as you can re-query state from the source, a missed signal is just a delayed reaction.
Where it does not fit: order state machines, financial ledger events, anything where “I missed it” means “I am now inconsistent.” Use Redis Streams or Kafka for those.
Channel naming that does not rot
This decision compounds. Bad channel names become load-bearing strings that you cannot refactor without touching every subscriber.
Use the pattern {service}.{entity}.{event}:
orders.order.created
orders.order.status_changed
inventory.product.stock_updated
notifications.email.queued
A few rules:
- No entity IDs in channel names.
orders.order.12345.status_changedmeans every subscriber has to subscribe to a wildcard pattern (PSUBSCRIBE orders.order.*.status_changed) and then filter in application code. Put the ID in the payload. - Verb is past tense.
order.creatednotorder.create. Events describe what happened, not what to do. - Keep the service prefix. When you have 12 services and a new engineer joins,
product.updatedis ambiguous — is this from the catalog service, the inventory service, or the pricing service?catalog.product.updatedis not.
Node.js publisher: straightforward, until it is not
// src/messaging/publisher.ts
import Redis from "ioredis";
// Pub/Sub requires separate connections — a subscribed client
// cannot send regular commands on the same connection.
const publisher = new Redis({
host: process.env.REDIS_HOST ?? "localhost",
port: Number(process.env.REDIS_PORT ?? 6379),
password: process.env.REDIS_PASSWORD,
enableAutoPipelining: true,
maxRetriesPerRequest: 3,
});
publisher.on("error", (err) => {
// Do not crash the process on Redis errors.
// Log and let the retry logic handle reconnection.
console.error("[redis:publisher] connection error", err.message);
});
export interface DomainEvent<T = unknown> {
eventId: string;
eventType: string;
occurredAt: string; // ISO 8601
payload: T;
sourceService: string;
}
export async function publish<T>(
channel: string,
event: DomainEvent<T>
): Promise<void> {
const serialized = JSON.stringify(event);
await publisher.publish(channel, serialized);
}
The eventId field is critical. Subscribers should store processed event IDs (in Redis with a short TTL, or in their own DB) to achieve idempotency. Without it, a subscriber restart that replays any buffered state will process duplicate events.
// src/services/order.service.ts
import { publish } from "../messaging/publisher";
import { randomUUID } from "crypto";
export async function createOrder(dto: CreateOrderDto): Promise<Order> {
const order = await db.orders.create(dto);
// Publish after DB commit — never before.
// If publish fails, the order still exists; a background job
// can re-publish from the DB. If you publish before the commit
// and the commit fails, you have an event about a non-existent order.
await publish("orders.order.created", {
eventId: randomUUID(),
eventType: "orders.order.created",
occurredAt: new Date().toISOString(),
sourceService: "order-service",
payload: {
orderId: order.id,
customerId: order.customerId,
totalAmount: order.totalAmount,
currency: "IDR",
},
});
return order;
}
Publish after the DB commit. This is the single most important ordering rule in event-driven systems built on non-transactional message buses.
Subscriber: reconnection is not optional
ioredis handles reconnection automatically, but the subscription state does not survive a disconnect by default. You need to re-subscribe on reconnect.
// src/messaging/subscriber.ts
import Redis from "ioredis";
type MessageHandler = (channel: string, message: string) => void | Promise<void>;
const subscriptions = new Map<string, MessageHandler[]>();
const subscriber = new Redis({
host: process.env.REDIS_HOST ?? "localhost",
port: Number(process.env.REDIS_PORT ?? 6379),
password: process.env.REDIS_PASSWORD,
// ioredis will automatically re-subscribe to channels
// after reconnection when this is set:
autoResubscribe: true,
enableOfflineQueue: true,
});
subscriber.on("reconnecting", () => {
console.info("[redis:subscriber] reconnecting...");
});
subscriber.on("ready", () => {
console.info("[redis:subscriber] connection ready");
// With autoResubscribe: true, ioredis handles re-subscription.
// Log the current subscription state for debugging.
console.info(
`[redis:subscriber] tracking ${subscriptions.size} channel(s)`
);
});
subscriber.on("message", async (channel, message) => {
const handlers = subscriptions.get(channel) ?? [];
for (const handler of handlers) {
try {
await handler(channel, message);
} catch (err) {
// Isolate handler errors — one bad handler should not
// prevent others from processing the same message.
console.error(
`[redis:subscriber] handler error on channel ${channel}`,
err
);
}
}
});
export function subscribe(channel: string, handler: MessageHandler): void {
const existing = subscriptions.get(channel) ?? [];
subscriptions.set(channel, [...existing, handler]);
subscriber.subscribe(channel);
}
The autoResubscribe: true flag tells ioredis to replay your subscription commands after reconnection. Without it, a Redis restart means your subscriber silently stops receiving messages — no error, no warning, just silence.
Consuming events: parse defensively
Every subscriber should validate the message shape before acting on it. Messages arrive as raw strings. Network issues, bugs in other services, and schema changes will eventually send you malformed payloads.
// src/messaging/handlers/order-created.handler.ts
import { subscribe } from "../subscriber";
import { z } from "zod";
const OrderCreatedPayloadSchema = z.object({
orderId: z.string().uuid(),
customerId: z.string().uuid(),
totalAmount: z.number().positive(),
currency: z.literal("IDR"),
});
const DomainEventSchema = z.object({
eventId: z.string().uuid(),
eventType: z.string(),
occurredAt: z.string().datetime(),
sourceService: z.string(),
payload: OrderCreatedPayloadSchema,
});
subscribe("orders.order.created", async (_channel, raw) => {
let event: z.infer<typeof DomainEventSchema>;
try {
event = DomainEventSchema.parse(JSON.parse(raw));
} catch (err) {
// Bad message shape — log with the raw payload for debugging,
// but do not crash the subscriber.
console.error("[handler:order-created] invalid message", { raw, err });
return;
}
// Check idempotency — has this eventId been processed before?
const alreadyProcessed = await redis.get(`processed:${event.eventId}`);
if (alreadyProcessed) return;
// Process the event.
await notificationService.sendOrderConfirmation(event.payload.customerId, {
orderId: event.payload.orderId,
amount: event.payload.totalAmount,
});
// Mark as processed with a TTL long enough to cover subscriber downtime.
await redis.setex(`processed:${event.eventId}`, 86400, "1"); // 24 hours
});
The idempotency key with a 24-hour TTL is enough for the message-loss scenario. If a subscriber goes down for more than a day, you have a deeper operational problem than Redis Pub/Sub can solve.
Pattern subscriptions: use them sparingly
Redis supports PSUBSCRIBE with glob patterns. orders.* will match orders.order.created, orders.order.status_changed, and anything else under the orders.* namespace.
// Subscribe to all events from the orders service
subscriber.psubscribe("orders.*");
subscriber.on("pmessage", (_pattern, channel, message) => {
console.log(`[${channel}]`, message);
});
Pattern subscriptions are useful for logging, auditing, and monitoring services. They are a bad idea for services with business logic. If your handler is processing orders.* and someone adds orders.draft.created next month, your handler will receive it whether you intended it to or not. Prefer explicit channel subscriptions for anything with side effects.
Monitoring: what to watch
Once this is in production, three metrics matter:
Subscriber lag — Redis does not expose this natively for Pub/Sub the way Kafka does. Proxy it: timestamp every event at publish time, record the processing timestamp at the subscriber, and emit the delta as a metric. Spikes indicate that your subscriber is slower than the publish rate.
redis_connected_slaves / client count — If a subscriber disconnects and does not reconnect, you want an alert, not a silent gap in your audit trail. Monitor the number of subscribers on each critical channel with PUBSUB NUMSUB channel1 channel2.
Publish error rate — await publisher.publish(...) can fail if Redis is unreachable. Track this separately from your application error rate; a publish failure means a missed fanout, not a failed request.
What this is not a replacement for
Redis Pub/Sub with ioredis will comfortably handle tens of thousands of messages per second. It will not give you message replay, consumer groups, or the ability to ask “what events happened between 14:00 and 14:15 yesterday.”
If you need those, Redis Streams is the next step — same Redis, same operational overhead, much closer semantics to Kafka. For a small-to-medium microservice system, the progression is: Pub/Sub for cache invalidation and real-time fanout, Streams for anything requiring delivery guarantees, Kafka only when Streams hits its limits.
The mistake is not using Redis Pub/Sub. The mistake is using it for the wrong class of problems, discovering the limitation in production, and blaming the tool.
What to do right now
If you have microservices communicating via REST polling or shared database tables, the entry point is simple: pick one domain event — orders.order.created is usually the highest-value first target — wire a publisher and one subscriber, deploy it, and observe the behavior under your real traffic patterns.
Channel design and connection management are the two decisions that will cost you the most time later if you get them wrong early. Both are addressed above. Everything else is iteration.
Ditulis oleh Reza Pradipta