Sub topic 14
Refunds, voids, and chargebacks
This chapter covers the flows that move money backwards or cancel it before it moves. It assumes you know the authorization, capture, and settlement steps. It also assumes you have seen the payment state machine, idempotency keys, and the double-entry ledger from earlier chapters.
Three different ways to undo a payment
The three operations look similar to a customer. They differ in who starts them, when they are allowed, and what they do to money.
| Operation | Starts from | Initiated by | Money moved? | Reversible by you? |
|---|---|---|---|---|
| Void | Authorized | Merchant | No. The hold on the cardholder's funds is released. | Yes, by authorizing again |
| Refund | Captured or settled | Merchant | Yes. Money is returned to the cardholder. | No, only by a new charge |
| Chargeback | Captured or settled | Cardholder, through the issuer | Yes. Funds are forcibly pulled back, often with a fee. | Only by winning a dispute |
A void is cheap because no funds have left the cardholder's account yet. The issuer only placed a hold, and the hold disappears. A refund is a new money movement in the opposite direction. A chargeback is an involuntary reversal that you did not request, so your system must be ready to receive it at any time.
Voids
You can void only while a payment is authorized. Once capture is sent to the PSP (payment service provider), the void window is closed. After that, the only option is a refund.
Two edge cases matter:
- Void racing capture. A void request and a capture request can arrive at nearly the same time. Use the state machine as the referee. Both operations must perform a conditional update such as
UPDATE ... SET status = 'voided' WHERE id = :id AND status = 'authorized'. Only one will match a row. The loser gets a clear error. - Void that the PSP rejects. Some PSPs reject a void when capture is already in progress on their side. Treat that rejection as a signal to re-read the PSP's state rather than assume your own state is right.
Refunds
A refund looks simple but has several rules that a payment system must enforce itself.
- Partial refunds are normal. A merchant may refund part of an order, then another part later.
- The total cannot exceed what was captured. Cumulative refunds must stay at or below the captured amount.
- Refunds need their own idempotency key. A retried refund request must not return money twice.
- Refunds can fail later. A PSP may accept the request and report failure days afterward, for example when the card account has been closed. Your system needs a
refund_failedpath and a way to pay the customer another way.
The spine's state table has captured -> refunded. With partial refunds, store a running total on the payment and move to refunded only when it equals the captured amount. Until then the payment stays captured. Each refund is its own record with its own status.
ALTER TABLE payments ADD COLUMN refunded_minor BIGINT NOT NULL DEFAULT 0;
CREATE TABLE refunds (
id UUID PRIMARY KEY,
payment_id UUID NOT NULL REFERENCES payments (id),
idempotency_key TEXT NOT NULL,
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (payment_id, idempotency_key)
);
-- Reserve refundable amount atomically. No row returned means the refund is not allowed.
UPDATE payments
SET refunded_minor = refunded_minor + :amount_minor
WHERE id = :payment_id
AND status = 'captured'
AND refunded_minor + :amount_minor <= amount_minor
RETURNING refunded_minor;The UPDATE is the important part. A check-then-write sequence in application code lets two concurrent refunds each see enough balance and both succeed. Putting the cap in the WHERE clause makes the database enforce it under concurrency. Run the INSERT into refunds and this UPDATE in one transaction. If the insert hits the unique constraint, you have a retry, so return the existing refund instead.
If the PSP call later fails, release the reserved amount by subtracting it again and marking the refund failed. Do this in a transaction that also writes the ledger reversal.
Recording the movement in the ledger
Refunds and chargebacks are new ledger transactions. Never edit or delete the original entries. A refund reverses the original capture entries, and a chargeback does the same and adds a fee.
from collections import defaultdict
def assert_balanced(entries):
net = defaultdict(int)
for _account, direction, amount, currency in entries:
net[currency] += amount if direction == "debit" else -amount
if any(total != 0 for total in net.values()):
raise ValueError("ledger transaction is not balanced")
def refund_entries(amount_minor, currency):
# Reverses the original capture: debit the merchant, credit the customer side.
entries = [
("merchant_payable", "debit", amount_minor, currency),
("customer_funds_receivable", "credit", amount_minor, currency),
]
assert_balanced(entries)
return entries
def chargeback_entries(amount_minor, fee_minor, currency):
# The merchant bears the disputed amount and the dispute fee.
entries = [
("merchant_payable", "debit", amount_minor + fee_minor, currency),
("customer_funds_receivable", "credit", amount_minor, currency),
("dispute_fee_revenue", "credit", fee_minor, currency),
]
assert_balanced(entries)
return entries
print(refund_entries(500, "USD"))
print(chargeback_entries(1999, 1500, "USD"))A merchant's merchant_payable balance can go negative after a refund or chargeback if they have already been paid out. Decide ahead of time how you recover that: net it against future payouts, hold a reserve, or debit a bank account.
Chargebacks
A chargeback begins when a cardholder tells the issuer that a transaction is wrong. The reasons include fraud, "item not received", a duplicate charge, or a billing error. The card network forwards the dispute through the acquirer and PSP to you. The merchant then has a limited time to submit evidence.
A chargeback is not a payment status change. It is a separate object, a dispute, linked to a payment. A payment can be captured and also have an open dispute, and one payment can have more than one dispute. Model it with its own states.
The funds usually leave the merchant's balance when the dispute opens, not when it ends. If the merchant wins, the funds come back, which is another ledger transaction. This is why you book the chargeback on opening and book a reversal on a win.
Dispute data arrives from the PSP, usually by webhook, so apply the same rules as other asynchronous events. Deduplicate by event ID and tolerate events arriving out of order. Store the deadline as a timestamp and alert before it passes, since a missed deadline is an automatic loss.
Common mistakes
- Refunding without a cap. This is the most common bug. Enforce the cumulative limit in the database.
- Treating a refund as a negative payment. Refunds have their own lifecycle and can fail. Keep a separate table.
- Refunding a payment that has an open dispute. Refunding and then losing the dispute pays the customer twice. Block or flag refunds on disputed payments.
- Mixing currencies. A refund must use the original payment's currency, even if exchange rates have moved.
- Skipping reconciliation. PSP reports are the source of truth for which refunds and disputes actually happened. Match them against your records daily.
Exercise
A merchant captured 5000 minor units (USD). They send two refund requests of 3000 each at the same moment, with different idempotency keys. Describe what should happen, and which mechanism guarantees it.
Show answer
Exactly one refund should be accepted and the other rejected. The conditional UPDATE adds the amount only when refundedminor + amount <= amountminor. The database serializes the two updates on the same row. The first moves refunded_minor to 3000. The second would make it 6000, which exceeds 5000, so its WHERE clause matches no row and the service returns an error. The cap is enforced in the database, not in application code, so concurrency cannot break it.
Exercise
A chargeback of 1999 USD arrives with a 1500 fee. Write the ledger entries, and explain why the original capture entries are left unchanged.
Show answer
Debit merchantpayable 3499, credit customerfundsreceivable 1999, and credit disputefee_revenue 1500. Debits equal credits at 3499. The original entries are left alone because the ledger is append-only. It must show the real history, a capture followed by a later reversal, so audits and reconciliation can reproduce every balance at any point in time.