Messaging from .NET
RasterizedDb.Messaging is a .NET client for RasterizedDB's message broker over its native protocol: declare queues and topics, produce messages, consume them with acknowledgements, and route them through exchanges. Use it when a .NET service needs work queues, event streams or pub/sub and you already run RasterizedDB. The broker itself, its other protocols (Kafka, AMQP, MQTT) and its BROKER SQL statements are described in the message broker.
Pre-production. The broker's native protocol (rdbmq/1) is not frozen, and this client has been tested mostly against a stand-in that speaks the protocol's frames; against a running broker, only queue delivery, negative acknowledgement, redelivery and dead-lettering are tested. Expect changes, and test your application against the server you will run before depending on it.
Installing
The package is RasterizedDb.Messaging (net8.0, net9.0, net10.0), on NuGet:
dotnet add package RasterizedDb.Messaging --version 1.1.0To build it from source instead, see Getting started.
It does not depend on RasterizedDb.Data.
Opening the broker port
The broker's native port is closed unless the server is started with one:
export RASTERIZEDDB_PASSWORD='change-me-now'
rasterizeddb --location ./rdb-data --rdb-user app --broker-port 7171| server flag | default | what it does |
|---|---|---|
--broker-port <PORT> | closed | The TCP port of the broker's native protocol; 7171 is the usual choice. |
--broker-socket <PATH> | none | Also (or only) serve it on a unix socket. Its permissions follow --socket-mode. |
--broker-addr <IP> | 127.0.0.1 | The address the broker's ports listen on. |
--broker-auth <password or trust> | password | password checks logins against the database's roles; trust asks nothing and is refused on anything but loopback. |
--broker-tls <on or off> | off | TLS on --broker-port, with the PostgreSQL listener's certificate (--pg-cert/--pg-key, or a self-signed one made at start). |
--broker-ddl <any or superuser> | any | Who may create and drop topics, queues, exchanges and bindings: any role that logged in, or superusers only. |
Connecting
using RasterizedDb.Messaging;
await using var broker = await RasterizedDbBroker.ConnectAsync(
"Host=127.0.0.1;Port=7171;Username=app;Password=change-me-now");
await broker.PingAsync();One RasterizedDbBroker carries any number of requests and subscriptions at once, and is safe to share between tasks: open one per process and keep it.
| keyword (aliases) | default | what it does |
|---|---|---|
Host (Server) | none | The broker's host. unix:/path names a unix socket instead. |
Port | 7171 | The broker's port. |
Socket (Unix Socket) | none | A unix socket's path, instead of Host. |
Username (User, User Id, UID) | none | The role to log in as. Without it, a broker that asks for a login is refused with AuthRequired. |
Password (PWD) | none | The role's password. |
Client Name (Application Name) | RasterizedDb.Messaging | The name this client gives the broker. |
Timeout (Command Timeout) | 30 | Seconds a request waits for its reply; fractions are allowed. |
Tls (Ssl) | false | TLS over TCP (true/false). Needs --broker-tls on. |
Trust Server Certificate | false | With Tls: accept any server certificate. Only for a network you trust. |
An unknown keyword throws ArgumentException. The same settings exist as properties of RasterizedDbBrokerOptions, which ConnectAsync also takes.
Over plain TCP the password crosses the network as it is. Use Tls=true against a broker started with --broker-tls on, a unix socket, or a network you trust. With TLS and without Trust Server Certificate, the server's certificate must be one the operating system trusts, issued for Host.
The model
| concept | what it is |
|---|---|
| topic | A named set of partitions. Each partition is an append-only log; every message in it has a 64-bit offset. Messages are kept until retention removes them, read or not. |
| subscription | A named reader of one topic, in one of three modes: Ordered (one consumer per partition, in order, with committed offsets), Shared (a work queue: each message goes to one consumer and is acknowledged one by one), Broadcast (every subscriber gets every message). |
| queue | A one-partition topic plus a Shared subscription of the same name. |
| exchange | A routing table that sends a published batch to the topics bound to it. |
A message has a value (bytes), an optional key (bytes) that picks its partition, headers (name and bytes), its partition, its offset and a time.
Queues
using System.Text;
using RasterizedDb.Messaging;
await using var broker = await RasterizedDbBroker.ConnectAsync("Host=127.0.0.1;Port=7171;Username=app;Password=change-me-now");
await broker.DeclareQueueAsync("jobs", new BrokerQueueConfig
{
AckTimeout = TimeSpan.FromMinutes(1),
MaxDeliveries = 5,
DeadLetter = "jobs.dead",
});
await broker.DeclareQueueAsync("jobs.dead");
// Producing: durable when the call returns.
await broker.ProduceAsync("jobs", Encoding.UTF8.GetBytes("send-welcome:42"), [new BrokerHeader("kind", "email")]);
// Consuming.
await using var jobs = await broker.ConsumeAsync("jobs", credits: 64);
await foreach (var message in jobs)
{
try
{
Console.WriteLine($"{message.Header("kind")}: {Encoding.UTF8.GetString(message.Value.Span)}");
jobs.Ack(message);
}
catch (Exception)
{
jobs.Nack(message, TimeSpan.FromSeconds(30)); // delivered again after 30 s
}
}Declaring
DeclareQueueAsync(name, BrokerQueueConfig? config = null, bool ifNotExists = true) creates the queue and returns its BrokerTopic. Declaring an existing queue with other settings is refused (Mismatch). DeleteQueueAsync(name, bool ifExists = true) returns whether it existed.
BrokerQueueConfig | default | |
|---|---|---|
Durability | Sync | see Durability |
AckTimeout | 30 s | how long a delivered message may stay unacknowledged before it is delivered again |
MaxDeliveries | 0 (no limit) | deliveries after which a message goes to DeadLetter |
DeadLetter | none | the queue that takes messages past MaxDeliveries |
MessageTtl | none | how long a message may wait in the queue |
MaxLength | -1 (no limit) | the most messages the queue holds; a full queue that rejects on overflow refuses with Full |
A dead-lettered message carries the headers x-death-reason, x-death-topic and x-death-subscription.
Consuming and settling
ConsumeAsync(queue, int credits = 256) subscribes to the queue's shared subscription. Read it with await foreach. The broker pushes up to credits messages and then waits; taking messages grants it more, so about that many are ever held in your process unread.
| call on the subscription | effect |
|---|---|
Ack(message), Ack(IEnumerable<BrokerMessage>) | Done: the message is not delivered again. Sent without waiting for a reply. |
Nack(message, TimeSpan delay = default), and the IEnumerable form | Give it back: it is delivered again, after delay if given, and counts towards MaxDeliveries. Not waited for. |
RenewAsync(message, TimeSpan extend = default) | Keep a delivered message for extend longer (zero: the acknowledgement timeout again), for work that outlasts the timeout. Returns false when its deadline had already passed and it went, or will go, to another consumer. |
RenewAsync(IEnumerable<BrokerMessage>, …) | The same for several; returns how many were still in flight. |
CloseAsync(), DisposeAsync() | Ends the subscription. Delivered, unacknowledged messages go to another consumer, or wait. |
Several consumers on the same queue share its messages. A message delivered and not acknowledged is delivered again when its acknowledgement timeout passes or its consumer goes away.
Scheduled delivery
await broker.ProduceAsync("jobs", Encoding.UTF8.GetBytes("reminder:42"), deliverAt: DateTime.UtcNow.AddHours(24));deliverAt holds a message back from a queue's consumers until that time; message.DeliverAt shows it on delivery. It is a header (rdb-deliver-at), which you can also add yourself with BrokerHeader.DeliverAt(time). Ordered and broadcast subscriptions ignore it.
Topics and subscriptions
using System.Text;
using RasterizedDb.Messaging;
await using var broker = await RasterizedDbBroker.ConnectAsync("Host=127.0.0.1;Port=7171;Username=app;Password=change-me-now");
await broker.CreateTopicAsync("orders", new BrokerTopicConfig { Partitions = 4, Retention = TimeSpan.FromDays(3) });
// The key decides the partition, so one order's events stay in order.
await broker.ProduceAsync("orders", Encoding.UTF8.GetBytes("{\"status\":\"paid\"}"), key: Encoding.UTF8.GetBytes("order-1001"));
await using var billing = await broker.SubscribeAsync(
"orders",
"billing",
new BrokerSubscriptionConfig { Mode = BrokerSubscriptionMode.Ordered, Start = BrokerStart.Earliest });
await foreach (var message in billing)
{
Console.WriteLine($"partition {message.Partition} offset {message.Offset}: {Encoding.UTF8.GetString(message.Value.Span)}");
await billing.CommitAsync(message.Partition, message.Offset + 1);
}CreateTopicAsync(name, BrokerTopicConfig? config = null, bool ifNotExists = true) returns the topic's BrokerTopic. DeleteTopicAsync(name, bool ifExists = true) returns whether it existed.
BrokerTopicConfig | default | |
|---|---|---|
Partitions | 1 | |
Durability | Sync | see Durability |
Retention | 7 days | how long messages are kept; null keeps them whatever their age |
RetentionBytes | -1 (no limit) | how many bytes are kept |
SegmentBytes | 256 MiB | |
MaxBatchBytes | 16 MiB | |
MemoryBytes | 64 MiB |
SubscribeAsync(topic, subscriptionName, BrokerSubscriptionConfig? config = null, int credits = 256) joins, or creates, a named subscription:
BrokerSubscriptionConfig | default | |
|---|---|---|
Mode | Shared | Ordered, Shared or Broadcast |
Start | BrokerStart.Earliest | where a new subscription starts: Earliest, Latest, Offset(n), or Time(utc) |
AckTimeout | 30 s | for Shared |
MaxDeliveries | 0 (no limit) | for Shared |
DeadLetter | none | for Shared |
- Ordered: members of the same subscription share the topic's partitions;
subscription.AssignedPartitionslists this member's, and the broker may change them. Record progress withCommitAsync(partition, offset), meaning everything beforeoffsetin that partition is done. - Shared: settle each message with
Ack/Nack, as for a queue. - Broadcast: every subscriber gets every message.
DeleteSubscriptionAsync(topic, subscriptionName, bool ifExists = true) removes a subscription.
Reading without a subscription
FetchAsync(BrokerTopic topic, uint partition, ulong offset, int maxBytes = 1 MiB, TimeSpan maxWait = default) reads stored messages of one partition from an offset on, waiting up to maxWait for some to arrive. It returns the messages, the next offset to ask for, and the partition's first stored offset:
var orders = await broker.ResolveAsync("orders");
var (messages, next, logStart) = await broker.FetchAsync(orders, partition: 0, offset: 0, maxWait: TimeSpan.FromSeconds(1));Producing
ProduceAsync(topic, ReadOnlyMemory<byte> value, IReadOnlyList<BrokerHeader>? headers = null, ReadOnlyMemory<byte>? key = null, BrokerAck ack = BrokerAck.Durable, DateTime? deliverAt = null) produces one message to a topic or queue by name. A message with a key goes to the partition its key decides; one without a key goes to a partition the broker picks in turn.
It returns a BrokerProduceResult: Partition, BaseOffset (the message's offset) and Duplicate.
BrokerAck | the call returns when |
|---|---|
Durable (default) | the broker has made the message durable as the topic's durability says |
Written | the broker has written it |
None | at once; nothing is waited for, and BaseOffset is ulong.MaxValue |
Batches
To send many messages in one request, build a batch:
using RasterizedDb.Messaging;
var orders = await broker.ResolveAsync("orders");
using var batch = new BrokerBatchBuilder();
for (var i = 0; i < 1000; i++)
{
batch.Add($"{{\"n\":{i}}}", key: $"order-{i % 50}");
}
var result = await broker.ProduceAsync(orders, batch.Seal(), partition: 0);BrokerBatchBuilder | |
|---|---|
Add(string value, string? key = null, headers = null) | A message from text (UTF-8). |
Add(ReadOnlySpan<byte> value, ReadOnlySpan<byte> key, headers = null) | A message with a key. |
Add(ReadOnlySpan<byte> value, ReadOnlySpan<byte> key = default, bool hasKey = false, headers = null) | The general form. |
Count, Length | Messages so far, and the batch's size in bytes. |
Seal() | Finishes the batch. Its bytes belong to the builder until Reset() or Dispose(). |
Reset() | Empties the builder for the next batch. |
ProduceAsync(BrokerTopic topic, ReadOnlyMemory<byte> batch, uint partition = RasterizedDbBroker.ByKey, BrokerAck ack = BrokerAck.Durable) sends a sealed batch: to the given partition, to the partition its keys decide (ByKey), or to one the broker picks (AnyPartition). ResolveAsync(name) gives the BrokerTopic of a name, asked of the broker once and remembered.
A message has at most 65535 headers; a batch holds at least one message and at most 1 GiB.
Durability
BrokerDurability | a durable produce is acknowledged when |
|---|---|
Sync (default) | the batch is on disk (one sync covers every batch appended since the last) |
Async | the batch is written; the broker syncs it within --broker-flush-ms |
Memory | the batch is in memory only; nothing is written to disk |
Exchanges
await broker.DeclareExchangeAsync("events", BrokerExchangeKind.Topic);
await broker.DeclareQueueAsync("audit");
await broker.BindAsync("events", "audit", key: "user.*");
using var batch = new BrokerBatchBuilder();
batch.Add("{\"user\":7}");
uint routedTo = await broker.PublishAsync("events", "user.created", batch.Seal(), mandatory: true);| call | effect |
|---|---|
DeclareExchangeAsync(name, BrokerExchangeKind kind, bool durable = true, string? alternate = null) | Creates an exchange, optionally with an alternate exchange. |
DeleteExchangeAsync(name, bool ifExists = true) | Returns whether it existed. |
BindAsync(exchange, topic, string key = "", bool matchAny = false, IReadOnlyList<BrokerHeader>? arguments = null) | Binds a topic or queue under a binding key. For a headers exchange, arguments are the header values to match, all of them or, with matchAny, any. |
UnbindAsync(…) | The same arguments; removes the binding. |
PublishAsync(exchange, routingKey, ReadOnlyMemory<byte> batch, BrokerAck ack = BrokerAck.Durable, bool mandatory = false) | Sends a sealed batch through the exchange; returns how many topics took it. With mandatory, a batch that no binding routes anywhere is refused (Unroutable). |
BrokerExchangeKind | a binding matches when |
|---|---|
Direct | its key equals the routing key |
Fanout | always |
Topic | its key matches the routing key word by word (words split on .; * matches one word, # zero or more) |
Headers | the message's headers match its arguments |
Mqtt | MQTT-style topic filters |
Monitoring
ListTopicsAsync() returns every topic and queue the role may see, as BrokerTopicInfo: Id, Name, Config, IsQueue, Messages and Bytes. PingAsync() checks the connection.
Errors and lost connections
Every failure is a BrokerException:
Codeis set when the broker refused the request:Permission,NoTopic,TopicExists,Mismatch,Full,Unroutable,TooLarge,AuthRequired,AuthFailed, and the otherBrokerErrorCodevalues. The connection goes on.Codeis null when the error came from the connection, not the broker: the connection was lost, or no reply came withinTimeout.IsConnectionLostistruefor both; checkbroker.IsConnectedto tell them apart.
The connection does not reconnect by itself. When it is lost:
- every pending request fails, and every subscription's
await foreachthrows; broker.ConnectionLostis raised once, andsubscription.Closedon each subscription;AckandNackthrow.
Connect again and subscribe again. Messages that were delivered and not acknowledged are delivered again by the broker, so make your handlers safe to run twice for the same message.
using RasterizedDb.Messaging;
while (true)
{
try
{
await using var broker = await RasterizedDbBroker.ConnectAsync("Host=127.0.0.1;Port=7171;Username=app;Password=change-me-now");
await using var jobs = await broker.ConsumeAsync("jobs");
await foreach (var message in jobs)
{
// handle, then:
jobs.Ack(message);
}
}
catch (BrokerException e) when (e.IsConnectionLost)
{
await Task.Delay(TimeSpan.FromSeconds(2));
}
}A subscription the broker closes (for example, because it was deleted) ends its await foreach with that error's code. Disposing the broker connection raises no ConnectionLost.
Privileges
Logins use the database's roles. Who may create and drop topics, queues, exchanges and bindings is the server's --broker-ddl (any role by default, or superusers only). Using them needs the object's privileges: its owner may do anything with it, and other roles need grants such as:
GRANT PRODUCE, CONSUME ON TOPIC orders TO app;
GRANT CONSUME ON QUEUE jobs TO worker;
GRANT PUBLISH, BIND ON EXCHANGE events TO app;A refused request fails with Permission, and ListTopicsAsync leaves out what the role cannot see. The full rules are in the message broker.
Limits
- Pre-production: the protocol may change, and the client is tested against a running broker only for queue delivery, negative acknowledgement, redelivery and dead-lettering.
- No automatic reconnect; your code reconnects and subscribes again.
- No compressed batches.
- The password is sent as it is over plain TCP; use TLS or a unix socket.