# The first opt-in JetStream driver had no redelivery cap

> gortexa's opt-in JetStream driver checks server support and preserves stream settings. Tests on nats-server 2.15.3 show why redelivery needs a cap.

Source: https://sheng.page/en/posts/jetstream-opt-in-defaults/ · Published: 2026-11-25 · Author: Sheng

In July 2026 I consolidated gortexa's messaging on NATS. Core NATS is the default; setting `mq.driver: "jetstream"` enables JetStream. I also removed the Kafka backend because it cost more to maintain and compatibility was worse for this use case, with problems such as full local queues in non-Java clients. JetStream was already part of nats.go v1.52.0, so no extra dependency was needed.

The driver probes for JetStream at start-up and checks for an existing stream before creating one, preserving its settings without calling `CreateOrUpdateStream`. It also rejects wildcard topics that could overlap across streams. The first version left failing messages without a delivery limit; that cap arrived in September. The examples below ran on OrbStack on a Mac with nats-server 2.15.3, nats.go v1.52.0 and Go 1.27.4.

## The first error arrives too late

The godoc for `jetstream.New` says it returns a new JetStream instance and doesn't say whether it talks to the server. Against a core server with JetStream switched off:

```go
nc, err := nats.Connect(url)
if err != nil {
	return fmt.Errorf("connect core: %w", err)
}
defer nc.Close()
js, err := jetstream.New(nc)
fmt.Println("jetstream.New error:", err)
if err != nil {
	return err
}
_, err = js.AccountInfo(ctx)
fmt.Println("AccountInfo error:", err)
_, err = js.Publish(ctx, "orders", []byte("x"))
fmt.Println("Publish error:", err)
```

```text
jetstream.New error: <nil>
AccountInfo error: nats: API error: code=503 err_code=10076 description=jetstream not enabled
Publish error: nats: no response from stream
```

`New` succeeds in this run. The next call, `AccountInfo`, returns 10076; Publish then reports that the stream did not respond, without identifying JetStream as disabled. If start-up only constructs the client, the failure can surface at the first publish with little indication of the cause.

gortexa's `NewJetStream` calls `AccountInfo` straight after `New` and fails start-up on `ErrJetStreamNotEnabled` or `ErrJetStreamNotEnabledForAccount`. The godoc warns that a cluster without JetStream may time out instead of returning the server-disabled error, so the driver rejects other probe failures too.

## CreateOrUpdateStream rewrites a stream someone else set up

Calling `CreateOrUpdateStream` for each topic creates a stream if it's missing and updates it if it exists. The operator may already have created it with their own retention settings, which the update can change. The example creates the stream with the operator's settings, then calls the API with the framework's defaults:

```go
_, err := js.CreateStream(ctx, jetstream.StreamConfig{
	Name: "app_orders", Subjects: []string{"orders"},
	MaxAge: 72 * time.Hour, MaxMsgs: 100000,
})
// ...
_, err = js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name: "app_orders", Subjects: []string{"orders"},
})
```

```text
operator  MaxAge=72h0m0s MaxMsgs=100000
CreateOrUpdateStream error: <nil>
after     MaxAge=0s MaxMsgs=-1
CreateStream with different config error: nats: API error: code=400 err_code=10058 description=stream name already in use
```

The call succeeds and removes both retention limits. Passing these defaults on every restart would keep overwriting the operator's settings, even though the framework only needs to ensure the stream exists. `CreateStream` with a different config for an existing name returns 10058 and leaves the stream alone.

gortexa looks the stream up first. If `Stream()` finds it, the framework keeps its settings and checks only that its subjects cover the topic. Otherwise, `CreateStream` makes one with a 24-hour age limit. If two instances try to create it at once, identical configs can both succeed; on `ErrStreamNameAlreadyInUse`, the instance looks it up again and checks the subjects. The stream name is `gortexa_` plus the topic, with characters replaced and a hash appended only when the topic contains characters that need replacing.

## Wildcard topics make stream subjects overlap

Core NATS subscriptions accept `*` and `>`. With a separate JetStream stream for each topic, a wildcard can make their subjects overlap:

```go
js.CreateStream(ctx, jetstream.StreamConfig{
	Name: "app_events_all", Subjects: []string{"events.*"},
})
_, err := js.CreateStream(ctx, jetstream.StreamConfig{
	Name: "app_events_created", Subjects: []string{"events.created"},
})
```

```text
second stream error: nats: API error: code=400 err_code=10065 description=subjects overlap with an existing stream
ErrorCode: 10065
```

