NATS and NATS JetStream: Cloud-Native Messaging and Stream Storage
NATS is a high-performance, lightweight, cloud-native messaging system written in Go. Operating with sub-millisecond latencies and a binary footprint under 20MB, it supports Pub/Sub, Request-Reply RPC, and JetStream distributed streaming persistence.
⚡ Quick Dive
Core NATS vs. NATS JetStream
| Feature | Core NATS | NATS JetStream |
|---|---|---|
| Delivery Model | At-most-once (Fire-and-forget in RAM) | At-least-once / Exactly-once |
| Storage Engine | In-memory only (Zero disk persistence) | Distributed disk log replicated via Raft |
| Consumer Model | Push only | Push or Pull consumers |
| Message Deduplication | ❌ No | ✅ Deduplication window |
| Key-Value Store | ❌ No | ✅ Embedded distributed KV store |
Subject Hierarchies & Wildcards
- Dot Separator (
.): Tokens separated by dots (e.g.orders.us.processed). - Single-Token Wildcard (
*): Matches exactly one token (orders.*.processedmatchesorders.us.processedbut notorders.us.east.processed). - Full-Tail Wildcard (
>): Matches one or more remaining tokens (orders.>matches all sub-subjects).
📖 Extended Guide
1. Synchronous Request-Reply over NATS
NATS implements request-reply RPC using dynamic Inbox Subjects:
Client Service
│ ─── Publish to 'orders.create' (ReplyTo: '_INBOX.8x7a') ──► │ (Processes order)
│ ◄── Publish to '_INBOX.8x7a' (Response: { orderId: 101 }) ─ │
2. JetStream Streams, Consumers & Deduplication
// Go JetStream Producer with Deduplication
js, _ := nc.JetStream()
// Publish message with Msg-Id for idempotent delivery
msg := nats.NewMsg("orders.created")
msg.Header.Set("Nats-Msg-Id", "order-uuid-12345")
msg.Data = []byte(`{"id":"order-uuid-12345","amount":99.99}`)
ack, err := js.PublishMsg(msg)