Debian Codegraph @

examples/docs/learn-jetstream-publishing-dedup/main.go

raw
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/nats-io/nats.go"
9 "github.com/nats-io/nats.go/jetstream"
10 )
11
12 func main() {
13 // Connect to the NATS server.
14 nc, err := nats.Connect("nats://localhost:4222")
15 if err != nil {
16 panic(err)
17 }
18 defer nc.Close()
19
20 // Create a JetStream context (the stream manager).
21 js, err := jetstream.New(nc)
22 if err != nil {
23 panic(err)
24 }
25
26 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
27 defer cancel()
28
29 payload := `{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}`
30
31 // NATS-DOC-START
32 // Publish the same message twice with a message ID. The stream uses the ID
33 // to detect duplicates within its dedupe window.
34 first, err := js.Publish(ctx, "orders.created", []byte(payload), jetstream.WithMsgID("ord_8w2k-created"))
35 if err != nil {
36 panic(err)
37 }
38 fmt.Printf("First: sequence %d, duplicate %t\n", first.Sequence, first.Duplicate)
39
40 // Re-publish with the same ID. The server recognizes it and reports the
41 // original sequence instead of storing the message again.
42 second, err := js.Publish(ctx, "orders.created", []byte(payload), jetstream.WithMsgID("ord_8w2k-created"))
43 if err != nil {
44 panic(err)
45 }
46 fmt.Printf("Second: sequence %d, duplicate %t\n", second.Sequence, second.Duplicate)
47 // NATS-DOC-END
48 }