← All blogs

FullStack Engineering CourseLesson 0 of 20 1 hr 52 min

Start Here: Designing an Enterprise Payment Service in .NET and Azure

The problem

A business needs to take payments from its customers, and charge a fee on each one. Say I need to build a full enterprise payment processor for it. How would I go about it? I start with what it must do.

I write the plan as a design document (RFC, request for comments), so the team can review it before I build anything. Its parts are the sections of this lesson:

  • The problem: why the work is needed
  • Functional requirements: what the system must do
  • What can fail and Non-functional requirements: how well it must do it
  • C4 diagrams: the shape of the solution
  • Threat model: how an attacker could abuse it
  • ADRs (architecture decision records): one per decision, with why I chose it and what it costs

The FRs are one section of the RFC, not the RFC itself. The RFC is the whole proposal. An ADR records one decision the RFC leads to. ADRs live in the repository next to the code, so they change in the same pull request.

Functional requirements

Functional requirements (FRs) say what the system does:

FRRequirement
FR1Accept a payment: request ID, customer, amount (and, in reality, a currency)
FR2Reject a payment above the customer's per-transaction limit
FR3Charge a fee by account type: 1% for Premium, 2% for Standard
FR4Record the payment
FR5Tell other systems a payment happened (ledger, notifications, analytics)
FR6Process each request only once, even if the client sends it again
FR7Return the result of the payment to the caller

A first solution

My first, straightforward solution meets all seven requirements:

C#
public class PaymentProcessor
{
    private static readonly Dictionary<string, decimal> CustomerLimits = new();
    private static readonly List<string> ProcessedRequests = new();

    public decimal Process(string requestId, string customerId, string accountType, decimal amount)   // FR1
    {
        if (ProcessedRequests.Contains(requestId))                                  // FR6
            return 0;

        ProcessedRequests.Add(requestId);

        if (!CustomerLimits.ContainsKey(customerId))
            CustomerLimits[customerId] = LoadCustomerLimit(customerId);

        if (amount > CustomerLimits[customerId])                                    // FR2
            throw new Exception("Limit exceeded");

        var fee = accountType == "PREMIUM" ? amount * 0.01m : amount * 0.02m;      // FR3

        SavePayment(requestId, customerId, amount, fee);                            // FR4
        PublishPaymentEvent(requestId, customerId, amount, fee);                    // FR5
        return fee;                                                                 // FR7
    }
    // LoadCustomerLimit, SavePayment and PublishPaymentEvent omitted
}

It works in a demo, on a laptop, with one user. The trouble starts in production.

What can fail

When I run it on several servers, with real clients, networks and databases, these things happen:

ScenarioWhat happens with the starting codeBreaks
The client times out and retries, and the retry reaches a different serverThat server has its own ProcessedRequests list, so it charges the customer twiceFR6
Two copies of the same request arrive at the same momentBoth pass Contains before either calls Add (a check-then-act race): charged twiceFR6
The server restartsThe in-memory list starts empty again, so every retry charges againFR6
Many requests run at once on one serverDictionary and List are not thread-safe: they can corrupt or throwFR1, FR6
The limit check throws, or SavePayment failsThe ID was already added, so a corrected retry returns 0 and the payment never happensFR4, FR7
A duplicate arrivesThe caller gets 0, which looks like a real feeFR7
The process crashes after SavePayment but before PublishPaymentEventThe payment exists, but no other system ever hears about itFR5
The event goes out, but the save rolls backOther systems act on a payment that does not existFR5
Finance raises a customer's limitThe cache keeps the old limit forever, until a restartFR2
A caller sends accountType = "PREMIUM"They pay 1% instead of 2%FR3
The limit service is slow or downEvery payment waits or fails, with no timeout, retry or fallbackFR2
The service has run for weeksProcessedRequests holds every ID ever seen; memory grows and Contains gets slowerFR6
Something goes wrong in productionA generic Exception, no logs, no metrics: nobody can tell what or whyall
The business needs a new account type or fee rateEdit the if, rebuild and redeployFR3

Non-functional requirements

Non-functional requirements (NFRs) say how well the system must do its job. Each failure above points to one. These NFRs drive every decision in the rest of this lesson:

NFRWhat it means for this serviceAddressed by
Idempotency and consistencyOne payment per request ID, across servers, restarts and races; the payment and its event always agreeADR 9: idempotency filter; ADR 10: SQL Server; ADR 13: outbox
CorrectnessValid amounts only, fees by agreed rules and rounding, pricing never taken from the callerADR 2: DDD; ADR 4: DI and fee strategy; ADR 8: Entra ID
SecurityOnly allowed callers may pay; no secrets in code or configurationADR 8: Entra ID; ADR 16: Container Apps
Reliability and resilienceKeep working when a dependency is slow or down; never lose an eventADR 7: two entry points; ADR 12: resilience; ADR 13: outbox
Performance and scalabilityHandle growing load on more servers; do not block threads or call a dependency on every requestADR 1: microservice; ADR 5: async I/O; ADR 7: two entry points; ADR 11: caching
ObservabilitySee what each payment did, and alert someone when something goes wrongADR 14: observability
Maintainability and testabilityChange rules and infrastructure safely; prove the hard cases, such as races, with testsADR 2: DDD; ADR 3: clean architecture; ADR 4: DI and fee strategy; ADR 6: minimal APIs; ADR 15: tests
DeployabilityEvery environment built from code; every change tested and released the same wayADR 16: Container Apps; ADR 17: Terraform and pipelines

How to collect NFRs, write the RFC and ADRs, and draw C4 diagrams: Lesson 11: Architecture Practice.

In the rest of this lesson I meet these requirements one decision at a time. For each decision I say what I chose, why, and what it costs, and I show the code. The finished service is on GitHub.

C4 diagrams

C4 (context, containers, components, code) draws a system at four zoom levels. I draw the first three; the code itself is the fourth.

Level 1, system context: who uses the service, and what it talks to.

  [Merchant app / client]          [Batch job / saga]           [Partner systems]
   waits for the result            does not wait                get signed webhooks
          │ HTTPS + token                 │ queue command                ▲ HTTPS POST
          ▼                               ▼                              │
  ┌──────────────────────────────────────────────────────────────────────────┐
  │                      Payment Service  (this system)                      │
  │   takes payments, applies limits and fees, records them, tells others    │
  └──────────────────────────────────────────────────────────────────────────┘
          │ token check            │ customer profile            │ events
          ▼                        ▼                             ▼
   [Microsoft Entra ID]     [Customer service]          [Ledger, notifications,
                                                          analytics (subscribers)]

Level 2, containers: the deployable parts and the stores they use. A container in C4 is anything that runs or stores data, not only a Docker container.

Clients ──HTTPS──►┌─────────────────────────────── Azure Container Apps ─┐
                   │  Payments.Api (one image)                            │
Queue "payment-    │   • HTTP endpoints                                   │
commands" ────────►│   • PaymentCommandConsumer      (background)         │
                   │   • OutboxProcessor             (background)         │
                   │   • WebhookFanOutConsumer and                        │
                   │     WebhookDeliveryProcessor    (background)         │
                   └──────┬──────────────┬───────────────┬───────────────┘
                          │ EF Core      │ cache          │ AMQP
                          ▼              ▼                ▼
                    [Azure SQL]      [Redis,         [Service Bus]
                    Payments,         optional]       topic "payments"
                    Outbox,                           queue "payment-commands"
                    IdempotencyKeys,                  subscription "webhooks"
                    InboxMessages,
                    Webhooks
All access to Azure uses the app's managed identity: no passwords in configuration.

Level 3, components: the layers inside Payments.Api, and the main classes in each.

Client who waits                         Batch job / saga (does not wait)
  │  POST /payments                         │  command on the "payment-commands" queue
  │  (Idempotency-Key + JSON body)          │  (MessageId + JSON body)
  ▼                                         ▼
Payments.Api ─────────────────────────────────────────────────────────────
  Authentication (Entra ID token) ─► Idempotency filter ─► Payment endpoint
  Errors become Problem Details responses        Messaging/: PaymentCommandConsumer ─►
                                                  ProcessPaymentMessageHandler (inbox, outcome ─► event)
  ▼
Payments.Application ─────────────────────────────────────────────────────
  ProcessPaymentHandler: validate ─► customer profile ─► limit ─► fee
  ▼
Payments.Domain ──────────────────────────────────────────────────────────
  Payment (refuses invalid data), fee policies, business exceptions
  ▲ implemented by
Payments.Infrastructure ──────────────────────────────────────────────────
  HybridCache ─► Customer service (with retries and a circuit breaker)
  EF Core ─► SQL Server: Payment + OutboxMessage in one transaction
  OutboxProcessor (background) ─► Azure Service Bus topic "payments"

