How to use NATS JetStream Key/Value Store in Golang

In this post, I will briefly introduce the NATS JetStream Key/Value Store using an example with Go programming language. If you’re using NATS ecosystem in your systems architecture, you can further leverage the Key/Value Store as a mechanism for a consistent key/value store for various use cases like dynamic configurations for distributed systems and microservices.

Introduction to JetStream Key/Value Store

The NATS JetSteam, the persistence layer of NATS, provides a distributed streaming platform that lets you capture streams of messages (stream of events) from distributed systems, IoT sensors and Edge devices, and persist these data streams into persistent stores. Because you persist these data streams into persistent stores, you can replay it for retrieval, processing, and reactive to those stream of events by using an event-driven architecture.

The JetSteam platform now introduces a Key/Value Store, which allows applications to create buckets and use them as an immediately consistent, Key/Value store by leveraging the existing capabilities of JetSteam.

Persistent Store of Key/Value Store

The Key/Value store uses Stream of JetStream to persist Key/Value store using buckets. The bucket of Key/Value store persist as a Stream of JetStream. For example, when you create a bucket with name discoveey for persisting Key/Value store associated with that particular bucket, it will create a Stream with name KV_discovery.

The figure below shows the storage representation of a bucket “discovery” as a Stream with file storage at the server.

Figure 1. Stream for a Key/Value store bucket “discovery”

You can persist and retrieve to and from the Key/Value store using the NATS CLI tool as well as programmatically using a Client SDK.

JetStream Key/Value Store example in Go

Let’s write a simple example to understand how to working with NATS JetStream Key/Value Store by using the nats.go Go client SDK.