How I avoided charging a PIX payment twice
PIX webhooks arrive duplicated. How I authenticated them with HMAC, confirmed them with a pessimistic lock in Postgres, and recorded everything in an append-only ledger.
A user pays with PIX (Brazil's instant payment system) in their banking app. My server takes no part in that: it only finds out about the payment when the payment service provider (the PSP) makes an HTTP call to a URL of mine. That call is the webhook. And the PSP only stops retrying when it gets a 2xx back.
This creates a problem every payment system has: the same notice can arrive twice, or twice at the same time, on different workers. In Kravva, a confirmation does four things: it marks the transaction as paid, grants access, books the sale in the financial records, and credits a partner's commission. The user paid once, but if I run those four things twice, I record two sales and pay double commission. That is the "charging twice" in the title: the effect on my side, not the debit on the customer's account.
There's a second problem: the URL is public. Anyone can send a JSON saying "I paid" and, if I believe it, I give away paid access for free.
I solved it in three layers: authenticate the call, make it idempotent, and record the money in a way that can't be rewritten.
Layer 1: prove the notice came from the PSP
HMAC is a hash that mixes in a key: HMAC(key, message). Without the key, nobody can compute the right result. Think of a wax seal pressed with a ring only the PSP has. It signs the request body and sends the result in a header; I recompute it and compare.
Two details that cost a lot when forgotten:
- The signature is valid for the exact bytes the PSP sent. If I let the framework turn the JSON into an object and serialize it again, whitespace and key order can change and the signature "fails". That's why NestJS starts with
rawBody: trueand I validate the raw body. - The comparison has to run in constant time. A
===stops at the first different character, and an attacker who measures response time can work out the signature bit by bit (a timing attack). Node'stimingSafeEqualalways compares everything, but it requires buffers of the same length, so I check the length first.
// Simplified from the real code
const esperada = createHmac('sha256', chave)
.update(Buffer.from(corpoCru, 'utf8')) // original bytes
.digest('base64');
const a = Buffer.from(esperada);
const b = Buffer.from(assinaturaDoHeader);
// length first, then constant-time comparison
return a.length === b.length && timingSafeEqual(a, b);
An honest caveat: with my PSP, the key used for the signature is published in their documentation. So the signature guarantees integrity and format, but it isn't enough on its own. That's why I require a second factor: a secret of mine, known only to me and the PSP, attached to the registered URL. Without both, the response is 401.
Layer 2: confirm only once
Idempotency is the property of an operation that, when repeated, has the same effect as running it once. Webhooks are "at least once" delivery: exactly once doesn't exist over the network. So idempotency has to live on my side.
The instinct is "I'll wrap it in a transaction". But a transaction alone doesn't prevent the race. At Postgres's default isolation level, two simultaneous deliveries read "pending", both decide they need to confirm, and both write "paid".
The way out is a pessimistic lock: assume the conflict will happen and lock first. SELECT ... FOR UPDATE reads the row and keeps it locked until the end of the transaction. Whoever arrives later waits. Analogy: a bathroom whose key is kept at the front desk. The second person doesn't try the door and fight with the first; they wait for the key to come back and, when they go in, see it has already been cleaned.
I chose pessimistic over optimistic (a version on the row, the loser retries) because the conflict is likely, since PSPs resend in bursts, and the critical section is short.
// TypeORM, simplified
return this.dataSource.transaction(async (manager) => {
// becomes SELECT ... FOR UPDATE
const tx = await manager.findOne(Transacao, {
where: { id: transacaoId },
lock: { mode: 'pessimistic_write' },
});
if (!tx) throw new Error('Transaction not found');
const jaEstavaPago = tx.statusPagamento === 'pago';
if (!jaEstavaPago) {
tx.statusPagamento = 'pago';
await manager.save(tx);
await this.razao.registrarVendaSeAusente(manager, tx);
await this.creditarComissao(manager, tx); // only the 1st time
}
// always runs: repairs access that went missing
await this.garantirAcessos(manager, tx);
});
Notice two details. The jaEstavaPago check happens with the row locked, so the second delivery sees the state already committed by the first. And granting access always runs, on purpose: if a partial state was left behind, the redelivery fixes the access without crediting the commission again.
There's also a rule about side effects: the real-time notice to the user only goes out after the commit. If the transaction rolls back, nobody is told about access that doesn't exist.
Layer 3: a ledger that only grows
The money goes into a ledger: a table where rows are never edited or deleted. A correction is a new row that offsets the previous one. A refund is a negative entry, and the balance is the sum.
type | amount_cents | period
sale | +4990 | 2026-08
refund | -4990 | 2026-09 (new row, negative)
Three decisions here:
- Integer cents.
0.1 + 0.2in JavaScript gives0.30000000000000004. With money, the error adds up. R$ 49.90 is4990. - Refunds booked in the period of the event. If a refund rewrote August, a month that was already closed would change value. With the negative row in September, "how much did I sell in August?" has the same answer today and a year from now.
- A unique constraint as a safety net. The code prevents duplicates, but the database is the last barrier if the code fails.
-- at most one sale and one refund per transaction
CREATE UNIQUE INDEX uq_lancamento_transacao_tipo
ON lancamentos_financeiros (transacao_id, tipo)
WHERE deleted_at IS NULL;
The ledger writers are "if absent" (they only insert if the entry doesn't exist yet) and receive the caller's EntityManager. That way, selling and booking happen in the same transaction: both or neither.
What to test
An idempotency test with mocks proves nothing, because a mock doesn't reproduce a lock. Mine run against a real Postgres and cover redelivery, failure halfway through, and two concurrent deliveries.
For concurrency, I don't hope the scheduler overlaps the calls. I use a "gate": a separate connection locks the row, I fire both deliveries, wait for both to be blocked, release the gate, and check the result: one access, one commission, one real-time event.
What I would do differently
Looking honestly at my code:
- The webhook history has no
UNIQUE. Deduplication there is "query, then insert", and two simultaneous deliveries get past the query before any insert. The financial effect is protected by the lock, but the history can be duplicated. The right fix is aUNIQUEwithON CONFLICT DO NOTHING. - The
FOR UPDATEalso looks up bygateway_id, which has no index. As the table grows, the lookup becomes a scan and the lock lasts longer. - A nonexistent transaction responds 500. The PSP keeps resending forever. A permanent failure should be logged and answered with 2xx.
- The ledger's immutability is only a convention. Nothing in the database prevents an
UPDATE, and the inheriteddeleted_atopens a gap for the partial index to stop seeing a row. I would add a trigger that rejectsUPDATEandDELETE. - Commission stays outside the ledger. Today it's an increment on a mutable balance, so the ledger doesn't reconcile with the cash. Double-entry bookkeeping would solve it.
Key takeaways
- Webhooks are "at least once" delivery: the same notice arrives repeated or in parallel, and your code needs to handle it.
- Validate the HMAC over the raw body, with
timingSafeEqual, and don't trust a signature whose key is public without a second factor. - A transaction isn't enough: use
SELECT ... FOR UPDATE, check the state with the row locked, and keep unique constraints as the last barrier. - Money goes in an append-only ledger, in integer cents, with refunds as negative rows; only notify the user after the commit.
- Test concurrency against a real Postgres, forcing the overlap.