Live Updates with tRPC SSE and Redis Pub/Sub
On this page
The goal
Ada has TaskBoard open in two tabs, or on her laptop and phone. She adds a task in one. The other should show it within a second, without polling.
The tRPC course built subscriptions over Server-Sent Events with an in-process EventEmitter. That works for one server. In production, the BFF runs several instances behind a load balancer, and the tab that creates a task and the tab that should see it are often connected to different instances.
The subscription procedure
The tasks team adds a subscription to its router:
onChanged: protectedProcedure
.input(z.object({ lastEventId: z.string().nullish() }).optional())
.subscription(async function* ({ ctx, signal }) {
for await (const [evt] of on(taskEvents.local, `user:${ctx.user.sub}`, { signal })) {
yield tracked(evt.id, evt);
}
}),It listens to a local event emitter, on a channel named after the user, so each subscriber only ever receives its own user's events. signal ends the loop when the tab disconnects, and tracked gives each event an id the browser remembers.
Fan-out through Redis
The local emitter is fed by Redis pub/sub. Every BFF instance subscribes to one Redis channel, and every publish reaches every instance:
// packages/bff/src/events.ts
const local = new EventEmitter();
local.setMaxListeners(0); // one listener per open tab is expected
const sub = new Redis(REDIS_URL); // a subscribing connection can't run other commands
sub.subscribe('task-events');
sub.on('message', (_channel, raw) => {
const { user, evt } = JSON.parse(raw);
local.emit(`user:${user}`, evt); // hand it to this instance's subscribers for that user
});
export const taskEvents = {
local,
async publish(user: string, evt: { type: string; task: unknown }) {
const id = `${Date.now()}-${process.pid}-${++seq}`;
await redis.publish('task-events', JSON.stringify({ user, evt: { id, ...evt } }));
},
};Two Redis connections are needed: once a connection subscribes, Redis allows it only pub/sub commands, so publishing and the session store use the other one.
The create mutation publishes after the tasks API confirms the save (Day 4). Publishing happens through Redis even on the instance that handled the mutation, so every instance, including its own, receives events by exactly one path.
The client side
The tasks micro-frontend subscribes and simply invalidates its list when anything arrives:
const live = useSubscription(trpc.tasks.onChanged.subscriptionOptions(undefined, {
onData: () => queryClient.invalidateQueries({ queryKey: trpc.tasks.list.queryKey() }),
}));The event says *something changed*, and the normal query fetches the truth from the tasks API. That keeps the event small and avoids two sources of truth on the client.
Authentication needs no extra work. The subscription is a same-origin GET, so the browser sends the session cookie, and createContext finds the session exactly as for a query. That's simpler than the connectionParams approach the tRPC course needed for token-based auth.
Proof across instances
The end-to-end test ran two BFF instances, on ports 5200 and 5201, sharing one Redis. Browsers don't scope cookies by port, so one sign-in covered both. The first tab used instance 5200; a second tab opened instance 5201 and waited for its subscription to connect:
tab on 5200: adds "Seen on instance two"
tab on 5201, live: [ '[ ] Wire up tRPC', '[ ] Seen on instance two' ]The mutation ran on 5200, Redis carried the event, and 5201 pushed it down the second tab's open stream.
The same test first failed in an instructive way: the second instance answered every call with a 500. Each instance had generated its own random key for encrypting tokens in Redis (the BFF course's AES-GCM seal), so instance 5201 couldn't decrypt sessions written by 5200. Every instance must share the same TOKEN_KEY, loaded from your secret store. Day 9 adds that to the deploy checklist.
What pub/sub doesn't give you
Redis pub/sub is fire and forget. A tab that's disconnected while an event is published never receives it. For TaskBoard that's acceptable: when the tab reconnects, its tasks.list query refetches and shows everything anyway.
If missed events matter, for a chat or an audit feed, use something that keeps history, like Redis Streams or a table of events, and replay from the lastEventId the browser sends on reconnect, as the tRPC course showed.
Keep subscriptions read-only. Day 3's CSRF rule only exempts event-stream GET requests because starting a subscription never changes anything.
Load to plan for
Each open tab holds one SSE connection to some BFF instance. A thousand users with two tabs each is two thousand long-lived connections. Plan for it:
- Set
sse.maxDurationMs(five minutes here) so connections recycle and spread across instances after deploys. - Enable
sse.ping(every 15 seconds here) so idle proxies don't cut quiet streams. - Check your load balancer's idle timeout and maximum connection count.
Check yourself
An EventEmitter lives inside one Node process, so an event emitted on the instance that handled the mutation only reaches tabs connected to that same instance. Behind a load balancer, most other tabs are on other instances and never hear it. Redis pub/sub delivers every event to every instance, which then hands it to its own subscribers.
The subscription is a same-origin GET to /trpc, so the browser attaches the session cookie automatically. The BFF's createContext reads the cookie and loads the session from Redis exactly as it does for a query, so protectedProcedure works unchanged. No token or parameter has to appear in the URL.
Each instance had its own random token encryption key, so one couldn't decrypt sessions written by the other. All instances must share the same key.
Once a Redis connection runs SUBSCRIBE, Redis only allows pub/sub commands on it. Session reads, profile writes and publishing need a normal connection, so the BFF keeps one of each.
Yes. Redis pub/sub doesn't keep history, so the tab misses those events, but when it reconnects its tasks.list query refetches and shows everything. If missed events themselves mattered, you'd use a store with history, such as Redis Streams, and replay from lastEventId.