Tyto.Transports.Postgres 0.1.0-alpha.16

This is a prerelease version of Tyto.Transports.Postgres.
dotnet add package Tyto.Transports.Postgres --version 0.1.0-alpha.16
                    
NuGet\Install-Package Tyto.Transports.Postgres -Version 0.1.0-alpha.16
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tyto.Transports.Postgres" Version="0.1.0-alpha.16" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tyto.Transports.Postgres" Version="0.1.0-alpha.16" />
                    
Directory.Packages.props
<PackageReference Include="Tyto.Transports.Postgres" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tyto.Transports.Postgres --version 0.1.0-alpha.16
                    
#r "nuget: Tyto.Transports.Postgres, 0.1.0-alpha.16"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tyto.Transports.Postgres@0.1.0-alpha.16
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tyto.Transports.Postgres&version=0.1.0-alpha.16&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Tyto.Transports.Postgres&version=0.1.0-alpha.16&prerelease
                    
Install as a Cake Tool

Tyto.Transports.Postgres

PostgreSQL-backed transport for Tyto. Designed for teams that want a real queue (ack/nack, retry, dead-letter, competing consumers) without operating Kafka or RabbitMQ — when you already run Postgres, this reuses it as the broker.

This is not a Kafka replacement. It targets thousands-of-messages/second workloads where operational simplicity and transactional integrity matter more than raw broker throughput.

How it works

A single table acts as the queue:

column purpose
id identity PK
queue endpoint address (logical queue)
payload / headers / message_* the MessageEnvelope
state 0=Ready, 1=InFlight, 2=DeadLetter
attempt delivery count, drives retry/dead-letter
visible_at delayed-visibility gate
locked_until crash-recovery lease guard
  • Send → INSERT a Ready row, then pg_notify to wake consumers.
  • Receive → SELECT ... FOR UPDATE SKIP LOCKED leases a batch and marks it InFlight with a locked_until lease. Consumers also LISTEN for instant wake-ups and fall back to polling (PollingInterval).
  • Settle → Complete deletes the row; Abandon/retry bumps attempt and delays visible_at; exceeding MaxRetryCount sets state = DeadLetter.
  • Crash safety → an InFlight row whose locked_until has passed is re-leased automatically (at-least-once delivery).

The table, schema and index are created idempotently at startup by PostgresTopologyManager (set AutoCreateSchema = false to run DDL-free under least-privilege credentials).

Priority queues

Each message carries a priority (default PostgresOptions.DefaultPriority, or a per-message Tyto-Priority header). Higher values are leased first — the lease order is priority DESC, visible_at, id, backed by a matching index.

// per-message
envelope.Headers["Tyto-Priority"] = "10";
// or a transport-wide default
pg.Configure(o => o.DefaultPriority = 0);

Retries, backoff & poison messages

A failed message is settled by policy, keyed off the DB attempt column (crash-safe — no reliance on headers):

  • Backoff: RetryStrategy is Exponential by default — the delay is RetryDelayMilliseconds * 2^(attempt-1), capped at MaxRetryDelayMilliseconds, with ±RetryJitterFactor random jitter to avoid retry stampedes. Set RetryStrategy = Fixed for a constant delay.
  • Give up: once attempt >= MaxRetryCount the message is dead-lettered.
  • Poison messages: exceptions that can never succeed on retry (validation, deserialization) can be dead-lettered immediately via NonRetryableExceptions or a custom ShouldRetry predicate — no wasted retries, no queue head-of-line blocking. The dead-letter reason records whether it was exhaustion or a non-retryable exception.
pg.Consumers(c => {
    c.MaxRetryCount = 5;
    c.RetryDelayMilliseconds = 1000;      // base delay
    c.RetryStrategy = PostgresRetryStrategy.Exponential;
    c.MaxRetryDelayMilliseconds = 30_000; // cap
    c.RetryJitterFactor = 0.2;            // ±20%

    // Poison-message protection: never retry these.
    c.NonRetryableExceptions.Add(typeof(ValidationException));
    c.NonRetryableExceptions.Add(typeof(JsonException));
    // or a predicate:
    c.ShouldRetry = ex => ex is not ArgumentException;
});

With the defaults above and base 1s: retries land at ~1s, ~2s, ~4s, ~8s … (each ±20%), until MaxRetryCount, then dead-letter.

A failed run is settled in one place, the consumer worker, so each failure moves attempt by one and MaxRetryCount = 3 means three runs.

Lost races

A unique key, a concurrency token, a deadlock or a serialization failure is not a failure: another writer got there first, and the same message handled again on what is there now succeeds. A queue can say so:

pg.Configure(o => o.ConsumerSettings.PerQueueSettings["orders"] = new() {
    LostRace = ex => ex is DbUpdateConcurrencyException
        || ex.InnerException is PostgresException { SqlState: "23505" or "40P01" or "40001" },
});

The worker then runs the pipeline again in a new service scope (a new DbContext, a new transaction) after a 10–100 ms jittered pause, at most PostgresQueueConsumerSettings.LostRaceReruns (4) times. Nothing is abandoned meanwhile, so the message is offered to nobody else and attempt does not move. After the last re-run the failure takes the normal path, so a conflict that never clears still dead-letters. Each re-run is counted on tyto.receive.lost_races, tagged with the queue. Opt in only where a handler is safe to run twice in one delivery: one that calls a provider or a webhook would call it again.

