Table of Contents

Request-Reply Pattern

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.

Create a service that will be responding to requests:

public class MyMathService : BackgroundService
{
    private readonly INatsClient _natsClient;

    public MyMathService(INatsClient natsClient)
    {
        _natsClient = natsClient;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var msg in _natsClient.SubscribeAsync<int>("math.double", cancellationToken: stoppingToken))
        {
            Console.WriteLine($"Received request: {msg.Data}");

            var result = 2 * msg.Data;

            await msg.ReplyAsync(result, cancellationToken: stoppingToken);
        }
    }
}

Reply to a request is asynchronously received using an inbox subscription behind the scenes:

await using var nc = new NatsClient();

NatsMsg<int> reply = await nc.RequestAsync<int, int>("math.double", 2);

Console.WriteLine($"Received reply: {reply.Data}");

Using request-reply you can build services that are resilient to failures. See also Services for a more structured approach to building services.