NATS
NATS provides lightweight, high-performance messaging with simple operations and cloud-native design.
Why NATS
Section titled “Why NATS”| Strength | Benefit |
|---|---|
| Lightweight | Single binary, minimal resources |
| Fast | Sub-millisecond latency |
| Simple | Minimal configuration |
| Cloud native | Built for Kubernetes |
| JetStream | Persistent streaming option |
Trade-offs
Section titled “Trade-offs”| Concern | Consideration |
|---|---|
| Less mature | Smaller ecosystem than Kafka/RabbitMQ |
| Durability | Requires JetStream for persistence |
Configuration
Section titled “Configuration”[bus]backend = "nats"
[bus.nats]url = "nats://localhost:4222"# For JetStream (persistent)jetstream = truestream_name = "angzarr-events"Environment Variables
Section titled “Environment Variables”export NATS_URL="nats://localhost:4222"export BUS_BACKEND="nats"Subject Layout
Section titled “Subject Layout”NATS uses dot-separated subjects for hierarchical routing:
angzarr.events.player.PlayerRegisteredangzarr.events.player.FundsDepositedangzarr.events.hand.CardsDealtSubscriptions
Section titled “Subscriptions”Wildcards enable flexible subscriptions:
angzarr.events.player.* # All player eventsangzarr.events.*.> # All eventsangzarr.events.hand.> # All hand events and sub-subjectsCore NATS vs JetStream
Section titled “Core NATS vs JetStream”Core NATS (Fire and Forget)
Section titled “Core NATS (Fire and Forget)”- Pub/sub without persistence
- At-most-once delivery
- Lowest latency
- Use for ephemeral events
JetStream (Persistent)
Section titled “JetStream (Persistent)”- Stream persistence
- At-least-once delivery
- Consumer replay
- Use for event sourcing
# Enable JetStream for event sourcing[bus.nats]jetstream = trueJetStream Configuration
Section titled “JetStream Configuration”# Create streamnats stream add angzarr-events \ --subjects "angzarr.events.>" \ --retention limits \ --max-msgs -1 \ --max-bytes -1 \ --max-age 7d \ --storage file \ --replicas 3
# Create consumernats consumer add angzarr-events player-projector \ --filter "angzarr.events.player.>" \ --ack explicit \ --deliver all \ --max-deliver 5 \ --replay instantDocker Setup
Section titled “Docker Setup”# Core NATSdocker run -p 4222:4222 nats:latest
# NATS with JetStreamdocker run -p 4222:4222 nats:latest -jsHelm Deployment
Section titled “Helm Deployment”bus: backend: nats
nats: enabled: true url: nats://nats.messaging.svc.cluster.local:4222 jetstream: true streamName: angzarr-eventsMonitoring
Section titled “Monitoring”NATS provides a monitoring endpoint:
http://localhost:8222/varz # Server statshttp://localhost:8222/connz # Connectionshttp://localhost:8222/subsz # Subscriptionshttp://localhost:8222/jsz # JetStream statsWhen to Use NATS
Section titled “When to Use NATS”- Edge computing — Minimal resource footprint
- Kubernetes native — Designed for containers
- Simple operations — Single binary, little config
- High performance — Sub-millisecond latency