Table of Contents

Core NATS

Core NATS is the base set of functionalities and qualities of service offered by a NATS service infrastructure. Core NATS is the foundation for JetStream and other services. For the sake of explanation, in a simplified sense you can think of Core NATS as the wire protocol defining a simple but powerful pub/sub functionality and the concept of Subject-Based Messaging.

Quick Start

Download the latest nats-server for your platform and run it without any arguments. nats-server will listen on its default TCP port 4222.

$ nats-server

Install NATS.Net and NATS.Client.Serializers.Json from Nuget.

Given that we have a plain class Bar, we can publish and subscribe to our nats-server sending and receiving Bar objects:

public record Bar(int Id, string Name);

Subscribe to all bar related subjects:

// required to serialize ad-hoc types
var opts = new NatsOpts { SerializerRegistry = NatsJsonSerializerRegistry.Default };

await using var nats = new NatsConnection(opts);

await foreach (var msg in nats.SubscribeAsync<Bar>("bar.>"))
{
    if (msg.Subject == "bar.exit")
        break;

    Console.WriteLine($"Received {msg.Subject}: {msg.Data}\n");
}

Publish Bar objects to related bar subjects:

var opts = new NatsOpts { SerializerRegistry = NatsJsonSerializerRegistry.Default };
await using var nats = new NatsConnection(opts);

for (var i = 0; i < 10; i++)
{
    Console.WriteLine($" Publishing {i}...");
    await nats.PublishAsync<Bar>($"bar.baz.{i}", new Bar(Id: i, Name: "Baz"));
}

await nats.PublishAsync("bar.exit");

Logging

You should also hook your logger to NatsConnection to make sure all is working as expected or to get help diagnosing any issues you might have:

(For this example you need to add Microsoft.Extensions.Logging.Console from Nuget.)

using var loggerFactory = LoggerFactory.Create(configure: builder => builder.AddConsole());

var opts = new NatsOpts { LoggerFactory = loggerFactory };

await using var nats = new NatsConnection(opts);

What's Next

Publish-Subscribe is the message distribution model for one-to-many communication.

Request-Reply is a common pattern in modern distributed systems. A request is sent, and the application either waits on the response with a certain timeout, or receives a response asynchronously.

Queue Groups enables the 1:N fan-out pattern of messaging ensuring that any message sent by a publisher, reaches all subscribers that have registered.