Podcast about DevSecOps

#65 - Understanding Nats: An Explainer Of Its Features And Capabilities

One Go binary handles service messaging, persistence and configuration, but data durability still takes planning.

18 min read

Join Andrey, Julien, and Mattias in this episode of DevSecOps Talks as they discuss Nats.io, a messaging system popular among people building on top of Kubernetes. Julien explains how Nats is different from Kafka and shares his personal experience with the product. The hosts discuss the various use cases of Nats and explore its features and capabilities. Tune in to find out if Nats is the right messaging system for you!

Discuss the episode or ask us anything on LinkedIn


Two services need to talk, and the broker is the expensive part

You have two services that need to exchange messages. The options are familiar: put an HTTP endpoint with JSON in front of one of them, use gRPC for service to service calls, or push the message onto a queue and let the other side consume it. On Kubernetes the first route means a Deployment, a Service in front of it, agreement on the protocol and schema handling somewhere in your code. In a cluster where something already isolates your Pods, the applicable policies have to allow the call too, because Pods are non-isolated until a policy selects them. Selectors cover groups, so a caller that already carries the right label costs you nothing, and only a caller outside the rules you wrote sends you back to the policy. The second route means running the queue: Kafka with ZooKeeper beside it, a Redis cluster for the small stuff, or a line on the cloud bill for a managed one. Either way the messaging layer ends up with more moving parts than the two services it connects.

NATS is the project people reach for when that ratio starts to look silly, and it has stayed under the radar for years. CNCF has hosted it since March 2018, where it was accepted at the incubating level. It is one Go binary, and clustering, JetStream, leaf nodes, MQTT and WebSocket are all configuration on the same process. Kafka has the bigger ecosystem, the clients and the install base, so the honest question is why you would give a second thought to anything else.

Two reasons, and both are about what you have to operate. NATS covers request-reply, publish-subscribe and work queues in one process, so the patterns that usually need a broker plus a mesh plus a cache come from one thing. And the floor is low enough that running it yourself stops being the expensive option. If your cloud already gives you a good managed queue, this is a comparison rather than a migration, and we get to that below.

Subjects give you a hierarchy you can query

Start where the daily work starts, which is deciding where messages go.

How do you read every region’s orders at once?

Publish to orders.europe, orders.us and orders.asia, then subscribe to orders.* when you want all of them and to orders.europe when you want one.

NATS calls these subjects, and the dot builds a hierarchy out of them. There are two wildcards: * matches exactly one token and > matches one or more trailing tokens, so orders.* stops at orders.europe while orders.> picks up orders.europe.priority as well. There is no partition count to choose up front and no query language to learn. Design the tree well and you can read your own routing off the subject names.

Those permissions are separate configuration, written in the same subject terms. A user gets a permissions block with independent publish and subscribe entries, each an allow or a deny list that takes wildcards, and once an allow list exists, anything off it is denied: an order service publishes to orders.>, subscribes to _INBOX.> and gets nothing else. Above users sit accounts, isolated subject spaces where two tenants can both use orders.europe and never see each other’s traffic, crossing only where one account exports a subject and another imports it. That is the multi-tenancy, in the same process, with no proxy in front of it.

Subjects also move. The server can rewrite them on arrival with a mappings block, before it looks for subscribers, so orders.placed can become orders.created without touching the publisher. Weights from 0 to 100 send a share of matched messages to a canary subject, matched tokens can be reused in the destination, and nats-server --signal reload applies the change without a restart. Compare that with a Kafka topic you have outgrown: there is no rename, so you create the new topic, move the consumers and migrate the data while the stream is still live and hot. One command against a config file is a different kind of afternoon.

Request-reply, fan-out and work queues in one system

Naming solves routing. The patterns above it are where a message queue usually sends you looking for a second tool.

Can one broker do request-reply and pub/sub?

It can, and that is the strongest practical argument for NATS: a request that gets a reply, a publish that is fire and forget, and queue groups where each message goes to one worker.

