I work on backend systems for banks in Brazil. This article starts with a real incident from my time at a Brazilian bank, where I worked on credit pipelines and direct debit processing. It then shows the same problem in a small .NET 8 webhook endpoint you can run yourself.
The incident
We received a CNAB file, the bank file format used in Brazil. While we were processing it, a timeout happened. The processing ran twice. We had two records for the same debits, and nothing in the code treated them as duplicates.
We noticed the problem when a duplicate debit arrived almost at the edge of the customer's account. The debit was already being sent to the customer. We had an event flagged by Dynatrace, a network service interruption. We went hunting for problems in the system in general, and that is when we caught some duplicate debits.
There was no financial loss. But if we had not caught it, the customer would have been debited twice.
We fixed it afterwards by putting a unique key on the debits.
We implemented the unique key generation in the producer. The producer sent a unique key with each debit. These files went to the Brazilian banks, and when the customer made the debit, the bank sent us back the payment receipt carrying the same key we had sent from the producer. That is how we started to detect duplicate debits.
We had no way to block it at the entrance, in the producer. If the producer made an error and sent two charges, the customer's bank (it could be any other bank) debited the customer twice and sent back to us the proof of payment. We received two identical keys.
Think of it like a utility bill. Imagine I send the electricity bill twice for automatic debit, and the customer pays twice. The bank returns two identical keys to me. Then I act: I cancel one of the payments at the other bank, the one that debited the customer twice, or I reimburse the customer automatically, so he has no loss.
Banks do not all behave the same way. In some situations a bank does not process two equal values twice, but it depends on the bank. Some banks processed the debit twice and accepted it. If I sent two duplicate keys with two duplicate values, they processed the payment and we had to reimburse the customer. Other banks had a lock. They did not do that automatically, unless we sent a new request.
That is the lesson for me: you cannot count on the other side to block a duplicate, because it varies from bank to bank. That is why we needed our own unique key and our own detection.
In general, any process that can run twice will run twice, usually on the worst possible day. The only reliable defense is to make running twice harmless.
The same problem with Stripe webhooks
Stripe delivers webhooks at least once. If your endpoint times out, or a deploy happens mid-request, Stripe sends the same event again. If your handler sends an email or grants access, a duplicate does real damage, just like our duplicate debit.
I have not run Stripe in production. I built an open source toolkit around it, and the pattern below is from that project and its tests. The repository with the full code and a passing CI run is here: https://github.com/rafengenharia/stripe-webhook-idempotent-dotnet.
What you need:
- .NET 8 SDK
- Stripe CLI logged in to a test account
- Packages:
Stripe.netandMicrosoft.EntityFrameworkCore.Sqlite
The endpoint follows three rules.
Rule 1: verify the signature on the raw body
Stripe signs the exact bytes it sends. If model binding parses and re-serializes the JSON first, verification fails. So read the body as a string and pass it to EventUtility.ConstructEvent together with the Stripe-Signature header and your endpoint secret. If it throws a StripeException, return 400.
Rule 2: use the event id as the unique key
This is the same idea as the unique key we used at that bank, but checked before the work instead of after. Every Stripe event has an id like evt_..., and retries reuse it. We store each processed id in a table where the id is the primary key. The database enforces the rule, so even if two deliveries arrive at the same moment, only one insert can win.
Rule 3: record the id and do the work in one transaction
The tempting version marks the event as processed first and then runs the handler. If the handler throws, the event is marked done but the work never happened, and Stripe's retry is ignored. The reverse order has the opposite bug.
Put both in one transaction. If the handler fails, the insert rolls back, you return 500, and Stripe retries later. If the commit fails because the id already exists, another delivery got there first, so you return 200.
The endpoint
app.MapPost("/stripe/webhook", async (HttpRequest req, AppDb db, IEventHandler handler,
IConfiguration cfg, TimeProvider clock, ILogger<Program> log) =>
{
var secret = cfg["Stripe:WebhookSecret"];
if (string.IsNullOrEmpty(secret))
{
log.LogError("Stripe:WebhookSecret is not configured");
return Results.StatusCode(500);
}
// 1. Read the RAW body. The signature is computed over the exact bytes Stripe sent.
var json = await new StreamReader(req.Body).ReadToEndAsync();
// 2. Verify the signature (and the 5 minute timestamp tolerance). Throws StripeException if invalid.
Event stripeEvent;
try
{
stripeEvent = EventUtility.ConstructEvent(
json, req.Headers["Stripe-Signature"], secret,
throwOnApiVersionMismatch: false);
}
catch (StripeException)
{
log.LogWarning("Webhook signature verification failed"); // never log the body
return Results.BadRequest();
}
// 3. Fast path: already processed this event id.
if (await db.ProcessedEvents.AnyAsync(e => e.Id == stripeEvent.Id))
{
log.LogInformation("Webhook {EventId} already processed, ignoring", stripeEvent.Id);
return Results.Ok();
}
// 4. Do the work and record the event id in ONE transaction.
await using var tx = await db.Database.BeginTransactionAsync();
try
{
db.ProcessedEvents.Add(new ProcessedEvent
{
Id = stripeEvent.Id,
Type = stripeEvent.Type,
At = clock.GetUtcNow()
});
await handler.HandleAsync(stripeEvent);
await db.SaveChangesAsync(); // a primary key violation here means a concurrent delivery won the race
await tx.CommitAsync();
log.LogInformation("Webhook {EventId} {EventType} processed", stripeEvent.Id, stripeEvent.Type);
return Results.Ok();
}
catch (DbUpdateException)
{
db.ChangeTracker.Clear();
if (await db.ProcessedEvents.AsNoTracking().AnyAsync(e => e.Id == stripeEvent.Id))
return Results.Ok(); // duplicate: a concurrent delivery won the race
log.LogError("Webhook {EventId} failed with a database error", stripeEvent.Id);
return Results.StatusCode(500); // Stripe will retry
}
catch (Exception ex)
{
// The transaction rolls back when it is disposed. Return 500 so Stripe retries later.
log.LogError("Webhook {EventId} failed: {ErrorType}", stripeEvent.Id, ex.GetType().Name);
return Results.StatusCode(500);
}
});
Read the catch blocks carefully. A DbUpdateException is treated as a duplicate only when the event id now exists in the table. Any other failure is logged without the payload and ends as a 500, so Stripe retries. The transaction rolls back when it is disposed, so a failed attempt leaves nothing behind.
A handler that is dangerous on purpose
The sample handler for invoice.paid does PaidInvoices++. Running it twice gives the wrong answer, which makes it a good test. Without the guard, a replayed event gives 2. With it, 1.
public class InvoiceEventHandler(AppDb db) : IEventHandler
{
public async Task HandleAsync(Event e)
{
if (e.Type != EventTypes.InvoicePaid) return;
var invoice = (Invoice)e.Data.Object;
var key = invoice.CustomerId ?? "none";
var sub = await db.Subscriptions.FindAsync(key)
?? db.Subscriptions.Add(new Subscription { Id = key }).Entity;
sub.Status = "active";
sub.PaidInvoices++;
}
}
Test it
The repository has an xUnit test that signs a fake event, posts it twice, and checks the counter.
[Fact]
public async Task Webhook_SameEventDeliveredTwice_ProcessedOnce()
{
var c = _factory.CreateClient();
var json = EventJson("evt_1");
Assert.Equal(HttpStatusCode.OK, (await c.SendAsync(Signed(json))).StatusCode);
Assert.Equal(HttpStatusCode.OK, (await c.SendAsync(Signed(json))).StatusCode);
Assert.Equal(1, PaidInvoices());
}
It runs with dotnet test tests/Tests.csproj. There are four more tests: two different events are both processed, a bad signature gets a 400, an old timestamp gets a 400, and a handler that fails once is rolled back and succeeds on the retry. All of them pass in GitHub Actions.
To try it by hand: run stripe listen --forward-to localhost:5000/stripe/webhook, copy the whsec_ secret into the config, run stripe trigger invoice.paid, then replay the same event with stripe events resend. The table should show one processed event and PaidInvoices at 1.
What I would watch in production
- Keep the signing secret out of source control. The tests use an obviously fake one.
- Return a 2xx quickly. For slow work, store the event and process it in a background worker.
- Do not rely on order. Stripe does not guarantee it, so fetch the current object from the API when order matters.
- Clean old rows from the processed events table after a few weeks.
- SQLite is only for the demo. The same primary key pattern works on SQL Server and PostgreSQL.
Wrap-up
At that bank, a timeout and a second run put duplicate debits close to real customers. We could not block them at the entrance, and we could not trust every bank to block them, so the unique key let us detect them and correct them, by cancelling one payment or reimbursing the customer. The webhook version uses the same idea in a smaller place, with one difference: here the key lets you stop the duplicate before it does any work. The three steps are: verify the raw body, use the event id as a unique key, and make the id insert and the side effects one transaction.
Top comments (3)
Once you return 200, Stripe is done with that event, so the background-worker version moves the retry problem into your own code. If the worker dies after you've recorded the id, nothing redelivers it, and the transaction pattern above won't help because the insert committed fine. That queue needs its own backoff and a way to replay. I built Webhook Relay for this exact case, it keeps every raw delivery and retries the failed ones.
On the gap Karolis raised, you don't need another service to close it. If the handler can do the work in the same database transaction as the event id insert, a crash rolls back both, and Stripe's retry finds nothing recorded. When the work has to run in a background worker, store the event with a status (received, then processed) and have a small sweeper re-run anything still stuck in received after a few minutes. The endpoint still acknowledges fast, and nothing is lost if the worker dies.
For the case where your endpoint was down long enough to miss retries, a periodic job that lists recent events from Stripe's Events API and processes any id you haven't stored is a cheap safety net. Same lesson as your CNAB story: don't rely on the other side to resend or to dedupe, make both cases harmless on yours.
Solid write-up, and I hit the same race on the creation side.
Two checkout clicks minted two payment links for one purchase, so a customer could pay twice and both callbacks would look legit. I fixed it by storing the link id on my payment row, reusing it while it's still open, and refusing to mint a new one when a payment is already marked success but the order isn't confirmed. That guard's the cheap one: a paid row with an unconfirmed order means something broke between two writes, and I'd rather throw than mint a second link.
I'd add one thing to your cleanup note. If you prune processed ids on a schedule, a late retry after the prune replays for real, so prune by age but keep the id indexed so my insert still fails fast.
Did you hit the reverse case, where the handler succeeds and the commit fails? I couldn't make that one quiet.