Idempotent Stripe webhooks in ASP.NET Core

Stripe delivers webhooks at least once. If your endpoint is slow, returns an error or the network drops the response, Stripe retries — so the same invoice.paid can arrive two or three times. Events can also arrive out of order. If your handler extends a subscription or emails a receipt every time it sees an event, sooner or later a customer gets it twice.

This is the pattern I used for sign-up and billing on the fleet management SaaS.

1. Verify the signature against the raw body

Read the body as a string before anything else touches it, and verify it with your endpoint's signing secret. Reject anything that fails.

app.MapPost("/webhooks/stripe", async (HttpRequest request, BillingDbContext db,
    IOptions<StripeSettings> settings, ILogger<Program> log) =>
{
    var json = await new StreamReader(request.Body).ReadToEndAsync();

    Event stripeEvent;
    try
    {
        stripeEvent = EventUtility.ConstructEvent(
            json, request.Headers["Stripe-Signature"], settings.Value.WebhookSecret);
    }
    catch (StripeException ex)
    {
        log.LogWarning(ex, "Rejected Stripe webhook: bad signature");
        return Results.BadRequest();
    }

    return await ProcessOnceAsync(db, stripeEvent, log);
});

One gotcha: ConstructEvent throws by default if the event's API version doesn't match the version your Stripe.net package was built for. Pin your webhook endpoint's API version in the Stripe dashboard to match the library, and upgrade both together.

2. Record the event ID in the same transaction as the work

Every event has a unique id. Keep a table of processed IDs with a unique index, and insert into it inside the same transaction as the business change. If the work fails, the marker rolls back with it and Stripe's retry gets a clean second attempt. If the event was already processed, the unique index stops you.

public class ProcessedStripeEvent
{
    public string EventId { get; set; } = "";   // unique index
    public string Type { get; set; } = "";
    public DateTime ProcessedAt { get; set; }
}

static async Task<IResult> ProcessOnceAsync(BillingDbContext db, Event e, ILogger log)
{
    await using var tx = await db.Database.BeginTransactionAsync();
    try
    {
        db.ProcessedStripeEvents.Add(new ProcessedStripeEvent
        {
            EventId = e.Id, Type = e.Type, ProcessedAt = DateTime.UtcNow
        });

        switch (e.Type)
        {
            case "checkout.session.completed":
                await HandleCheckoutCompleted(db, (Stripe.Checkout.Session)e.Data.Object);
                break;
            case "invoice.paid":
                await HandleInvoicePaid(db, (Invoice)e.Data.Object);
                break;
            // ignore everything else, but still record it
        }

        await db.SaveChangesAsync();
        await tx.CommitAsync();
        return Results.Ok();
    }
    catch (DbUpdateException ex) when (IsUniqueViolation(ex))
    {
        log.LogInformation("Stripe event {Id} already processed", e.Id);
        return Results.Ok(); // tell Stripe to stop retrying
    }
}

static bool IsUniqueViolation(DbUpdateException ex) =>
    ex.InnerException is SqlException { Number: 2601 or 2627 };

Any other exception escapes, the transaction rolls back, the endpoint returns a 500, and Stripe tries again later. That is what you want for a temporary failure.

3. Don't trust the order

A customer.subscription.updated sent at 10:01 can arrive after one sent at 10:02. Two ways to cope:

  • Store the event's Created timestamp against the subscription and ignore anything older than what you already applied.
  • Treat the event as a nudge and fetch the current object from the Stripe API before acting. Slower, but always right.

For subscription status the second approach is the safer default; for append-only events such as a paid invoice, the first is usually enough.

4. Keep the handler quick

Stripe expects a 2xx response within a few seconds. Database updates are fine inline; emails, PDFs and calls to other services belong in a background job that reads from a table the handler writes to. A slow handler causes timeouts, which cause retries — exactly what you were trying to avoid.

Checklist

  • Signature verified against the raw body.
  • Unique event ID recorded in the same transaction as the work.
  • Duplicate returns 200; real failure returns 500.
  • Out-of-order events can't move state backwards.
  • Slow side effects moved to a background job.
Share This Post
GM
Ghulam Murtaza

Ghulam Murtaza

Senior Full Stack .NET developer in Lahore with 6+ years building web platforms, REST APIs and mobile back-ends on ASP.NET Core, C# and SQL Server.

Related Posts

Designing a batched GPS ingestion API
Designing a batched GPS ingestion API
Read More
Multi-tenant isolation with EF Core global query filters
Multi-tenant isolation with EF Core global query filters
Read More
Newsletter

Get the latest posts delivered to your inbox