You can have each of those elsewhere. gRPC does client-side load balancing with no proxy in front of it, and RabbitMQ does request-reply with a callback queue and a correlation id. What NATS saves you is the assembly. All three patterns run over the same subject tree on the same connection, so moving a service from fire and forget to a pool of workers is a change to the subscribe call rather than a second system to operate. Queue groups are the scaling knob, load balancing where each message goes to exactly one group member, so workers in one group share the load while a second group on the same subject gets its own copy of everything.

Get delivery straight before you put an order in it. Core NATS is at-most-once, with no broker queue, no storage and no acknowledgement: a message reaches the subscribers connected at the moment it is published, and a consumer that is offline never sees it. The reply in request-reply is your own service answering on an _INBOX subject, so what it tells the requester is that somebody took the message. When no reply arrives before the timeout, your code decides what happens next, and the retry count you set in a client library is that client publishing again. Acknowledgements the server tracks, and redelivery the server performs, belong to JetStream, below.

No schema registry, and that is the trade

What NATS leaves out matters as much as what it ships with.

Where does schema validation live?

In your code. NATS carries bytes on a subject, so Protobuf, JSON or anything else is an agreement your own services make.

Teams coming from Kafka usually mean Confluent Schema Registry, and it is worth being exact about where that acts. The check that rejects a badly shaped payload runs in the producer’s serializer, inside your application, against a schema the registry stores and versions. The broker-side piece is the confluent.value.schema.validation topic setting, off by default, and it checks that the schema ID in the wire format is registered under a valid subject rather than introspecting the data. The registry buys you a central contract and clients that honour it. NATS gives you neither half: a producer that renames a field ships the rename to every consumer, and the server has no opinion about it. You pay for that with a shared library, a review habit and someone who cares about compatibility. If that discipline isn’t there on your team, a registry is buying you something real and you should keep it.

The upside is that no serialization format is privileged. The server moves serialized bytes, so Protobuf is a common choice on the wire, and a call that would have been a gRPC method becomes a request on a subject instead.

Processing sits outside the broker too, and that is where Benthos earns its place beside NATS. You declare small functions that consume from a subject, enrich the message, maybe add metadata or resolve a location, then pipe it onwards, and its adapters reach most things you already run. The protocol is simple enough that other tools speak it without much work.

One binary where you had a platform

Operational size is the other half of the argument, and it is the half you feel every quarter.

What do you actually deploy?

One Go binary. Clustering, JetStream, leaf nodes, MQTT and WebSocket are configuration on that same process, not extra components to schedule.

Put the alternatives next to it. Redis Cluster wants at least three master nodes, and its docs strongly recommend six, three masters and three replicas, which is a lot of pods for a key-value store. Kafka needed ZooKeeper until recently: the 3.5.0 release in June 2023 marked ZooKeeper deprecated and planned its removal in 4.0, and migrating an existing cluster to KRaft only became production ready in 3.6.0. Those systems were designed before anyone ran everything in containers, and it shows in their footprint.

The NATS server was under 20 MB when we last looked, which means a Raspberry Pi runs it. If your application is Go you can go further and run the server inside it: the server package starts one in process, so two modules in the same program talk over NATS instead of over a socket you hand-rolled, and a test starts a server instead of waiting on a container.

The throughput story is the part that sounds wrong. NATS speaks a text protocol, which is not what you expect under a few million messages a second, and Derek Collison’s GopherCon 2014 slides explain how it holds up: the Ruby original used regular expressions, the first Go port copied that approach, and the version that got fast is a hand-written byte parser with zero allocations. We benchmarked it on a machine with two CPUs and four gigabytes of RAM and ran out of network first.

When the managed queue is still the right answer

A small binary is not a reason to run infrastructure you could have rented, and the cloud bill is what sends most teams looking in the first place.

Should you run NATS on AWS?

Probably not for a new queue. If your provider has SQS, EventBridge or Kinesis, the operational overhead you’re trying to remove has already been removed for you.

The choice there is about shape rather than ops. A distributed application with many workers pulling from one queue wants SQS. Event-driven routing fits EventBridge better, and we have seen people use Kinesis in its place. Managed Kafka is the one that stings, because MSK bills per broker hour plus storage and those brokers run whether or not messages flow. NATS gets interesting the moment there is no comparable managed service: a smaller provider, your own hardware, an edge site, a cluster where the queue is one more thing you install from a chart.

