Scale across nodes with PostgreSQL
If your app already runs on PostgreSQL, a group of Cabby nodes can share everything through it,
without Redis or NATS to run. Postgres can do three jobs, and you pick each one separately:
pub/sub between the nodes, a broker that keeps stream history and sessions for all of them, and a
broadcast adapter that lets your app broadcast by inserting a row, inside its own transactions.
All three connect to the database in --postgres_url.
If you'd rather use Redis or NATS, the Redis guide and the NATS guide cover them.
Turn it on
Run every node with the same URL.
--pubsub=postgrescarries broadcasts between the nodes, so a broadcast received by one node reaches the clients of all of them.--broker=postgreskeeps stream history and sessions in Postgres. A client that reconnects to any node catches up on what it missed and gets its session back. It doesn't pick a pub/sub adapter, so keep--pubsub=postgresnext to it.--broadcast_adapter=postgrestakes broadcasts from a table your app inserts into. Withhttp,postgres, your app can keep broadcasting over HTTP as well.
The URL starts with postgres:// or postgresql://. A key/value connection string such as
host=db.internal dbname=app user=cabby works too. You can set it as CABBY_POSTGRES_URL
instead, or in the configuration file:
# cabby.toml
pubsub_adapter = "postgres"
broadcast_adapters = ["http", "postgres"]
[broker]
adapter = "postgres"
[postgres]
url = "postgres://cabby:secret@db.internal:5432/app"
Without a URL, Cabby stops at startup and names the adapter that needs one. The --postgres_*
settings are Cabby's own, so their environment variables have CABBY_POSTGRES_* names only.
History is kept within --history_limit and --history_ttl, and sessions within
--sessions_ttl, as with the other brokers. Configuration lists them.
Broadcasting from a transaction
With --broadcast_adapter=postgres, your app broadcasts by inserting a row into
cabby_broadcasts. Do it in the transaction that changes your data, and the two can't disagree:
BEGIN;
INSERT INTO messages (room_id, body) VALUES (42, 'hello');
INSERT INTO cabby_broadcasts (payload)
VALUES ('{"stream":"chat_42","data":"{\"text\":\"hello\"}"}');
COMMIT;
payload is the JSON you'd send as an HTTP broadcast: a stream, the data as a JSON string
and an optional meta, or an array of such messages. When the transaction commits, one node
picks the row up, passes it through the broker and on to every node, and deletes it. Rows go out
in the order of their id. If the transaction rolls back, nothing is broadcast.
Your framework's AnyCable integration doesn't write to this table, so its broadcasts keep going over HTTP. The insert is for the broadcasts you want tied to a transaction, from any language that can run SQL.
Delivery is at least once. Cabby deletes a row only when the broker has taken it. If a node crashes or loses its connection in between, the row is still there and goes out again, so once in a while clients get the same message twice. Put an ID in the message, so that a client can skip one it has already handled. When the broker can't take a row, for example because Postgres went away for a moment, the row stays and Cabby retries until it goes through. Only a row that isn't a valid broadcast, or that the Postgres broker can't store, is dropped: Cabby logs it and deletes it.
For messages that need neither history nor a transaction, such as a typing indicator, there's a shortcut:
SELECT pg_notify('cabby_internal_in', '{"stream":"chat_42","data":"{\"text\":\"typing\"}"}');
Every node delivers it to its own clients right away. It isn't stored in history, and it has to fit in a notification, which holds less than 8000 bytes.
| How a broadcast arrives | Delivered live | Stored in history |
|---|---|---|
http |
Yes | Yes |
A row in cabby_broadcasts |
Yes | Yes |
pg_notify on cabby_internal_in |
Yes | No |
Setting up Postgres
Tables. At its first start, Cabby creates everything it needs, so there's no migration to run. Nodes that start together don't get in each other's way.
| Table | What it holds |
|---|---|
cabby_broadcasts |
The rows your app inserts, until they're broadcast |
cabby_streams, cabby_history, cabby_sessions, cabby_meta |
The broker's offsets, history, sessions and epoch |
cabby_pubsub_overflow |
Pub/sub messages too large for a notification, for 60 seconds |
Cabby also puts a trigger on cabby_broadcasts, named cabby_broadcasts_notify like the
function it calls, so the nodes hear about a new row at once. Everything goes in the public
schema. --postgres_schema picks another one, which Cabby creates if it's missing, and
--postgres_table_prefix replaces cabby_. To run two separate groups of Cabby nodes on one
database, give each group its own schema or prefix, and its own --postgres_channel, which is
cabby_internal by default.
The role. The role in the URL has to be able to create those tables. The quickest way is to
give Cabby the role your app connects with: the tables land next to yours, and the app can insert
into cabby_broadcasts right away. To keep Cabby apart, give it a role and a schema of its own,
then let your app's role insert broadcasts:
CREATE ROLE cabby LOGIN PASSWORD 'secret';
AUTHORIZATION cabby;
-- After Cabby's first start with --postgres_schema=cabby:
USAGE ON SCHEMA cabby TO app;
INSERT ON cabby.cabby_broadcasts TO app;
USAGE ON SEQUENCE cabby.cabby_broadcasts_id_seq TO app;
The app then inserts into cabby.cabby_broadcasts. A schema of its own also keeps Cabby's tables
out of your app's schema dump, such as db/schema.rb in Rails.
If the role can't create tables, set --postgres_auto_migrate=false and create them
beforehand with the SQL in the
Cabby repository.
Cabby then only checks that they exist, and stops at startup if one is missing:
failed to start subscriber, cause: failed to prepare the Postgres schema, cause: table public.cabby_pubsub_overflow is missing: create it with the DDL in docs/postgres.md or set --postgres_auto_migrate=true
On tables it didn't create, Cabby's role needs SELECT, INSERT, UPDATE and DELETE, and
USAGE on their sequences.
Connections. Point Cabby at Postgres itself, or at a PgBouncer pool in session mode. Cabby
listens for notifications on a long-lived connection, and PgBouncer's transaction mode breaks
that. With all three adapters, a node keeps up to 11 connections open (pub/sub opens one of them
when it first deletes expired rows from cabby_pubsub_overflow), so count them in
max_connections. In pg_stat_activity, their application_name starts with cabby. Cabby
needs PostgreSQL 12 or newer.
After a database crash. Every table but cabby_broadcasts is UNLOGGED by default. That
makes writes cheaper, and it means PostgreSQL empties those tables when it recovers from a crash
and doesn't copy them to replicas. A clean restart keeps them. So after a crash, or a failover to
a replica, history and sessions are gone and Cabby starts a new epoch. Reconnecting clients notice
and resync cleanly, exactly as after a restart with the in-memory broker. They never skip a
message silently. Rows waiting in cabby_broadcasts survive, because that table is a regular
one. To get regular tables everywhere, set --postgres_unlogged=false before Cabby creates them.
TLS
Cabby reads sslmode from the URL:
sslmode |
TLS | Certificate check |
|---|---|---|
disable |
No | None |
prefer (the default) |
If the server offers it | Chain and host name |
require |
Yes | Chain and host name |
verify-ca |
Yes | Chain only |
verify-full |
Yes | Chain and host name |
Whenever Cabby uses TLS, it checks the server's certificate, with prefer and require too. A
certificate that doesn't pass is a connection error: Cabby never falls back to an unencrypted
connection.
The certificate has to be signed by a CA your system trusts, and sslrootcert=system in the URL
says so explicitly. Managed Postgres services often sign theirs with a CA of their own. Download
that CA's certificate and name the file in sslrootcert, or in --postgres_tls_ca_cert_path:
Without it, Cabby stops at startup with invalid peer certificate: UnknownIssuer in the error.
On a network you trust, --postgres_tls_verify=false turns the check off for prefer and
require.
Limits
- No presence. Presence commands get an error, Pusher
presence-channels can't be subscribed to, and the users endpoints of the API and of the Pusher REST API answer501. If you need presence, use the in-memory broker on a single node. - Large messages take a detour. A Postgres notification holds less than 8000 bytes. When a
message between nodes is larger than 7500 bytes, Cabby stores it in
cabby_pubsub_overflowfor 60 seconds, and the other nodes read it from there. You don't have to do anything, and a broadcast over HTTP or throughcabby_broadcastscan be larger than a notification. Each one costs an extra write and an extra read per node, though, so keep the messages you send often small. A node that falls more than 60 seconds behind skips such a message and logs a warning. - Postgres has to be reachable. Cabby connects at startup and stops if it can't. If a connection drops later, Cabby reconnects by itself, waiting at most 30 seconds between attempts. Until then, the broker can't store anything, so a broadcast over HTTP fails with an error and isn't delivered, and a node misses what the other nodes publish. Clients catch up from history when they reconnect.
Logs and metrics
At startup, each adapter says what it uses. These lines and Cabby's errors name the host, the port and the database, never the password:
INF Using Postgres broker: db.internal:5432/app (history limit: 100, history ttl: 300s, sessions ttl: 300s)
INF Starting Postgres pub/sub: db.internal:5432/app (channel: cabby_internal, table: public.cabby_pubsub_overflow) context=pubsub provider=postgres
INF Postgres broker is ready (schema: public, table prefix: cabby_) context=broker provider=postgres epoch=Xm7H
INF Starting Postgres broadcaster: db.internal:5432/app (table: public.cabby_broadcasts, channel: cabby_internal_in) context=broadcast provider=postgres
When a connection drops, the log has LISTEN connection lost, reconnecting, then
LISTEN connection restored. After a database crash, each node logs epoch updated.
| Metric | Meaning |
|---|---|
postgres_errors_total |
Failed operations: queries, publications, lost connections |
postgres_query_ms |
How long the most recent operation took, in milliseconds |
postgres_reconnects_total |
Listening connections opened again after a lost one |
postgres_claimed_broadcasts_total |
Rows from cabby_broadcasts handed to the broker |
postgres_broadcast_retries_total |
Rows tried again because the broker couldn't take them |
postgres_spillover_total |
Messages between nodes that went through cabby_pubsub_overflow |
postgres_dropped_total |
Received messages a node dropped because it couldn't keep up |