Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 10 · Lesson 94 · 10 min read

Design an E-Commerce Checkout: Sagas and Payments

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Order State Machine, Reservation, Payment Intent and a Verified Webhook
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Design a checkout that never oversells or double charges, coordinate inventory, payment and order state with a saga and compensations, handle payment provider webhooks securely and idempotently, minimize PCI scope, and present honest pending states in the React interface.

Concept Explanation

Checkout is where correctness has a price tag. Requirements: a customer converts a cart into an order, stock is reserved so items are not oversold, payment is taken exactly once, the customer receives confirmation, and failures leave the system in a consistent state that can be explained. The non-functional needs are strict: no lost orders, no double charges, no oversold inventory, an audit trail for every state change, and resilience to a payment provider being slow, down, or delivering the same notification twice. Volume is modest, perhaps a few orders per second at peak, so this is a correctness design, not a scale design, and a well-structured modular monolith with SQL Server is the right foundation.

The core difficulty is that checkout spans systems that cannot share a transaction: your database, and an external payment provider. You cannot roll back a charge by aborting a SQL transaction. The saga pattern, a sequence of local transactions with compensating actions, replaces the distributed transaction. The order moves through explicit states: Pending when created, then Reserved once inventory is held, then PaymentAuthorized or Paid when the provider confirms, and Confirmed when complete. If a step fails, compensations run: release the reservation, cancel or refund the payment, mark the order Cancelled. Modeling the order as a state machine with the legal transitions of Day 62, persisted after every step, makes the process recoverable: after a crash, a worker resumes any order stuck in an intermediate state.

Inventory reservation uses the atomic conditional update of Day 37, which decrements stock only if enough remains and reports whether it succeeded, so two shoppers racing for the last item cannot both win. Reservations carry an expiry; a background job releases reservations for orders that were never paid within, say, fifteen minutes, which prevents abandoned carts from holding stock forever. The price must be recomputed on the server from the database at checkout, never trusted from the client, as Day 1 showed. Payments use the provider's intent model: the server creates a payment intent with an idempotency key derived from the order identifier, the client confirms it using a client secret, and the final result arrives through a webhook. Using the provider's hosted card fields means card numbers never touch your servers, which keeps you in the lightest tier of PCI DSS scope, and you store only tokens and the last four digits.

Webhooks are inbound requests from the outside world, so they are untrusted input. Verify the signature: providers sign the payload with a shared secret, and you recompute the HMAC over the raw body and compare using a constant-time comparison. Check the timestamp within a tolerance to prevent replay of captured requests, and process each event identifier once by recording it in an inbox table, because providers deliver at least once and may retry for days. Acknowledge quickly with a 2xx and do the heavy work asynchronously. The React side should reflect reality: after the customer confirms payment, the order is Pending until the webhook lands, so show a clear processing state and update through polling or SignalR, and never present success purely because the client-side call returned. The shopping cart itself is a famous example of designing for availability: Amazon's Dynamo paper described choosing to always accept additions to the cart and merge conflicting versions later, because an unavailable cart costs more than a rare duplicate item.

ConcernDesignReason
No oversellAtomic conditional stock update with reservation expiryCorrect under concurrency
No double chargeIdempotency key from the order id, webhook dedupe by event idRetries and duplicates are safe
Cross-system consistencySaga with persisted states and compensationsNo distributed transaction exists
Price integrityServer recomputes totals from the databaseClient values are untrusted
Card dataProvider-hosted fields, tokens onlyMinimal PCI DSS scope
Webhook securitySignature check, timestamp tolerance, event inboxInbound requests are hostile until verified
User experienceHonest pending state, live updateSuccess is defined by the provider's confirmation

Worked Example: The Order State Machine, Reservation, Payment Intent and a Verified Webhook

The listings show the order model, the checkout command with atomic reservation, the webhook handler, and the timeout compensation.

C#
public enum OrderState { Pending, Reserved, PaymentPending, Paid, Confirmed, Cancelled }

public sealed class Order
{
    public Guid Id { get; private set; } = Guid.CreateVersion7();
    public Guid UserId { get; private set; }
    public OrderState State { get; private set; } = OrderState.Pending;
    public decimal Total { get; private set; }
    public string? PaymentIntentId { get; private set; }
    public DateTimeOffset ReservationExpiresAt { get; private set; }
    public List<OrderLine> Lines { get; private set; } = [];
    public byte[] RowVer { get; private set; } = [];

