> ## Content Index
> Fetch the complete content index at: https://stalin-pereira.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Postgres as Your socket.io Scale-Out Bus, and Why It Needs Its Own Pool
- URL: https://stalin-pereira.com/postgres-as-your-socket-io-scale-out-bus-and-why-it-needs-its-own-pool/
- Published: 2026-11-09T08:30:00.000Z
- Updated: 2026-11-09T08:30:00.000Z
- Description: Fan out realtime events across server instances with Postgres LISTEN/NOTIFY instead of Redis, without letting the adapter break your pool sizing, your tests, or your large broadcasts.
- Author: Stalin Pereira
- Tags: Distributed Systems

The first time I ran a socket.io server as two instances behind a load balancer, nothing broke. That was the problem. No errors, no failed health checks, no red in the logs. Half the people watching a live dashboard simply stopped seeing updates, and from where they sat the screen looked exactly like a slow afternoon with nothing happening.

This post is about the fix I chose for that, which was to use Postgres as the message bus between instances instead of adding Redis, and about the two places where doing that naively will bite you.

## Why a second instance goes silent

socket.io keeps its rooms in process memory. When instance 1 calls `io.to(room).emit(...)`, it delivers to the sockets *it* holds in that room. A browser that happened to connect to instance 2 is in instance 2's copy of the room, and instance 1 has never heard of it.

So an update that lands on instance 1 reaches roughly half your viewers. Nothing throws, because from each process's point of view it did its job perfectly. You find out when a user says "live updates feel a bit patchy", which is about the least actionable bug report there is.

Sticky sessions don't solve this. They pin each *client* to one instance, which helps with the socket.io handshake, but the *event* can still originate anywhere: a write that comes in through an HTTP request on instance 1 still has to reach viewers pinned to instance 2\. You need a shared bus.

## The usual answer, and the one I used

The standard bus is Redis with `@socket.io/redis-adapter`. It works well. It is also another stateful service to run, monitor, secure and back up, and for an app doing a handful of events per second I didn't want one just for this.

Postgres already has a pub/sub mechanism: `LISTEN` and `NOTIFY`. Any connection can `LISTEN` on a channel, and any other connection can `NOTIFY` it with a small payload. `@socket.io/postgres-adapter` uses exactly that. Each instance keeps one connection listening; when it broadcasts, it also sends a `NOTIFY`, and every other instance picks it up and delivers to its own local sockets.

1. **Client A**makes a change
2. **Instance 1**emits to its own sockets, then sends NOTIFY
3. **Postgres**one channel, payload under \~8 KB (bigger ones spill to a table)
4. **Instance 2**hears it on its LISTEN connection
5. **Client B**gets the event

**App pool (per instance)**Request queries only. Sized for your concurrency, and every query is yours.

**Bus pool (per instance, max 2)**One connection held forever for LISTEN, plus the adapter's periodic cleanup query.

The event crosses instances through Postgres. The listening connection lives in its own tiny pool, not in the one your requests use.

Wiring it up is a few lines. The adapter takes a node-postgres pool. The interesting decision is *which* pool.

## Trap 1: don't hand it your app's pool

The obvious move is to pass in the pool your app already has. I didn't, for two reasons that both looked like unrelated bugs until I traced them.

**It permanently takes a connection.** The listening connection is checked out for the life of the process. If your pool has a max of 10, your requests now have 9, and nobody told your pool sizing. That matters if you've sized the pool deliberately, for example so a burst of concurrent requests that all race for the same row lock behaves predictably. One connection fewer changes the behaviour you tested.

**It runs queries you didn't write.** The adapter periodically deletes old spill rows (more on those below), on a timer around every 30 seconds. If you have any test that counts queries on your pool, say "loading this view must be exactly one query", that test now fails at random, about twice a minute, depending on whether the timer happened to fire during it. A flaky test that points at the view, when the view is fine, is an expensive afternoon.

Both go away with a separate, small pool:

```js
import pg from "pg";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/postgres-adapter";

// Your requests. Sized for your workload, and every query on it is yours.
const appPool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });

// The realtime bus. One LISTEN connection plus room for the cleanup query.
const busPool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
busPool.on("error", (err) => {
  // A dropped LISTEN means broadcasts stop crossing instances.
  // Log it loudly; don't crash. One instance serving its own clients
  // is a better failure than none.
  logger.error("realtime bus pool error", err);
});

const io = new Server(httpServer);
io.adapter(createAdapter(busPool));
```

The cost is one extra Postgres connection per instance. That's the honest price, and you should count it against your database's connection limit, especially if you scale instances up and down.

A related gotcha on shutdown: the adapter shares one listening connection across all socket.io namespaces and only releases it when the *last* namespace's adapter closes. socket.io always creates the default `/` namespace, even if you never use it. If your shutdown closes only your own namespace and then calls `busPool.end()`, that call waits for the borrowed connection forever, with no error. Close the server (or every namespace) first, then end the pool.

## Trap 2: the spill table must ship as a migration

A `NOTIFY` payload is capped at just under 8 KB. The adapter handles larger (or binary) payloads by writing them to a table and sending a pointer in the notification instead. That table has to exist.

The README shows the `CREATE TABLE`, and the tempting thing is to run it once by hand, or have the app create it on boot. Don't. If the table is missing, the app still boots, small events still flow, and every *large* broadcast quietly fails to reach other instances. That's the same invisible failure we started with, just narrower and harder to spot.

So it goes in your migrations like any other table, even though none of your code ever reads it:

```sql
-- Spill table for the socket.io Postgres adapter.
-- Not read by app code; the adapter writes and cleans it up.
CREATE TABLE socket_io_attachments (
  id         bigserial UNIQUE,
  created_at timestamptz DEFAULT now(),
  payload    bytea
);
```

Leave a comment saying whose table it is. Six months from now someone will see an unreferenced table and want to drop it.

## Prove it crosses

The failure is silent, so the test has to be explicit. Mine starts two server instances, each on its own port, pointed at the same database, connects a client to the second, triggers an event through the first, and asserts it arrives. Make sure nothing else can bridge them (an in-memory event bus, a shared process), or the test proves nothing. Then remove the adapter and confirm the test fails. I've written enough tests that pass for the wrong reason to not skip that step.

## When not to do this

- **High event volume.** NOTIFY traffic is per database, not per room. Every instance wakes for every broadcast and filters locally. At a few events per second that's nothing. At thousands per second you're putting a fan-out workload on your primary database, and Redis is the better tool.
- **You already run Redis.** Then the "no new infrastructure" argument is gone and the Redis adapter is the faster, more trodden path.
- **Events that must not be lost.** NOTIFY isn't durable. An instance that's restarting when a broadcast happens never sees it. That's fine if events are hints and clients refetch on reconnect (the approach I described in my post on having realtime events invalidate the cache rather than carry state). It's wrong if events are the source of truth.

Switching later is cheap either way: the adapter is one line, so this isn't a decision you're locked into.

## Takeaway

If you already run Postgres and your realtime traffic is modest, LISTEN/NOTIFY is a perfectly good bus between socket.io instances. Give it its own small pool so it can't distort your sizing or your query-count tests, ship its spill table as a real migration, and write the two-instance test, because when this breaks, nothing tells you.