Azure: Container Apps · Azure SQL · Service Bus · managed identity · Terraform · GitHub Actions

Threat model

A threat model lists how someone could abuse the system, and what stops them. I use STRIDE (six kinds of threat), and I look first at the trust boundaries (lines in the diagrams where data crosses from someone I do not control): the API, the queue, and the webhook calls out to partners.

Threat (STRIDE)Example in this serviceWhat stops it
Spoofing: pretending to be someone elseA service calls POST /payments as another clientEntra ID tokens with scp/roles checks: ADR 8: Entra ID
Someone sends a partner a fake payment webhookEvery webhook is signed with HMAC (a keyed hash) and a per-subscription secret: ADR 7: two entry points
Tampering: changing dataA retry reuses an idempotency key with a different amountThe stored request hash does not match, so 422: ADR 9: idempotency filter
A caller sends accountType = "PREMIUM" to pay a lower feeThe service reads the account type from the customer profile: ADR 8: Entra ID
Repudiation: denying an actionA client says it never sent a paymentEach payment stores its request ID and caller; traces and logs record who did what: ADR 14: observability
Information disclosure: leaking dataSecrets in configuration, or stack traces in error repliesManaged identity, so no passwords in configuration: ADR 16: Container Apps; Problem Details without internals: ADR 6: minimal APIs
Denial of service: making it unavailableA slow customer service ties up every requestTimeouts, retries and a circuit breaker: ADR 12: resilience
A bad message fails forever on the queueMax delivery count, then the dead-letter queue: ADR 7: two entry points
Elevation of privilege: doing more than allowedA webhook URL points at an internal address (SSRF, server-side request forgery)URL rules at registration, a private-IP block on every connection, and no redirects: ADR 7: two entry points
A client without permission manages webhooksA separate Webhooks.Manage scope: ADR 8: Entra ID