    private static readonly Dictionary<OrderState, OrderState[]> Allowed = new()
    {
        [OrderState.Pending] = [OrderState.Reserved, OrderState.Cancelled],
        [OrderState.Reserved] = [OrderState.PaymentPending, OrderState.Cancelled],
        [OrderState.PaymentPending] = [OrderState.Paid, OrderState.Cancelled],
        [OrderState.Paid] = [OrderState.Confirmed],
        [OrderState.Confirmed] = [], [OrderState.Cancelled] = [],
    };
    public Result<bool> Transition(OrderState next) =>
        Allowed[State].Contains(next) ? Apply(next) : Result<bool>.Fail("order.transition", $"{State} to {next} is not allowed.");
    private Result<bool> Apply(OrderState next) { State = next; return Result<bool>.Ok(true); }
}
C#
// Step 1: reserve stock atomically and create the order with a server-computed total. One local transaction.
public async Task<Result<Guid>> StartCheckoutAsync(StartCheckout cmd, CancellationToken ct)
{
    var strategy = db.Database.CreateExecutionStrategy();
    return await strategy.ExecuteAsync(async () =>
    {
        await using var tx = await db.Database.BeginTransactionAsync(ct);
        var products = await db.Products.AsNoTracking().Where(p => cmd.Lines.Select(l => l.ProductId).Contains(p.Id)).ToDictionaryAsync(p => p.Id, ct);
        decimal total = 0;

        foreach (var line in cmd.Lines)
        {
            if (line.Quantity is < 1 or > 20 || !products.TryGetValue(line.ProductId, out var p) || !p.IsActive)
                return Result<Guid>.Fail("cart.invalid", "An item in your cart is unavailable.");

            // Atomic: decrements only if enough stock remains. Zero rows affected means someone else got the last one.
            var reserved = await db.Products.Where(x => x.Id == p.Id && x.Stock >= line.Quantity)
                .ExecuteUpdateAsync(s => s.SetProperty(x => x.Stock, x => x.Stock - line.Quantity), ct);
            if (reserved == 0) return Result<Guid>.Fail("stock.insufficient", $"{p.Name} is no longer available in that quantity.");
            total += p.Price * line.Quantity;                                  // price from the database, never the client
        }

        var order = Order.Create(cmd.UserId, cmd.Lines, total, reservationTtl: TimeSpan.FromMinutes(15));
        order.Transition(OrderState.Reserved);
        db.Orders.Add(order);
        await db.SaveChangesAsync(ct);
        await tx.CommitAsync(ct);
        return Result<Guid>.Ok(order.Id);
    });
}

// Step 2: create the payment intent with an idempotency key derived from the order. A retry creates no second intent.
var intent = await payments.CreateIntentAsync(new(order.Total, "usd", Metadata: new() { ["orderId"] = order.Id.ToString() }),
                                              idempotencyKey: $"order-{order.Id}", ct);
order.AttachIntent(intent.Id); order.Transition(OrderState.PaymentPending);
// Return intent.ClientSecret to React. Card fields are provider-hosted iframes: card numbers never reach our servers.
C#
// Step 3: the provider's webhook. Verify, deduplicate, then transition. The handler acknowledges quickly.
app.MapPost("/webhooks/payments", async (HttpRequest req, AppDb db, IConfiguration cfg, PaymentSaga saga, CancellationToken ct) =>
{
    using var reader = new StreamReader(req.Body);
    var raw = await reader.ReadToEndAsync(ct);                             // the RAW body: signatures cover exact bytes
    var header = req.Headers["Payments-Signature"].ToString();             // format: t=timestamp,v1=hexsignature

    if (!SignatureVerifier.IsValid(raw, header, cfg["Payments:WebhookSecret"]!, tolerance: TimeSpan.FromMinutes(5)))
        return Results.Unauthorized();                                     // forged, tampered, or replayed

    var evt = JsonSerializer.Deserialize<PaymentEvent>(raw)!;
    if (await db.Inbox.AnyAsync(i => i.MessageId == evt.Id, ct)) return Results.Ok();      // already processed: idempotent

    db.Inbox.Add(new InboxMessage(evt.Id, DateTimeOffset.UtcNow));
    await saga.HandleAsync(evt, ct);                                        // Paid -> Confirmed; failed -> compensation; saves both together
    return Results.Ok();
}).AllowAnonymous().DisableAntiforgery();                                   // authenticated by signature, not by cookie

