Skip to content

feat: add Postgres bus driver - #125

Open
gkachru wants to merge 1 commit into
Julien-R44:mainfrom
gkachru:pr/postgres-bus
Open

gkachru wants to merge 1 commit into
Julien-R44:mainfrom
gkachru:pr/postgres-bus

Conversation

@gkachru

@gkachru gkachru commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Adds postgresBusDriver, a bus driver that uses Postgres LISTEN/NOTIFY, so apps that already run Postgres can sync their L1 caches without running Redis. It is exported from bentocache/drivers/postgres. pg and @types/pg are optional peer dependencies (pg ^8.0.3).

import { BentoCache, bentostore } from 'bentocache'
import { memoryDriver } from 'bentocache/drivers/memory'
import { postgresBusDriver } from 'bentocache/drivers/postgres'

const bento = new BentoCache({
  default: 'cache',
  stores: {
    cache: bentostore()
      .useL1Layer(memoryDriver({ maxSize: '10mb' }))
      .useBus(postgresBusDriver({ connection: process.env.DATABASE_URL! })),
  },
})

Why it lives in BentoCache and not in @boringnode/bus

A NOTIFY payload is text and must be under 8000 bytes, and every NOTIFY transaction costs Postgres a transaction id and a WAL record. To stay within those limits, the transport reads the CacheBusMessage it is given (type, namespace, keys):

  • It merges messages with the same channel, type and namespace into one, with duplicate keys removed, so a burst of writes becomes a few notifications in one transaction.
  • It splits a message with many keys across notifications and transactions. A single key too long for a notification becomes a clear of its namespace.
  • It uses a compact, versioned ASCII wire format for those fields.

A generic transport in @boringnode/bus only sees an opaque payload, so it could do none of this.

How it works

  • Two connections from one connection string: a listener and a publisher. Either is replaced on its own when it fails. It creates no table or other database object.
  • Each batch is sent in one transaction and one round trip, with synchronous_commit off. Messages published while a transaction runs go in the next one. batchDelay (default 0) trades write latency for fewer transactions.
  • Publishes wait for the first connection at startup. Later, they fail fast while the publisher is down, so the bus keeps them in its retry queue. disconnect() sends pending messages first.
  • An end-to-end heartbeat (every 30s by default, 15s timeout) replaces a listener that is still open but no longer receives notifications. That happens behind transaction-mode poolers, which accept LISTEN but never deliver, and when a load balancer or NAT silently drops an idle connection. Time the process was frozen doesn't count against it. The error links to a docs section on the usual causes, and the docs say when heartbeat: false is safe.
  • Errors go to onError. Without it, they are logged with console.error, each distinct message at most once a minute.
  • Destroys the socket of a connection a stalled server or proxy never closes, so it can't keep the process alive.
  • Names its sessions bentocache-bus:listener and bentocache-bus:publisher unless an application name is set.
  • Turns off idle_session_timeout on the listener with a plain SET.
  • Channel names that are too long or not ASCII are mapped to a hash.

Docs

multi_tier.md gets a Postgres bus section: options, what the connection must support (direct connections and session-mode poolers work; transaction-mode poolers don't, with the connection strings to use on Supabase, Neon, DigitalOcean and Azure), how it behaves, the heartbeat, and its effect on the rest of the database.

Tests

  • tests/bus/postgres_bus.spec.ts (42 tests) runs against the Postgres from the repo's compose file. It covers delivery, merging and splitting, reconnects after the server terminates either connection, a TCP proxy that freezes connections without closing them, startup and shutdown, and option validation.
  • tests/bus/postgres_encoding.spec.ts (21 tests) covers the wire format.
  • The bus tests also pass on pg 8.0.3, 8.4, 8.6, 8.7, 8.8, 8.11 and 8.23. Below 8.6, importing pg from ESM prints a harmless "Cannot find module 'pg-native'" message.
  • tsc, oxlint and oxfmt are clean.

I didn't open an issue first. If you'd rather discuss the design before reviewing, I'm happy to.

This PR was written with the help of AI.

@changeset-bot

changeset-bot Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 417f14d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
bentocache Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@gkachru gkachru closed this Nov 4, 2026
@gkachru gkachru reopened this Nov 4, 2026
Add postgresBusDriver, a bus driver that uses Postgres LISTEN/NOTIFY,
exported from bentocache/drivers/postgres. pg and @types/pg are
optional peer dependencies.

- Opens two connections from one connection string, a listener and a
  publisher. Either is replaced on its own when it fails. It creates no
  table or other database object.
- Sends each batch in one transaction and one round trip, with
  synchronous_commit off. Messages published while a transaction runs
  go in the next one, merged by channel, type and namespace with
  duplicate keys removed. batchDelay (default 0) trades write latency
  for fewer transactions.
- Splits large messages across notifications and transactions. A key
  too long for a notification becomes a clear of its namespace and is
  reported to onError.
- An end-to-end heartbeat (every 30s by default) replaces a listener
  that silently stops receiving notifications. Time the process was
  frozen doesn't count against it. Its error links to the docs on the
  usual causes.
- Errors go to onError. Without it, they are logged with console.error,
  each distinct message at most once a minute.
- Destroys the socket of a connection a stalled server doesn't close,
  so it can't keep the process alive. Names its sessions
  bentocache-bus:listener and :publisher unless an application name is
  set.
- At startup, publishes wait for the first connection. Later, they fail
  fast while the publisher is down, so the bus keeps them in its retry
  queue. disconnect() sends pending messages first.
- Versioned ASCII wire format whose fields are only appended. Channel
  names that are too long or not ASCII are mapped to a hash.
- Turns off idle_session_timeout on the listener with a plain SET,
  which poolers such as PgDog keep to that client.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant