AI agents: use the documentation index at llms.txt to locate machine-readable pages. This section is indexed by https://docs.particular.net/samples/llms.txt. The markdown version of this page is served as plain text. An MCP server at /mcp serves the same content via the search_docs and read_doc tools; it is read-only and needs no credentials. Markdown versions of documentation pages are available by appending .md to the page URL. Directory URLs use index.md. They are served as text/plain because some retrieval backends reject text/markdown.

DynamoDB persistence with transactions

NuGet Package:
NServiceBus.Persistence.DynamoDB 4.x
Target Version:
NServiceBus 10.x

This sample uses DynamoDB persistence to commit saga changes and outbox records atomically. It also shows how to write application data in the same transaction as the outbox record for the message being handled.

Prerequisites

The sample connects to DynamoDB Local at http://localhost:8000 using dummy credentials. It does not need an AWS account. With Docker Compose installed, download and extract the sample, then run this command from the directory containing DynamoDB.sln:

docker compose up -d

To run DynamoDB Local without Docker, follow the AWS setup instructions and use the default port, 8000.

Run the sample

From the solution directory, run the server and client in separate terminals:

dotnet run --project Server
dotnet run --project Client

If either project prompts you to press a key to start, do so. Once the server reports that it has started, press S in the client. The server starts the order saga, handles the shipping command, and completes the saga when its five-second timeout fires. The client logs Received OrderCompleted for OrderId with the same order ID it sent.

Inspect the records

Use NoSQL Workbench for DynamoDB to connect to DynamoDB Local on port 8000 and open the Samples.DynamoDB.Transactions table. To see the saga item, open the table before sending an order, then scan before the five-second timeout. The screenshot shows the records after the shipping command ran and before the saga completed:

  • The saga item has SAGA# prefixes in its partition key (PK) and sort key (SK).
  • The outbox metadata items have OUTBOX# in PK and OUTBOX#METADATA# in SK.
  • The OrderShippingInformation item uses the same shipping record ID in PK and SK.

DynamoDB Local table with one shipping item, one saga item, and three outbox metadata items

Scan again after the client receives OrderCompleted. The saga item is gone, but the shipping item remains and there is an additional outbox metadata item for the timeout.

When finished, stop both projects and run docker compose down if you started DynamoDB Local with Docker. The container stores its data in memory, so stopping it discards the records.

Projects

Client

  • Sends StartOrder to the server.
  • Handles the OrderCompleted event.

Server projects

  • OrderSaga handles StartOrder, sends a local ShipOrder command, and requests a CompleteOrder timeout.
  • ShipOrderHandler writes OrderShippingInformation and publishes OrderShipped. OrderSaga logs the shipping date.
  • When the timeout fires, OrderSaga marks itself complete and publishes OrderCompleted.

SharedMessages

Contains the shared message contracts used by all endpoints.

Persistence config

Configure the endpoint to use DynamoDB Persistence.

var amazonDynamoDbClient = new AmazonDynamoDBClient(
    new BasicAWSCredentials("localdb", "localdb"),
    new AmazonDynamoDBConfig
    {
        ServiceURL = "http://localhost:8000"
    });

var endpointConfiguration = new EndpointConfiguration("Samples.DynamoDB.Transactions.Server");
endpointConfiguration.UseSerialization<SystemJsonSerializer>();

var persistence = endpointConfiguration.UsePersistence<DynamoPersistence>();
persistence.DynamoClient(amazonDynamoDbClient);
persistence.UseSharedTable(new TableConfiguration
{
    TableName = "Samples.DynamoDB.Transactions"
});

endpointConfiguration.EnableOutbox();

ShipOrderHandler adds the OrderShippingInformation write to the synchronized storage session. The write commits in the same DynamoDB transaction as the outbox record for ShipOrder.

var orderShippingInformation = new OrderShippingInformation
{
    Id = Guid.NewGuid(),
    OrderId = message.OrderId,
    ShippedAt = DateTimeOffset.UtcNow,
};

var session = context.SynchronizedStorageSession.DynamoPersistenceSession();

session.Add(new TransactWriteItem
{
    Put = new Put
    {
        TableName = "Samples.DynamoDB.Transactions",
        Item = orderShippingInformation.ToMap()
    }
});

Order saga data

public class OrderSagaData :
    ContainSagaData
{
    public Guid OrderId { get; set; }
    public string OrderDescription { get; set; }
}

Order saga

public class OrderSaga(ILogger<OrderSaga> logger):
    Saga<OrderSagaData>,
    IAmStartedByMessages<StartOrder>,
    IHandleMessages<OrderShipped>,
    IHandleTimeouts<CompleteOrder>
{
    protected override void ConfigureHowToFindSaga(SagaPropertyMapper<OrderSagaData> mapper)
    {
        mapper.MapSaga(saga => saga.OrderId)
            .ToMessage<StartOrder>(msg => msg.OrderId)
            .ToMessage<OrderShipped>(msg => msg.OrderId);
    }

    public async Task Handle(StartOrder message, IMessageHandlerContext context)
    {
        var orderDescription = $"The saga for order {message.OrderId}";
        Data.OrderDescription = orderDescription;

        logger.LogInformation("Received StartOrder message {OrderId}. Starting Saga", Data.OrderId);

        var shipOrder = new ShipOrder
        {
            OrderId = message.OrderId
        };

        logger.LogInformation("Order will complete in 5 seconds");
        var timeoutData = new CompleteOrder
        {
            OrderDescription = orderDescription,
            OrderId = Data.OrderId,
        };

        await Task.WhenAll(
            context.SendLocal(shipOrder),
            RequestTimeout(context, TimeSpan.FromSeconds(5), timeoutData)
        );
    }

    public Task Handle(OrderShipped message, IMessageHandlerContext context)
    {
        logger.LogInformation("Order with OrderId {OrderId} shipped on {ShippingDate}", Data.OrderId, message.ShippingDate);
        return Task.CompletedTask;
    }

    public async Task Timeout(CompleteOrder state, IMessageHandlerContext context)
    {
        logger.LogInformation("Saga with OrderId {OrderId} completed", Data.OrderId);
        MarkAsComplete();
        var orderCompleted = new OrderCompleted
        {
            OrderId = Data.OrderId
        };
        await context.Publish(orderCompleted);
    }
}

Related Articles

  • Sagas
    Master NServiceBus sagas to coordinate distributed workflows and ensure reliable long-running processes.