public static class SignatureVerifier
{
    public static bool IsValid(string rawBody, string header, string secret, TimeSpan tolerance)
    {
        var parts = header.Split(',').Select(p => p.Split('=', 2)).Where(p => p.Length == 2).ToDictionary(p => p[0], p => p[1]);
        if (!long.TryParse(parts.GetValueOrDefault("t"), out var t) || !parts.TryGetValue("v1", out var sig)) return false;
        if (Math.Abs((DateTimeOffset.UtcNow - DateTimeOffset.FromUnixTimeSeconds(t)).TotalSeconds) > tolerance.TotalSeconds) return false;   // replay window

        var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"{t}.{rawBody}"));
        byte[] provided; try { provided = Convert.FromHexString(sig); } catch (FormatException) { return false; }
        return CryptographicOperations.FixedTimeEquals(expected, provided);              // constant time: no timing side channel
    }
}
C#
// Compensation: abandoned or failed checkouts release stock and cancel the intent. Runs on a schedule with a single-instance lock (Day 87).
public async Task ExpireReservationsAsync(CancellationToken ct)
{
    var expired = await db.Orders.Include(o => o.Lines)
        .Where(o => o.State is OrderState.Reserved or OrderState.PaymentPending && o.ReservationExpiresAt < clock.GetUtcNow())
        .Take(100).ToListAsync(ct);

    foreach (var order in expired)
    {
        if (order.PaymentIntentId is { } id) await payments.CancelIntentAsync(id, idempotencyKey: $"cancel-{order.Id}", ct);   // safe to repeat
        foreach (var line in order.Lines)
            await db.Products.Where(p => p.Id == line.ProductId).ExecuteUpdateAsync(s => s.SetProperty(p => p.Stock, p => p.Stock + line.Quantity), ct);
        order.Transition(OrderState.Cancelled);
    }
    await db.SaveChangesAsync(ct);          // a crash midway leaves orders in their old state; the next run finishes the job
}
JavaScript
// React: success means the provider confirmed, not that the button was clicked.
const confirm = async () => {
  const { error } = await stripe.confirmPayment({ elements, redirect: 'if_required' });      // provider-hosted fields
  if (error) return setError(error.message);
  setPhase('processing');                                                                     // we do not know the outcome yet
};
const { data: order } = useQuery({ queryKey: ['order', id], queryFn: () => request(`/api/orders/${id}`, OrderSchema),
  refetchInterval: (q) => (['Paid', 'Confirmed', 'Cancelled'].includes(q.state.data?.state ?? '') ? false : 2000) });
return <OrderStatus state={order?.state} />;   // "Processing your payment" until the webhook has moved the order to Confirmed

Write tests for the scenarios that break naive designs: fifty concurrent buyers for ten units, the same webhook delivered twice, a webhook with a bad signature, a webhook with an old timestamp, and a crash between payment and confirmation, verified by running the recovery job.

An order moves Pending, Reserved, PaymentPending, Paid, Confirmed. Stock is reserved with an atomic conditional update. The provider webhook is verified and deduplicated before it moves the order to Paid, and failures or timeouts release stock and cancel the payment intent.
An order moves Pending, Reserved, PaymentPending, Paid, Confirmed. Stock is reserved with an atomic conditional update. The provider webhook is verified and deduplicated before it moves the order to Paid, and failures or timeouts release stock and cancel the payment intent.

Real-World Examples

  • Stripe documents that webhook requests are signed with a Stripe-Signature header containing a timestamp and an HMAC-SHA256 of the payload, and recommends verifying the signature with the raw request body, rejecting timestamps outside a tolerance of five minutes by default, and handling duplicate events idempotently because events may be delivered more than once. The scheme in this lesson follows that model, and similar signing designs are used by GitHub and Shopify webhooks.
  • Amazon's 2007 Dynamo paper described the shopping cart as a motivating use case for an always-writable store: rather than reject an add-to-cart during a partition, the system accepts writes and reconciles divergent versions later, accepting an occasional resurrected deleted item in exchange for availability. It illustrates the same principle behind sagas, that in commerce it is often better to accept work and correct with compensations than to block on global consistency.
Key TakeawaysModel checkout as a saga with an explicit order state machine, so every step can be retried safely or undone cleanly. Use atomic inventory reservation with expiry, server-computed prices, and provider payment intents keyed by idempotency keys. Treat webhooks as hostile: verify signatures over the raw body with constant-time comparison, enforce a timestamp tolerance, and deduplicate by event id. Keep card data on the provider's hosted fields, run compensations for failures and timeouts, and show honest pending states in the interface.

Review Questions & Answers

The provider is an external system that cannot participate in your database's transaction, so atomic commit across both is impossible. A saga breaks the process into local transactions with persisted states and defines compensating actions, such as releasing stock or canceling the payment, so failures are corrected explicitly and the process can resume after a crash.

The idempotency key derived from the order id makes retries of the create-payment call return the same intent instead of creating another charge. Recording each webhook event id in an inbox means a repeated delivery is recognized and ignored, so the order transitions once. One protects the outbound call and the other the inbound notification.

The signature is computed over the exact bytes sent, so re-serializing parsed JSON can change the bytes and break or weaken verification. A normal string comparison exits at the first differing byte, leaking timing information that can help an attacker forge signatures, whereas a fixed-time comparison takes the same time regardless of where they differ.

The client-side confirmation only means the customer submitted their details, not that the provider approved the charge or that your server processed the webhook. The definitive result arrives asynchronously, so showing success prematurely can mislead the user if the payment later fails. The interface should wait for the order state from the server.