NATS JetStream in .NET: Durable Jobs, Replay and Duplicate Handling

Companion to the video MQTT vs Kafka vs NATS: Pick Your Event Backbone. The video compares the three; this article goes one level down into the NATS half, with runnable .NET code. If you're new to NATS, start with NATS Message Broker in .NET: Subjects and Queue Groups.

"NATS doesn't persist messages." I hear it in design reviews as a reason to rule NATS out. It's true of Core NATS. It's false of JetStream, the persistence layer built into the same server.

Core NATS answers "who is listening right now?" JetStream answers "what was stored, who has processed it, and what must be sent again?" Those are different contracts, and your .NET code has to say which one it relies on.

This article builds the second one with NATS.Net 3.4.1 against nats-server 2.15. Every snippet below comes from one file I ran end to end; the output is at the bottom.

Table of Contents

The scenario

Same factory as in the video. Sensors publish temperatures on factory.<line>.temperature. Two consumers care about them differently:

  • Quality analytics goes offline for a day and must catch up on everything it missed.
  • Report workers receive reports.requested jobs. A worker can crash halfway, and the job must not be lost or produce two reports.

A live dashboard would also subscribe, but it only needs the latest value, and Core NATS is fine for that. The other two need storage.

What Core NATS promises

Core NATS is at most once. The server forwards a message to the subscribers connected at that moment, then forgets it. A subscriber that's offline misses it. A queue group spreads messages across workers, but if the chosen worker dies mid-job, nothing brings the message back.

For live telemetry, request-reply and control signals, "now or never" is often what you want. It becomes a problem when you need "eventually, even after a crash."

Run a JetStream server

JetStream is a flag on the normal server:

nats-server -js -sd ./nats-data

-sd sets the storage directory. On Windows, winget install NATSAuthors.NATSServer gets you the binary. Then add the client:

dotnet add package NATS.Net

Everything starts from a NatsClient and a JetStream context:

using NATS.Client.Core;
using NATS.Client.JetStream;
using NATS.Client.JetStream.Models;
using NATS.Net;

await using var client = new NatsClient("nats://localhost:4222");
var js = client.CreateJetStreamContext();

record ReportRequested(string JobId, string Line);

NatsClient serializes records like ReportRequested as JSON with reflection. If you publish with Native AOT (file-based dotnet run app.cs apps default to it), register a source-generated JsonSerializerContext instead. Otherwise the first publish throws Reflection-based serialization has been disabled. I hit exactly that on the first run.

Two streams, two retention promises

A stream captures messages published on its subjects and stores them. Its retention policy decides when a message is removed, so that's where you write down the contract.

// History: analytics may replay up to 7 days, capped at 1 GB.
await js.CreateOrUpdateStreamAsync(new StreamConfig("SENSORS", ["factory.*.temperature"])
{
    Storage = StreamConfigStorage.File,
    Retention = StreamConfigRetention.Limits,
    MaxAge = TimeSpan.FromDays(7),
    MaxBytes = 1L * 1024 * 1024 * 1024,
    NumReplicas = 1,
});

// Jobs: a message leaves the stream once a worker acknowledges it.
await js.CreateOrUpdateStreamAsync(new StreamConfig("REPORTS", ["reports.requested"])
{
    Storage = StreamConfigStorage.File,
    Retention = StreamConfigRetention.Workqueue,
    DuplicateWindow = TimeSpan.FromMinutes(2),
    NumReplicas = 1,
});
  • Limits retention keeps messages until an age, size or count limit is hit, whether anyone read them or not. Several consumers read independently. This is your replay buffer.
  • Work-queue retention removes a message once it's acknowledged. It's a job queue: each message is consumed once, and the server rejects consumers whose filters overlap.

CreateOrUpdateStreamAsync is idempotent, so it's safe at application startup. NumReplicas = 1 matches a single dev server; in a three-node cluster, use 3 so one node can fail without losing stored messages.

Answer the retention question before the code: if analytics is down longer than MaxAge, the gap is gone. Size the window for your longest realistic outage.

Publish and wait for the store

The JetStream context has its own PublishAsync, and it returns something the core one doesn't:

// Core publish: fire and forget. No confirmation that anything stored it.
await client.PublishAsync("reports.requested", new ReportRequested("job-42", "line-3"));

// JetStream publish: waits for the stream's PubAck.
var job = new ReportRequested("job-42", "line-3");
var ack = await js.PublishAsync("reports.requested", job,
    opts: new NatsJSPubOpts { MsgId = job.JobId });
ack.EnsureSuccess();
Console.WriteLine($"stored seq={ack.Seq} duplicate={ack.Duplicate}");

When I showed this run, people were surprised that the core publish was stored too. It landed in REPORTS as sequence 1, because the stream captures its subject whoever publishes. What the core publisher didn't get is proof. If the server had been down, or the subject mistyped, client.PublishAsync would have completed just the same.

The PubAck means the stream stored the message (on the configured number of replicas). It doesn't say any consumer received it, let alone processed it. It's the producer's handoff receipt.

Deduplicate retries with a message ID

A producer that times out waiting for the PubAck doesn't know whether the message was stored. The safe move is to retry, and that's where duplicates come from. MsgId sets the Nats-Msg-Id header, and the stream drops a second message with the same ID inside its DuplicateWindow:

var retry = await js.PublishAsync("reports.requested", job,
    opts: new NatsJSPubOpts { MsgId = job.JobId });
// retry.Seq == ack.Seq, retry.Duplicate == true

Note the limits:

  • The window is time-bound (2 minutes by default). A retry after that is a new message.
  • It protects the stream, not your database. It knows nothing about what a consumer did with the first copy.
  • The core publish above had no MsgId, so the stream kept it as a separate message. In this run the stream held two job-42 messages before any worker started, which is why the consumer needs its own protection.

