NATS Logo by Example

Core Publish-Subscribe in Messaging

This example demonstrates the core NATS publish-subscribe behavior. This is the fundamental pattern that all other NATS patterns and higher-level APIs build upon. There are a few takeaways from this example:

  • Delivery is an at-most-once. For MQTT users, this is referred to as Quality of Service (QoS) 0.
  • There are two circumstances when a published message won’t be delivered to a subscriber:
    • The subscriber does not have an active connection to the server (i.e. the client is temporarily offline for some reason)
    • There is a network interruption where the message is ultimately dropped
  • Messages are published to subjects which can be one or more concrete tokens, e.g. greet.bob. Subscribers can utilize wildcards to show interest on a set of matching subjects.
CLI Go Python Deno Node Rust C# Java Ruby Elixir Crystal C
Jump to the output or the recording
$ nbe run messaging/pub-sub/cli
View the source code or learn how to run this example yourself

Code

#!/bin/sh

The nats CLI utilizes the NATS_URL environment variable if set. However, if you want to manage different contexts for connecting or authenticating, check out the nats context commands. For example:

nats context save --server=$NATS_URL local
NATS_URL="${NATS_URL:-nats://localhost:4222}"

Publish a message to the subject ‘greet.joe’. Nothing will happen since the subscription is not yet setup.

nats pub 'greet.joe' 'hello'

Let’s start a subscription in the background that will print the output to stdout.

nats sub 'greet.*' &

This just captures the process ID of the previous command in this shell.

SUB_PID=$!

Tiny sleep to ensure the subscription connected.

sleep 0.5

Now we can publish a couple times..

nats pub 'greet.joe' 'hello'
nats pub 'greet.pam' 'hello'
nats pub 'greet.bob' 'hello'

Remove the subscription.

kill $SUB_PID

Publishing again will not result in anything.

nats pub 'greet.bob' 'hello'

Output

Network e113dd2b_default  Creating
Network e113dd2b_default  Created
Container e113dd2b-nats-1  Creating
Container e113dd2b-nats-1  Created
Container e113dd2b-nats-1  Starting
Container e113dd2b-nats-1  Started
             _             _               
 _ __   __ _| |_ ___      | |__   _____  __
| '_ \ / _` | __/ __|_____| '_ \ / _ \ \/ /
| | | | (_| | |_\__ \_____| |_) | (_) >  < 
|_| |_|\__,_|\__|___/     |_.__/ \___/_/\_\
                                           
nats-box v0.12.0
12:08:34 Published 5 bytes to "greet.joe"
12:08:34 Subscribing on greet.*
12:08:34 Published 5 bytes to "greet.joe"
[#1] Received on "greet.joe"
hello

[#2] Received on "greet.pam"
hello

12:08:34 Published 5 bytes to "greet.pam"
[#3] Received on "greet.bob"
hello

12:08:34 Published 5 bytes to "greet.bob"
12:08:35 Published 5 bytes to "greet.bob"

Recording

Note, playback is half speed to make it a bit easier to follow.