Your First Messages
Outcome: you have published messages and watched a subscriber receive them — and you have seen, in the same transcript, the message that was published too early and never arrived at all.
Every command in this chapter names the lab's server
(--server nats://127.0.0.1:18084). On your own machine,
substitute your server's address — if it listens on the
default port of the same computer, plain
nats://127.0.0.1:4222.
Publish first, and learn the lesson once
The lab began by publishing to nobody:
$ nats pub greetings "early message, nobody listening"
00:55:28 Published 31 bytes to "greetings"
The command reports success, and it is telling the truth:
the server accepted the message and delivered it to every
current subscriber of greetings. There were none. Core
NATS keeps no copy, so that message's story is over. This
is the single most important behaviour in the whole
system, and it is worth meeting in your first five
minutes rather than your first outage.
Now subscribe, then publish
Start a subscriber in one terminal:
nats sub greetings
and publish from another:
nats pub greetings "hello one"
nats pub greetings "hello two"
nats pub greetings "hello three"
The subscriber's window (transcript t02):
Subscribing on greetings
[#1] Received on "greetings"
hello one
[#2] Received on "greetings"
hello two
[#3] Received on "greetings"
hello three
Three messages, in order, each with its subject and a running count. Note what is not there: the early message. The transcript is the demonstration chapter 1 promised — the forgetful core, observed.
A few habits worth forming here:
- The publisher never waits.
nats pubreturns as soon as the server has the message. Publishing is not a conversation; there is no "delivered" receipt in core NATS, because "delivered to whom?" has no fixed answer. - Subscribers are independent. Start a second
nats sub greetingsand publish again: both windows print the message. Subscribing never consumes; every subscriber gets its own copy. (Chapter 7 shows the deliberate opposite — a group that shares.) - Bodies are bytes. The examples use short text, but the server neither knows nor cares. JSON, readings, small images — bytes are bytes, up to the 1 MB ceiling from chapter 2.
Stopping and tidiness
Ctrl-C ends a subscriber. Nothing is left behind on the
server: a core subscription exists only while its client
is connected. Disconnect, and the server forgets you were
ever interested — the mirror image of it forgetting your
messages.
Check: publish before subscribing and confirm the early message never appears; then subscribe first and confirm three of three arrive. If both halves behave as the transcript shows, you understand core NATS delivery — the rest of the guide is refinement.