Running a basic NATS JetStream cluster


Running a basic NATS JetStream cluster

NATS JetStream

NATS is a system that allows applications to communicate. According to their official page “… is responsible for addressing, discovery and exchanging of messages that drive the common patterns in distributed systems”. Meanwhile, JetStream is a built-in distributed persistence system, that further enhances NATS. It provides streaming, replay/retention policies, mirroring, and many other features.

Downloading NATS Server

The latest release is available at https://github.com/nats-io/nats-server/releases. After downloading the one that suits you the most, extract the contents to a folder.

Configuring a NATS JetStream cluster

After following the installation steps above, we must now configure our cluster. To do so, we must create a config file for each one of our nodes. We are going for a very simple example, so they will be minimal and similar to each other. We will be calling our files “node1.conf“, “node2.conf” and “node3.conf“.

server_name=n1-c1
listen=4222

jetstream {
   store_dir=/nats/storage
}

cluster {
  name: C1
  listen: 0.0.0.0:6222
  routes: [
    nats://0.0.0.0:6223
    nats://0.0.0.0:6224
  ]
}
server_name=n2-c1
listen=4223

jetstream {
   store_dir=/nats/storage
}

cluster {
  name: C1
  listen: 0.0.0.0:6223
  routes: [
    nats://0.0.0.0:6222
    nats://0.0.0.0:6224
  ]
}
server_name=n3-c1
listen=4224

jetstream {
   store_dir=/nats/storage
}

cluster {
  name: C1
  listen: 0.0.0.0:6224
  routes: [
    nats://0.0.0.0:6223
    nats://0.0.0.0:6222
  ]
}

Let’s go over the settings and see what they mean:

  • server_name: a name that must be unique across the cluster.
  • listen: the IP address to listen for client connections. In this case, since we only specified the port, it defaults to localhost.
  • jetstream.store_dir: the directory for JetStream storage.
  • cluster.name: the name of our cluster.
  • cluster.listen: the IP address to listen for route connections from other nodes in the cluster.
  • cluster.routes: the list of other nodes in the cluster to connect to.

Running the NATS cluster

These configurations will be enough to get us a basic NATS cluster. Now, we need a way to actually start our cluster. We can do so by creating a simple .bat file that boots up three NATS nodes. The script below assumes that we are completely disregarding any organization practices and dumping all files in one folder, otherwise it will fail to start the nats-server, and also to find its .conf file.

start nats-server -c node1.conf
start nats-server -c node2.conf
start nats-server -c node3.conf