NATS is a lightweight, high-throughput messaging system popular for microservices, IoT, and cloud-native architectures. UUID v7 pairs naturally with NATS JetStream’s deduplication model and request-reply patterns — the timestamp prefix aligns deduplication windows with real time. See UUID v7 in Microservices for the broader distributed systems context.

JetStream with UUID v7 message IDs (Go)

package main

import (
    "context"
    "log"
    "time"

    "github.com/google/uuid"
    "github.com/nats-io/nats.go"
    "github.com/nats-io/nats.go/jetstream"
)

func main() {
    nc, _ := nats.Connect(nats.DefaultURL)
    defer nc.Close()

    js, _ := jetstream.New(nc)

    // Create stream with deduplication window
    _, err := js.CreateStream(context.Background(), jetstream.StreamConfig{
        Name:       "ORDERS",
        Subjects:   []string{"orders.>"},
        Duplicates: 5 * time.Minute, // UUID v7 dedup window
    })
    if err != nil {
        log.Println("Stream exists:", err)
    }

    // Publish with UUID v7 message ID
    msgID, _ := uuid.NewV7()
    _, err = js.Publish(context.Background(), "orders.created", []byte(`{
        "order_id": "018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f",
        "total": 49.99
    }`), jetstream.WithMsgID(msgID.String()))
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Published with ID: %s", msgID)
}

Consumer with deduplication (Go)

func consumeOrders(js jetstream.JetStream) {
    consumer, _ := js.CreateConsumer(context.Background(), "ORDERS", jetstream.ConsumerConfig{
        Name:       "order-processor",
        FilterSubject: "orders.>",
        AckPolicy:  jetstream.AckExplicitPolicy,
    })

    consumer.Consume(func(msg jetstream.Msg) {
        msgID := msg.Headers().Get(nats.MsgIdHdr) // UUID v7

        // Extract creation time from UUID v7 message ID
        id, _ := uuid.Parse(msgID)
        ts, _ := uuid.TimestampFromV7(id)
        t, _ := ts.Time()
        log.Printf("Processing message created at %s [id=%s]", t.Format(time.RFC3339), msgID)

        if err := processOrder(msg.Data()); err != nil {
            msg.Nak()
            return
        }
        msg.Ack()
    })
}

JavaScript/Node.js with UUID v7

import { connect, StringCodec, headers } from 'nats';
import { v7 as uuidv7 } from 'uuid';

const nc = await connect({ servers: 'nats://localhost:4222' });
const js = nc.jetstream();
const sc = StringCodec();

// Publish with UUID v7 message ID
async function publishOrder(orderId: string, total: number) {
  const msgId = uuidv7(); // UUID v7 message ID
  const h = headers();
  h.set('Nats-Msg-Id', msgId);
  h.set('X-Correlation-Id', msgId); // Also usable as correlation ID

  await js.publish('orders.created',
    sc.encode(JSON.stringify({ orderId, total })),
    { headers: h }
  );
  return msgId;
}

// Request-reply with UUID v7 correlation
async function getOrderStatus(orderId: string): Promise<string> {
  const correlationId = uuidv7();
  const h = headers();
  h.set('X-Correlation-Id', correlationId);

  const response = await nc.request(
    `orders.${orderId}.status`,
    sc.encode(JSON.stringify({ correlationId })),
    { timeout: 5000, headers: h }
  );

  const body = JSON.parse(sc.decode(response.data));
  // correlationId in response matches our UUID v7 — confirms round-trip
  return body.status;
}

UUID v7 in NATS subject routing

// Embed UUID v7 in subject for per-order routing
const orderId = uuidv7();
const subject = `orders.${orderId}.created`;

// Publisher
await nc.publish(subject, sc.encode(JSON.stringify({ total: 49.99 })));

// Subscriber: listen to all orders from a specific time window
const startTime = uuidv7({ msecs: Date.now() - 3600_000 }); // 1 hour ago UUID
const endSubject = `orders.${startTime}.>`;

const sub = nc.subscribe('orders.>');
for await (const msg of sub) {
  const orderIdFromSubject = msg.subject.split('.')[1]; // UUID v7
  const createdMs = parseInt(orderIdFromSubject.replace(/-/g, '').slice(0, 12), 16);

  if (createdMs >= Date.now() - 3600_000) {
    console.log(`Recent order: ${orderIdFromSubject}`);
  }
}

Further reading

External references

Frequently asked questions

How do I use UUID v7 as a NATS JetStream message ID?

Set the Nats-Msg-Id header on published messages: msg.Header.Set(nats.MsgIdHdr, uuidV7String) in Go, or { headers: { 'Nats-Msg-Id': uuidv7() } } in JavaScript. JetStream uses this header for exactly-once deduplication — if a message with the same ID is published within the deduplication window, JetStream discards the duplicate. UUID v7's timestamp lets you set a deduplication window that naturally expires old IDs.

How does UUID v7 work as a NATS subject token for routing?

NATS subjects support token wildcards: orders.> matches all sub-subjects. Embedding a UUID v7 in a subject token (e.g. orders.018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f.created) enables per-order subscriptions and routing while preserving chronological ordering. A consumer subscribing to orders.> receives messages ordered by subject lexicographically — which equals creation time for UUID v7 subjects.

Can I use UUID v7 for NATS request-reply correlation?

Yes. Generate a UUID v7 before sending a NATS request and include it in the request payload as a correlation_id. The replier echoes the correlation ID back in the response. UUID v7's timestamp prefix tells you how long the request took from when it was sent (embedded in the ID) to when you received the reply. This replaces custom timestamp headers.