NATS Tutorial: Messaging Your Shop Orders Can Trust
Quick answer NATS is a lightweight messaging system: one part of your program publishes a message to a subject, another subscribes to it, and neither side knows about the other.
Core NATS delivers only to subscribers connected at that moment, so a late one misses the message. This post publishes five shop orders, shows a late subscriber receiving none, then fixes it with a JetStream durable consumer that replays all five, totalling Rs 57,500.
A shop checkout takes an order, and three things need to happen: the warehouse packs it, the courier collects the address, and accounts records the sale. The straightforward way is to call each step from the checkout code. It works, until one step is slow or down, and the customer waits at checkout for a warehouse problem.
Messaging breaks that chain: checkout publishes one order event and moves on, and each step picks it up when ready. The question is what happens to an event published while a step is offline. This post answers it with a live server and five orders.
What I would check before using it
My first check is whether a message must survive a restart. Core NATS keeps nothing: if no subscriber is listening when a message is published, it is gone. That suits live updates such as a stock ticker, not an order or a payment. JetStream adds a stream on the server that stores messages for later replay. The demo below shows both sides.
My second check is volume and replay. NATS with JetStream handles a shop and a small fleet of services without fuss. If the job is replaying a year of events at massive volume, Kafka Explained: The Event Backbone of Big Systems is built for that scale, and NATS is the lighter tool. Pick the log when the log is the product, NATS when messaging is plumbing.
My third check is what the queue must do after delivery. NATS queue groups share work, and JetStream consumers acknowledge each message, so a crashed worker gets its work redelivered. If you need dead-letter queues and delayed retries as first-class features, RabbitMQ Tutorial: An Order Queue That Never Loses Work has the deeper queue. If you only need a fast list shared between two services, the Redis Explained: The In-Memory Store That Speeds Things Up post covers the simpler option.
My verdict, as judgement: adopt NATS with JetStream where losing a message is a real problem, such as orders, payments, and stock changes. The recommendation flips if every message is disposable live data, because then core NATS alone is enough, or if nobody will run and back up the server, because an unlooked-after JetStream store is a single point of failure wearing a durability badge.
Five orders published, one subscriber too late, and the replay that saved them
The demo is a small shop with five orders: Sana and Hamza in Karachi, Daniyal and Ayesha in Lahore, Mahnoor in Islamabad. Checkout publishes each order to the subject orders.new, and a worker processes them.
The publisher could sit inside the checkout handler from the Build Your First REST API With Node.js and Express post; here it runs alone so the messaging is easy to see.
First the server: NATS ships as one binary, and -js switches on JetStream with file storage in ./data.
$ ./nats-server -js -sd ./data -p 4222
[INF] Starting nats-server
[INF] Starting JetStream
[INF] Listening for client connections on 0.0.0.0:4222
[INF] Server is ready
Then the client library:
$ npm install nats@2.29.3
added 3 packages
The publisher creates a stream called ORDERS capturing every subject under orders, then publishes five orders and prints each sequence number:
import { connect , JSONCodec } from "nats" ;
const orders = [ { id : "ORD-501" , customer : "Sana" , city : "Karachi" , total : 12400 } , { id : "ORD-502" , customer : "Daniyal" , city : "Lahore" , total : 9750 } , { id : "ORD-503" , customer : "Mahnoor" , city : "Islamabad" , total : 15800 } , { id : "ORD-504" , customer : "Hamza" , city : "Karachi" , total : 8300 } , { id : "ORD-505" , customer : "Ayesha" , city : "Lahore" , total : 11250 } , ] ;
const nc = await connect ( { servers : "127.0.0.1:4222" } ) ;
const jsm = await nc . jetstreamManager ( ) ;
const stream = await jsm . streams . add ( { name : "ORDERS" , subjects : [ "orders.>" ] , } ) ;
console . log ( `Stream ${stream.config.name} created, subjects: ${stream.config.subjects.join(", ")}` ) ;
const js = nc . jetstream ( ) ;
const jc = JSONCodec ( ) ;
for ( const order of orders ) { const ack = await js . publish ( "orders.new" , jc . encode ( order ) ) ; console . log ( `Published ${order.id} (${order.customer}, ${order.city}, Rs ${order.total.toLocaleString("en-US")}) seq ${ack.seq}` ) ; }
await nc . close ( ) ;
console . log ( "Publisher done." ) ;
$ node publish.mjs
Stream ORDERS created, subjects: orders.>
Published ORD-501 (Sana, Karachi, Rs 12,400) seq 1
Published ORD-502 (Daniyal, Lahore, Rs 9,750) seq 2
Published ORD-503 (Mahnoor, Islamabad, Rs 15,800) seq 3
Published ORD-504 (Hamza, Karachi, Rs 8,300) seq 4
Published ORD-505 (Ayesha, Lahore, Rs 11,250) seq 5
Publisher done.
All five orders are out. Now the thing that goes wrong: a plain subscriber starts after publishing and listens on the same subject:
import { connect , StringCodec } from "nats" ;
const nc = await connect ( { servers : "127.0.0.1:4222" } ) ;
const sc = StringCodec ( ) ;
let received = 0 ;
const sub = nc . subscribe ( "orders.new" ) ;
console . log ( "Plain subscriber listening on orders.new (started after publishing)..." ) ;
const done = ( async ( ) => { for await ( const msg of sub ) { received ++ ; console . log ( `Received: ${sc.decode(msg.data)}` ) ; } } ) ( ) ;
await new Promise ( ( resolve ) => setTimeout ( resolve , 3000 ) ) ;
sub . unsubscribe ( ) ;
await nc . drain ( ) ;
await done ;
console . log ( `Plain subscriber received ${received} orders.` ) ;
console . log ( "No orders arrived: core NATS only delivers to subscribers connected at publish time." ) ;
$ node subscribe-plain.mjs
Plain subscriber listening on orders.new (started after publishing)...
Plain subscriber received 0 orders.
No orders arrived: core NATS only delivers to subscribers connected at publish time.
Zero orders. The subscriber did nothing wrong: it connected, subscribed, and waited three seconds. Core NATS is fire and forget, and the five orders were fired before it arrived. In a real shop this is the worker that restarts during a deploy and quietly loses the orders placed while it was down.
The fix is a JetStream durable consumer, which replays every stored message and acknowledges each one after processing it:
import { connect , JSONCodec } from "nats" ;
const nc = await connect ( { servers : "127.0.0.1:4222" } ) ;
const jsm = await nc . jetstreamManager ( ) ;
await jsm . consumers . add ( "ORDERS" , { durable_name : "order-processor" , deliver_policy : "all" , ack_policy : "explicit" , } ) ;
const js = nc . jetstream ( ) ;
const consumer = await js . consumers . get ( "ORDERS" , "order-processor" ) ;
const jc = JSONCodec ( ) ;
const totals = { } ;
let grandTotal = 0 ;
let count = 0 ;
const messages = await consumer . fetch ( { max_messages : 5 } ) ;
for await ( const msg of messages ) { const order = jc . decode ( msg . data ) ; console . log ( `Processing ${order.id} (${order.customer}, ${order.city}, Rs ${order.total.toLocaleString("en-US")})` ) ; totals [ order . city ] = ( totals [ order . city ] || 0 ) + order . total ; grandTotal += order . total ; count ++ ; msg . ack ( ) ; }
console . log ( "Shop orders by city (Rs):" ) ;
for ( const city of Object . keys ( totals ) . sort ( ) ) { console . log ( `${city}: Rs ${totals[city].toLocaleString("en-US")}` ) ; }
console . log ( `Grand total: Rs ${grandTotal.toLocaleString("en-US")} across ${count} orders` ) ;
console . log ( `All ${count} orders processed and acknowledged.` ) ;
await nc . close ( ) ;
$ node subscribe-durable.mjs
Processing ORD-501 (Sana, Karachi, Rs 12,400)
Processing ORD-502 (Daniyal, Lahore, Rs 9,750)
Processing ORD-503 (Mahnoor, Islamabad, Rs 15,800)
Processing ORD-504 (Hamza, Karachi, Rs 8,300)
Processing ORD-505 (Ayesha, Lahore, Rs 11,250)
Shop orders by city (Rs):
Islamabad: Rs 15,800
Karachi: Rs 20,700
Lahore: Rs 21,000
Grand total: Rs 57,500 across 5 orders
All 5 orders processed and acknowledged.
All five orders replayed, and the totals check out: Karachi Rs 20,700, Lahore Rs 21,000, Islamabad Rs 15,800, a grand total of Rs 57,500. Running the same consumer a second time processed zero orders, because the server remembered every acknowledgement. A restart no longer means rework or lost work.
Common mistakes and how to fix them
First, subscribing after publishing and expecting old messages. The symptom is a subscriber that connects cleanly and receives nothing. The fix is JetStream: create a stream, then a durable consumer with deliver policy all.
Second, publishing through JetStream before creating the stream. The symptom is a publish that fails with a 503 error. The fix is to create the stream first, with the subject pattern the publisher uses, because JetStream has nowhere to store the message.
Third, forgetting to acknowledge a message. The symptom is the same order processed twice after a restart, because the server redelivers anything unacknowledged. The fix is to call msg.ack() after the work is done, not before, so a crash mid-processing gets a second chance.
Fourth, re-running a durable consumer and expecting the same orders again. The symptom is zero orders on the second run, which looks like the stream is empty. The fix is to remember the consumer tracks its own position: use a fresh durable name when you genuinely want a replay.
Frequently Asked Questions
Is NATS a replacement for Kafka? Not quite. NATS is the lighter tool for service-to-service messaging; Kafka is an event log for massive volume and long replay.
Do I need JetStream for every NATS app? No. Core NATS is enough for disposable live data. Add JetStream when a lost message costs money, such as an order or a payment.
Can NATS deliver one message to more than one subscriber? Yes. Every subscriber on a subject receives a copy, and a queue group shares the work so each message goes to one member.
Is NATS free? Yes. NATS is open source under the Apache 2.0 licence, and the server is a single binary you run yourself.
How is NATS different from WebSockets? WebSockets hold an open connection between a browser and a server; NATS moves messages between services. The WebSockets Explained: Real-Time Data Without Refreshing post covers the browser side.
What to remember
- Core NATS delivers only to subscribers connected at publish time; a late subscriber gets nothing.
- JetStream stores messages in a stream, and a durable consumer replays them from the start.
- A durable consumer remembers acknowledgements, so a restart replays zero old orders.
- Create the stream before publishing through JetStream, or the publish fails with a 503 error.
- Acknowledge after the work is done, so a crash still gets a redelivery.
Where this leaves you
NATS earns its place the moment a service restarts and no order goes missing with it. The demo showed both halves honestly: a plain subscriber that received nothing because it arrived late, and a durable consumer that replayed all five orders and totalled Rs 57,500 without a duplicate.
That is the line to draw in your own system: live data can travel on core NATS, and anything worth money goes through JetStream. Start the server with JetStream on, publish one real event from your own app, and watch a durable consumer pick it up after a restart.
Further reading
- NATS documentation
- JetStream concepts
- Kafka Explained: The Event Backbone of Big Systems
- RabbitMQ Tutorial: An Order Queue That Never Loses Work
- Redis Explained: The In-Memory Store That Speeds Things Up
- Build Your First REST API With Node.js and Express
- WebSockets Explained: Real-Time Data Without Refreshing
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Comments
No comments yet. Start the discussion.