NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / MESSAGE BROKER

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

FlagProtocolClients
--broker-port / --broker-socketnative (rdbmq/1)the Rust client's broker API (Rust client: broker)
--kafka-portKafkalibrdkafka, the Java client, franz-go, kcat, …
--amqp-portAMQP 0-9-1RabbitMQ clients: pika, amqplib, lapin, the Java and .NET clients
--mqtt-portMQTT 3.1.1 and 5.0mosquitto clients, paho, rumqtt, …
any SQL connectionBROKER … statementspsql, 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:

sh
RASTERIZEDDB_PG_PASSWORD=secret rasterizeddb \
    --location /var/lib/rasterizeddb \
    --protocol pgwire \
    --broker-port 7171 \
    --kafka-port 9092 \
    --amqp-port 5672 \
    --mqtt-port 1883

Then, from psql, make a topic, write to it and read it back:

sql
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. After MAX DELIVERIES attempts 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 shared subscription 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.
PatternHow
1 → 1 queuea queue, one consumer
N → M work queuea queue (or a topic with a shared subscription), M consumers
1 → N fan-outone topic, N subscriptions (each sees every message)
N → M ordered streamP partitions and an ordered subscription, at most P active members
pub/suba topic with broadcast subscriptions, or a memory topic
routingan 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:

DURABILITYA write is acknowledged whenSurvives
sync (default)it is synced to disk. One sync covers every write that arrived since the last, across all connections.power loss
asyncit 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
memoryit is in an in-memory ring buffernothing: never written to disk

Server flags

Broker and native protocol

FlagDefaultWhat it does
--broker-port PORTclosedServe the native protocol on this TCP port (7171 is the usual choice).
--broker-socket PATHnoneServe 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 IP127.0.0.1Address the broker's ports listen on. The Kafka, AMQP and MQTT ports use it too unless given their own.
--broker-auth password|trustpasswordpassword checks clients against the database's roles. trust asks for nothing and is refused on anything but loopback.
--broker-tls on|offoffTLS 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 None per CPUI/O threads for the broker's ports (Kafka, AMQP and MQTT included).
--broker-flush-ms MS10Milliseconds between syncs of async topics.
--broker-ddl any|superuseranyWho may create, alter and drop topics, queues, exchanges, subscriptions and bindings: any role that logged in, or only superusers.

Kafka

FlagDefaultWhat it does
--kafka-port PORTclosedServe the Kafka protocol on this port (9092 is Kafka's own).
--kafka-addr ADDR--broker-addrAddress the Kafka port listens on.
--kafka-advertised-host HOSTthe listen addressThe 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 PORTthe listen portThe port clients are told, when a proxy or NAT puts them on another.
--kafka-auth sasl|trustsaslsasl is SASL PLAIN against the database's roles. trust asks for nothing, loopback only.
--kafka-tls on|offoffTLS 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|falsetrueCreate a topic the first time a client names it, like Kafka's auto.create.topics.enable.
--kafka-default-partitions N1Partitions of a topic created that way.

AMQP 0-9-1

FlagDefaultWhat it does
--amqp-port PORTclosedServe AMQP 0-9-1 on this port (5672 is RabbitMQ's).
--amqp-addr ADDR--broker-addrAddress the AMQP port listens on.
--amqp-auth password|trustpasswordpassword is PLAIN/AMQPLAIN against the database's roles. trust is loopback only.
--amqp-tls on|offoffTLS on the AMQP port (amqps://), with the PostgreSQL port's certificate.
--amqp-heartbeat SECONDS60The heartbeat the server proposes; 0 turns heartbeats off.
--amqp-consumer-timeout-ms MS1800000How 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

FlagDefaultWhat it does
--mqtt-port PORTclosedServe MQTT 3.1.1 and 5.0 on this port (1883 is usual; 8883 with TLS).
--mqtt-addr ADDR--broker-addrAddress the MQTT port listens on.
--mqtt-auth password|trustpasswordpassword checks CONNECT's user name and password against the database's roles. trust is loopback only.
--mqtt-tls on|offoffTLS on the MQTT port, with the PostgreSQL port's certificate.
--mqtt-durability sync|asyncasyncHow persistent sessions' messages are synced: async (synced every --broker-flush-ms) or sync (QoS 1 and 2 acknowledged once synced).
--mqtt-max-packet BYTES16777216The 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

sql
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.

OptionDefaultMeaning
PARTITIONS n1Number of partitions. Set at creation.
DURABILITY sync|async|memorysyncSee Durability.
RETENTION duration'7d'How long messages are kept. FOREVER (or -1) keeps them.
RETENTION BYTES sizeunlimitedThe 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

sql
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;
OptionDefaultMeaning
DURABILITY sync|async|memorysyncSee Durability.
ACK TIMEOUT duration'30s'How long a consumer may hold a message unacked before it is redelivered.
MAX DELIVERIES n0 (unlimited)Attempts before a message is dead-lettered.
DEAD LETTER namenoneThe topic or queue that receives messages that ran out of attempts. Without one they are dropped.
TTL durationnoneHow long a message waits in the queue.
MAX LENGTH nnoneThe most messages the queue holds.

Subscriptions

sql
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;
OptionDefaultMeaning
MODE ordered|sharedsharedSee Concepts. broadcast is refused from SQL.
FROM EARLIEST|LATEST|offset|TIME µsEARLIESTWhere 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 n0 (unlimited)As for queues.
DEAD LETTER topicnoneAs for queues.

Exchanges and bindings

sql
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;
TYPEA message goes to every topic bound with…
direct (default)a key equal to the routing key
fanoutany key (every binding)
topica matching pattern: words split on ., * matches one word and # matches zero or more
headersMATCH 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

sql
-- 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

sql
-- 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

sql
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;
StatementColumns
SHOW TOPICSname, id, partitions, durability, queue, messages, bytes, retention_ms
SHOW QUEUESname, messages, ready, unacked, consumers
SHOW SUBSCRIPTIONS [ON topic]topic, name, mode, members, backlog, inflight, delivered, acked, dead
SHOW EXCHANGESname, type, durable, bindings
SHOW BINDINGSexchange, topic, key
SHOW PARTITIONS topicpartition, 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.

sql
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;
PrivilegeOnLets a role
PRODUCEtopic or queuewrite to it, directly or through the default exchange
CONSUMEtopic or queueread, subscribe, pop, purge, list offsets, commit, and manage its subscriptions
PUBLISHexchangepublish through it
BINDexchangebind 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:

ProtocolRefusal
SQLpermission denied for topic x or must be owner of topic x
nativea Permission error on the request
KafkaTOPIC_AUTHORIZATION_FAILED for that topic; unseen topics are left out of metadata
AMQPthe channel is closed with 403 ACCESS_REFUSED
MQTTa 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:

sh
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=secret

With --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:

text
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:

sh
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 1

QoS 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.
  • memory topics 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.mqtt or none of it.
  • Subscriptions have no owner of their own: a role with CONSUME on a topic manages all its subscriptions.
  • The number of partitions of a topic is fixed when it is created.
  • BROKER statements are not transactional, and topics cannot be read with SELECT; use BROKER 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.
✓ page rendered in 218 µs axum + tera + htmx · no other javascript