The comparison worth making is against the stack you assemble when services talk inside a cluster: a Service per Deployment, protocol agreement, policy rules that cover each caller once something isolates your Pods, and for some teams a service mesh on top. A broker doesn’t exempt you from the policy. It changes the shape of it, because every client needs a route to the broker rather than a route to everything it calls, so one rule stands in for a set that would otherwise track your call graph. Istio has been removing the per-pod sidecar since it introduced ambient mesh in 2022, replacing it with a shared per-node ztunnel, and the capture that makes it work happens inside the pod’s network namespace rather than through eBPF. A mesh buys real things. It also buys someone whose week goes into maintaining it.

Having written against NATS and run it, we land on the same verdict from both sides of that fence.

Fewer people and less mental overhead: that is what picking something simple and adding your own schema validation on top buys, against carrying the infrastructure, the network policies and the rest. The single binary pitch is one we have heard before, for Nomad, where you drop one binary on a host until you install the plugins and it is no longer one binary you distribute. That was Nomad, and nothing we found says NATS ends the same way. Take it as the question to ask: write down what you will switch on, then check what each needs before you bank the footprint as a saving.

Persistence, replay and key-value without another service

Core NATS forgets by design. JetStream is the part that remembers, and it is where the comparison with Kafka and Redis actually happens.

What do you get when you turn JetStream on?

Streams that hold messages until a consumer shows up, replay of acknowledged messages under the default retention, and key-value buckets, all from the same process you already run.

The key-value part removes a loop Kubernetes users will recognise, though it is smaller than it usually gets described. A ConfigMap mounted as a volume is updated in place by the kubelet, so an application that watches the file sees a change without a rollout. Consume the same ConfigMap as environment variables, or mount it with subPath, and it never updates: that change needs a new Pod. An application that reads its configuration once at startup needs a restart either way, which is where the rollout, or a controller that triggers one, comes back. A KV bucket is a different shape. Your application watches the bucket, gets a snapshot of every key and then live updates. Expiry is bucket-wide rather than per key: the bucket carries the underlying stream’s max_age, and every value older than that goes. Underneath it is a stream named KV_<bucket>, so it replicates like any other stream.

Delivery guarantees need reading carefully. JetStream is at-least-once: the server redelivers a message until a reader acknowledges it, within the bounds you configure. A consumer’s max_deliver caps the attempts, and the stream’s retention policy decides what survives. The default limits retention ignores acknowledgements entirely and drops messages when max_msgs, max_bytes or max_age is hit, read or not, which is both why an unacknowledged message can disappear and why an acknowledged one is still there to replay. Choose interest or workqueue instead and a message leaves once its consumers ack it, so there is nothing left to replay.

Exactly-once is two mechanisms working together. On publish, the server rejects a second message carrying the same Nats-Msg-Id within the stream’s duplicate window, two minutes by default. On consume, a double ack waits for the server to confirm it recorded the acknowledgement before the message counts as done. Both cost: a round trip per message for the double ack, and a window wide enough to cover however long your producer keeps retrying.

Storage is memory or file. We once mounted a bucket into the container as a filesystem and the performance was not what we wanted, which isn’t a NATS problem: it writes to the filesystem it is given and can’t go faster than that.

What happens when the network splits

Feature lists are easy to compare. Failure behaviour is what you live with at three in the morning.

How many servers does a stream need to survive one of them dying?

Three, holding three copies. A stream takes a single replica by default, and an R1 stream lives on one server, so while that server is out the stream is unavailable, and the loss becomes permanent if its one stored copy goes with the disk. Ask for R3 when the data has to outlive a node.

Two positions on that number, and they are about different layers. Mattias Hemmingsson holds that two servers can run, the one that gets there first taking the lead, and that you add servers as you grow; Andrey Devyatkin holds that consensus needs three, so you can’t run two. Core NATS has no majority to lose: servers are joined by routes, and a client whose server dies reconnects to another in the cluster and keeps publishing. Raft is how JetStream’s servers agree on a stream, and an R3 stream needs two of its three replicas communicating to maintain quorum. An R2 stream elects a leader while both are up, but a majority of two is still two, so the first failure leaves that stream without one. Hence the odd number, three or five: three tolerate one failure, four tolerate the same one while costing you a server. Lose two of three and the stream stops accepting new messages until a server returns.

