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 / SETUP SCRIPTS / A MESSAGE BROKER IN THE DATABASE

A message broker in the database

Starts a server that is also a message broker: topics, queues and exchanges kept inside the database, served on four ports at once. Its own native protocol (7171) is for rasterizeddb_client::broker; Kafka clients use 9092, RabbitMQ (AMQP 0-9-1) clients 5672, and MQTT 3.1.1 and 5.0 clients 1883. Every protocol logs in with the database's roles, and BROKER … statements on the SQL port reach the same topics. Use it when an application needs a queue or an event stream and you would rather not run a second system. It runs in the foreground.

Before you start

  • A server binary, 1.1.0 or later (the release archives and images have the broker; 1.0.1 has none). The script checks --help for --broker-port and stops if it is missing.
  • Free ports: 7171, 9092, 5672 and 1883 by default, plus 5432 and 61170 for SQL.
  • A password for the role rasterized in RASTERIZEDDB_PG_PASSWORD.

Settings

bash variablePowerShell parameterDefaultWhat it does
RDB_BIN-RdbBinrasterizeddb / rasterizeddb.exeThe server binary.
RDB_DATA-Data./dataThe database directory; topics are stored in it.
RDB_LISTEN-Listen127.0.0.1The address every broker port and PostgreSQL bind.
RDB_ADVERTISED_HOST-AdvertisedHostthe listen address, or this host's name for 0.0.0.0The host Kafka clients are told to connect to.
RDB_BROKER_PORT-BrokerPort7171Native broker protocol. off (bash) or 0 (PowerShell) leaves it closed.
RDB_KAFKA_PORT-KafkaPort9092Kafka. off / 0 leaves it closed.
RDB_AMQP_PORT-AmqpPort5672AMQP 0-9-1. off / 0 leaves it closed.
RDB_MQTT_PORT-MqttPort1883MQTT. off / 0 leaves it closed.
RDB_BROKER_TLS=on-TlsoffTLS on every broker port (SSL/SASL_SSL for Kafka, amqps://, MQTT over TLS), with the PostgreSQL certificate.
RDB_TLS_CERT, RDB_TLS_KEY-CertPath, -KeyPathnoneThat certificate. Without one, a self-signed certificate is made at each start.
RDB_BROKER_DDL-BrokerDdlanyWho may create, change and drop topics, queues, exchanges and bindings: any role that logged in, or superuser only.

Each protocol checks passwords against the database's roles: Kafka with SASL PLAIN, AMQP with PLAIN/AMQPLAIN, MQTT with the CONNECT user name and password. trust (no password) exists for each protocol but is refused on anything but loopback; this recipe always uses passwords. More flags (MQTT packet size and durability, AMQP heartbeat and consumer timeout, Kafka partitions for auto-created topics, thread counts) are listed by rasterizeddb --help.

Run it

sh
export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
./setup.sh
# reachable from other machines:
RDB_LISTEN=0.0.0.0 RDB_ADVERTISED_HOST=mq.example.com ./setup.sh
powershell
$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
.\setup.ps1

Check that it works

From SQL, make a queue, put a message on it and take it off:

sh
export PGPASSWORD='use-a-long-secret'
psql "postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require" \
  -c "BROKER CREATE QUEUE IF NOT EXISTS jobs MAX DELIVERIES 5" \
  -c "BROKER PUBLISH jobs 'hello'" \
  -c "BROKER POP jobs LIMIT 10" \
  -c "BROKER SHOW QUEUES"

From a Kafka client, with the password in a configuration file rather than on the command line (kcat.conf):

text
bootstrap.servers=127.0.0.1:9092
security.protocol=SASL_PLAINTEXT
sasl.mechanisms=PLAIN
sasl.username=rasterized
sasl.password=use-a-long-secret
sh
kcat -F kcat.conf -L
echo 'order 1' | kcat -F kcat.conf -P -t orders
kcat -F kcat.conf -C -t orders -o beginning -e

A topic a Kafka client names is created on first use. RabbitMQ clients connect to amqp://rasterized:<password>@host:5672/; MQTT clients to host:1883 with user rasterized and the password.

Grant other roles access

Objects belong to the role that created them; other roles need grants:

sql
CREATE USER worker PASSWORD 'another-long-secret';
GRANT CONSUME ON QUEUE jobs TO worker;
GRANT PRODUCE, CONSUME ON TOPIC orders TO worker;
BROKER SHOW GRANTS ON QUEUE jobs;

Stop or undo

Ctrl+C stops the server. BROKER DROP TOPIC IF EXISTS orders removes a topic and its messages.

Limits

  • Each topic's durability is chosen when it is created: sync (the default, acknowledged after the disk sync), async (synced on a timer; a power loss can lose the last moments) or memory (not written to disk at all).
  • Kafka support covers producing, fetching, consumer groups, offsets, idempotent producers and topic creation and deletion over the classic protocol; AMQP covers exchanges, queues, bindings, acknowledgements, publisher confirms, TTL, dead-lettering and max-length; MQTT covers QoS 0-2, retained messages, persistent sessions, wills and shared subscriptions.
  • MQTT permissions apply to the whole of amq.mqtt: a role may publish to all MQTT topics or none, not per topic filter.

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB as a message broker: topics, queues and exchanges inside the
# database, reachable over its native broker protocol, Kafka, AMQP 0-9-1
# (RabbitMQ clients) and MQTT, with logins against the database's roles.
# Runs in the foreground. Needs release 1.1.0 or later.
#
# Every setting can be overridden from the environment; set a port to "off"
# to leave that protocol closed, for example:
#   RDB_LISTEN=0.0.0.0 RDB_KAFKA_PORT=off ./setup.sh
set -euo pipefail

RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}"                  # topics are kept here, beside the tables
RDB_LISTEN="${RDB_LISTEN:-127.0.0.1}"
RDB_ADVERTISED_HOST="${RDB_ADVERTISED_HOST:-}"  # the host Kafka clients are told to use; needed with 0.0.0.0
RDB_BROKER_PORT="${RDB_BROKER_PORT:-7171}"      # native protocol (rasterizeddb_client::broker)
RDB_KAFKA_PORT="${RDB_KAFKA_PORT:-9092}"
RDB_AMQP_PORT="${RDB_AMQP_PORT:-5672}"
RDB_MQTT_PORT="${RDB_MQTT_PORT:-1883}"
RDB_BROKER_TLS="${RDB_BROKER_TLS:-off}"         # on: every broker port uses TLS, with the PostgreSQL certificate
RDB_TLS_CERT="${RDB_TLS_CERT:-}"
RDB_TLS_KEY="${RDB_TLS_KEY:-}"
RDB_BROKER_DDL="${RDB_BROKER_DDL:-any}"         # who may create topics and queues: any or superuser