Two threats stay open, on purpose:

  • Floods of requests. The service has no rate limiting (a cap on requests per caller). I would put it in front, in Azure API Management or Front Door, so it applies to every service.
  • Card data. The service never sees card numbers. A payment provider handles them, which keeps the service out of PCI DSS scope (the card industry's security rules).

How to run a threat model with a team: Lesson 11: Architecture Practice.

Architecture decision records

Each decision below is one ADR. Its heading is the decision, Why is the context and the reasons, and Trade-offs are the consequences I accept. In the repository, each one is a short file with a status (proposed, accepted or superseded).

ADR 1: a separate payment microservice

I make payments a separate service (a microservice: a small service that owns one business capability and its own data), with its own database and its own deployments. Other services talk to it only through its API and its events.

Why:

  • Payments have their own rules, data and compliance needs (card and banking regulations). Keeping them in one place limits who can touch payment data, and how much of the system an audit must cover.
  • I can deploy, scale and protect payments on their own schedule, without releasing the whole system.
  • A failure elsewhere, such as in a reporting module, cannot take payments down with it.
  • Other teams use a clear contract (the API and the PaymentProcessed event) instead of reading payment tables.

Trade-offs:

  • Calls between services go over the network: slower, and they can fail. That is why I make ADR 11: caching and ADR 12: resilience.
  • No transaction can span two services. Other services see payments a moment later (eventual consistency), through events.
  • More to run: its own pipeline, database, monitoring and on-call.
  • For a small team or an early product, a modular monolith (one deployable app with strict internal modules) is often the better first step. If I keep the modules clean, I can split payments out later.

Go deeper: Lesson 8: Architecture Styles: DDD, Clean Architecture and Microservices.

ADR 2: domain-driven design for the payment rules

The business rules (limits, fees, money, "exactly once") are the reason the service exists, so I model them first, in the language the business uses (DDD's ubiquitous language). I make Payment an aggregate root (the one object that guards its own consistency): nothing can create it in an invalid state.

Why:

  • Rules live in one place. A payment with a negative amount, three decimals or a fee above the amount cannot exist anywhere in the code.
  • Code and conversations use the same words: payment, fee policy, per-transaction limit, account type. New developers and finance read the same model.
  • I can test the rules alone, in milliseconds, with no database.

Trade-offs:

  • More classes and more ceremony than a simple CRUD (create, read, update, delete) service. For screens that only edit data, it is overkill.
  • EF Core needs some help to save rich objects: private setters and a private constructor.
  • The model needs real conversations with the business to be right. Here I keep it light: one aggregate, value-like rules, domain exceptions.

A rich domain entity guards its own rules. Nothing outside can create an invalid payment:

C#
// src/Payments.Domain/Payments/Payment.cs
public sealed class Payment
{
    private Payment() { }   // for EF Core

    public Guid Id { get; private set; }
    public string RequestId { get; private set; } = null!;
    public decimal Amount { get; private set; }
    public decimal Fee { get; private set; }
    // ... CustomerId, AccountType, Currency, CreatedAt

    public static Payment Create(string requestId, string requestHash, string customerId,
        AccountType accountType, decimal amount, string currency, decimal fee, DateTimeOffset createdAt)
    {
        if (amount <= 0)
            throw new InvalidPaymentException("Amount must be greater than zero.");
        if (decimal.Round(amount, 2) != amount)
            throw new InvalidPaymentException("Amount can have at most two decimal places.");
        if (fee < 0 || fee > amount)
            throw new InvalidPaymentException("Fee must be between zero and the amount.");
        // ... checks on the IDs and the currency

        return new Payment { Id = Guid.CreateVersion7(), RequestId = requestId, Amount = amount, Fee = fee /* ... */ };
    }
}

Go deeper: Lesson 8: Architecture Styles: DDD, Clean Architecture and Microservices.

ADR 3: clean architecture inside the service

I split the code into four projects, and dependencies only point inwards. The business rules in the middle know nothing about databases, HTTP or Azure.

src/
  Payments.Domain/          Payment, AccountType, IFeePolicy, PercentageFeePolicy, exceptions
  Payments.Application/     ProcessPaymentHandler, validator, request hasher, FeeCalculator,
                            interfaces: IPaymentRepository, IOutbox, IInbox, IUnitOfWork, ICustomerProfileProvider, IIdempotencyStore
  Payments.Infrastructure/  EF Core, outbox processor, Service Bus publisher, cache, Customer service client
  Payments.Api/             Program.cs and the inbound adapters (code that brings outside input into the app):
                            endpoints, error handling, authentication, idempotency filter,
                            Messaging/: the queue consumer and its message handler
tests/
  Payments.UnitTests/
  Payments.IntegrationTests/
infra/                      Terraform for Azure
.github/workflows/          ci, infra and deploy pipelines

An endpoint and a queue listener are both inbound adapters, so both live in Payments.Api. Infrastructure holds the outbound adapters: the code that calls out to a database, a broker or another service.

Why:

  • I can test Domain and Application without a database, a web server or Azure.
  • I can change Infrastructure (another database, another message broker) without touching a business rule.
  • The compiler enforces the rule through project references, so it cannot erode quietly over time.

Trade-offs:

  • More projects, interfaces and mapping than putting everything in one project.
  • Simple features touch several layers. For a service with many small, independent features, vertical slices (one folder per feature, with its own handler and data access) can be simpler.
  • Interfaces with only one implementation can feel like ceremony. They pay off in tests and when infrastructure changes.

Each project references only the layer inside it. The project files enforce the rule:

HTML
<!-- src/Payments.Domain/Payments.Domain.csproj: no references at all -->

<!-- src/Payments.Application/Payments.Application.csproj -->
<ProjectReference Include="..\Payments.Domain\Payments.Domain.csproj" />

<!-- src/Payments.Infrastructure/Payments.Infrastructure.csproj -->
<ProjectReference Include="..\Payments.Application\Payments.Application.csproj" />

<!-- src/Payments.Api/Payments.Api.csproj: the composition root (the one place that wires everything) -->
<ProjectReference Include="..\Payments.Infrastructure\Payments.Infrastructure.csproj" />

Application defines the ports (interfaces) it needs; Infrastructure implements them:

C#
// src/Payments.Application/Abstractions/IPaymentRepository.cs
public interface IPaymentRepository
{
    Task<Payment?> GetByRequestIdAsync(string requestId, CancellationToken ct);
    void Add(Payment payment);
}

// src/Payments.Infrastructure/Persistence/EfPaymentRepository.cs
internal sealed class EfPaymentRepository(PaymentsDbContext db) : IPaymentRepository
{
    public Task<Payment?> GetByRequestIdAsync(string requestId, CancellationToken ct) =>
        db.Payments.AsNoTracking().FirstOrDefaultAsync(p => p.RequestId == requestId, ct);

    public void Add(Payment payment) => db.Payments.Add(payment);
}

Go deeper: Lesson 8: Architecture Styles: DDD, Clean Architecture and Microservices.

ADR 4: dependency injection, options and a fee strategy

Classes ask for what they need in their constructor; the DI container (the part of .NET that creates objects and their dependencies) supplies it. Fees use the strategy pattern: one IFeePolicy per account type, with rates from configuration.

Why:

  • I can test each class with fakes, because no class creates its own dependencies.
  • I set lifetimes explicitly: handlers are scoped (one per request); so is the profile provider, because it uses a typed HttpClient.
  • A new account type means a new policy and a new configuration line, not an edited if (the open/closed principle). Finance can change rates without a code change.
  • ValidateOnStart stops the app at startup if a rate is missing, instead of failing the first payment.

Trade-offs:

  • Indirection: to follow a call, you look at the registration as well as the class.
  • With only two account types, an if would be shorter. The strategy earns its place once rates change often or the business adds types.
  • A wrong lifetime (for example, a scoped service captured in a singleton) is a classic bug that the container only partly detects.

Each layer registers its own services, and Program.cs calls them:

C#
// src/Payments.Api/Program.cs
builder.Services.AddApplication(builder.Configuration);
builder.Services.AddInfrastructure(builder.Configuration);

// src/Payments.Application/DependencyInjection.cs
services.AddOptions<FeeOptions>()
    .Bind(configuration.GetSection(FeeOptions.SectionName))
    .Validate(o => o.Rates.Values.All(rate => rate is >= 0 and <= 1), "Fee rates must be between 0 and 1.")
    .Validate(o => Enum.GetValues<AccountType>().All(o.Rates.ContainsKey), "Every account type needs a fee rate.")
    .ValidateOnStart();   // a bad configuration stops the app at startup

services.AddSingleton<FeeCalculator>();
services.AddScoped<ProcessPaymentHandler>();

The strategy pattern: one fee policy per account type, chosen by the calculator:

C#
// src/Payments.Domain/Fees/IFeePolicy.cs
public interface IFeePolicy
{
    AccountType AccountType { get; }
    decimal CalculateFee(decimal amount);
}

// src/Payments.Domain/Fees/PercentageFeePolicy.cs
public sealed class PercentageFeePolicy(AccountType accountType, decimal rate) : IFeePolicy
{
    public AccountType AccountType => accountType;

    public decimal CalculateFee(decimal amount) =>
        Math.Round(amount * rate, 2, MidpointRounding.ToEven);   // an explicit rounding rule
}

// src/Payments.Application/Fees/FeeCalculator.cs
public sealed class FeeCalculator(IOptions<FeeOptions> options)
{
    private readonly Dictionary<AccountType, IFeePolicy> _policies = options.Value.Rates.ToDictionary(
        rate => rate.Key, rate => (IFeePolicy)new PercentageFeePolicy(rate.Key, rate.Value));

    public decimal Calculate(AccountType accountType, decimal amount) =>
        _policies[accountType].CalculateFee(amount);
}
JSON
// src/Payments.Api/appsettings.json
"Fees": {
  "Rates": { "Standard": 0.02, "Premium": 0.01 }
}

Go deeper: Lesson 3: SOLID, Design Principles and Dependency Injection.

ADR 5: async I/O and an injectable clock

I make every database, cache and HTTP call async, and pass a CancellationToken through. Time comes from TimeProvider, not DateTime.UtcNow.

Why:

  • While a request waits for I/O, its thread serves other requests, so the same servers handle far more load.
  • If the client disconnects, the token cancels the work that is still running.
  • Tests control time with FakeTimeProvider: they can move the clock past a timeout instead of waiting for it.

Trade-offs:

  • Async spreads through every signature ("async all the way"), and blocking on it with .Result can deadlock or starve the thread pool.
  • Stack traces and debugging are a little harder to read.
  • It does not make CPU-heavy work faster; it only frees threads while waiting.
C#
// src/Payments.Application/Payments/ProcessPaymentHandler.cs
public sealed class ProcessPaymentHandler(
    IPaymentRepository payments,
    IOutbox outbox,
    IUnitOfWork unitOfWork,
    ICustomerProfileProvider customers,
    FeeCalculator fees,
    TimeProvider clock,                       // not DateTime.UtcNow: tests can control time
    PaymentsMetrics metrics,
    ILogger<ProcessPaymentHandler> logger)
{
    public async Task<PaymentResult> HandleAsync(ProcessPaymentCommand command, CancellationToken ct)
    {
        var customer = await customers.GetAsync(command.CustomerId, ct);   // the token flows to every call
        // ...
        var payment = Payment.Create(/* ... */, clock.GetUtcNow());
        // ...
        await unitOfWork.SaveChangesAsync(ct);
    }
}

// src/Payments.Infrastructure/DependencyInjection.cs
services.TryAddSingleton(TimeProvider.System);

// tests/Payments.UnitTests/ProcessPaymentHandlerTests.cs
private readonly FakeTimeProvider _clock = new(new DateTimeOffset(2026, 11, 23, 10, 0, 0, TimeSpan.Zero));

Go deeper: Lesson 1: Async, Threads and Concurrency.

ADR 6: minimal APIs with Problem Details

I write the endpoints as minimal APIs (routes mapped straight to methods, without controllers) that return typed results. I turn every error into a Problem Details response (a standard JSON error format, RFC 9457), with a trace ID and never a stack trace.

Why:

  • Less code and faster startup than controllers, and typed results describe every possible response for OpenAPI.
  • Callers get one error format for everything, with a status code that says what to do: fix the request (400), retry later (409), or stop (422).
  • One exception handler maps business exceptions to responses, so handlers stay free of HTTP code.

Trade-offs:

  • Large APIs need discipline to stay organised: route groups and one endpoints file per area.
  • Some controller features (filters by attribute, conventions) work differently, so teams used to MVC need to adjust.
SituationStatusBody
New payment201 CreatedThe payment, with a Location header
Same key, same body, already done201 Created (replayed)The first response, byte for byte, with an Idempotent-Replayed: true header
Same key, still being processed409 ConflictProblem Details, with a Retry-After: 1 header
Missing key, or an invalid body400 Bad RequestValidation Problem Details, with errors per field
Same key, different body422 Unprocessable EntityProblem Details
Over the limit, or unknown customer422 Unprocessable EntityProblem Details, with the limit
No or invalid token401 UnauthorizedEmpty
Token without the Payments.Write scope or role403 ForbiddenEmpty
Anything unexpected500Problem Details with a trace ID, never a stack trace
C#
// src/Payments.Api/Endpoints/PaymentEndpoints.cs
public static IEndpointRouteBuilder MapPaymentEndpoints(this IEndpointRouteBuilder app)
{
    var group = app.MapGroup("/payments").WithTags("Payments");

    group.MapPost("/", CreatePaymentAsync)
        .RequireAuthorization(AuthPolicies.PaymentsWrite)
        .WithIdempotency()
        .ProducesValidationProblem()
        .ProducesProblem(StatusCodes.Status409Conflict)
        .ProducesProblem(StatusCodes.Status422UnprocessableEntity);

    group.MapGet("/{requestId}", GetPaymentAsync).RequireAuthorization(AuthPolicies.PaymentsRead);
    return app;
}

private static async Task<Results<Created<PaymentResponse>, Ok<PaymentResponse>>> CreatePaymentAsync(
    [FromHeader(Name = "Idempotency-Key")] string? idempotencyKey,
    CreatePaymentRequest body,
    ProcessPaymentHandler handler,
    CancellationToken ct)
{
    var result = await handler.HandleAsync(
        new ProcessPaymentCommand(idempotencyKey ?? "", body.CustomerId, body.Amount, body.Currency), ct);
    var response = PaymentResponse.From(result);

    return result.IsReplay
        ? TypedResults.Ok(response)
        : TypedResults.Created($"/payments/{Uri.EscapeDataString(result.RequestId)}", response);
}

One exception handler turns business errors into Problem Details:

C#
// src/Payments.Api/ErrorHandling/ApiExceptionHandler.cs
internal sealed class ApiExceptionHandler(IProblemDetailsService problemDetails) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
    {
        ProblemDetails? details = exception switch
        {
            RequestValidationException e => new HttpValidationProblemDetails(e.Errors) { Status = 400, Title = "The request is not valid." },
            LimitExceededException e => Problem(422, "Payment limit exceeded.", e.Message, ("limit", e.Limit)),
            CustomerNotFoundException e => Problem(422, "Unknown customer.", e.Message),
            _ => null   // anything else: the default 500, without a stack trace
        };
        if (details is null) return false;

        http.Response.StatusCode = details.Status!.Value;
        return await problemDetails.TryWriteAsync(new() { HttpContext = http, ProblemDetails = details, Exception = exception });
    }
}

// src/Payments.Api/Program.cs
builder.Services.AddProblemDetails(options =>
    options.CustomizeProblemDetails = context =>
        context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier);
builder.Services.AddExceptionHandler<ApiExceptionHandler>();
app.UseExceptionHandler();

Go deeper: Lesson 4: Building Web APIs with ASP.NET Core.

ADR 7: two entry points, and webhooks for partners

I give the service two ways in, and both run the same ProcessPaymentHandler. Callers who wait for the answer, such as a checkout screen, use POST /payments. Callers who do not wait, such as batch jobs, a saga orchestrator or a bursty producer, send a command to the payment-commands queue. I use a queue, not a topic: a topic is for events that many subscribers may read, while a command must be handled exactly once.

HTTP APICommand queue
Request IDThe Idempotency-Key headerThe Service Bus MessageId
DuplicatesThe idempotency filter, then the unique indexAn inbox row for the MessageId, saved in the same transaction as the work; Service Bus duplicate detection; then the unique index
Success201 Created with the paymentA PaymentProcessed event
Business rejection400 or 422 Problem DetailsA PaymentRejected event, with a reason
Unexpected error500; the client retries with the same keyThe message goes back on the queue; after 10 deliveries, to the dead-letter queue

Why:

  • An HTTP caller gets the result, or a clear error, in the same call. That is what a person at a checkout needs.
  • A queue caller does not depend on the payment service being up at that moment: the message waits until the service is back.
  • The queue levels the load (absorbs bursts), so a spike of batch payments cannot overwhelm the service.
  • Because the business logic lives in Application, not in the endpoint, the second entry point is a thin adapter: no business rule is written twice.

Trade-offs:

  • A queue caller has no response. It must listen for PaymentProcessed or PaymentRejected, and match them by request ID.
  • Two paths to operate and monitor, including a dead-letter queue that someone must watch.
  • Service Bus delivers at least once, so the queue handler must be idempotent too. It uses an inbox table, not the HTTP claim-first store (see below).
  • Two deliveries of one message can run at once. Both do the work, and the second rolls back at commit. That wastes a little work, but nothing is charged or published twice.
  • The inbox grows with every message. A clean-up job must delete rows older than the redelivery window.

Where does the queue code go? An endpoint and a queue listener are both inbound adapters, so I put the queue code in Payments.Api/Messaging, next to the endpoints. Each entry point does the edge jobs its own way, and both call the same Application handler:

JobHTTPQueue
ReceiveThe endpointPaymentCommandConsumer
IdempotencyIdempotencyFilter: claim first, in its own transactionProcessPaymentMessageHandler: an inbox row, in the same transaction as the work
Errors become a replyApiExceptionHandler: Problem DetailsProcessPaymentMessageHandler: a PaymentRejected event
Business logicProcessPaymentHandler (Application)ProcessPaymentHandler (Application)

Both run in one container, so HTTP and queue load scale together. If that ever hurts, I move Messaging/ into its own worker project and scale it on queue length.

Why an inbox, and not the claim-first store the HTTP filter uses? Claim first commits the claim, then the work, then "done": three transactions. If the process crashes after the work but before "done", the redelivery finds no record and does the work again. For a payment, the unique index stops a second charge. For a rejection, nothing stops a second PaymentRejected.

An inbox (a table of the messages a consumer has handled) closes that gap. The handler adds the inbox row to the same transaction as the payment, or as the rejection event:

Claim first (HTTP)Inbox (queue)
TransactionsThree: claim, work, doneOne: the work and the inbox row together
A crash between the work and "done"A redelivery can publish a second rejectionCannot happen: both commit, or neither does
Two copies at onceThe second waits: 409 for HTTPBoth run; the second rolls back on the inbox key
Why this path needs itA retry must get a 409 or the stored responseNobody waits for a response, so no stored response and no "in progress" state

The message handler stages the inbox row first, so the payment handler's save commits it with the payment:

C#
// src/Payments.Api/Messaging/ProcessPaymentMessageHandler.cs
public async Task<MessageOutcome> HandleAsync(ProcessPaymentCommand command, CancellationToken ct)
{
    var requestHash = RequestHasher.Compute(command);

    // 1. A quick check. The commit below is the real guard.
    var handled = await inbox.FindAsync(Consumer, command.RequestId, ct);
    if (handled is not null)
        return handled.RequestHash == requestHash ? MessageOutcome.Duplicate : MessageOutcome.MessageIdReused;

    // 2. Stage the inbox row: the payment handler's SaveChanges commits it with the payment and its event
    inbox.MarkHandled(Consumer, command.RequestId, requestHash, "Processed");
    string reason, detail;
    try
    {
        var result = await payments.HandleAsync(command, ct);        // the same handler as the API
        if (!result.IsReplay) return MessageOutcome.Processed;
        await RecordDuplicateAsync(command, requestHash, ct);         // another delivery won the race
        return MessageOutcome.Duplicate;
    }
    catch (IdempotencyConflictException) { return MessageOutcome.MessageIdReused; }
    catch (LimitExceededException e)     { (reason, detail) = ("limit_exceeded", e.Message); }
    catch (CustomerNotFoundException e)  { (reason, detail) = ("customer_not_found", e.Message); }
    catch (RequestValidationException e) { (reason, detail) = ("invalid_request", string.Join(" ", e.Errors.SelectMany(x => x.Value))); }

    // 3. A rejection is a result, not a failure. The event and the inbox row commit together.
    inbox.MarkHandled(Consumer, command.RequestId, requestHash, "Rejected");
    outbox.Enqueue(new PaymentRejected(command.RequestId, /* ... */ reason, detail, clock.GetUtcNow()));
    try { await unitOfWork.SaveChangesAsync(ct); }
    catch (DuplicateRequestException) { return MessageOutcome.Duplicate; }   // the other delivery committed first
    return MessageOutcome.Rejected;
}

A message ID reused for a different command is a sender bug. The consumer dead-letters it, and publishes no event: a PaymentRejected with that ID would tell subscribers that the original payment failed.

The consumer only deals with the transport: complete, retry or dead-letter:

C#
// src/Payments.Api/Messaging/PaymentCommandConsumer.cs
private async Task HandleMessageAsync(ProcessMessageEventArgs args)
{
    var message = args.Message;
    var body = message.Body.ToObjectFromJson<PaymentCommandMessage>(JsonSerializerOptions.Web);
    if (body is null)
    {
        await args.DeadLetterMessageAsync(message, "InvalidBody", "The body must be {customerId, amount, currency}.");
        return;   // it can never succeed: no point retrying
    }

    try
    {
        await using var scope = scopeFactory.CreateAsyncScope();
        var handler = scope.ServiceProvider.GetRequiredService<ProcessPaymentMessageHandler>();
        var outcome = await handler.HandleAsync(/* ... */);
        if (outcome == MessageOutcome.MessageIdReused)
        {
            await args.DeadLetterMessageAsync(message, "MessageIdReused", "...");   // a sender bug: keep it for a person
            return;
        }
        await args.CompleteMessageAsync(message);   // only after the work is saved
    }
    catch (Exception ex) when (ex is not OperationCanceledException)
    {
        await args.AbandonMessageAsync(message);    // retry; after max deliveries, the dead-letter queue
    }
}
Terraform
# infra/servicebus.tf
resource "azurerm_servicebus_queue" "payment_commands" {
  name                                    = "payment-commands"
  namespace_id                            = azurerm_servicebus_namespace.main.id
  requires_duplicate_detection            = true    # a sender's retry with the same MessageId is dropped
  duplicate_detection_history_time_window = "PT10M"
  max_delivery_count                      = 10      # then the dead-letter queue
}

resource "azurerm_role_assignment" "api_receives_commands" {
  scope                = azurerm_servicebus_queue.payment_commands.id
  role_definition_name = "Azure Service Bus Data Receiver"   # receive from this queue only
  principal_id         = azurerm_user_assigned_identity.api.principal_id
}

Queue callers inside our Azure estate subscribe to the events. External partners, who cannot join our Service Bus, need results pushed to them over HTTPS. The obvious answer is a callback: the caller sends a URL with each payment, and the service calls it when done. I do not do that. Instead, partners register an endpoint once, and a webhook dispatcher delivers the events to it:

Callback URL in each requestWebhook dispatcher (what I build)
Where the URL comes fromAny caller, on every requestRegistered in advance, by someone with the Webhooks.Manage permission
SSRF (tricking our server into calling an internal address, such as the cloud metadata endpoint)Every request is a chance to point us at an internal addressChecked at registration (https only, no private addresses), and every address checked again just before connecting; no redirects
Can the partner trust the call?Only if each caller arranges somethingEvery request is signed (Standard Webhooks: webhook-id, webhook-timestamp, webhook-signature)
The partner is downThe result is lost, or the payment code blocks retryingThe delivery is stored and retried for about 30 hours, then marked Failed and can be replayed
DuplicatesUp to each receiverEach event is queued once per subscription, and webhook-id stays the same on every retry
Effect on payment codePayment code must call out and handle failuresNone: the dispatcher is one more consumer of the events on the topic

Why:

  • Partners get results without joining our Service Bus, over plain HTTPS.
  • The payment path stays fast and simple: it publishes events, as before, and never calls partner URLs.
  • Signing, retries and replay are built once, for every partner and every event type.

Trade-offs:

  • More to run: two tables, a fan-out consumer, a delivery processor and an admin API.
  • Partners must verify signatures and drop duplicates, and get their endpoint registered before they can receive anything.
  • Signing secrets live in the database (encrypted at rest by Azure SQL). Stricter setups keep them in Key Vault.
  • A partner that is down for longer than the retry schedule needs a replay, or a status endpoint to catch up.

Every call is signed, so the partner can check it came from us and was not changed:

C#
// src/Payments.Application/Webhooks/WebhookSignature.cs (the Standard Webhooks scheme)
public static string Sign(string secret, string id, long timestamp, string body)
{
    var key = Convert.FromBase64String(secret["whsec_".Length..]);
    var signed = Encoding.UTF8.GetBytes($"{id}.{timestamp}.{body}");   // the timestamp stops old requests being replayed
    return "v1," + Convert.ToBase64String(HMACSHA256.HashData(key, signed));
}

// src/Payments.Infrastructure/Webhooks/WebhookSender.cs
request.Headers.Add("webhook-id", delivery.EventId.ToString());      // the same on every retry
request.Headers.Add("webhook-timestamp", timestamp.ToString(CultureInfo.InvariantCulture));
request.Headers.Add("webhook-signature", WebhookSignature.Sign(subscription.Secret, id, timestamp, delivery.Payload));

The SSRF guard checks every address at connect time, so a public host name that is later pointed at an internal address is still refused:

C#
// src/Payments.Infrastructure/Webhooks/SafeWebhookHandler.cs
public static SocketsHttpHandler Create(WebhookOptions options) => new()
{
    AllowAutoRedirect = false,   // a redirect could lead to an internal address
    ConnectCallback = async (context, ct) =>
    {
        var addresses = await Dns.GetHostAddressesAsync(context.DnsEndPoint.Host, ct);
        var allowed = addresses.Where(a => !WebhookUrlRules.IsBlocked(a)).ToArray();   // no 10.x, 192.168.x, 169.254.x ...
        if (allowed.Length == 0)
            throw new HttpRequestException($"Refusing to connect to {context.DnsEndPoint.Host}: it resolves to an internal address.");

        var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
        await socket.ConnectAsync(allowed, context.DnsEndPoint.Port, ct);
        return new NetworkStream(socket, ownsSocket: true);
    }
};

A failed delivery waits longer before each retry, so a partner that is down for hours still gets every event without being flooded:

C#
// src/Payments.Application/Webhooks/WebhookRetrySchedule.cs
private static readonly TimeSpan[] Delays =
[
    TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30),
    TimeSpan.FromHours(2), TimeSpan.FromHours(5), TimeSpan.FromHours(10), TimeSpan.FromHours(10)
];

// src/Payments.Infrastructure/Webhooks/WebhookDeliveryProcessor.cs (after a failed attempt)
if (WebhookRetrySchedule.NextDelay(delivery.Attempts, _options.MaxAttempts) is { } delay)
    delivery.NextAttemptAt = clock.GetUtcNow() + delay;
else
    delivery.Status = WebhookDeliveryStatus.Failed;   // POST /webhooks/deliveries/{id}/replay sends it again

Go deeper: Lesson 9: Event-Driven Design: Messaging, Outbox, Sagas and CQRS; Lesson 4: Building Web APIs with ASP.NET Core; Lesson 12: Identity and Security.

ADR 8: Entra ID tokens, and trust nothing the caller says about money

Callers sign in with Microsoft Entra ID and send a JWT (a signed token that says who they are and what they may do). The API checks its issuer, audience, lifetime and signature, then a policy checks the permission. I read the account type, which decides the fee, from the customer's profile, never from the request.

Why:

  • No passwords or user tables in the service: the identity provider does sign-in, MFA and token signing.
  • Users get a scope (Payments.Write, a permission the user granted to the app); other services get an app role (a permission given to an application). One policy accepts both.
  • Taking pricing data from the server side closes the "send PREMIUM, pay less" hole in the original code.

Trade-offs:

  • The service depends on the identity provider, and on correct token settings (authority and audience). A wrong setting rejects every call.
  • One extra lookup per payment for the profile; ADR 11: caching caches it.
  • Every client must obtain and refresh tokens, which is more work for callers than an API key.