TTL / expiry & retention

  • Messages with ExpiresAt in the past are never leased and are reclaimed by the maintenance worker.
  • Completed messages are deleted on Complete, so they never accumulate.
  • Dead-lettered rows are purged after Maintenance.DeadLetterRetention (default 7 days; TimeSpan.Zero keeps them forever for inspection).

PostgresMaintenanceWorker runs these sweeps on Maintenance.Interval (default 5 min), keeping table bloat — and the resulting autovacuum pressure — in check.

pg.Configure(o => {
    o.Maintenance.Interval = TimeSpan.FromMinutes(2);
    o.Maintenance.DeadLetterRetention = TimeSpan.FromDays(3);
    o.Maintenance.DeleteExpiredMessages = true;
});

Observability (OpenTelemetry)

Meter and ActivitySource are both named Tyto.Transports.Postgres.

  • Traces: postgres.send (producer), postgres.receive (consumer).
  • Metrics: enqueued, leased, completed, abandoned, deadlettered, expired, retention.deleted counters and a processing.duration histogram (all under tyto.transports.postgres.*).
tracing.AddSource("Tyto.Transports.Postgres");
metrics.AddMeter("Tyto.Transports.Postgres");

Usage

services.AddTyto(tyto => {
    tyto.Transports(t => {
        t.AddPostgres("Postgres_Main", pg => {
            pg.Connection("Host=localhost;Database=app;Username=app;Password=secret");
            pg.Schema("public");        // optional, default "public"
            pg.Table("tyto_messages");  // optional
            pg.Consumers(c => {
                c.DefaultConcurrencyLimit = 4;
                c.MaxRetryCount = 5;
                c.RetryDelayMilliseconds = 2000;
                c.PerQueueSettings["orders"] = new() { ConcurrencyLimit = 8 };
            });
        });
    });
    // ... endpoints route to "Postgres_Main" like any other transport
});

Transactional outbox seam

IPostgresMessageStore.EnqueueAsync accepts an optional caller-owned NpgsqlConnection / NpgsqlTransaction. When supplied, the message is inserted in the same transaction as the caller's business data — the foundation for a true transactional outbox (message and state commit atomically, or not at all).

The current "publish now" path (PostgresSendingTransport) passes null, opening its own connection. When the outbox module is wired into Tyto's send pipeline, it can call the store directly with its transaction — no transport changes required.

Graceful shutdown and queue upgrade

On stop, consumers stop acquiring new work. A handler that has already started can finish until the PostgreSQL shutdown budget reaches its final settlement window (up to one second, or one fifth of a short budget). The container/host shutdown deadline can shorten the shared stop even if another caller started it earlier. Settlement called through the handler or receive pipeline still honors handler and caller cancellation; the independent cleanup window is for worker-owned settlement after processing ends. The transport returns unstarted leases without recording a failed attempt; a canceled handler's lease is returned only after the handler unwinds. If a process dies, does not cooperate, or cannot reach PostgreSQL during shutdown, ordinary visibility expiry still provides at-least-once redelivery. Set VisibilityTimeout to cover the longest supported processing and batch wait. Use a durable inbox/idempotency key for application effects: a commit before acknowledgment may be delivered again.

Bootstrap now adds nullable lease_id uuid to existing queue tables without rewriting pending messages. With AutoCreateSchema = false, apply the equivalent ALTER TABLE <queue table> ADD COLUMN IF NOT EXISTS lease_id uuid NULL migration first. Fence checks protect only workers that use this version's lease identity. Stop old consumers before starting new ones on the same queue; a rolling mix with older ID-only settlement is not safe.

The PostgreSQL dead-letter row is authoritative. The optional IDeadLetterSink is notified only after the owned lease's dead-letter transition commits; its callback is best-effort, not a second persistent delivery. A failing callback is logged without putting the message back on the receive queue.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0-alpha.16 13 12/3/2026
0.1.0-alpha.15 57 11/30/2026
0.1.0-alpha.14 61 11/29/2026
0.1.0-alpha.13 64 11/29/2026
0.1.0-alpha.12 71 11/27/2026
0.1.0-alpha.11 82 10/5/2026
0.1.0-alpha.10 178 10/1/2026
0.1.0-alpha.9 90 9/27/2026
0.1.0-alpha.8 72 9/26/2026
0.1.0-alpha.7 100 9/25/2026
0.1.0-alpha.6 86 9/24/2026
0.1.0-alpha.5 128 9/21/2026
0.1.0-alpha.4 91 9/20/2026
0.1.0-alpha.3 78 9/20/2026
0.1.0-alpha.2 81 9/20/2026
0.1.0-alpha.1 78 9/20/2026
0.0.1-alpha.106 74 9/15/2026
0.0.1-alpha.105 97 9/14/2026
0.0.1-alpha.104 363 9/10/2026
0.0.1-alpha.103 94 9/4/2026
Loading failed