die() { echo "error: $*" >&2; exit 1; }

command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
case "$("$RDB_BIN" --help)" in
  *--broker-port*) ;;
  *) die "this $RDB_BIN has no broker; it needs server 1.1.0 or later, built with the broker feature" ;;
esac
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized}"
export RASTERIZEDDB_PG_PASSWORD

mkdir -p "$RDB_DATA"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"
if [ -z "$RDB_ADVERTISED_HOST" ]; then
  if [ "$RDB_LISTEN" = 0.0.0.0 ] || [ "$RDB_LISTEN" = "::" ]; then
    RDB_ADVERTISED_HOST="$(hostname -f 2>/dev/null || hostname)"
  else
    RDB_ADVERTISED_HOST="$RDB_LISTEN"
  fi
fi

args=(--location "$RDB_DATA" --protocol both --pg-addr "$RDB_LISTEN"
  --broker-addr "$RDB_LISTEN" --broker-ddl "$RDB_BROKER_DDL")
[ -z "$RDB_TLS_CERT" ] || args+=(--pg-cert "$RDB_TLS_CERT" --pg-key "$RDB_TLS_KEY")
if [ "$RDB_BROKER_PORT" != off ]; then
  args+=(--broker-port "$RDB_BROKER_PORT" --broker-tls "$RDB_BROKER_TLS")
fi
if [ "$RDB_KAFKA_PORT" != off ]; then
  args+=(--kafka-port "$RDB_KAFKA_PORT" --kafka-advertised-host "$RDB_ADVERTISED_HOST" --kafka-tls "$RDB_BROKER_TLS")
fi
if [ "$RDB_AMQP_PORT" != off ]; then
  args+=(--amqp-port "$RDB_AMQP_PORT" --amqp-tls "$RDB_BROKER_TLS")
fi
if [ "$RDB_MQTT_PORT" != off ]; then
  args+=(--mqtt-port "$RDB_MQTT_PORT" --mqtt-tls "$RDB_BROKER_TLS")
fi

h="$RDB_ADVERTISED_HOST"
echo "SQL:    psql \"postgresql://rasterized@$h:5432/postgres?sslmode=require\" -c \"BROKER SHOW TOPICS\""
[ "$RDB_BROKER_PORT" = off ] || echo "Native: $h:$RDB_BROKER_PORT (rasterizeddb_client::broker)"
[ "$RDB_KAFKA_PORT" = off ] || echo "Kafka:  bootstrap.servers=$h:$RDB_KAFKA_PORT, SASL PLAIN as rasterized"
[ "$RDB_AMQP_PORT" = off ] || echo "AMQP:   amqp$([ "$RDB_BROKER_TLS" = on ] && echo s)://rasterized:<password>@$h:$RDB_AMQP_PORT/"
[ "$RDB_MQTT_PORT" = off ] || echo "MQTT:   $h:$RDB_MQTT_PORT, user rasterized"
echo "Stop with Ctrl+C."
echo

