Message broker
RasterizedDB has a message broker built in: durable topics, work queues, consumer groups, pub/sub and routing exchanges, stored beside the database's tables. Use it when your application needs messaging and you would rather not run Kafka, RabbitMQ or an MQTT broker next to the database. Existing Kafka, AMQP 0-9-1 and MQTT clients connect to it unchanged, and BROKER … statements reach the same broker from SQL.
The broker costs nothing until you use it. Nothing is opened or started until one of its port flags is given, or until a BROKER statement first needs it.
Ways to connect
| Flag | Protocol | Clients |
|---|---|---|
--broker-port / --broker-socket | native (rdbmq/1) | the Rust client's broker API (Rust client: broker) |
--kafka-port | Kafka | librdkafka, the Java client, franz-go, kcat, … |
--amqp-port | AMQP 0-9-1 | RabbitMQ clients: pika, amqplib, lapin, the Java and .NET clients |
--mqtt-port | MQTT 3.1.1 and 5.0 | mosquitto clients, paho, rumqtt, … |
| any SQL connection | BROKER … statements | psql, any driver |
Each port is closed unless you give its flag. The native protocol is the fastest: messages are stored in exactly the format a native producer sends and a native consumer receives. The Kafka, AMQP and MQTT ports translate at their edge, so they cost a little more.
The broker's ports serve the default database (--pg-default-db). Each database has a broker of its own, which BROKER statements reach when you are connected to it.
Quick start
Start the server with the ports you want:
RASTERIZEDDB_PG_PASSWORD=secret rasterizeddb \
--location /var/lib/rasterizeddb \
--protocol pgwire \
--broker-port 7171 \
--kafka-port 9092 \
--amqp-port 5672 \
--mqtt-port 1883Then, from psql, make a topic, write to it and read it back:
BROKER CREATE TOPIC orders PARTITIONS 4;
BROKER PUBLISH orders '{"id": 1, "total": 42}' KEY 'customer-7';
BROKER READ orders FROM EARLIEST LIMIT 10;READ returns one row per message, with the columns partition, offset, time_us (microseconds since the epoch), key, value and headers. The key customer-7 is hashed to choose one of the four partitions, so every message with that key lands in the same partition, in order.
Concepts
- Topic. A named set of partitions. Each partition is an append-only log, and every message in it has a 64-bit offset. Messages are kept until retention removes them (by age, size or both), whether or not anyone has read them.
- Subscription. A named reader of one topic, in one of three modes:
ordered: one committed offset per partition, with the partitions shared out among the group's members. This is a Kafka consumer group: order holds within a partition.shared: competing consumers that ack each message. A message goes to one consumer and is redelivered on a nack, on an ack timeout, or when its consumer disconnects. AfterMAX DELIVERIESattempts it moves to a dead-letter topic (or is dropped if none is set). This is a work queue.broadcast: each connection gets its own in-memory cursor starting at the tail. This is plain pub/sub. A broadcast subscription belongs to a connection, so it is made over a broker port, not from SQL.
- Queue. A one-partition topic with a
sharedsubscription of the same name. AMQP's queues are exactly this. - Exchange. A named routing table that sends a published message to one or more topics or queues by its routing key or headers.
| Pattern | How |
|---|---|
| 1 → 1 queue | a queue, one consumer |
| N → M work queue | a queue (or a topic with a shared subscription), M consumers |
| 1 → N fan-out | one topic, N subscriptions (each sees every message) |
| N → M ordered stream | P partitions and an ordered subscription, at most P active members |
| pub/sub | a topic with broadcast subscriptions, or a memory topic |
| routing | an exchange bound to several topics |
Delivery is at least once. After a restart nothing is in flight, and anything not acked is delivered again.
Durability
Each topic or queue has a durability:
DURABILITY | A write is acknowledged when | Survives |
|---|---|---|
sync (default) | it is synced to disk. One sync covers every write that arrived since the last, across all connections. | power loss |
async | it is in the operating system's page cache. A flusher syncs every --broker-flush-ms (default 10 ms). | a process crash; loses up to the flush interval on power loss |
memory | it is in an in-memory ring buffer | nothing: never written to disk |
Server flags
Broker and native protocol
| Flag | Default | What it does |
|---|---|---|
--broker-port PORT | closed | Serve the native protocol on this TCP port (7171 is the usual choice). |
--broker-socket PATH | none | Serve the native protocol on a unix socket, beside --broker-port or instead of it. Permissions and group come from --socket-mode and --socket-group. |
--broker-addr IP | 127.0.0.1 | Address the broker's ports listen on. The Kafka, AMQP and MQTT ports use it too unless given their own. |
--broker-auth password|trust | password | password checks clients against the database's roles. trust asks for nothing and is refused on anything but loopback. |
--broker-tls on|off | off | TLS on --broker-port, with the PostgreSQL port's certificate (--pg-cert/--pg-key, or a self-signed pair made at start). Needs --broker-port; the unix socket is always plain. |
--broker-threads N | one per CPU | I/O threads for the broker's ports (Kafka, AMQP and MQTT included). |
--broker-flush-ms MS | 10 | Milliseconds between syncs of async topics. |
--broker-ddl any|superuser | any | Who may create, alter and drop topics, queues, exchanges, subscriptions and bindings: any role that logged in, or only superusers. |
Kafka
| Flag | Default | What it does |
|---|---|---|
--kafka-port PORT | closed | Serve the Kafka protocol on this port (9092 is Kafka's own). |
--kafka-addr ADDR | --broker-addr | Address the Kafka port listens on. |
--kafka-advertised-host HOST | the listen address | The host Kafka clients are told to connect to. Required when the listen address is a wildcard such as 0.0.0.0. |
--kafka-advertised-port PORT | the listen port | The port clients are told, when a proxy or NAT puts them on another. |
--kafka-auth sasl|trust | sasl | sasl is SASL PLAIN against the database's roles. trust asks for nothing, loopback only. |
--kafka-tls on|off | off | TLS on the Kafka port (SSL / SASL_SSL to a client), with the PostgreSQL port's certificate. Without it, SASL PLAIN passwords cross the network in clear text; the server logs a warning when that happens off loopback. |
--kafka-auto-create true|false | true | Create a topic the first time a client names it, like Kafka's auto.create.topics.enable. |
--kafka-default-partitions N | 1 | Partitions of a topic created that way. |
AMQP 0-9-1
| Flag | Default | What it does |
|---|---|---|
--amqp-port PORT | closed | Serve AMQP 0-9-1 on this port (5672 is RabbitMQ's). |
--amqp-addr ADDR | --broker-addr | Address the AMQP port listens on. |
--amqp-auth password|trust | password | password is PLAIN/AMQPLAIN against the database's roles. trust is loopback only. |
--amqp-tls on|off | off | TLS on the AMQP port (amqps://), with the PostgreSQL port's certificate. |
--amqp-heartbeat SECONDS | 60 | The heartbeat the server proposes; 0 turns heartbeats off. |
--amqp-consumer-timeout-ms MS | 1800000 | How long a delivered message may stay unacked before another consumer gets it, like RabbitMQ's consumer_timeout. A queue's x-consumer-timeout overrides it. |
MQTT
| Flag | Default | What it does |
|---|---|---|
--mqtt-port PORT | closed | Serve MQTT 3.1.1 and 5.0 on this port (1883 is usual; 8883 with TLS). |
--mqtt-addr ADDR | --broker-addr | Address the MQTT port listens on. |
--mqtt-auth password|trust | password | password checks CONNECT's user name and password against the database's roles. trust is loopback only. |
--mqtt-tls on|off | off | TLS on the MQTT port, with the PostgreSQL port's certificate. |
--mqtt-durability sync|async | async | How persistent sessions' messages are synced: async (synced every --broker-flush-ms) or sync (QoS 1 and 2 acknowledged once synced). |
--mqtt-max-packet BYTES | 16777216 | The largest packet accepted. |
The broker from SQL
BROKER statements work on any SQL connection, whether or not a broker port is open. Arguments are bare words or single-quoted strings ('' for a quote inside one), and any argument can be hex bytes written x'…'. Names are taken as written: case and dots are kept.
A BROKER statement takes effect when it runs. It is not part of the surrounding SQL transaction, and ROLLBACK does not undo it.
Topics
BROKER CREATE TOPIC orders PARTITIONS 8 DURABILITY sync RETENTION '7d';
BROKER CREATE TOPIC IF NOT EXISTS clicks PARTITIONS 4 DURABILITY async RETENTION BYTES '10gb';
BROKER CREATE TOPIC ticks DURABILITY memory MEMORY BYTES '128mb';
BROKER ALTER TOPIC orders SET RETENTION '30d' RETENTION BYTES '50gb';
BROKER DROP TOPIC IF EXISTS clicks;CREATE TOPIC returns the topic's name, id and partitions.
| Option | Default | Meaning |
|---|---|---|
PARTITIONS n | 1 | Number of partitions. Set at creation. |
DURABILITY sync|async|memory | sync | See Durability. |
RETENTION duration | '7d' | How long messages are kept. FOREVER (or -1) keeps them. |
RETENTION BYTES size | unlimited | The most each partition keeps. -1 is unlimited. |
SEGMENT BYTES size | '256mb' | Size at which a new segment file is started. Retention removes whole segments. |
MAX BATCH size | '16mb' | The largest batch a producer may send. |
MEMORY BYTES size | '64mb' | The ring buffer of a memory topic. |
Durations are '7d', '12h', '30m', '45s', '500ms' or a bare number of milliseconds. Sizes are '512kb', '512mb', '4gb', '1tb' or a number of bytes. ALTER TOPIC … SET takes RETENTION, RETENTION BYTES, MAX BATCH and SEGMENT BYTES.
Queues
BROKER CREATE QUEUE jobs MAX DELIVERIES 5 DEAD LETTER jobs_dead ACK TIMEOUT '60s';
BROKER CREATE QUEUE IF NOT EXISTS emails DURABILITY async TTL '1h' MAX LENGTH 100000;
BROKER DROP QUEUE jobs;| Option | Default | Meaning |
|---|---|---|
DURABILITY sync|async|memory | sync | See Durability. |
ACK TIMEOUT duration | '30s' | How long a consumer may hold a message unacked before it is redelivered. |
MAX DELIVERIES n | 0 (unlimited) | Attempts before a message is dead-lettered. |
DEAD LETTER name | none | The topic or queue that receives messages that ran out of attempts. Without one they are dropped. |
TTL duration | none | How long a message waits in the queue. |
MAX LENGTH n | none | The most messages the queue holds. |
Subscriptions
BROKER CREATE SUBSCRIPTION billing ON orders MODE ordered FROM EARLIEST;
BROKER CREATE SUBSCRIPTION workers ON orders MODE shared ACK TIMEOUT '2m' MAX DELIVERIES 3 DEAD LETTER orders_dead;
BROKER DROP SUBSCRIPTION IF EXISTS workers ON orders;| Option | Default | Meaning |
|---|---|---|
MODE ordered|shared | shared | See Concepts. broadcast is refused from SQL. |
FROM EARLIEST|LATEST|offset|TIME µs | EARLIEST | Where a new subscription starts: the oldest message kept, the tail, an offset, or a time in microseconds since the epoch. |
ACK TIMEOUT duration | '30s' | As for queues. |
MAX DELIVERIES n | 0 (unlimited) | As for queues. |
DEAD LETTER topic | none | As for queues. |
Exchanges and bindings
BROKER CREATE EXCHANGE events TYPE topic;
BROKER CREATE EXCHANGE audit TYPE fanout ALTERNATE unrouted;
BROKER BIND events TO orders KEY 'order.*';
BROKER BIND events TO everything KEY '#';
BROKER CREATE EXCHANGE by_region TYPE headers;
BROKER BIND by_region TO eu_orders MATCH ALL HEADER 'region' 'eu';
BROKER UNBIND events FROM everything KEY '#';
BROKER DROP EXCHANGE audit;TYPE | A message goes to every topic bound with… |
|---|---|
direct (default) | a key equal to the routing key |
fanout | any key (every binding) |
topic | a matching pattern: words split on ., * matches one word and # matches zero or more |
headers | MATCH ALL or MATCH ANY of the binding's HEADER name value pairs |
ALTERNATE name sends messages that match no binding to another exchange. TRANSIENT makes an exchange that is not kept across restarts. A message that matches several bindings to one topic is written to it once. A message that matches nothing, with no alternate, is dropped.
The built-in exchanges amq.direct, amq.fanout, amq.topic, amq.headers, amq.match and amq.mqtt always exist and cannot be dropped.
Publish
-- straight to a topic or queue; the key picks the partition
BROKER PUBLISH orders '{"id": 2}' KEY 'customer-9' HEADER 'trace' 'a1b2';
BROKER PUBLISH orders '{"id": 3}' PARTITION 0;
BROKER PUBLISH jobs 'resize image 77';
-- through an exchange, with a routing key
BROKER SEND events 'order.created' '{"id": 2}';The value comes first, then any of KEY k, PARTITION n and HEADER name value (repeatable). PUBLISH returns the topic, partition and offset the message was written at; SEND returns one such row for each topic the exchange delivered to.
Read and take
-- look without consuming: leaves no trace
BROKER READ orders PARTITION 0 FROM 100 LIMIT 10;
BROKER READ orders FROM TIME 1795000000000000 LIMIT 100;
-- take from a queue: each message is acked as it is returned
BROKER POP jobs LIMIT 10;
BROKER POP orders SUBSCRIPTION workers LIMIT 50;
-- binary keys and values as bytea
BROKER BINARY READ orders LIMIT 5;
BROKER BINARY POP jobs;Both return partition, offset, time_us, key, value and headers. READ reads every partition unless you give one, from EARLIEST by default, up to LIMIT (default 100) messages. POP takes from a queue (or from a named shared subscription on a topic), one message by default. Keys and values come back as text unless you put BINARY before READ or POP; a value that is not UTF-8 is refused without it.
Inspect
BROKER SHOW TOPICS;
BROKER SHOW QUEUES;
BROKER SHOW SUBSCRIPTIONS;
BROKER SHOW SUBSCRIPTIONS ON orders;
BROKER SHOW EXCHANGES;
BROKER SHOW BINDINGS;
BROKER SHOW PARTITIONS orders;
BROKER SHOW GRANTS ON TOPIC orders;| Statement | Columns |
|---|---|
SHOW TOPICS | name, id, partitions, durability, queue, messages, bytes, retention_ms |
SHOW QUEUES | name, messages, ready, unacked, consumers |
SHOW SUBSCRIPTIONS [ON topic] | topic, name, mode, members, backlog, inflight, delivered, acked, dead |
SHOW EXCHANGES | name, type, durable, bindings |
SHOW BINDINGS | exchange, topic, key |
SHOW PARTITIONS topic | partition, start, next, durable, bytes, segments |
SHOW GRANTS [ON TOPIC|QUEUE|EXCHANGE name] | object_type, object, owner, grantee, privilege, grantor, grantable |
The SHOW statements list only what your role holds a privilege on.
Permissions
Clients log in with the database's roles on every protocol (see Security). Who may create, alter and drop broker objects is --broker-ddl. Using an object follows the database's own privileges: a topic or exchange is owned by the role that created it, and everyone else needs a grant.
GRANT PRODUCE, CONSUME ON TOPIC orders TO app;
GRANT CONSUME ON QUEUE jobs TO worker; -- a queue is a topic
GRANT PUBLISH, BIND ON EXCHANGE events TO app;
GRANT ALL ON ALL TOPICS TO admin_app;
REVOKE ALL ON TOPIC orders FROM PUBLIC;
ALTER TOPIC orders OWNER TO billing;| Privilege | On | Lets a role |
|---|---|---|
PRODUCE | topic or queue | write to it, directly or through the default exchange |
CONSUME | topic or queue | read, subscribe, pop, purge, list offsets, commit, and manage its subscriptions |
PUBLISH | exchange | publish through it |
BIND | exchange | bind a topic to it (which also needs PRODUCE on the topic) |
Altering or deleting an object, and granting on it, are for its owner (or a superuser). GRANT … ON ALL TOPICS grants on every topic that exists at that moment, like PostgreSQL's ALL TABLES IN SCHEMA; topics made later need their own grant.
The built-in amq.* exchanges belong to the database owner, with PUBLISH and BIND granted to PUBLIC, so AMQP and MQTT clients work for every role until you revoke that. For MQTT, publishing (and a will) needs PUBLISH on amq.mqtt, and subscribing needs BIND on it.
A GRANT or REVOKE reaches open connections at their next request. A native subscription stops at its next credit, ack or commit; an AMQP or MQTT consumer that is already receiving keeps its subscription until it reconnects.
How each protocol reports a refusal:
| Protocol | Refusal |
|---|---|
| SQL | permission denied for topic x or must be owner of topic x |
| native | a Permission error on the request |
| Kafka | TOPIC_AUTHORIZATION_FAILED for that topic; unseen topics are left out of metadata |
| AMQP | the channel is closed with 403 ACCESS_REFUSED |
| MQTT | a refused publish is acked 0x87 (5.0) or dropped (3.1.1); a refused filter gets 0x87/0x80 |
Kafka clients
The server presents itself as a one-broker Kafka cluster. Producers, consumer groups and admin clients work: idempotent producers (on by default in current clients), consumer group membership and committed offsets, CreateTopics, DeleteTopics and DescribeConfigs. Compressed batches (gzip, snappy, lz4, zstd) are accepted. A Kafka topic is a broker topic, and a consumer group is an ordered subscription named after the group.
With the default --kafka-auth sasl, clients use SASL PLAIN with a database role:
echo 'hello' | kcat -b 127.0.0.1:9092 -t orders -P \
-X security.protocol=SASL_PLAINTEXT -X sasl.mechanisms=PLAIN \
-X sasl.username=rasterized -X sasl.password=secret
kcat -b 127.0.0.1:9092 -t orders -C -o beginning -e \
-X security.protocol=SASL_PLAINTEXT -X sasl.mechanisms=PLAIN \
-X sasl.username=rasterized -X sasl.password=secretWith --kafka-tls on, use security.protocol=SASL_SSL. When the server listens on 0.0.0.0, set --kafka-advertised-host to the name clients reach it by, or they will be told to connect to an address they cannot use.
AMQP clients
RabbitMQ clients connect to the default virtual host / with a database role:
amqp://rasterized:secret@127.0.0.1:5672/Exchanges (direct, fanout, topic, headers, the amq.* ones and the default exchange), queues, bindings, basic.qos prefetch, ack/nack/reject, publisher confirms, mandatory/return, message TTL, dead-letter exchanges and max-length work. A durable queue is sync; a transient one is memory. The queue arguments x-message-ttl, x-max-length, x-delivery-limit, x-dead-letter-exchange, x-dead-letter-routing-key and x-consumer-timeout map onto the queue's settings. Publisher confirms are sent once a message is durable. Unacked messages return to the queue when the channel closes.
MQTT clients
MQTT 3.1.1 and 5.0 clients connect with a database role as user name and password:
mosquitto_sub -h 127.0.0.1 -p 1883 -u rasterized -P secret -t 'sensors/#' -q 1 &
mosquitto_pub -h 127.0.0.1 -p 1883 -u rasterized -P secret -t sensors/room1/temp -m 21.5 -q 1QoS 0, 1 and 2, retained messages, persistent sessions, wills, keep-alive and shared subscriptions ($share/<group>/<filter>) work. A persistent session's messages wait while its client is away and survive a restart; --mqtt-durability decides how they are synced. MQTT 5 message properties travel with the message. QoS 0 messages to connected subscribers are not stored.
A persistent session belongs to the role that created it: another role connecting with the same client id is refused.
Replication
On a node with replication on, the broker replicates with the database: topic, queue, subscription, exchange and binding changes, every stored message at its offset, and subscription progress (commits and acks).
- Write each partition on one node at a time. Two nodes appending to the same partition diverge; the second node's messages are counted as conflicts on the first. Send each partition's producers (or each queue's) to one node.
memorytopics are each node's own and are not replicated.- Retention is applied by each node on its own clock.
Limits
- Messages are delivered at least once; consumers must tolerate a repeat after a restart or a timeout.
- Kafka: transactions are not supported. Only SASL PLAIN is offered (no SCRAM).
- AMQP: transactions (
tx.*) and exchange-to-exchange bindings are not supported; message priorities are accepted and ignored. - Grants cannot be scoped to individual MQTT topic filters: a role may publish to all of
amq.mqttor none of it. - Subscriptions have no owner of their own: a role with
CONSUMEon a topic manages all its subscriptions. - The number of partitions of a topic is fixed when it is created.
BROKERstatements are not transactional, and topics cannot be read withSELECT; useBROKER READ.- Delivery counts used for redelivery flags are kept in memory and start again from 1 after a restart.
- The broker ports serve only the default database.