10065 means the subjects overlap, and retrying won't fix it while the configuration stays the same. gortexa's JetStream driver accepts literal topics only: `*`, `>` or an empty token makes Publish and Subscribe return InvalidArgument, and wildcards are left to core NATS. Consumers also set `FilterSubject`, so an operator's stream carrying extra subjects still delivers only the requested topic.

## Where a failing handler should stop

JetStream is at-least-once by default. When a handler returns an error and the driver calls `NakWithDelay`, the same message comes back after the delay:

```text
got "order o1 credit 100" delivery=1
got "order o1 credit 100" delivery=2
```

A message can be processed more than once, so handlers have to be idempotent. gortexa's fan-out uses an ephemeral consumer with `DeliverNewPolicy`, which receives only messages published after the consumer is created. Members with a group_id share a durable consumer: each delivery goes to one member, and a redelivery may go to someone else.

An ephemeral consumer's `InactiveThreshold` defaults to 5 seconds only when neither the consumer nor the stream sets it; a pull consumer counts as inactive when no pull requests arrive.

With `MaxDeliver` unset, repeated handler failures have no delivery cap: the server default is -1. In the example the handler Naks every delivery with a 100 ms delay:

```text
poison-max-0 server MaxDeliver=-1
poison-max-0 deliveries in 3s: 30
poison-max-3 server MaxDeliver=3
poison-max-3 deliveries in 3s: 3
```

The consumer without a limit took 30 deliveries in three seconds, a number that depends on scheduling. With the limit at 3 it stopped at the third. The limit counts the first delivery, and stopping redelivery doesn't mean the message was handled.

In the first version, from July 2026, every handler error led to `NakWithDelay(1s)` with `MaxDeliver` unset. Streams created by the framework have a 24-hour age limit, after which the message can no longer be redelivered. On an existing stream with no age limit, redelivery can continue while the message remains and the consumer keeps running, occupying an ack-pending slot.

A review in September led to a `MaxDeliver` limit of 10 and delays that increase with the delivery count: 1 second, 5 seconds, 30 seconds, 1 minute, then 5 minutes for every later attempt. The framework treats a handler's InvalidArgument as non-retryable and calls `Term`, so misclassifying an error can stop redelivery prematurely.

The backoff doesn't use `ConsumerConfig.BackOff`, because that would also replace `AckWait` with its first step of 1 second. A slow first attempt could then be redelivered before it finishes.

A `Nats-Msg-Id` header lets the stream drop duplicates within its `Duplicates` window, 2 minutes by default, and `DoubleAck` waits for the server to confirm the ack. These mechanisms don't guarantee exactly-once effects in an external system. gortexa doesn't implement this combination, so its handlers still need to be idempotent.

## Notes

- In the example, `jetstream.New` succeeds against a server without JetStream. `AccountInfo` reports the missing support; Publish only gives "no response from stream".
- In the example, `CreateOrUpdateStream` reset MaxAge and MaxMsgs to unlimited without an error; gortexa looks streams up first and keeps an existing stream's settings.
- Overlapping stream subjects fail with 10065. Retrying with the same configuration cannot resolve the overlap, so the JetStream driver accepts literal topics only.
- Under at-least-once delivery, handlers have to be idempotent, and `MaxDeliver` defaults to -1 with no limit. gortexa's first version missed this; September added a cap of 10 and increasing delays. A handler's InvalidArgument causes `Term`.

## Further reading

- nats.go, "[jetstream package](https://pkg.go.dev/github.com/nats-io/nats.go@v1.52.0/jetstream)": official godoc for `New`, `AccountInfo`, `CreateStream` and `CreateOrUpdateStream`, and the `ConsumerConfig` defaults for `MaxDeliver`, `AckWait` and `InactiveThreshold`.
- NATS Docs, "[JetStream errors](https://docs.nats.io/reference/2.11/jetstream/errors)": the official error code table; 10065 is `JSStreamSubjectOverlapErr`.
- NATS Docs, "[Ack responses and redelivery](https://docs.nats.io/learn/jetstream/acknowledgment)": official documentation on acks, Nak and redelivery.
- NATS Docs, "[JetStream](https://docs.nats.io/concepts/jetstream)": official overview; core NATS is at-most-once and JetStream is at-least-once.
- Wikipedia, "[Publish–subscribe pattern](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)": encyclopaedia entry; pub/sub alone doesn't guarantee delivery, which has to be designed in separately.

> Ideas and technical judgement by Sheng; drafted with Claude · Examples run in OrbStack containers on a Mac (nats-server 2.15.3, nats.go v1.52.0, Go 1.27.4); gortexa code as of commit b79a99a.