C#
// src/Payments.Api/Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Auth:Authority"];   // https://login.microsoftonline.com/<tenant>/v2.0
        options.Audience = builder.Configuration["Auth:Audience"];     // api://payments-api
        options.MapInboundClaims = false;   // keep "scp" and "roles" as they are in the token
    });
builder.Services.AddAuthorizationBuilder().AddPaymentPolicies();

app.UseAuthentication();
app.UseAuthorization();

// src/Payments.Api/Auth/AuthPolicies.cs
public static AuthorizationBuilder AddPaymentPolicies(this AuthorizationBuilder builder) => builder
    .AddPolicy(PaymentsWrite, p => p.RequireAuthenticatedUser()
        .RequireAssertion(c => HasPermission(c.User, "Payments.Write")));

// Users get delegated scopes in "scp"; other services get app roles in "roles"
private static bool HasPermission(ClaimsPrincipal user, string permission) =>
    user.FindAll("scp").SelectMany(c => c.Value.Split(' ')).Contains(permission) ||
    user.FindAll("roles").Any(c => c.Value == permission);

Go deeper: Lesson 12: Identity and Security.

ADR 9: exactly once with a claim-first idempotency filter

Clients retry when a call times out. An idempotency key (a unique ID the client sends with a request, and repeats on every retry) lets the server recognise the retry. Checking "already processed?" first is not enough: two requests can both check, both find nothing, and both do the work (a race condition). So I add a filter that claims the key in the database before the endpoint runs:

  • It inserts a row into IdempotencyKeys with status "Processing", committed at once. Only one insert can succeed, on any server.
  • The loser reads the row: still running gives 409 with Retry-After; already done replays the first response; a different request with the same key gives 422.
  • Exceptions and 5xx responses release the key, so the client can retry. A claim times out after two minutes, so a crashed request does not block its key forever.
  • A unique index on Payments.RequestId stays as the final guard.
StepRequest ARequest B
1Inserts the claim: succeedsInserts the claim: fails with a duplicate key
2Runs the endpoint: limit, fee, payment and outbox row in one transactionReads the row: still "Processing", claim not expired
3Stores the 201 response and marks the key "Completed"Returns 409 Conflict with Retry-After: 1. It charges nothing
4Returns 201 CreatedThe client retries after a second and gets A's 201 response replayed, with Idempotent-Replayed: true

Why:

  • It works across any number of servers and survives restarts, because the database is the single source of truth.
  • It is one line per endpoint (.WithIdempotency()), so every endpoint that changes state gets the same, tested behaviour.
  • Status codes follow the IETF Idempotency-Key draft, so clients know what each answer means.

Trade-offs:

  • An extra database write and read on every request, and stored responses take space: a clean-up job must delete old keys.
  • The filter stores the response just after the endpoint commits, so the resource still needs its own unique index for the small gap in between.
  • Redis would be faster for the claim, but it is one more dependency, and it is not in the same database as the payment.
  • Clients must send a key, and keep the same key across retries.
C#
// PaymentEndpoints.cs. The store behind the filter is registered by AddInfrastructure.
group.MapPost("/", CreatePaymentAsync)
    .RequireAuthorization(AuthPolicies.PaymentsWrite)
    .WithIdempotency();   // retries with the same Idempotency-Key get the first response

The heart of the filter, in the Api layer:

C#
// src/Payments.Api/Idempotency/IdempotencyFilter.cs
var key = http.Request.Headers[options.HeaderName].ToString();
if (string.IsNullOrWhiteSpace(key))
    return TypedResults.ValidationProblem(new Dictionary<string, string[]>
        { [options.HeaderName] = ["The Idempotency-Key header is required."] });

var scope = BuildScope(http, endpointOptions);            // "POST /payments/|<caller>"
var requestHash = HashArguments(invocation, hashedArguments);

