How-to guide / Package task guides
Deploy NATS with JetStream
These docs describe Kix's main branch, which can include changes not yet released. Read the docs for the latest release.
Use packages.experimental.nats to deploy NATS 2.15.3 (nats:2.15.3-alpine) with JetStream persistence. Each instance creates a StatefulSet, a client Service (<instance>) on port 4222, a headless Service (<instance>-headless) on port 8222 for pod DNS and HTTP monitoring, and a ConfigMap for nats.conf. Because this package is experimental, breaking changes may ship in any release.
Add a NATS instance and login secret
Section titled “Add a NATS instance and login secret”Add a NATS instance and a natsAuth secret with username and password keys in the same namespace:
1instances.messaging = {2 nats.package = packages.experimental.nats;3 nats-auth = {4 package = packages.secret;5 aliases = [ "natsAuth" ];6 config = {7 source = ./secrets/nats-auth.sops.yaml;8 keys = [ "username" "password" ];9 };10 };11};Client authentication is always on. Every instance requires a natsAuth secret (such as packages.secret or packages.secret-ref) in the same namespace with username and password keys, or kix check fails. nats-server reads those credentials from environment variables so they stay out of the ConfigMap. Changing a packages.secret login restarts the NATS pods automatically. Changing an external Secret referenced with packages.secret-ref does not restart them.
Do not put single quotes (') in username or password. nats-server uses the Secret value byte for byte, so a trailing newline becomes part of the password. If password starts with a bcrypt hash prefix ($2a$, $2b$, $2x$, or $2y$ followed by two digits), nats-server checks client passwords against that hash.
Cluster routes on port 6222 (when clustered) and HTTP monitoring on port 8222 do not use authentication. Port 8222 exposes subjects, client addresses, and connection names, and port 6222 carries cluster traffic. Turn on generated network policy (networkPolicy.enable = true) to restrict port 6222 to the NATS pods and port 8222 to pods that read the monitoring address. Without network policy enforcement, any pod in the cluster can reach both ports.
This package configures no NATS system account, so nats CLI commands that require one (such as nats server list and nats server report) are rejected. Query the HTTP endpoints on port 8222 instead.
You can run multiple NATS instances in one cluster. Instances in different namespaces can share the name nats. To run more than one NATS instance in the same namespace, give each a distinct name, point each instance at its login secret with deps.natsAuth = ref.<namespace>.<secret-instance>, and set deps.nats = ref.<namespace>.<instance> on every consumer in that namespace so Kix knows which NATS instance to connect to.
Choose the topology and storage
Section titled “Choose the topology and storage”Set clustered to choose between a standalone server and a NATS cluster:
- Standalone (
clustered = false, default): runs 1 server (replicasmust be1) and requires availability levelnone. - Clustered (
clustered = true): runs an odd number of at least 3 servers (replicasdefaults to3;5tolerates two lost servers) because JetStream requires a majority quorum. Requires availability levelpod,node, orzone. Pods connect to each other on port 6222 through<instance>-headless. The NATS cluster is named after the instance, and each server is named after its pod.
An instance inherits cluster.availability.default unless you set instances.<namespace>.<instance>.availability. Availability levels never change clustered automatically, and kix check rejects any mismatch before deploying so running servers and their streams stay untouched. For example, if you raise cluster.availability.default from none to pod, kix check stops on every standalone NATS instance until you choose how to handle it:
- Keep an existing server standalone: set
instances.<namespace>.<instance>.availability = "none". - Start a new cluster with no existing streams: set
clustered = true. - Migrate an instance that already holds streams (either direction):
- Back up every stream with
nats stream backup. - Delete every stream with
nats stream rm. - When moving from standalone to clustered, delete the StatefulSet with
kubectl delete statefulset -n <namespace> <instance>. Its PersistentVolumeClaims stay, so all pods start clustered together. - Change
clustered(and the availability level if needed), then runkix deploy. - Restore every stream with
nats stream restore.
- Back up every stream with
JetStream is on by default (jetstream.enabled = true) and mounts a PersistentVolumeClaim at /data on each pod. Set jetstream.enabled = false to run in-memory core NATS with no volumes. Memory-backed JetStream streams are off by default (max_memory_store = 0); set settings.jetstream.max_memory_store to allow them.
storage.size defaults to 10Gi and sets both the volume request and the default settings.jetstream.max_file_store. Kubernetes cannot resize a StatefulSet’s volumeClaimTemplates in place, so changing storage.size does not resize existing PersistentVolumeClaims. Set storage.storageClassName to choose a StorageClass. When it is null, Kix uses the cluster’s storageClasses provider if one is configured, or falls back to the cluster’s default StorageClass.
Configure availability, clustering, storage, and nats.conf settings on the instance:
1instances.messaging.nats = {2 availability = "pod";3 config = {4 clustered = true;5 replicas = 3;6 storage.size = "20Gi";7 settings = {8 max_payload = 8388608;9 jetstream.max_memory_store = 1073741824;10 };11 };12};settings merges lowercase nats.conf keys over the package defaults. When NATS accepts aliases for a key (such as max_file for max_file_store), use max_file_store (the primary name). Kix rejects settings that this package manages itself (ports, listen addresses, client_advertise, http_base_path, server_name, pid_file, lame duck timings, store_dir, log files, syslog, ports_file_dir, client authentication, and cluster name and routes) as well as features this package does not support (client and route TLS, route authorization, NATS accounts, JWT authentication, remote syslog, the profiling port, leaf nodes, gateways, WebSocket, MQTT, and JetStream encryption).
resources defaults to 500m CPU and 1Gi memory (requests equal to limits) for development. For production JetStream clusters, upstream NATS recommends equal requests and limits of at least 2 CPU and 8Gi memory. GOMEMLIMIT defaults to 80% of resources.limits.memory; set env.GOMEMLIMIT to override it.
Each pod runs a prometheus-nats-exporter sidecar by default (metrics.enabled = true), so adding a prometheus provider later does not restart the NATS pods. When a prometheus provider is configured, Kix creates a metrics Service, a ServiceMonitor, and Prometheus alerts for missing server metrics, failing /healthz, connections above 90% of max_connections, slow consumers dropping messages, and (when JetStream is enabled) file storage above 90% of max_file_store. Set metrics.enabled = false to remove the sidecar; changing metrics.enabled restarts the pods.
Connect an application
Section titled “Connect an application”A package that depends on NATS takes a nats build argument and reads nats.out:
| Key | Value |
|---|---|
out.url | nats://<client-service>:4222 |
out.host, out.port | Client Service DNS name and port "4222" |
out.monitoringHost, out.monitoringPort | Headless Service DNS name and monitoring port "8222" |
out.credentials | The natsAuth secret (same-namespace consumers only) |
out.jetstream | true when JetStream is enabled |
out.version | NATS version parsed from image.tag (for example, "2.15.3") |
In the same namespace, Kix connects the nats dependency automatically when there is one NATS instance. Pass the client URL and login credentials to your application container:
1build =2 { self, scope, kix, nats, ... }:3 {4 deployment = scope.mkDeployment {5 name = scope.instanceName;6 spec = {7 selector.matchLabels = scope.selectorLabels;8 template.spec.containers = [9 {10 name = "app";11 image = "registry.example.com/app:1.0.0";12 env = kix.mkEnvVars {13 NATS_URL = nats.out.url;14 NATS_USER = nats.out.credentials.out.keyRef "username";15 NATS_PASSWORD = nats.out.credentials.out.keyRef "password";16 };17 }18 ];19 };20 };21 root = self.deployment;22 };To connect from another namespace, point deps.nats at the NATS instance with ref.<namespace>.<instance> and create a matching login secret in the consumer’s own namespace. Kubernetes Pods can read Secrets only in their own namespace, so kix check fails if a consumer in another namespace reads nats.out.credentials:
1instances.apps = {2 nats-login = {3 package = packages.secret;4 aliases = [ "natsLogin" ];5 config = {6 source = ./secrets/nats-auth.sops.yaml;7 keys = [ "username" "password" ];8 };9 };10 orders = {11 package = ordersPackage;12 deps.nats = ref.messaging.nats;13 };14};Here, ordersPackage reads nats.out.url for the server address and reads username and password from its natsLogin dependency.
When networkPolicy.enable = true, Kix opens only the port each consumer reads:
- Cluster route port 6222 is open only between the NATS instance’s own pods.
- Reading
out.urlorout.hostopens client port 4222 only. - Reading
out.monitoringHost(for example, to poll/healthzor/jsz) opens monitoring port 8222 only, from the same namespace or another:
1env = kix.mkEnvVars {2 NATS_MONITOR = "${nats.out.monitoringHost}:${nats.out.monitoringPort}";3};Pods that do not depend on the NATS instance cannot reach any of its ports. If you pass out.monitoringHost in a custom resource read by an external operator (such as a KEDA ScaledObject with a NATS JetStream trigger), tell Kix which operator pods connect to that resource with cluster.factBehavior, or allow access on port 8222 with networkPolicy.platformIntents.
Deploy and connect
Section titled “Deploy and connect”Check the cluster definition:
❱ kix check my-cluster Deploy the cluster and check the instance status:
❱ kix deploy my-cluster❱ kix status my-cluster Each pod runs HTTP probes on port 8222: /healthz for startup (allowing up to 15 minutes for JetStream recovery), /healthz?js-server-only=true for readiness, and /healthz?js-enabled-only=true for liveness. Those query flags keep a server in the Service and prevent restarts when its streams fall behind. On shutdown, a preStop hook puts nats-server into lame duck mode: it stops accepting new connections, waits 10 seconds, and closes existing client connections over the remaining 20 seconds so clients reconnect to another server.
After the pods become ready, a post-deploy Job connects through the client Service, publishes and reads back a test message, queries JetStream account info when JetStream is enabled, and verifies that unauthenticated connections are rejected. If this Job fails, kix deploy fails. Set healthCheck.enabled = false to skip it.
By default, kix deploy waits 180s (3 minutes) for each resource to become ready. If JetStream recovery or a rollout across many servers takes longer, pass --timeout (for example, kix deploy my-cluster --timeout 15m). If a pod stays Pending, inspect its PersistentVolumeClaim and confirm that the StorageClass can provision ReadWriteOnce volumes.
To test the instance locally, forward the client port:
❱ kix port-forward my-cluster messaging/nats 4222 With the port-forward running, publish a message and list streams from another terminal:
❱ nats --server nats://localhost:4222 --user app --password '<password>' pub orders.test hello❱ nats --server nats://localhost:4222 --user app --password '<password>' stream ls Clustered NATS replicates a stream across servers only when you create the stream with more than one replica:
❱ nats --server nats://localhost:4222 --user app --password '<password>' stream add ORDERS --subjects 'orders.>' --storage file --replicas 3 --defaults A single-replica stream is stored on one server and is unavailable while that pod restarts.