The count is per stream rather than per cluster. Three servers full of R1 streams give you three independent places to lose data, so you ask for replication when you create the stream.

What you don’t configure is the election: you give each server the URLs of the others and Raft does the rest, with no master to nominate. The same simplicity produces leaf nodes, servers that dial out to a remote system and carry only the subjects with interest on the other side. A factory floor behind a firewall needs no inbound rule and no public address: its machines connect to the local leaf as ordinary clients, and the hub sees one link.

Then the honest part. Without persistence, messages in flight when a node drops out are gone, which is the risk you took when you left it off. With it, replicas in different availability zones survive a zone and bill you for the traffic between them.

We have yet to meet the company that doesn’t care about data consistency.

What this means for teams

NATS is not a Kafka replacement project, whatever the comparisons say. It is a smaller tool belt that covers more of the ground between your services than a queue does, and the case for it is operational: one process, one config file, a subject tree you can reason about, and features you enable rather than install. The case against it is equally plain. If your cloud rents you a queue that fits the shape of your traffic, rent it. Need a schema registry to keep your teams honest? NATS won’t give you one.

A few things worth doing this week:

  • Download the server and run it locally, then work through two or three examples from NATS by Example against it. If your application is Go, start the server inside a test and see how much container plumbing that deletes.
  • Write down the subject tree for one existing service pair before you write any code, and decide where the wildcards and the allow lists sit. That naming is the part you can’t refactor cheaply later, even with mappings.
  • Go through your message flows and mark which ones can tolerate at-most-once delivery. Everything else belongs in a JetStream stream, where the consumer acknowledges and the server redelivers until it does. Decide replication separately: R3 is what survives losing a server, and it needs three eligible servers to place the copies on.
  • Price both sides properly. Broker hours and storage on the managed service, against people time, cross-zone replication traffic and the pager on your own.

Common questions, answered

How do I rename a NATS subject without changing the publishers?

Add a mappings block to the server configuration that maps the old subject to the new one, then reload with nats-server --signal reload. The server rewrites the subject as the message arrives, before it looks for subscribers, so the publisher keeps publishing the old name and never finds out. Weights from 0 to 100 let you send a share of the traffic to the new subject first. Mappings belong to an account, and they can divert messages away from subscribers still listening on the old subject, so check the subscriber side before you reload.

How do I test against NATS without running a broker container?

If your service is in Go, start the server in your test process with the server package instead of a container. You still drive the lifecycle: NewServer and Start, then ReadyForConnections before the first client connects, and Shutdown once the clients are closed. What you drop is Docker and the image pull, not the readiness check or the cleanup. For other languages the single binary is the next best thing: one process per test suite, and no cluster to stand up first. Needing Kafka on your laptop is what makes local testing hard in the first place.

Does a JetStream key-value bucket replace Redis?

For application configuration and small values, usually yes, and it comes from a server you already run. Size the saving honestly: six nodes is what Redis Cluster’s docs recommend, so you only save six if a Redis Cluster is what you are replacing, and a single Redis instance is one process. Compare at matching availability, an R3 bucket against a replicated Redis. What a bucket doesn’t give you is Redis data structures, per-key expiry or the Redis client ecosystem. If your code leans on sorted sets or Lua scripts, that is a port rather than a swap.

Resources

Since we recorded

Benthos, the stream processor we suggested pairing with NATS, was acquired by Redpanda on 30 May 2024 and now ships as Redpanda Connect. Kafka finished the job it had started: 4.0.0, released in March 2025, runs without ZooKeeper at all, so the operational gap we described has narrowed. NATS itself had a governance scare in 2025 that ended with CNCF and Synadia agreeing that the trademarks go to the Linux Foundation and development continues under Apache-2.0 in CNCF repositories, which is worth knowing if you are betting a platform on it. We returned to the underlying question, self-hosting against managed services, in #90 K8s vs Managed Services: Cost, Lock-In, and Reality.