Opening: Two Clicks, Two Charges
A buyer presses Pay. The signal is weak and the spinner keeps spinning. They press it again.
Two orders are recorded. Two charges go out.
Meanwhile, the payment gateway sends a "payment succeeded" notification. Our server answers a bit late, so the notification is sent again. Two notifications arrive almost together, and the buyer receives two tickets for one payment.
Both problems share one root: operations that are not safe to repeat. Part 4 ended with a promise: graceful shutdown is not always guaranteed, so the other half of the answer is making operations safe to repeat. This is that half: idempotency.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. According to the HTTP spec, which method is not idempotent?
- A.
GET - B.
PUT - C.
DELETE - D.
POST
Show the answer to question 1
D: POST. GET, PUT and DELETE are defined as idempotent: repeating them adds no further effect. POST is not, and POST is exactly what we use for "create order" or "pay". But remember: the definition is a promise, not a guarantee. A DELETE you write yourself can still be non-idempotent if the code is wrong.
Question 2. This webhook handler receives the same notification twice, at the same time. How many tickets are issued?
async function webhookNaif(pesananId) {
const { rows } = await pool.query('SELECT status FROM pesanan WHERE id = $1', [pesananId]);
if (rows[0].status !== 'pending') return 'sudah diproses';
await tunggu(50); // pretend there is other work here
await pool.query("UPDATE pesanan SET status = 'paid', dibayar_pada = now() WHERE id = $1", [pesananId]);
await pool.query('INSERT INTO tiket (pesanan_id) VALUES ($1)', [pesananId]);
return 'tiket terbit';
}
- A. 1
- B. 2
Show the answer to question 2
B: 2. (pesanan = order, tiket = ticket, sudah diproses = already processed, tiket terbit = ticket issued.) Both requests read the pending status before either one changes it. Both pass the check. This is the check-then-act pattern, and section 3 shows the test result on PostgreSQL.
Question 3. Can a payment gateway such as Midtrans send the same notification more than once?
- A. No, every event is sent exactly once
- B. Yes
Show the answer to question 3
B. The Midtrans documentation says that in extremely rare cases it may send multiple notifications for the same transaction event, and that this must not cause double entries on the merchant's side. Notifications are also resent when our server answers with an error code.
Question 4. The client sends an Idempotency-Key header. When is a new key created?
- A. Every time a request is sent, including retries
- B. Once per user action. Retries reuse the same key.
Show the answer to question 4
B. The key represents the intent ("I want to create this order"), not the delivery attempt. If every retry uses a new key, the server cannot tell it is the same request.
Question 5. UPDATE pesanan SET status = 'paid' WHERE id = $1 AND status = 'pending' returns a rowCount of 0. What does that mean?
- A. Something went wrong, return 500
- B. The order was already processed, do not process it again
Show the answer to question 5
B. No row matched, because the status is no longer pending. Another request got there first. For a webhook, just answer 200, because the event is already recorded.
What did you score? Let's take them apart.
1. What Does Idempotent Mean?
An idempotent operation: running it twice has the same result as running it once.
Compare two buttons:
- A lift button. Press it once or ten times, the lift still comes once. Idempotent.
- A coin vending machine. Put in a coin twice and you pay twice. Not idempotent.
In a backend, "set the order status to paid" can be made to behave like the lift button. "Add one ticket row" naturally behaves like the coin machine. Our job is to wrap coin-machine operations so they behave like lift buttons.
2. Why the Same Request Arrives Twice
Click the diagram to see it full size.
Duplicates are not an edge case. They come from many directions:
- A user clicks twice, because the screen feels slow.
- A client retries after a timeout. The sneaky part: often the first request actually succeeded, and only its response got lost on the way back.
- A payment gateway resends a webhook, because our server was slow to answer or answered with an error.
- A queue delivers at least once. Almost every queue system prefers "maybe twice" over "maybe lost".
- A process dies halfway (Part 4), and another worker picks the job up again.
Networks and distributed systems cannot guarantee "exactly once" delivery. What we can guarantee is that the effect happens exactly once.
3. Tool 1: Check and Change in One Statement
The problem in question 2 is the gap between reading and changing. As long as that gap exists, another request can slip in.
The fix: move the check into the UPDATE itself.
async function webhookAman(pesananId) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rowCount } = await client.query(
"UPDATE pesanan SET status = 'paid', dibayar_pada = now() WHERE id = $1 AND status = 'pending'",
[pesananId],
);
if (rowCount === 0) {
await client.query('ROLLBACK');
return 'sudah diproses';
}
await tunggu(50);
await client.query('INSERT INTO tiket (pesanan_id) VALUES ($1)', [pesananId]);
await client.query('COMMIT');
return 'tiket terbit';
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
I ran both versions on PostgreSQL 16, each with two identical notifications sent at the same time through Promise.all:
naif: ["tiket terbit","tiket terbit"] -> 2 tiket
aman: ["tiket terbit","sudah diproses"] -> 1 tiket
(naif = naive, aman = safe.) Why is this safe? PostgreSQL locks the row being updated. The second request waits until the first finishes, then re-checks the status = 'pending' condition. It no longer holds, so rowCount is 0.
The pattern works anywhere: make the state transition a condition in the WHERE. pending → paid can only happen once, and the database enforces it.
From my own project: CahTix
A bug with the same root showed up in CahTix, a ticketing product I built. For general admission ticket quotas, the flow read first (SELECT), then changed (UPDATE), then deleted (DELETE). Under PostgreSQL's default READ COMMITTED isolation, two transactions running together could return the quota twice.
The fix matches this section: merge those steps into one atomic statement, a DELETE ... RETURNING inside a CTE, so only one transaction "gets" the row. For numbered seats, there is a race test with the same pattern: 30 concurrent requests for one seat. The old code let 30 out of 30 through. The new code lets exactly 1 through.
4. Tool 2: A Unique Constraint as the Last Net
Code can be wrong. The database is the last guard that cannot be bypassed. If, in business terms, one order may only have one ticket, write that rule into the schema:
ALTER TABLE tiket ADD CONSTRAINT tiket_pesanan_unik UNIQUE (pesanan_id);
Now even the naive code from question 2 cannot issue a second ticket:
try {
await pool.query('INSERT INTO tiket (pesanan_id) VALUES ($1)', ['INV-1']);
console.log('tiket terbit');
} catch (err) {
if (err.code === '23505') console.log('ditolak database: tiket untuk pesanan ini sudah ada');
else throw err;
}
tiket terbit
ditolak database: tiket untuk pesanan ini sudah ada
(The second line reads "rejected by the database: a ticket for this order already exists".) 23505 is PostgreSQL's code for a unique violation. If duplicates are expected, you do not even need to catch an error:
INSERT INTO tiket (pesanan_id) VALUES ('INV-1') ON CONFLICT (pesanan_id) DO NOTHING;
ON CONFLICT DO NOTHING, baris baru: 0
(baris baru = new rows.) Use tool 1 for the correct logic, and tool 2 as the seatbelt.
5. Tool 3: Idempotency-Key for Client Requests
Tools 1 and 2 work because we have a natural key: pesanan_id. But for "create a new order", the order does not exist yet. Two clicks produce two orders with different IDs.
The fix: the client creates a unique key once per action (for example a UUID when Pay is first pressed), and sends it in an Idempotency-Key header on every attempt. The server remembers that key:
async function denganIdempotencyKey(key, kerja) {
const redisKey = `idem:${key}`;
const dapat = await redis.set(redisKey, JSON.stringify({ status: 'proses' }), 'EX', 60, 'NX');
if (dapat !== 'OK') {
const tersimpan = JSON.parse(await redis.get(redisKey));
if (tersimpan.status === 'proses') {
return { kode: 409, body: { error: 'request yang sama masih diproses' } };
}
return tersimpan.respons; // exactly the same response as the first time
}
try {
const respons = await kerja();
await redis.set(redisKey, JSON.stringify({ status: 'selesai', respons }), 'EX', 24 * 60 * 60);
return respons;
} catch (err) {
await redis.del(redisKey); // failed: release the key so a retry is allowed
throw err;
}
}
(kerja = the work, proses = in progress, selesai = done, tersimpan = stored.) The test: two clicks almost together, then one retry after that, all with the key 3f1c9a:
{"kode":201,"body":{"pesananId":"INV-1"}}
{"kode":409,"body":{"error":"request yang sama masih diproses"}}
{"kode":201,"body":{"pesananId":"INV-1"}}
pesanan yang benar-benar dibuat: 1
The second click gets 409 ("the same request is still in progress") because the first is still running. The retry afterwards gets exactly the same response as the first, without creating a new order. The last line confirms only one order was really created. The client does not need to know whether its first request succeeded: it just retries with the same key.
SET ... NX here is the same pattern as the cron lock in Part 3: only one caller gets OK.
For production, add:
- Scope keys per user (
idem:${userId}:${key}), so nobody can use someone else's key. - Store a hash of the body. The same key with a different body is a client bug: reject it with
422. - An expiry, for example 24 hours. After that the key can be forgotten.
6. Payment Webhooks: Where All the Tools Meet
I have led the development of a payment service with Midtrans on a project. A payment webhook is where all three tools get used together. The checklist:
-
Verify the signature first. Midtrans includes a
signature_key= SHA-512 oforder_id + status_code + gross_amount + server key. Ignore any notification whose signature is wrong.JSfunction signatureValid(notif, serverKey) { const expected = crypto .createHash('sha512') .update(notif.order_id + notif.status_code + notif.gross_amount + serverKey) .digest('hex'); const a = Buffer.from(expected, 'hex'); const b = Buffer.from(String(notif.signature_key ?? ''), 'hex'); return a.length === b.length && crypto.timingSafeEqual(a, b); }TEXTasli : true dipalsu: false kosong : false(asli = genuine, dipalsu = forged, kosong = empty.)
timingSafeEqualcompares without leaking information through timing. -
Validate the body with a schema (Part 8).
-
A conditional state transition (tool 1), and a unique constraint on derived tables such as tickets (tool 2).
-
If it was already processed, answer
200. Do not answer with an error for a duplicate, because that triggers yet another resend. -
Answer fast. Heavy work such as sending email or building a ticket PDF goes to a queue (Part 1).
-
When in doubt, ask for the status. Midtrans also provides an API to check a transaction's status straight from the source.
7. Three Idempotency Traps
Trap 1: a new key on every retry
That is question 4. If the client code calls crypto.randomUUID() inside the function that gets retried, every attempt looks like a new request. Create the key when the action starts, store it, and reuse it.
Trap 2: marking "done" before the work is done
If the key is marked done and the process then dies before the order is saved, a retry receives "success" for an order that never existed. Mark it done after the work is really saved, and release the key on failure.
Trap 3: effects outside the database
An UPDATE can be rolled back. An email that has been sent cannot. If a transaction changes the database and then sends an email, and the transaction is repeated, the email can go out twice. The common pattern: save "email to send" as a row in the same transaction (an outbox), and let a separate worker send it and mark it as sent.
Summary
- Idempotent: twice is the same as once. A lift button, not a coin machine.
- Duplicates are normal: double clicks, retries after timeouts, resent webhooks, at-least-once queues, processes dying halfway.
- Tool 1: the state transition as a
WHEREcondition. In the test: naive gave 2 tickets, safe gave 1. - Tool 2: a unique constraint as the last net (
23505,ON CONFLICT DO NOTHING). - Tool 3: an
Idempotency-Keyonce per action, stored withSET NX, replaying the first response. - Webhooks: verify the signature, validate, transition conditionally, answer
200for duplicates, answer fast.
Closing & What's Next
The two clicks from the opening now produce one order, and two notifications produce one ticket.
In the final part of this series, we tidy up the other side of all the errors we have met: 409, 422, 23505, ZodError, and unexpected bugs. How to translate all of them in one place, with a consistent response shape, without leaking internal details to users. That is centralized error handling.
Grab your coffee, see you in the next part!

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