var claim = await store.TryClaimAsync(scope, key, requestHash, http.RequestAborted);
switch (claim.Outcome)
{
    case ClaimOutcome.Completed:
        return new StoredResponseResult(claim.Response!);   // replay the first response
    case ClaimOutcome.InProgress:
        http.Response.Headers.RetryAfter = "1";
        return TypedResults.Problem(statusCode: 409, title: "A request with this idempotency key is still being processed.");
    case ClaimOutcome.Mismatch:
        return TypedResults.Problem(statusCode: 422, title: "Idempotency key reused with a different request.");
}

StoredResponse response;
try
{
    var result = await next(invocation);            // run the endpoint
    response = await CaptureAsync(http, result);    // write it to a buffer, then to the client
}
catch
{
    await store.ReleaseAsync(scope, key, CancellationToken.None);   // failed: let the client retry
    throw;
}

if (response.StatusCode >= 500)
    await store.ReleaseAsync(scope, key, CancellationToken.None);
else
    await store.CompleteAsync(scope, key, response, CancellationToken.None);

return Results.Empty;   // the response has already been written

The port in Application, and the claim in the Infrastructure store:

C#
// src/Payments.Application/Idempotency/IIdempotencyStore.cs
public interface IIdempotencyStore
{
    Task<ClaimResult> TryClaimAsync(string scope, string key, string requestHash, CancellationToken ct);
    Task CompleteAsync(string scope, string key, StoredResponse response, CancellationToken ct);
    Task ReleaseAsync(string scope, string key, CancellationToken ct);
}

// src/Payments.Infrastructure/Persistence/EfIdempotencyStore.cs
try
{
    // A plain INSERT, committed on its own: the claim is visible to every server immediately.
    await db.Database.ExecuteSqlAsync($"""
        INSERT INTO IdempotencyKeys (Scope, [Key], RequestHash, Status, CreatedAt, LockedUntil)
        VALUES ({scope}, {key}, {requestHash}, {processing}, {now}, {lockedUntil})
        """, ct);
    return ClaimResult.Claimed;
}
catch (SqlException e) when (e.Number is 2601 or 2627)
{
    // The key is taken: read the row and answer Completed, InProgress or Mismatch,
    // or take over a claim whose timeout has passed.
}

Go deeper: Lesson 5: Idempotency, Concurrency and Distributed Locks.

ADR 10: SQL Server with EF Core

I keep payments, outbox messages, idempotency keys and inbox messages in one SQL Server (Azure SQL) database, and map them with EF Core.

Why:

  • Transactions: the payment and its outbox row commit together, or not at all.
  • Unique constraints turn "never twice" into a rule the database enforces, whatever the code does.
  • Exact decimal(18,2) money types, mature tooling, and a team that already knows it.
  • EF Core removes most hand-written SQL, and EnableRetryOnFailure handles short Azure SQL outages (transient faults).

Trade-offs:

  • Writes scale mainly by a bigger server (scaling up). At very high volume you would partition or shard.
  • EF Core adds some overhead and can hide slow queries; you still need indexes and to read the SQL it generates.
  • A document database such as Cosmos DB scales out more easily, but makes multi-row transactions and uniqueness harder.
C#
// src/Payments.Infrastructure/Persistence/Configurations/PaymentConfiguration.cs
internal sealed class PaymentConfiguration : IEntityTypeConfiguration<Payment>
{
    public void Configure(EntityTypeBuilder<Payment> builder)
    {
        builder.ToTable("Payments");
        builder.HasKey(p => p.Id);
        builder.Property(p => p.RequestId).HasMaxLength(100).IsRequired();
        builder.HasIndex(p => p.RequestId).IsUnique();               // "never twice", enforced by the database
        builder.Property(p => p.Amount).HasPrecision(18, 2);
        builder.Property(p => p.Fee).HasPrecision(18, 2);
        builder.Property(p => p.Currency).HasMaxLength(3).IsFixedLength().IsUnicode(false);
        builder.Property(p => p.AccountType).HasConversion<string>().HasMaxLength(20);
        builder.HasIndex(p => new { p.CustomerId, p.CreatedAt });   // "payments for a customer" queries
    }
}

// src/Payments.Infrastructure/Persistence/EfUnitOfWork.cs
public async Task SaveChangesAsync(CancellationToken ct)
{
    try
    {
        await db.SaveChangesAsync(ct);   // one transaction: payment + outbox row
    }
    catch (DbUpdateException e) when (e.InnerException is SqlException { Number: 2601 or 2627 })
    {
        db.ChangeTracker.Clear();
        throw new DuplicateRequestException(e);   // the handler returns the existing payment
    }
}

// src/Payments.Infrastructure/DependencyInjection.cs
services.AddDbContext<PaymentsDbContext>(options =>
    options.UseSqlServer(connectionString, sql => sql.EnableRetryOnFailure(maxRetryCount: 5)));

Go deeper: Lesson 13: Data: SQL Tuning, Indexing and EF Core.

ADR 11: cache customer profiles with HybridCache

The profile (account type and limit) comes from a Customer service. I cache it with HybridCache: an in-memory level on each server, plus Redis when configured, with a five-minute expiry.

Why:

  • Most payments need no network call for the profile, so they are faster and the Customer service gets far less load.
  • Stampede protection (only one load per key at a time) stops many requests on the same server loading the same profile together.
  • The expiry bounds how stale a profile can be.

Trade-offs:

  • A changed limit can take up to five minutes to apply. If that is too slow, the Customer service publishes a change event and this service removes the entry.
  • Stampede protection is per server: ten servers can still load the same profile once each.
  • Redis is one more thing to run, and a cache can hide a slow or failing dependency until entries expire.
C#
// src/Payments.Infrastructure/Customers/CachedCustomerProfileProvider.cs
internal sealed class CachedCustomerProfileProvider(HybridCache cache, ICustomerProfileSource source)
    : ICustomerProfileProvider
{
    private static readonly HybridCacheEntryOptions EntryOptions = new()
    {
        Expiration = TimeSpan.FromMinutes(5),             // shared level (Redis)
        LocalCacheExpiration = TimeSpan.FromMinutes(1)    // in-memory level on each server
    };

    public async Task<CustomerProfile?> GetAsync(string customerId, CancellationToken ct) =>
        await cache.GetOrCreateAsync<CustomerProfile?>(
            $"customer-profile:{customerId}",
            async token => await source.GetAsync(customerId, token),   // runs once per key, even under load
            EntryOptions,
            ["customer-profiles"],                                     // a tag, to clear them all at once
            ct);
}

// src/Payments.Infrastructure/DependencyInjection.cs
var redis = configuration.GetConnectionString("Redis");
if (!string.IsNullOrWhiteSpace(redis))
    services.AddStackExchangeRedisCache(options => options.Configuration = redis);   // becomes the shared level
services.AddHybridCache();

Go deeper: Lesson 6: Caching in .NET.

ADR 12: resilience on every outgoing call

I call the Customer service through a typed HttpClient from IHttpClientFactory, with AddStandardResilienceHandler. That one line adds timeouts, retries with exponential backoff and jitter (waiting longer after each failure, with a little randomness), and a circuit breaker (which stops calling for a while after many failures).

Why:

  • The handler retries short network blips, so they never reach the user.
  • The circuit breaker gives a struggling service room to recover, instead of hammering it.
  • The factory pools and recycles connections, so the client picks up DNS changes and does not exhaust sockets.

Trade-offs:

  • Retries add load and latency. Without limits they can make an outage worse (a retry storm).
  • Retry only safe operations. Reading a profile is safe; retrying a payment needs idempotency, which is why I need ADR 9: idempotency filter.
  • The default settings will not fit every dependency; slow ones need their own timeouts.
