Example in Go
Create a KV Bucket
js, _ := nc.JetStream() kv, _ := js.CreateKeyValue(&nats.KeyValueConfig{ Bucket: "CONFIGS", })
Put a Value
kv.Put("featureX.enabled", []byte("true"))
Get a Value
entry, _ := kv.Get("featureX.enabled") fmt.Printf("Value: %s\n", string(entry.Value()))
Watch for Changes
watch, _ := kv.Watch("featureX.*") for update := range watch.Updates() { if update != nil { fmt.Printf("Key %s changed to %s\n", update.Key(), string(update.Value())) } }
With Watch
, any time a key is updated, subscribers get notified instantly.
Use Case Examples
- Feature Flags
- Key:
featureX.enabled
→ Value:true/false
. - All services watch this key and automatically switch behavior when it changes.
- Key:
- Service Discovery (Lightweight)
- Key:
service.auth.url
→ Value:http://10.0.0.5:8080
. - Clients always read the latest location of a service.
- Key:
- Leader Election
- Services write a key like
leader=node1
. - Others watch the key to know who the leader is.
- Services write a key like
Final Thoughts
The NATS KV store is not meant to replace a full database, but it’s perfect for lightweight state, configuration, and coordination. Because it’s built on top of JetStream, it’s reliable and supports history of changes.
Pages: 1 2
Category: NATS