exec "$RDB_BIN" "${args[@]}"
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB as a message broker: topics, queues and exchanges inside the
  database, reachable over its native broker protocol, Kafka, AMQP 0-9-1
  (RabbitMQ clients) and MQTT, with logins against the database's roles.
  Runs in the foreground. Needs release 1.1.0 or later.
.EXAMPLE
  $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
  .\setup.ps1
.EXAMPLE
  .\setup.ps1 -Listen 0.0.0.0 -KafkaPort 0     # 0 leaves a protocol closed
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
    # Topics are kept here, beside the tables.
    [string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
    [string]$Listen = $(if ($env:RDB_LISTEN) { $env:RDB_LISTEN } else { '127.0.0.1' }),
    # The host Kafka clients are told to use; needed with 0.0.0.0.
    [string]$AdvertisedHost = $env:RDB_ADVERTISED_HOST,
    [int]$BrokerPort = $(if ($env:RDB_BROKER_PORT) { [int]$env:RDB_BROKER_PORT } else { 7171 }),
    [int]$KafkaPort = $(if ($env:RDB_KAFKA_PORT) { [int]$env:RDB_KAFKA_PORT } else { 9092 }),
    [int]$AmqpPort = $(if ($env:RDB_AMQP_PORT) { [int]$env:RDB_AMQP_PORT } else { 5672 }),
    [int]$MqttPort = $(if ($env:RDB_MQTT_PORT) { [int]$env:RDB_MQTT_PORT } else { 1883 }),
    # Every broker port uses TLS, with the PostgreSQL certificate.
    [switch]$Tls = ($env:RDB_BROKER_TLS -eq 'on'),
    [string]$CertPath = $env:RDB_TLS_CERT,
    [string]$KeyPath = $env:RDB_TLS_KEY,
    # Who may create topics and queues.
    [ValidateSet('any', 'superuser')]
    [string]$BrokerDdl = $(if ($env:RDB_BROKER_DDL) { $env:RDB_BROKER_DDL } else { 'any' })
)
$ErrorActionPreference = 'Stop'

$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }
if (-not ((& $cmd.Source --help) -match '--broker-port')) { throw "This $RdbBin has no broker; it needs server 1.1.0 or later, built with the broker feature." }
if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized.' }

New-Item -ItemType Directory -Force -Path $Data | Out-Null
$Data = (Resolve-Path -LiteralPath $Data).Path
if (-not $AdvertisedHost) {
    $AdvertisedHost = if ($Listen -in @('0.0.0.0', '::')) { [System.Net.Dns]::GetHostEntry('').HostName } else { $Listen }
}
$tlsValue = if ($Tls) { 'on' } else { 'off' }

$serverArgs = @('--location', $Data, '--protocol', 'both', '--pg-addr', $Listen,
    '--broker-addr', $Listen, '--broker-ddl', $BrokerDdl)
if ($CertPath) { $serverArgs += @('--pg-cert', (Resolve-Path -LiteralPath $CertPath).Path, '--pg-key', (Resolve-Path -LiteralPath $KeyPath).Path) }
if ($BrokerPort -gt 0) { $serverArgs += @('--broker-port', "$BrokerPort", '--broker-tls', $tlsValue) }
if ($KafkaPort -gt 0) { $serverArgs += @('--kafka-port', "$KafkaPort", '--kafka-advertised-host', $AdvertisedHost, '--kafka-tls', $tlsValue) }
if ($AmqpPort -gt 0) { $serverArgs += @('--amqp-port', "$AmqpPort", '--amqp-tls', $tlsValue) }
if ($MqttPort -gt 0) { $serverArgs += @('--mqtt-port', "$MqttPort", '--mqtt-tls', $tlsValue) }

$h = $AdvertisedHost
Write-Host "SQL:    psql `"postgresql://rasterized@${h}:5432/postgres?sslmode=require`" -c `"BROKER SHOW TOPICS`""
if ($BrokerPort -gt 0) { Write-Host "Native: ${h}:$BrokerPort (rasterizeddb_client::broker)" }
if ($KafkaPort -gt 0) { Write-Host "Kafka:  bootstrap.servers=${h}:$KafkaPort, SASL PLAIN as rasterized" }
if ($AmqpPort -gt 0) { Write-Host "AMQP:   amqp$(if ($Tls) { 's' })://rasterized:<password>@${h}:$AmqpPort/" }
if ($MqttPort -gt 0) { Write-Host "MQTT:   ${h}:$MqttPort, user rasterized" }
Write-Host 'Stop with Ctrl+C.'
Write-Host ''

& $cmd.Source @serverArgs
exit $LASTEXITCODE
✓ page rendered in 141 µs axum + tera + htmx · no other javascript