C#
// src/Payments.Infrastructure/DependencyInjection.cs
services.AddHttpClient<ICustomerProfileSource, CustomerProfileApiClient>(client =>
        client.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/"))
    .AddStandardResilienceHandler();   // timeouts, retries with backoff and jitter, circuit breaker

// Scoped, not singleton: it uses a typed HttpClient, which must not live for the app's lifetime
services.AddScoped<ICustomerProfileProvider, CachedCustomerProfileProvider>();

// src/Payments.Infrastructure/Customers/CustomerSources.cs
internal sealed class CustomerProfileApiClient(HttpClient http) : ICustomerProfileSource
{
    public async Task<CustomerProfile?> GetAsync(string customerId, CancellationToken ct)
    {
        using var response = await http.GetAsync($"customers/{Uri.EscapeDataString(customerId)}/payment-profile", ct);
        if (response.StatusCode == HttpStatusCode.NotFound)
            return null;

        response.EnsureSuccessStatusCode();
        var dto = await response.Content.ReadFromJsonAsync<CustomerProfileDto>(ct);
        return new CustomerProfile(customerId, dto!.AccountType, dto.PerTransactionLimit);
    }
}

Go deeper: Lesson 7: Resilience.

ADR 13: publish events through a transactional outbox

Saving to SQL Server and publishing to Service Bus cannot be one transaction. So I save the event to an OutboxMessages table in the same transaction as the payment, and a background service publishes it afterwards.

Why:

  • No lost events and no ghost events: the event exists if, and only if, the payment does.
  • Publishing can retry for as long as Service Bus is down, without failing the payment.
  • Several instances can publish at once without taking the same rows (UPDLOCK, READPAST).

Trade-offs:

  • Delivery is at least once: a message can arrive twice. Consumers must drop repeats, with the stable MessageId, Service Bus duplicate detection and an inbox table.
  • Events arrive a little later than the payment (the polling interval).
  • One more table and background job to run, monitor and clean up.
  • Change data capture (CDC, reading the database's change log) avoids the polling, but adds tooling and ties consumers to table shapes.

The handler adds the payment and its event to the same unit of work:

C#
// src/Payments.Application/Payments/ProcessPaymentHandler.cs
payments.Add(payment);
outbox.Enqueue(PaymentProcessed.From(payment));
await unitOfWork.SaveChangesAsync(ct);   // both rows, one transaction

// src/Payments.Infrastructure/Persistence/EfOutbox.cs
public void Enqueue<TEvent>(TEvent integrationEvent) where TEvent : class =>
    db.OutboxMessages.Add(new OutboxMessage
    {
        Id = Guid.CreateVersion7(),
        Type = typeof(TEvent).Name,
        Payload = JsonSerializer.Serialize(integrationEvent, Json),
        OccurredAt = clock.GetUtcNow()
    });

The background processor claims a batch, then publishes each message with a stable ID:

SQL
WITH batch AS (
    SELECT TOP (@batchSize) *
    FROM OutboxMessages WITH (ROWLOCK, UPDLOCK, READPAST)
    WHERE ProcessedAt IS NULL
      AND Attempts < @maxAttempts
      AND (LockedUntil IS NULL OR LockedUntil < @now)
    ORDER BY OccurredAt
)
UPDATE batch SET LockedUntil = @lockedUntil
OUTPUT inserted.*;
C#
// src/Payments.Infrastructure/Messaging/ServiceBusEventPublisher.cs
var busMessage = new ServiceBusMessage(BinaryData.FromString(message.Payload))
{
    MessageId = message.Id.ToString(),   // the same ID on every retry: duplicates can be dropped
    Subject = message.Type,
    ContentType = "application/json"
};
await sender.SendMessageAsync(busMessage, ct);

// src/Payments.Infrastructure/Outbox/OutboxProcessor.cs (after each send)
message.ProcessedAt = clock.GetUtcNow();
// on failure: message.Attempts++, back off exponentially, and give up after MaxAttempts (a poison message)

Go deeper: Lesson 9: Event-Driven Design: Messaging, Outbox, Sagas and CQRS.

ADR 14: observability from day one

I build structured logs, OpenTelemetry traces and metrics, and health checks into the first version, instead of adding them after the first incident.

Why:

  • Traces show one payment's path through the API, the Customer service and Service Bus, so a slow step is easy to find.
  • Business metrics (payments processed, replayed, rejected by reason) show problems a CPU graph cannot, such as a sudden rise in limit rejections.
  • Health checks let Azure restart a broken instance (liveness) and stop sending it traffic (readiness).
  • OpenTelemetry is vendor-neutral: switch from one monitoring tool to another without changing code.

Trade-offs:

  • Telemetry costs money to send and store. High-volume traces usually need sampling.
  • Logs and traces can leak personal data if fields are not chosen with care.
  • A readiness check that depends on the database takes every instance out of service during a database outage, which is right for payments but not for every service.
C#
// src/Payments.Application/Diagnostics/PaymentsMetrics.cs
public sealed class PaymentsMetrics
{
    public const string Name = "Payments";
    public static readonly ActivitySource ActivitySource = new(Name);   // for custom trace spans

    private readonly Counter<long> _processed;
    private readonly Counter<long> _rejected;

    public PaymentsMetrics(IMeterFactory meterFactory)
    {
        var meter = meterFactory.Create(Name);
        _processed = meter.CreateCounter<long>("payments.processed");
        _rejected = meter.CreateCounter<long>("payments.rejected");
    }

    public void Rejected(string reason) => _rejected.Add(1, new KeyValuePair<string, object?>("reason", reason));
}

// src/Payments.Api/Program.cs
builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource.AddService("payments-api"))
    .WithTracing(tracing => tracing
        .AddSource(PaymentsMetrics.Name)
        .AddSource("Azure.*")                 // Service Bus spans
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddOtlpExporter())                   // set OTEL_EXPORTER_OTLP_ENDPOINT
    .WithMetrics(metrics => metrics
        .AddMeter(PaymentsMetrics.Name)
        .AddAspNetCoreInstrumentation()
        .AddMeter("System.Runtime")
        .AddOtlpExporter());

builder.Services.AddHealthChecks().AddDbContextCheck<PaymentsDbContext>("database", tags: ["ready"]);
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready") });

// Structured logging: named properties, not string concatenation
logger.LogInformation("Payment {PaymentId} processed for request {RequestId}, customer {CustomerId}, fee {Fee}",
    payment.Id, payment.RequestId, payment.CustomerId, payment.Fee);

Go deeper: Lesson 16: Observability and Reliability.

ADR 15: unit tests plus integration tests on a real database

TestWhat it provesNeeds
Fee policy testsFees and rounding for each rateNothing
Payment testsIt refuses invalid amounts, currencies and feesNothing
Handler tests with in-memory fakesFees by account type, limits, retry after rejection, and the final guard (a fake unit of work saves a competing payment just before commit)Nothing
Integration testsThe real API, filter and SQL Server: replayed responses, 409 for a key in progress, taking over a crashed claim, no key left after a rejection, the outbox row, and 10 parallel requests with one keyDocker

Why:

  • Unit tests with in-memory fakes run in milliseconds and cover every business rule.
  • Integration tests run the real API against a real SQL Server in Docker (Testcontainers), so they catch what fakes cannot: mappings, SQL, unique constraints and the filter's behaviour under a race.
  • The parallel test (10 requests, one key, exactly one payment) is the only proof that "exactly once" really holds.

Trade-offs:

  • Integration tests need Docker and take seconds, not milliseconds.
  • Fakes can drift from real behaviour; that is why I test the important paths both ways.
  • No end-to-end tests yet: contract tests and a few smoke tests after deployment would close that gap.

A unit test with in-memory fakes, and the parallel integration test against a real SQL Server:

C#
// tests/Payments.UnitTests/ProcessPaymentHandlerTests.cs
[Fact]
public async Task Over_the_limit_is_rejected_and_nothing_is_saved()
{
    var error = await Assert.ThrowsAsync<LimitExceededException>(() => Pay("req-1", "C-STANDARD", 30_000m));

    Assert.Equal(25_000m, error.Limit);
    Assert.Empty(_store.Payments);
    Assert.Empty(_store.PublishedEvents);
}

// tests/Payments.IntegrationTests/PaymentsApiFactory.cs: the real API, a real SQL Server in Docker
public sealed class PaymentsApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly MsSqlContainer _sql = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest").Build();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseSetting("ConnectionStrings:Payments", _sql.GetConnectionString());
        builder.ConfigureTestServices(services =>
            services.AddAuthentication(TestAuthHandler.SchemeName)
                .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.SchemeName, null));
    }
    // ... start and stop the container
}

// tests/Payments.IntegrationTests/PaymentsApiTests.cs
[Fact]
public async Task Parallel_requests_with_the_same_key_create_exactly_one_payment()
{
    var key = Guid.NewGuid().ToString();

    var responses = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => PostPayment(key, "C-1001", 500m)));

    Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created && !IsReplay(r));
    var rows = await InDatabase(db => db.Payments.CountAsync(p => p.RequestId == key));
    Assert.Equal(1, rows);
}

Go deeper: Lesson 17: Testing.

ADR 16: Azure Container Apps with managed identity

I run the service as a container on Azure Container Apps (a managed platform that runs containers and scales them on demand). A user-assigned managed identity (an identity Azure gives the app) lets it pull images, connect to SQL and send to Service Bus, with no passwords anywhere.

Why:

  • Containers run the same locally (Docker Compose), in tests and in Azure.
  • Container Apps gives scaling, revisions and health probes without running Kubernetes yourself.
  • No secrets to store, rotate or leak: SQL accepts Entra ID logins only, and Service Bus has key-based access turned off.
  • Least privilege: the identity may only send to the one payments topic.