A durable pull consumer for workers

A consumer is the server-side record of what has been delivered and acknowledged. A durable one has a name and survives client restarts. A pull consumer lets each worker fetch work at its own pace, so scaling out means starting more processes with the same consumer name.

var workers = await js.CreateOrUpdateConsumerAsync("REPORTS", new ConsumerConfig("report-workers")
{
    AckPolicy = ConsumerConfigAckPolicy.Explicit,
    AckWait = TimeSpan.FromSeconds(30),
    MaxDeliver = 5,
});

await foreach (var msg in workers.ConsumeAsync<ReportRequested>(cancellationToken: ct))
{
    var request = msg.Data!;
    try
    {
        if (!await store.ExistsAsync(request.JobId))
            await store.CreateReportAsync(request);   // job ID is the idempotency key

        await msg.AckAsync(cancellationToken: ct);
    }
    catch (TransientException)
    {
        await msg.NakAsync(delay: TimeSpan.FromSeconds(10), cancellationToken: ct);
    }
    catch (InvalidReportException)
    {
        await msg.AckTerminateAsync(cancellationToken: ct);
    }
}

Each acknowledgement tells the server something different:

Call Meaning to JetStream
AckAsync Done. With work-queue retention, the message is removed.
NakAsync(delay) Not now. Redeliver after the delay.
AckTerminateAsync Never. Stop redelivering this message.
(nothing) The worker crashed or hung. Redeliver after AckWait.

AckWait must exceed your realistic processing time, or a slow worker gets its job redelivered to a second worker while still working on it. For long jobs, call msg.AckProgressAsync() to extend the deadline. MaxDeliver caps attempts. After the fifth, JetStream stops redelivering and publishes a max-deliveries advisory. Alert on it; that's your poison-message signal.

Delivered is not completed

The loop writes the report, then acks. If the process crashes between those two lines, the report exists, the ack never arrives, and after AckWait the job comes back.

JetStream did its job correctly. If the handler creates a second report now, that's your bug. So the handler checks the job ID before doing work. In production, ExistsAsync + CreateReportAsync should be one database operation: a unique constraint on JobId, or recording "job-42 done" in the same transaction as the report. The CorrelationId and duplicate-message article covers the table design.

In the run, two job-42 messages were delivered (the core one and the JetStream one), and one report was created.

Acknowledging first and processing after is the opposite trade: no duplicates, but a crash loses the job. Pick it only if losing work is acceptable, and say so in the design doc.

On the producer side, the mirror problem is "save the order, then publish". A crash between the two loses the event. The outbox pattern solves that half, and its relay should publish with MsgId so its own retries collapse.

Replay for a late consumer

Analytics was offline yesterday. With the SENSORS stream on limits retention, it creates its own durable consumer and starts from a point in time:

var analytics = await js.CreateOrUpdateConsumerAsync("SENSORS", new ConsumerConfig("quality-analytics")
{
    AckPolicy = ConsumerConfigAckPolicy.Explicit,
    DeliverPolicy = ConsumerConfigDeliverPolicy.ByStartTime,
    OptStartTime = DateTimeOffset.UtcNow.AddDays(-1),
});

Its progress is tracked separately from every other consumer on the stream, and acknowledging doesn't delete anything; only the stream limits do. DeliverPolicy also supports All, Last, New and ByStartSequence.

Replay isn't exclusive to Kafka, and the question is the same in both: is the data still retained when the consumer comes back? Check before relying on it:

var info = await js.GetStreamAsync("SENSORS");
Console.WriteLine($"{info.Info.State.Messages} msgs since {info.Info.State.FirstTs}");

var consumer = await js.GetConsumerAsync("REPORTS", "report-workers");
Console.WriteLine($"pending={consumer.Info.NumPending}");

FirstTs tells you how far back replay can go. NumPending on the work queue tells you how far behind the workers are. Both are worth exporting as metrics.

What the run printed

From one execution against nats-server -js 2.15.2 on an empty data directory (the core publish took sequence 1):

stored seq=2 duplicate=False
retry seq=2 duplicate=True
REPORTS before consume=2
got job-42 delivered=1
got job-42 delivered=1
pending=0
REPORTS after ack=0
reports created=1

Reading it line by line:

  1. The JetStream publish was stored as sequence 2.
  2. The retry with the same MsgId was recognised as a duplicate: same sequence, nothing new stored.
  3. The stream held two messages, because the core publish had no message ID.
  4. Both were delivered once each.
  5. After the acks, work-queue retention emptied the stream.
  6. The idempotent handler turned two deliveries into one report.

What JetStream will not do for you

  • Exactly-once side effects. Deduplication covers the stream inside a window; your database, emails and HTTP calls need idempotency keys.
  • Keeping data forever. MaxAge and MaxBytes are deletion rules, and a consumer that's down longer than the window has a gap.
  • Choosing your ack timing. Ack after the work and you get duplicates on crash; ack before and you get loss. Decide which one the business tolerates.
  • High availability on one replica. Use replicas in a cluster, and test a node failure with your real configuration.

Key takeaways

  • Core NATS is at most once; JetStream is the storage layer of the same server. "NATS doesn't persist" describes only half of it.
  • The retention policy is the contract. Limits retention is a replay buffer for many readers; work-queue retention is a job queue that deletes on ack.
  • A PubAck proves storage, not processing. Use js.PublishAsync when the producer needs that receipt.
  • MsgId collapses producer retries inside the duplicate window. It doesn't protect anything after delivery.
  • A delivered message isn't a completed job. Use explicit acks, a sane AckWait, a MaxDeliver alert, and a handler that's idempotent on the job ID.

References