Debian Codegraph @

jetstream/MIGRATION.md

raw
1 # Migrating from Legacy JetStream API to `jetstream` Package
2
3 This guide helps you migrate from the legacy JetStream API in the `nats` package
4 (`nats.JetStreamContext`) to the new `jetstream` package
5 (`github.com/nats-io/nats.go/jetstream`).
6
7 - [Why Migrate?](#why-migrate)
8 - [Getting Started](#getting-started)
9 - [Stream Management](#stream-management)
10 - [Consumer Management](#consumer-management)
11 - [Publishing](#publishing)
12 - [Consuming Messages](#consuming-messages)
13 - [Replacing js.Subscribe()](#replacing-jssubscribe)
14 - [Replacing js.PullSubscribe()](#replacing-jspullsubscribe)
15 - [Ordered Consumers](#ordered-consumers)
16 - [Push Consumers](#push-consumers)
17 - [Subscription Options Mapping](#subscription-options-mapping)
18 - [Error Handling in Consume/Messages](#error-handling-in-consumemessages)
19 - [Message Acknowledgement](#message-acknowledgement)
20 - [KeyValue Store](#keyvalue-store)
21 - [Object Store](#object-store)
22
23 ## Why Migrate?
24
25 The legacy JetStream API (`nats.JetStreamContext`) is deprecated. The `jetstream`
26 package provides a cleaner, more predictable API with several key improvements:
27
28 - **Explicit resource management.** Streams and consumers are created and managed
29 explicitly. The legacy `js.Subscribe()` implicitly created consumers behind
30 the scenes, leading to surprising behavior.
31
32 - **Pull consumers as the default.** Pull consumers with `Consume()` and
33 `Messages()` provide the same continuous message delivery as the legacy push-based
34 `Subscribe()`, but with better flow control and no slow consumer issues.
35
36 - **`context.Context` throughout.** All API calls accept `context.Context` for
37 timeout and cancellation, replacing the mix of `MaxWait`, `AckWait`, and
38 `Context()` options.
39
40 - **Clear interface separation.** Instead of one large `JetStreamContext` interface,
41 functionality is split across focused interfaces: `JetStream`, `Stream` and
42 `Consumer`.
43
44 ## Getting Started
45
46 The core NATS connection remains unchanged. Only the JetStream initialization
47 differs:
48
49 ```go
50 import (
51 "github.com/nats-io/nats.go"
52 "github.com/nats-io/nats.go/jetstream"
53 )
54
55 nc, _ := nats.Connect(nats.DefaultURL)
56 ```
57
58 **Legacy:**
59
60 ```go
61 js, _ := nc.JetStream()
62
63 // With domain
64 js, _ := nc.JetStream(nats.Domain("hub"))
65
66 // With custom API prefix
67 js, _ := nc.JetStream(nats.APIPrefix("myprefix"))
68 ```
69
70 **New:**
71
72 ```go
73 js, _ := jetstream.New(nc)
74
75 // With domain
76 js, _ := jetstream.NewWithDomain(nc, "hub")
77
78 // With custom API prefix
79 js, _ := jetstream.NewWithAPIPrefix(nc, "myprefix")
80 ```
81
82 ### Initialization Options
83
84 | Legacy | New |
85 |-----------------------------------|--------------------------------------------|
86 | `nats.Domain(domain)` | `jetstream.NewWithDomain(nc, domain)` |
87 | `nats.APIPrefix(prefix)` | `jetstream.NewWithAPIPrefix(nc, prefix)` |
88 | `nats.PublishAsyncMaxPending(n)` | `jetstream.WithPublishAsyncMaxPending(n)` |
89 | `nats.PublishAsyncErrHandler(cb)` | `jetstream.WithPublishAsyncErrHandler(cb)` |
90
91 ## Stream Management
92
93 `StreamConfig` is essentially the same struct — it just lives in the `jetstream`
94 package now. The new API takes `StreamConfig` by value (not pointer) and
95 management methods return a `Stream` handle instead of `*StreamInfo`.
96
97 | Legacy | New | Notes |
98 |---------------------------------|-------------------------------------|-------------------------------------------------------------------|
99 | `js.AddStream(cfg)` | `js.CreateStream(ctx, cfg)` | Also: `CreateOrUpdateStream()` |
100 | `js.UpdateStream(cfg)` | `js.UpdateStream(ctx, cfg)` | |
101 | `js.DeleteStream(name)` | `js.DeleteStream(ctx, name)` | |
102 | `js.StreamInfo(name)` | `s.Info(ctx)` / `s.CachedInfo()` | Get stream handle first via `js.Stream(ctx, name)` |
103 | `js.PurgeStream(name, opts...)` | `s.Purge(ctx, opts...)` | Options: `WithPurgeSubject`, `WithPurgeSequence`, `WithPurgeKeep` |
104 | `js.GetMsg(name, seq)` | `s.GetMsg(ctx, seq)` | |
105 | `js.GetLastMsg(name, subj)` | `s.GetLastMsgForSubject(ctx, subj)` | |
106 | `js.DeleteMsg(name, seq)` | `s.DeleteMsg(ctx, seq)` | Also: `s.SecureDeleteMsg()` |
107 | `js.Streams()` | `js.ListStreams(ctx)` | Returns lister with `.Info()` channel and `.Err()` |
108 | `js.StreamNames()` | `js.StreamNames(ctx)` | Returns lister with `.Name()` channel and `.Err()` |
109
110 The key architectural difference is that stream-specific operations (purge, get/delete
111 messages) now live on the `Stream` interface instead of the top-level context. Get
112 a stream handle first, then operate on it:
113
114 ```go
115 s, _ := js.Stream(ctx, "ORDERS")
116 s.Purge(ctx)
117 msg, _ := s.GetMsg(ctx, 100)
118 ```
119
120 ## Consumer Management
121
122 The biggest conceptual change: in the legacy API, `js.Subscribe()` would
123 implicitly create consumers. In the new API, consumer creation is always explicit
124 and separate from message consumption.
125
126 | Legacy | New | Notes |
127 |------------------------------------------|----------------------------------------|----------------------------------------------------------------|
128 | `js.AddConsumer(stream, cfg)` | `js.CreateConsumer(ctx, stream, cfg)` | Also: `CreateOrUpdateConsumer()`, `UpdateConsumer()` |
129 | `js.Subscribe(subj, handler)` (implicit) | No equivalent | Must create consumer explicitly first |
130 | `js.ConsumerInfo(stream, name)` | `cons.Info(ctx)` / `cons.CachedInfo()` | Get consumer handle first via `js.Consumer(ctx, stream, name)` |
131 | `js.DeleteConsumer(stream, name)` | `js.DeleteConsumer(ctx, stream, name)` | |
132 | `js.Consumers(stream)` | `s.ListConsumers(ctx)` | Returns lister with `.Info()` channel and `.Err()` |
133 | `js.ConsumerNames(stream)` | `s.ConsumerNames(ctx)` | Returns lister with `.Name()` channel and `.Err()` |
134
135 Consumer management is available at two levels:
136
137 - On `JetStream` — requires stream name as parameter (e.g. `js.CreateConsumer(ctx, "ORDERS", cfg)`), bypassing the need to fetch a stream
138 - On `Stream` — no stream name needed (e.g. `s.CreateConsumer(ctx, cfg)`)
139
140 The new API provides three creation methods:
141
142 - `CreateConsumer` — fails if the consumer already exists with different config
143 - `UpdateConsumer` - fails if the consumer does not exist
144 - `CreateOrUpdateConsumer` — creates or updates as needed
145
146 **Additional notes on consumer behavior:**
147
148 - The default ack policy changed between the APIs. In the legacy API,
149 `AddConsumer()` defaulted to `AckNone`. In the new API, the default is
150 `AckExplicit`.
151
152 - In the legacy API, `sub.Unsubscribe()` on an implicitly created
153 consumer would automatically delete that consumer on the server. The new API
154 does not perform any automatic cleanup - consumers must be deleted explicitly
155 via `DeleteConsumer()`, or via `InactiveThreshold` on the consumer
156 config to let the server remove it automatically after a period of inactivity.
157
158 Push consumers use separate methods: `CreatePushConsumer`, `CreateOrUpdatePushConsumer`,
159 `UpdatePushConsumer`, and `PushConsumer` (for getting a handle).
160
161 ```go
162 s, _ := js.Stream(ctx, "ORDERS")
163 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
164 Durable: "processor",
165 })
166 ```
167
168 ## Publishing
169
170 Publishing is largely the same, with the addition of `context.Context` for
171 synchronous operations.
172
173 ### Synchronous Publish
174
175 **Legacy:**
176
177 ```go
178 ack, _ := js.Publish("ORDERS.new", []byte("hello"))
179 ack, _ = js.PublishMsg(&nats.Msg{
180 Subject: "ORDERS.new",
181 Data: []byte("hello"),
182 })
183 ```
184
185 **New:**
186
187 ```go
188 ack, _ := js.Publish(ctx, "ORDERS.new", []byte("hello"))
189 ack, _ = js.PublishMsg(ctx, &nats.Msg{
190 Subject: "ORDERS.new",
191 Data: []byte("hello"),
192 })
193 ```
194
195 ### Async Publish
196
197 **Legacy:**
198
199 ```go
200 ackF, _ := js.PublishAsync("ORDERS.new", []byte("hello"))
201
202 select {
203 case ack := <-ackF.Ok():
204 fmt.Println(ack.Sequence)
205 case err := <-ackF.Err():
206 fmt.Println(err)
207 }
208
209 // Wait for all pending acks
210 <-js.PublishAsyncComplete()
211 ```
212
213 **New:**
214
215 ```go
216 // Async publish does not take context (returns immediately)
217 ackF, _ := js.PublishAsync("ORDERS.new", []byte("hello"))
218
219 select {
220 case ack := <-ackF.Ok():
221 fmt.Println(ack.Sequence)
222 case err := <-ackF.Err():
223 fmt.Println(err)
224 }
225
226 <-js.PublishAsyncComplete()
227 ```
228
229 ### Publish Options
230
231 | Legacy | New |
232 |------------------------------------------|---------------------------------------------------|
233 | `nats.MsgId(id)` | `jetstream.WithMsgID(id)` |
234 | `nats.ExpectStream(name)` | `jetstream.WithExpectStream(name)` |
235 | `nats.ExpectLastSequence(seq)` | `jetstream.WithExpectLastSequence(seq)` |
236 | `nats.ExpectLastSequencePerSubject(seq)` | `jetstream.WithExpectLastSequencePerSubject(seq)` |
237 | `nats.ExpectLastMsgId(id)` | `jetstream.WithExpectLastMsgID(id)` |
238 | `nats.RetryWait(dur)` | `jetstream.WithRetryWait(dur)` |
239 | `nats.RetryAttempts(n)` | `jetstream.WithRetryAttempts(n)` |
240 | `nats.StallWait(dur)` | `jetstream.WithStallWait(dur)` |
241
242 ## Consuming Messages
243
244 This is the most significant area of change. The legacy API offered many
245 subscription flavors (`Subscribe`, `SubscribeSync`, `QueueSubscribe`,
246 `ChanSubscribe`, `PullSubscribe`) that blurred the line between consumer
247 creation, stream lookup and message consumption. The new API separates these
248 concerns: first create a consumer, then choose how to receive messages.
249
250 With the exception of PullSubscribe, all legacy subscription flavors utilized push consumers under the hood. The new API recommends pull consumers for all use cases, as they provide better flow control and no risk of slow consumer issues. Pull-based consumption is available via `Consume()` and `Messages()`, which maintain persistent pull subscriptions with pre-buffering for efficient continuous delivery. Push consumers are still supported for users who prefer that model, but pull consumers are the recommended default.
251
252 ### Replacing `js.Subscribe()`
253
254 The legacy `js.Subscribe()` created a push consumer behind the scenes (unless
255 explicitly specified otherwise via `nats.Bind()` or `nats.Durable()`) and
256 delivered messages either via a callback. In the new API, the recommended
257 replacement is a **pull consumer** with `Consume()` or `Messages()`. These
258 provide the same continuous delivery with better flow control.
259
260 #### Legacy: callback subscription
261
262 ```go
263 sub, _ := js.Subscribe("ORDERS.*", func(msg *nats.Msg) {
264 fmt.Printf("Received: %s\n", string(msg.Data))
265 msg.Ack()
266 }, nats.Durable("processor"), nats.ManualAck)
267 defer sub.Unsubscribe()
268 ```
269
270 #### New: callback with `Consume()`
271
272 `Consume()` is the closest equivalent to `js.Subscribe()` — it delivers messages
273 to a callback function continuously.
274
275 ```go
276 s, _ := js.Stream(ctx, "ORDERS")
277 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
278 Durable: "processor",
279 FilterSubject: "ORDERS.*",
280 })
281
282 cc, _ := cons.Consume(func(msg jetstream.Msg) {
283 fmt.Printf("Received: %s\n", string(msg.Data()))
284 msg.Ack()
285 })
286 defer cc.Stop()
287 ```
288
289 > Note: `ManualAck()` is not needed — messages are never auto-acknowledged in
290 > the new API.
291
292 #### New: iterator with `Messages()`
293
294 `Messages()` provides an iterator-based approach, useful when you want explicit
295 control over when the next message is fetched.
296
297 ```go
298 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
299 Durable: "processor",
300 FilterSubject: "ORDERS.*",
301 })
302
303 iter, _ := cons.Messages()
304 for {
305 msg, err := iter.Next()
306 if err != nil {
307 // handle error
308 }
309 fmt.Printf("Received: %s\n", string(msg.Data()))
310 msg.Ack()
311 }
312 // Call iter.Stop() when done
313 ```
314
315 Both `Consume()` and `Messages()` maintain overlapping pull requests to the
316 server, providing efficient continuous delivery without gaps.
317
318 #### Legacy: synchronous subscription
319
320 ```go
321 sub, _ := js.SubscribeSync("ORDERS.*", nats.Durable("processor"))
322 msg, _ := sub.NextMsg(time.Second)
323 ```
324
325 **New:** Use `Messages()` and call `Next()`:
326
327 ```go
328 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
329 Durable: "processor",
330 FilterSubject: "ORDERS.*",
331 })
332
333 iter, _ := cons.Messages()
334 msg, _ := iter.Next()
335 ```
336
337 #### Legacy: queue subscription
338
339 ```go
340 // Multiple instances share work via a queue group
341 sub, _ := js.QueueSubscribe("ORDERS.*", "workers", handler,
342 nats.Durable("processor"))
343 ```
344
345 **New with pull consumers:** With pull consumers, there is no need for an
346 explicit queue group. Multiple application instances (or goroutines) calling
347 `Consume()` or `Messages()` on the same durable consumer will naturally
348 distribute messages among themselves — the server tracks pending acknowledgements
349 and avoids delivering the same message to multiple consumers:
350
351 ```go
352 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
353 Durable: "processor",
354 })
355
356 cc, _ := cons.Consume(handler)
357 defer cc.Stop()
358 ```
359
360 **New with push consumers:** If you need push-based queue semantics, set
361 `DeliverGroup` on a push consumer — this is the direct equivalent of the legacy
362 queue group:
363
364 ```go
365 cons, _ := s.CreateOrUpdatePushConsumer(ctx, jetstream.ConsumerConfig{
366 Durable: "processor",
367 DeliverSubject: "deliver.orders",
368 DeliverGroup: "workers",
369 })
370
371 cc, _ := cons.Consume(handler)
372 defer cc.Stop()
373 ```
374
375 > **Note:** Push consumers with `DeliverGroup` cannot be flow controlled. If you
376 > experience slow consumer issues, consider using pull-based consumers instead —
377 > multiple instances on the same durable consumer achieve the same work
378 > distribution without the slow consumer risk.
379
380 #### Legacy: channel subscription
381
382 ```go
383 ch := make(chan *nats.Msg, 64)
384 sub, _ := js.ChanSubscribe("ORDERS.*", ch, nats.Durable("processor"))
385
386 for msg := range ch {
387 msg.Ack()
388 }
389 ```
390
391 **New:** There is no direct channel-based equivalent. Use `Consume()` or
392 `Messages()` instead.
393
394 ### Replacing `js.PullSubscribe()`
395
396 The legacy pull subscription required creating a subscription and then calling
397 `Fetch()` in a loop.
398
399 #### Legacy: pull subscribe + fetch loop
400
401 ```go
402 sub, _ := js.PullSubscribe("ORDERS.*", "processor")
403
404 for {
405 msgs, _ := sub.Fetch(10, nats.MaxWait(5*time.Second))
406 for _, msg := range msgs {
407 fmt.Printf("Received: %s\n", string(msg.Data))
408 msg.Ack()
409 }
410 }
411 ```
412
413 **New with `Fetch()`/`FetchNoWait()` (one-off batch):**
414
415 If you specifically need one-off batch fetching, `Fetch()` is available directly
416 on the consumer — no separate subscription step:
417
418 ```go
419 cons, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
420 Durable: "processor",
421 FilterSubject: "ORDERS.*",
422 })
423
424 // non-blocking, returns a `FetchResult` that provides messages and error
425 msgs, _ := cons.Fetch(10, jetstream.FetchMaxWait(5*time.Second))
426 for msg := range msgs.Messages() {
427 fmt.Printf("Received: %s\n", string(msg.Data()))
428 msg.Ack()
429 }
430 if msgs.Error() != nil {
431 // handle error
432 }
433 ```
434
435 > **Warning:** `Fetch()`, `FetchNoWait()`, and `FetchBytes()` are one-off,
436 > single pull requests. They do not perform pre-buffering optimizations. For
437 > continuous message processing, always prefer `Consume()` or `Messages()`.
438 > When using `FetchBytes()`, the requested byte size must stay under the
439 > client's max pending bytes limit (64MB by default), otherwise it will trigger
440 > slow consumer errors on the underlying subscription.
441
442 ### Ordered Consumers
443
444 Ordered consumers provide strictly ordered, gap-free message delivery. The library
445 automatically recreates the underlying consumer on sequence gaps or heartbeat
446 failures.
447
448 **Legacy:**
449
450 ```go
451 sub, _ := js.Subscribe("ORDERS.*", handler, nats.OrderedConsumer())
452 ```
453
454 **New:**
455
456 ```go
457 cons, _ := js.OrderedConsumer(ctx, "ORDERS", jetstream.OrderedConsumerConfig{
458 FilterSubjects: []string{"ORDERS.*"},
459 })
460
461 // Use the same consumption methods as regular consumers
462 cc, _ := cons.Consume(func(msg jetstream.Msg) {
463 fmt.Printf("Received: %s\n", string(msg.Data()))
464 })
465 defer cc.Stop()
466 ```
467
468 ### Push Consumers
469
470 Pull consumers are recommended for most use cases, but push consumers are also
471 supported. Push consumers require `DeliverSubject` in their config and only
472 support `Consume()` (not `Fetch()` or `Messages()`).
473
474 **Legacy:**
475
476 ```go
477 sub, _ := js.Subscribe("ORDERS.*", handler,
478 nats.Durable("processor"),
479 nats.DeliverSubject("deliver.orders"),
480 nats.IdleHeartbeat(30*time.Second),
481 )
482 ```
483
484 **New:**
485
486 ```go
487 cons, _ := s.CreateOrUpdatePushConsumer(ctx, jetstream.ConsumerConfig{
488 Durable: "processor",
489 FilterSubject: "ORDERS.*",
490 DeliverSubject: "deliver.orders",
491 IdleHeartbeat: 30 * time.Second,
492 })
493
494 cc, _ := cons.Consume(func(msg jetstream.Msg) {
495 fmt.Printf("Received: %s\n", string(msg.Data()))
496 msg.Ack()
497 })
498 defer cc.Stop()
499 ```
500
501 ### Subscription Options Mapping
502
503 Most legacy `SubOpt` options map directly to `ConsumerConfig` fields. Since
504 consumer creation is explicit, these are set at creation time rather than passed
505 as subscription options.
506
507 | Legacy SubOpt | New ConsumerConfig field |
508 |-------------------------------------|---------------------------------------------------------------------------|
509 | `nats.Durable("name")` | `Durable: "name"` |
510 | `nats.ConsumerName("name")` | `Name: "name"` |
511 | `nats.Description("desc")` | `Description: "desc"` |
512 | `nats.DeliverAll()` | `DeliverPolicy: jetstream.DeliverAllPolicy` |
513 | `nats.DeliverLast()` | `DeliverPolicy: jetstream.DeliverLastPolicy` |
514 | `nats.DeliverLastPerSubject()` | `DeliverPolicy: jetstream.DeliverLastPerSubjectPolicy` |
515 | `nats.DeliverNew()` | `DeliverPolicy: jetstream.DeliverNewPolicy` |
516 | `nats.StartSequence(seq)` | `DeliverPolicy: jetstream.DeliverByStartSequencePolicy, OptStartSeq: seq` |
517 | `nats.StartTime(t)` | `DeliverPolicy: jetstream.DeliverByStartTimePolicy, OptStartTime: &t` |
518 | `nats.AckExplicit()` | `AckPolicy: jetstream.AckExplicitPolicy` |
519 | `nats.AckAll()` | `AckPolicy: jetstream.AckAllPolicy` |
520 | `nats.AckNone()` | `AckPolicy: jetstream.AckNonePolicy` |
521 | `nats.ManualAck()` | Not needed (messages are never auto-acked) |
522 | `nats.MaxDeliver(n)` | `MaxDeliver: n` |
523 | `nats.MaxAckPending(n)` | `MaxAckPending: n` |
524 | `nats.BackOff(durations)` | `BackOff: durations` |
525 | `nats.ReplayOriginal()` | `ReplayPolicy: jetstream.ReplayOriginalPolicy` |
526 | `nats.ReplayInstant()` | `ReplayPolicy: jetstream.ReplayInstantPolicy` |
527 | `nats.RateLimit(bps)` | `RateLimit: bps` |
528 | `nats.HeadersOnly()` | `HeadersOnly: true` |
529 | `nats.InactiveThreshold(dur)` | `InactiveThreshold: dur` |
530 | `nats.ConsumerFilterSubjects(s...)` | `FilterSubjects: s` |
531 | `nats.ConsumerReplicas(n)` | `Replicas: n` |
532 | `nats.ConsumerMemoryStorage()` | `MemoryStorage: true` |
533
534 The following options have no direct equivalent — use the consumer handle
535 directly instead:
536
537 | Legacy SubOpt | New equivalent |
538 |-------------------------------|---------------------------------------------------------------------|
539 | `nats.Bind(stream, consumer)` | `js.Consumer(ctx, stream, consumer)` or `s.Consumer(ctx, consumer)` |
540 | `nats.BindStream(stream)` | Use `js.Stream(ctx, stream)` to get a stream handle |
541 | `nats.OrderedConsumer()` | `js.OrderedConsumer(ctx, stream, cfg)` |
542
543 ### Consume/Messages Options
544
545 `Consume()` and `Messages()` accept options that control pull request behavior:
546
547 | Option | Description |
548 |----------------------------|--------------------------------------------------------------|
549 | `PullMaxMessages(n)` | Max messages buffered (default: 500) |
550 | `PullMaxBytes(n)` | Max bytes buffered (mutually exclusive with PullMaxMessages) |
551 | `PullExpiry(dur)` | Pull request timeout (default: 30s) |
552 | `PullHeartbeat(dur)` | Idle heartbeat interval |
553 | `PullThresholdMessages(n)` | Refill threshold (default: 50% of max) |
554 | `PullThresholdBytes(n)` | Byte-based refill threshold |
555 | `StopAfter(n)` | Auto-stop after N messages |
556 | `ConsumeErrHandler(fn)` | Custom error handler |
557
558 ### Error Handling in Consume/Messages
559
560 Both `Consume()` and `Messages()` handle server-sent status messages internally.
561 Some errors are terminal (stop consumption), while others are recoverable
562 (consumption continues).
563
564 **Terminal errors** — consumption stops automatically:
565
566 - `ErrConsumerDeleted` — the consumer was deleted on the server
567 - `ErrBadRequest` — invalid request (e.g. misconfigured consumer)
568 - Connection closed — for `Consume()` this surfaces as `ErrConnectionClosed`;
569 for `Messages()`, `Next()` returns `ErrMsgIteratorClosed`
570
571 **Recoverable errors** — reported via error handler, consumption continues:
572
573 - `ErrNoHeartbeat` — missed idle heartbeats from server; a new pull request
574 is issued automatically
575 - `ErrConsumerLeadershipChanged` — consumer moved to a different server in the
576 cluster; pending counts are reset
577 - `nats.ErrNoResponders` — no JetStream service available (temporary)
578
579 #### Error handling with `Consume()`
580
581 Use `ConsumeErrHandler` to be notified about both terminal and recoverable errors:
582
583 ```go
584 cc, _ := cons.Consume(func(msg jetstream.Msg) {
585 msg.Ack()
586 }, jetstream.ConsumeErrHandler(func(cc jetstream.ConsumeContext, err error) {
587 if errors.Is(err, jetstream.ErrConsumerDeleted) ||
588 errors.Is(err, jetstream.ErrBadRequest) {
589 log.Fatalf("terminal consumer error: %v", err)
590 }
591 log.Printf("recoverable consumer error: %v", err)
592 }))
593 defer cc.Stop()
594 ```
595
596 #### Error handling with `Messages()`
597
598 With `Messages()`, terminal errors are returned directly by `Next()`. By default,
599 `ErrNoHeartbeat` is also returned by `Next()` (controlled by
600 `WithMessagesErrOnMissingHeartbeat`), but it is not terminal — you can continue
601 calling `Next()`:
602
603 ```go
604 iter, _ := cons.Messages()
605 for {
606 msg, err := iter.Next()
607 if err != nil {
608 if errors.Is(err, jetstream.ErrMsgIteratorClosed) {
609 // iterator was stopped (either explicitly or due to connection close)
610 break
611 }
612 if errors.Is(err, jetstream.ErrNoHeartbeat) {
613 // recoverable — new pull request is issued, keep going
614 log.Println("missed heartbeat, re-pulling")
615 continue
616 }
617 // ErrConsumerDeleted, ErrBadRequest are terminal
618 log.Fatalf("terminal error: %v", err)
619 }
620 msg.Ack()
621 }
622 ```
623
624 ## Message Acknowledgement
625
626 Ack methods are similar, with minor naming changes. The main difference is that
627 message fields are accessed via methods instead of struct fields.
628
629 | Legacy | New |
630 |-------------------------|------------------------------|
631 | `msg.Ack()` | Unchanged |
632 | `msg.AckSync()` | `msg.DoubleAck(ctx)` |
633 | `msg.Nak()` | Unchanged |
634 | `msg.NakWithDelay(dur)` | Unchanged |
635 | `msg.InProgress()` | Unchanged |
636 | `msg.Term()` | Unchanged |
637 | N/A | `msg.TermWithReason(reason)` |
638 | `msg.Metadata()` | Unchanged |
639
640 ### Accessing Message Data
641
642 **Legacy:** Direct struct fields on `*nats.Msg`:
643
644 ```go
645 fmt.Println(string(msg.Data))
646 fmt.Println(msg.Subject)
647 fmt.Println(msg.Header.Get("key"))
648 ```
649
650 **New:** Methods on `jetstream.Msg` interface:
651
652 ```go
653 fmt.Println(string(msg.Data()))
654 fmt.Println(msg.Subject())
655 fmt.Println(msg.Headers().Get("key"))
656 ```
657
658 ## KeyValue Store
659
660 The KV API is nearly identical. The main changes are:
661
662 1. All methods take `context.Context` as the first parameter
663 2. New `CreateOrUpdateKeyValue()` and `UpdateKeyValue()` methods
664 3. Types live in the `jetstream` package
665
666 **Legacy:**
667
668 ```go
669 js, _ := nc.JetStream()
670 kv, _ := js.CreateKeyValue(&nats.KeyValueConfig{
671 Bucket: "profiles",
672 })
673
674 kv.Put("sue.color", []byte("blue"))
675 entry, _ := kv.Get("sue.color")
676 fmt.Println(string(entry.Value()))
677
678 watcher, _ := kv.Watch("sue.*")
679 defer watcher.Stop()
680 ```
681
682 **New:**
683
684 ```go
685 js, _ := jetstream.New(nc)
686 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{
687 Bucket: "profiles",
688 })
689
690 kv.Put(ctx, "sue.color", []byte("blue"))
691 entry, _ := kv.Get(ctx, "sue.color")
692 fmt.Println(string(entry.Value()))
693
694 watcher, _ := kv.Watch(ctx, "sue.*")
695 defer watcher.Stop()
696 ```
697
698 ### KV Management Methods
699
700 | Legacy | New |
701 |-----------------------------|---------------------------------------|
702 | `js.KeyValue(bucket)` | `js.KeyValue(ctx, bucket)` |
703 | `js.CreateKeyValue(cfg)` | `js.CreateKeyValue(ctx, cfg)` |
704 | N/A | `js.UpdateKeyValue(ctx, cfg)` |
705 | N/A | `js.CreateOrUpdateKeyValue(ctx, cfg)` |
706 | `js.DeleteKeyValue(bucket)` | `js.DeleteKeyValue(ctx, bucket)` |
707 | `js.KeyValueStoreNames()` | `js.KeyValueStoreNames(ctx)` |
708 | `js.KeyValueStores()` | `js.KeyValueStores(ctx)` |
709
710 ## Object Store
711
712 Same pattern as KV — all methods gain `context.Context`, types move to `jetstream`
713 package.
714
715 **Legacy:**
716
717 ```go
718 js, _ := nc.JetStream()
719 os, _ := js.CreateObjectStore(&nats.ObjectStoreConfig{
720 Bucket: "configs",
721 })
722
723 os.PutString("config-1", "data")
724 result, _ := os.Get("config-1")
725 data, _ := io.ReadAll(result)
726 ```
727
728 **New:**
729
730 ```go
731 js, _ := jetstream.New(nc)
732 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{
733 Bucket: "configs",
734 })
735
736 os.PutString(ctx, "config-1", "data")
737 result, _ := os.Get(ctx, "config-1")
738 data, _ := io.ReadAll(result)
739 ```
740
741 ### Object Store Management Methods
742
743 | Legacy | New |
744 |--------------------------------|------------------------------------------|
745 | `js.ObjectStore(bucket)` | `js.ObjectStore(ctx, bucket)` |
746 | `js.CreateObjectStore(cfg)` | `js.CreateObjectStore(ctx, cfg)` |
747 | N/A | `js.UpdateObjectStore(ctx, cfg)` |
748 | N/A | `js.CreateOrUpdateObjectStore(ctx, cfg)` |
749 | `js.DeleteObjectStore(bucket)` | `js.DeleteObjectStore(ctx, bucket)` |