Trade-offs:

  • Less control than AKS (Azure Kubernetes Service) for advanced networking or custom operators; more moving parts than App Service for a simple web app.
  • Managed identity needs a one-time database step (CREATE USER ... FROM EXTERNAL PROVIDER) that Terraform cannot do.
  • Local development uses a SQL login and a development sign-in handler, so local and cloud differ a little.

Go deeper: Lesson 14: Azure Services for .NET.

ADR 17: Terraform and pipelines for every change

I describe every Azure resource in Terraform, in infra/, next to the code. GitHub Actions workflows build and test every pull request, plan and apply Terraform, and build one image per commit, deploy it and smoke-test /health/ready.

Why:

  • I can rebuild every environment from code, and every change goes through a pull request.
  • Resources only this service uses live in its own repository, so a change that needs code and infrastructure is one pull request. Shared foundations (networks, DNS, state storage) live in a platform repository.
  • OIDC sign-in (a short-lived token instead of a stored secret) means no Azure credentials in GitHub.
  • The pipeline builds one image per commit, tags it with the commit, and promotes that same image, so what ran in the tests is what runs in production.

Trade-offs:

  • Terraform state needs safe storage and protection, because it holds secrets in plain text.
  • Bicep is simpler for an Azure-only team and needs no state file; Terraform wins when the system spans several clouds or SaaS products.
  • Pipelines are code too, and need the same care: approvals, concurrency limits and their own reviews.

The identity and its permissions, in Terraform:

Terraform
# infra/main.tf
resource "azurerm_user_assigned_identity" "api" {
  name                = "id-${local.name}-api"
  resource_group_name = azurerm_resource_group.main.name
  location            = azurerm_resource_group.main.location
}

# infra/servicebus.tf: the API may only send to this one topic
resource "azurerm_role_assignment" "api_sends_events" {
  scope                = azurerm_servicebus_topic.payments.id
  role_definition_name = "Azure Service Bus Data Sender"
  principal_id         = azurerm_user_assigned_identity.api.principal_id
}

# infra/containerapp.tf: settings become environment variables ("__" means ":")
ConnectionStrings__Payments         = "Server=tcp:${azurerm_mssql_server.main.fully_qualified_domain_name},1433;Database=Payments;Authentication=Active Directory Managed Identity;User Id=${azurerm_user_assigned_identity.api.client_id}"
ServiceBus__FullyQualifiedNamespace = "${azurerm_servicebus_namespace.main.name}.servicebus.windows.net"
AZURE_CLIENT_ID                     = azurerm_user_assigned_identity.api.client_id

The app uses the identity with no secret in the code:

C#
// src/Payments.Infrastructure/DependencyInjection.cs
services.AddSingleton(_ => new ServiceBusClient(
    serviceBus.FullyQualifiedNamespace!, new DefaultAzureCredential()));   // managed identity in Azure

The container app. Terraform hands the image over to the deploy pipeline:

Terraform
# infra/containerapp.tf
resource "azurerm_container_app" "api" {
  # ...
  template {
    container {
      name  = "payments-api"
      image = var.container_image   # a placeholder on first creation

      readiness_probe {
        transport = "HTTP"
        port      = 8080
        path      = "/health/ready"
      }
    }
  }

  lifecycle {
    ignore_changes = [template[0].container[0].image]   # the deploy pipeline owns the image
  }
}

The deploy workflow builds one image per commit and rolls it out:

# .github/workflows/deploy.yml (main steps)
permissions:
  id-token: write          # OIDC login: no stored Azure secret
steps:
  - uses: azure/login@v2
    with:
      client-id: ${{ vars.AZURE_CLIENT_ID }}
      tenant-id: ${{ vars.AZURE_TENANT_ID }}
      subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
  - run: |
      az acr login --name ${{ vars.ACR_NAME }}
      docker build -t "$IMAGE" .            # IMAGE = <registry>/payments-api:<commit SHA>
      docker push "$IMAGE"
  - run: az containerapp update --name ${{ vars.CONTAINER_APP_NAME }} --resource-group ${{ vars.RESOURCE_GROUP }} --image "$IMAGE"
  - run: curl -fsS "$url/health/ready"       # smoke test

Go deeper: Lesson 15: DevOps: Containers, Infrastructure as Code and CI/CD.

What this design leaves out

LessonWhy not here
Lesson 2: Memory Management and Garbage CollectionNo hot paths that need pooling or Span<T>; the service is I/O-bound
Lesson 10: Integration and MigrationA single new service: no legacy system to migrate or wrap
Lesson 18: React Architecture; Lesson 19: Web Performance, Accessibility and Front-End SecurityThe frontend sample comes next
Lesson 20: AI EngineeringNo AI features in the payment flow. For AI agents that apply this way of working to your own requirements, see Use this design on your own requirements

Run it yourself

Shell
git clone https://github.com/vibhu12345/payment-service.git
cd payment-service

# Everything in Docker: SQL Server, Redis and the API on http://localhost:5080
docker compose up --build

# Or: database in Docker, API from your IDE (for debugging)
docker compose up sql redis -d
dotnet run --project src/Payments.Api

# Tests (the integration tests need Docker running)
dotnet test

Then send the sample requests in src/Payments.Api/Payments.Api.http. Send the first one twice: both return 201 with the same payment, and the second has Idempotent-Replayed: true.

Use this design on your own requirements

The repository ships two AI agents that work the way this lesson does. They run in Claude Code and in GitHub Copilot, and both tools get the same instructions:

AgentWhat it does
dotnet-azure-developerTurns plain requirements into an RFC, C4 diagrams, a threat model and ADRs, then writes layered code, tests and infrastructure
dotnet-azure-reviewerChecks the change against its requirements, its ADRs and a checklist, runs the build and tests, and reports findings without editing anything

They are not tied to payments. They work in any business domain, such as bookings, stock or claims:

  • Each agent first reads the repository it is in: the README, any docs/ folder, the solution layout and one feature that goes end to end.
  • It follows the repository's own conventions. Where there are none, it uses .NET and Azure defaults like the ones in this lesson.
  • It leaves out what the requirements do not need. A service with no partners gets no webhooks, and one with no other callers gets no queue.
  • Every choice it makes must trace back to a functional requirement, a non-functional requirement or a failure scenario, and gets an ADR.

I use them in this order:

  • Ask the developer agent for a feature, for example: "Use the dotnet-azure-developer agent to add refunds: a customer can refund a payment within 30 days."
  • Read its RFC and ADRs before its code. That is where a wrong assumption is cheapest to fix.
  • Ask the reviewer agent to review the change. It has a separate context (it has not seen the developer's reasoning), so it checks the work instead of defending it.
  • Send the findings back to the developer, and repeat until the reviewer approves.
  • Review the result myself before I merge. The agents speed up the work; they do not replace my judgment.

To use them in another repository, copy .claude/agents/ (Claude Code) and .github/agents/ (GitHub Copilot). Copy docs/templates/ too, so they start from the same RFC, ADR and review formats. Setup and examples: AI agents in the repository README. How agents and prompts work: Lesson 20: AI Engineering.

Exercises

Check your understanding

QuestionShort answer
When would you not make payments a separate microservice?For a small team or an early product: a modular monolith with a clean payments module costs less, and I can split payments out later.
What does DDD add over a simple CRUD model here?The rules live in the Payment aggregate and the fee policies, so an invalid payment cannot exist and I can test the rules alone.
What does clean architecture cost?More projects, interfaces and mapping; vertical slices can be simpler for many small features.
Why is checking "already processed?" not enough for idempotency?Two requests can both check, both find nothing, and both do the work. Claiming the key with an insert first means only one can win.
Why does the account type come from the customer profile?The server cannot trust values from the caller for pricing; anyone could claim the cheaper type.
What problem does the outbox solve, and what does it cost?It makes the event part of the payment's transaction. The cost: at-least-once delivery, so consumers must drop duplicates, plus a table and a background job.
What is the price of caching profiles?A changed limit can take up to the cache expiry to apply, unless a change event clears it.
Why managed identity?There are no secrets to store, rotate or leak, and I give each permission to the app's identity, as narrowly as possible.

Summary

  • I start from the requirements that "enterprise" adds: exactly once, correct money, reliable events, security, resilience, visibility and repeatable delivery.
  • Each of my ADRs answers one of them, and each has a cost: a microservice costs network calls and eventual consistency; DDD and clean architecture cost ceremony; the outbox costs at-least-once delivery.
  • A good design names those costs and chooses them on purpose.
  • Each section linked to the lesson behind it. Continue with Lesson 1, or follow any link.

Found this useful? Share it: LinkedIn X

Comments