Most first payment integrations look alike: call the provider, get a success response, mark the order as paid. It works in the demo, and it keeps working for the first few hundred customers. Then a provider has a slow afternoon, a few requests time out, a few customers tap “Pay” again, and someone in finance asks why the books are off.
This part explains why. Before ledgers, queues or locks, you need a clear picture of what a payment is, and a way to say where each payment is in its life. The rest of the handbook builds on both.
Chapter 1
Why processing payments is harder than it looks
To the customer, a payment is one action: tap a button and the money is gone. Behind that button, several companies and their computers have to agree on what happened, and they don't all get there at the same time.
A payment is not one HTTP request
When you call POST /charges on a provider, it is tempting to treat the response as the whole story. It isn't. A card payment goes through several stages that happen at different times and are run by different parties:
- Initiation. The customer says “I want to pay €40”. Nothing has happened to any money yet; so far it is only a request in our system.
- Authorisation. The customer's bank checks the card and puts a hold on €40. The money is still in the customer's account, but it is reserved.
- Capture. The merchant (us, through our provider) says “yes, take the money we reserved”. This can happen right away or later, for example when an order ships.
- Settlement. Money moves between banks and lands in the merchant's account, usually in a batch, often a day or more later.
- Reconciliation. We compare our records with the provider's reports and the bank statement, and make sure every cent is explained.
Not every payment method has all five stages. Some methods, like many bank transfers and real-time payment schemes, collapse authorisation and capture into one step. The general shape still holds: the moment the customer sees “paid” is not the moment the money moves.
Authorisation, capture and settlement
People mix these three words up a lot, and the difference shows as soon as something goes wrong.
| Stage | What it means | Who does it | Has money moved? |
|---|---|---|---|
| Authorisation | The bank approves the payment and reserves the amount. | Customer's bank (the issuer) | No. It is a hold. |
| Capture | The merchant confirms it wants the reserved money. | Merchant, via the provider | Not yet. It is now owed. |
| Settlement | Funds are transferred between banks. | Banks and card networks | Yes. |
An authorisation does not last forever. Stripe, for example, says an authorisation for an online card payment is usually valid for 7 days, with shorter windows for some cases (Stripe: place a hold on a payment method). If you authorise and never capture, the hold expires and you never get paid. Nothing throws an error when that happens, which is why it's easy to miss.
Payment success is not business success
When a provider tells you a payment succeeded, it means their part worked. Your part still has to happen: credit a wallet, mark an order as paid, give the customer the thing they bought. These are two different facts:
- Payment success: “PayCo charged the customer €40.”
- Business success: “We credited the customer's wallet with €40, exactly once.”
Either can be true while the other is false. The provider can charge the customer and our server can crash before crediting them, so the customer has paid and got nothing. Or, as the example below shows, we can credit the wallet twice for one charge. A good payment system tracks the two facts separately and has a plan for when they disagree.
Confirmation usually arrives later, and sometimes more than once
Many payments are not decided inside the request that starts them. The customer may need to approve the payment in their banking app, pass a 3-D Secure check, or finish on the provider's hosted page.
In all of these cases the final answer reaches us asynchronously, meaning later and through a different channel. Usually that channel is a webhook: the provider calls a URL on our side to tell us what happened.
Webhooks are convenient, but you can't count on them to behave. Stripe's documentation says plainly that endpoints “might occasionally receive the same event more than once”, and that it “doesn't guarantee the delivery of events in the order that they're generated” (Stripe: webhooks). Expect the same from other providers. From day one, the code that handles a payment result has to cope with:
- the same event arriving twice (or ten times),
- events arriving in the wrong order, like “succeeded” before “processing”,
- an event arriving late, after we have already given up on the payment,
- an event never arriving at all.
Because of that last case, I never rely on webhooks alone: we also ask the provider for the status ourselves, and we reconcile.
A timeout does not mean the payment failed
If you take one idea from this chapter, take this one. When our call to the provider times out, there are three possibilities, and from our side they look identical:
- The request never reached the provider. Nothing happened.
- The request reached the provider, and the payment failed.
- The request reached the provider, the payment succeeded, and the response got lost on the way back.
“Unknown” is a real state, and the system needs somewhere to keep it; the next chapter calls it PROCESSING. From there we find out what happened by asking the provider for the payment's status, by waiting for the webhook or, as a last resort, through reconciliation.
Three systems, three answers
Taken together, this leads somewhere uncomfortable: at any moment, each system involved in one payment can believe something different, and none of them is wrong.
Our database is one of these views, and often the least informed. That is why the third principle of this handbook is never blindly trust any component, our own database included. We design for disagreement and check for it.
Worked example: how a retry credits a customer twice
A common setup makes this concrete. The customer pays on PayCo's hosted page. When they come back to our app, the app calls our API to confirm the payment. Our API asks PayCo for the status, and if it says “succeeded”, we credit the customer's wallet.
The obvious implementation, in Python with FastAPI and psycopg, looks like this. (The payco client is fictional, and so are pool and load_payment, which stand for a connection pool and a small query helper.)
# Naive version: do not use
@app.post("/payments/{payment_id}/confirm")
def confirm_payment(payment_id: str):
payment = load_payment(payment_id)
result = payco.get_payment(payment.provider_payment_id)
if result.status == "succeeded":
with pool.connection() as conn:
conn.execute("UPDATE payments SET status = 'SUCCESS' WHERE id = %s", (payment_id,))
conn.execute(
"UPDATE wallets SET balance_minor = balance_minor + %s WHERE id = %s",
(payment.amount_minor, payment.wallet_id),
)
return {"status": result.status}On a first read it looks fine. On a slow day, this happens:
- The customer pays €40 on PayCo's page. PayCo charges them.
- The app calls
/confirm. Our API asks PayCo, gets “succeeded” and credits the wallet with €40. The database commits. - But all of that took longer than the app's 10-second timeout (because PayCo was slow that afternoon). The app gives up and shows “Something went wrong, try again”.
- The customer taps “Try again”. The app calls
/confirma second time. PayCo still says “succeeded”, because it did. Our API credits the wallet again.
The customer paid €40 and now has €80 in their wallet. The retry path isn't the only way in, either: the same thing happens if the webhook handler and the confirm call both credit the wallet, or if PayCo delivers the webhook twice.
What went wrong
Three things went wrong, and all three come back in later chapters. First, the credit is tied to “seeing a success” rather than to the payment: the code credits every time it observes success, when it should credit once per payment however often success is observed.
Second, nothing guards the state change. UPDATE payments SET status = 'SUCCESS' succeeds even if the status is already SUCCESS, so nothing in the database says “this already happened”. And third, several paths apply the same outcome (confirm, webhook, maybe a cron job) without knowing about each other.
The fix: make the state change the guard
Credit the wallet only if this request is the one that moved the payment into SUCCESS. The database can tell us whether it was. A conditional update, UPDATE … WHERE status IN ('PENDING', 'PROCESSING'), changes the row only while the payment is still waiting, so when two requests race, only one can make the change; the other finds the row already in SUCCESS and changes nothing.
PostgreSQL's RETURNING clause gives back values “based on each row actually updated” (PostgreSQL: UPDATE). A row back means we won and should credit. No row means someone else got there first, and we leave the wallet alone.
@app.post("/payments/{payment_id}/confirm")
def confirm_payment(payment_id: str):
payment = load_payment(payment_id) # plain read, no transaction held open
if payment.status not in ("PENDING", "PROCESSING"):
return {"status": payment.status} # already decided: answer from our records
result = payco.get_payment(payment.provider_payment_id) # network call, outside any transaction
if result.status != "succeeded":
return {"status": payment.status}
if (result.amount_minor, result.currency) != (payment.amount_minor, payment.currency):
raise HTTPException(status_code=409, detail="amount mismatch, flagged for review")
with pool.connection() as conn, conn.transaction():
row = conn.execute(
"""
UPDATE payments
SET status = 'SUCCESS', updated_at = now()
WHERE id = %s AND status IN ('PENDING', 'PROCESSING')
RETURNING wallet_id, amount_minor
""",
(payment_id,),
).fetchone()
if row is not None: # this request moved it to SUCCESS: credit once
wallet_id, amount_minor = row
conn.execute(
"UPDATE wallets SET balance_minor = balance_minor + %s WHERE id = %s",
(amount_minor, wallet_id),
)
return {"status": load_payment(payment_id).status}Some details in there are deliberate:
- The status update and the credit are in one transaction. Either both happen or neither does. psycopg's
conn.transaction()block commits when it exits normally and rolls back if an exception escapes it (psycopg: transactions). - The call to PayCo happens before the transaction opens, never inside it. A transaction that waits on a slow network call holds database locks and a connection the whole time. Chapter 13 covers this in depth.
- We check the amount and currency the provider reports against what we expected. If they differ, we don't guess; we stop and flag it. This is “never blindly trust any component” applied to the provider.
- Amounts are integers in minor units (cents), never floats. Chapter 3 explains why.
The webhook handler needs the same guard. The simplest way to guarantee that is one function that applies a success, called from every path that learns about one. In Go with pgx, it looks like this:
var ErrAmountMismatch = errors.New("provider amount does not match payment")
// ApplySuccess moves a payment to SUCCESS and credits the wallet, at most once.
// The confirm endpoint, the webhook consumer and reconciliation all call this.
func ApplySuccess(ctx context.Context, pool *pgxpool.Pool, paymentID string, gotAmountMinor int64, gotCurrency string) error {
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
var walletID, currency string
var amountMinor int64
err := tx.QueryRow(ctx, `
UPDATE payments
SET status = 'SUCCESS', updated_at = now()
WHERE id = $1 AND status IN ('PENDING', 'PROCESSING')
RETURNING wallet_id, amount_minor, currency`, paymentID).
Scan(&walletID, &amountMinor, ¤cy)
if errors.Is(err, pgx.ErrNoRows) {
// Already SUCCESS, or in a state where success can't be applied
// automatically. Either way: no second credit. Chapter 2 tells these apart.
return nil
}
if err != nil {
return err
}
if amountMinor != gotAmountMinor || currency != gotCurrency {
return ErrAmountMismatch // returning an error rolls back the status change too
}
_, err = tx.Exec(ctx,
`UPDATE wallets SET balance_minor = balance_minor + $1 WHERE id = $2`,
amountMinor, walletID)
return err
})
}pgx.BeginFunc starts a transaction, runs the function, and commits if it returns nil or rolls back if it returns an error (pgx v5 docs). That makes the transaction boundary easy to see: everything inside the function is atomic, and nothing outside it is.
Two more protections complete the picture. Both get their own chapters later.
- Idempotency keys on the way in. When the app creates a payment, it sends a unique key (for example a UUID it generated). If the create request is retried, we return the existing payment instead of creating a new one. Providers do the same on their side: Stripe compares the parameters of a retried request with the original and returns an error if they differ (Stripe: idempotent requests). Chapter 6 covers how to choose and store these keys.
- A unique constraint on the provider's payment ID, so the same provider payment can never be attached to two of our payments.
What to monitor
- Payments stuck in PENDING or PROCESSING, by age. A payment that has been “unknown” for an hour needs a person or a job to look at it.
- How often the guard fires: confirm calls and webhooks that found the payment already decided. A sudden jump usually means a client retry loop or a provider redelivering events.
- Amount mismatches. There should be close to none, and each one is worth investigating.
- Timeouts to the provider, as a rate. They are the main source of “unknown” payments.
What to test
- Call confirm twice for the same payment, one after the other. Expect exactly one credit.
- Call confirm twice at the same time (two goroutines or threads). Expect exactly one credit.
- Deliver the same success webhook ten times. Expect exactly one credit.
- Make the provider respond after your client's timeout. Expect the payment to end up in
SUCCESSwith one credit, not two, and not a failure. - Return a different amount from the fake provider. Expect no credit and a flagged payment.
Checklist
- A timeout is treated as “unknown”, never as success or failure.
- Every path that learns about a success calls the same function.
- The credit happens in the same database transaction as the status change.
- The status change is conditional, so only one caller can win.
- Network calls to providers happen outside database transactions.
- Provider-reported amounts and currencies are checked against our own records.
- Webhooks are expected to be duplicated, reordered, late or missing.
Chapter 2
Designing a payment lifecycle
Chapter 1 ended with a status column doing real work: WHERE status IN ('PENDING', 'PROCESSING') was the thing that stopped a double credit. This chapter designs that column on purpose: which states a payment can be in, which moves between them are allowed, and what happens when something tries a move that isn't.
Why a few booleans are not enough
A lot of payment tables start like this: is_paid, is_credited, is_refunded, is_failed. Four booleans give you sixteen combinations, and most of them make no sense. What does is_paid = true, is_failed = true mean? What about refunded but never paid?
Each of these combinations will show up in production eventually, usually because two pieces of code updated different flags at the same time, and then someone has to work out by hand what happened.
A single status column with a fixed set of values, and a fixed set of allowed moves between them, rules those combinations out. That's all a state machine is: a list of states, plus rules for moving between them.
The states
| State | What it means | Terminal? |
|---|---|---|
| CREATED | We recorded the customer's request. Nothing has been sent to a provider yet. | No |
| PENDING | Sent to the provider, waiting on the customer or the provider to act (approve in their bank app, finish 3-D Secure). | No |
| PROCESSING | The provider has it and is working on it, or we lost track (a timeout) and are finding out. | No |
| SUCCESS | The provider confirmed the money was taken, and we applied it (credited the wallet, marked the order). | For this flow, yes, but see below |
| FAILED | The provider declined or errored, and no money was taken. | Yes |
| CANCELLED | Stopped before any money moved: the customer abandoned it, or it expired. | Yes |
| REFUNDED | Money was sent back to the customer through the provider. | Yes |
| REVERSED | We undid a successful payment internally, with a compensating ledger entry. | Yes |
A terminal state is one that nothing can move out of. SUCCESS is a slightly special case: the payment flow is finished, but the payment can still be refunded or reversed later. Those later moves are new operations with their own records (a refund has its own lifecycle with the provider), and they point back to the original payment. They don't rewrite it.
Three words that people often use interchangeably mean different things here:
- Cancellation happens before money moves. Nothing needs to be undone.
- Refund happens after money moved, and sends money back to the customer through the provider. It is a new money movement.
- Reversal undoes a successful payment in our books, for example because we credited the wrong wallet. It writes a new, opposite ledger entry rather than deleting the old one. Chapter 4 covers this in detail.
The allowed moves
| From | Allowed to | Typical trigger |
|---|---|---|
| CREATED | PENDING, CANCELLED | Sent to provider; customer abandons before we send |
| PENDING | PROCESSING, SUCCESS, FAILED, CANCELLED | Provider events; expiry |
| PROCESSING | SUCCESS, FAILED | Provider event, status check or reconciliation |
| SUCCESS | REFUNDED, REVERSED | Refund completes; internal reversal |
| FAILED | none | Terminal |
| CANCELLED | none | Terminal |
| REFUNDED | none | Terminal |
| REVERSED | none | Terminal |
PENDING → SUCCESS is allowed on purpose. Webhooks arrive out of order, so we may hear “succeeded” before we ever hear “processing”, and the state machine has to accept the real world rather than an idealised version of it.
The arrows that aren't there do most of the protecting. Nothing leaves FAILED, and nothing goes backwards from SUCCESS to PROCESSING.
Why every transition must be checked
Imagine a status column with no rules, where every event handler just writes the status it was given. Two ordinary things break it.
Out-of-order events. PayCo sends “processing” and then “succeeded”, but they arrive the other way round. Without rules, the payment ends up in PROCESSING even though it succeeded. It now looks stuck, someone may retry it, and the customer may be charged again.
Late success after failure. We call PayCo, it times out, and after a while we give up and mark the payment FAILED. The customer sees “payment failed” and pays again with another card. An hour later a webhook arrives: the first payment had succeeded after all.
If we write SUCCESS, we credit a payment the customer believes failed, on top of the one they made after it. If we ignore the event, we keep the customer's money with nothing recorded against it.
Other illegal moves are harmless. A processing event that arrives after SUCCESS is stale news; ignore it, but log it.
Payouts have their own lifecycle
Money going out, to a customer's bank account for a withdrawal, has its own flow and its own states. The part to watch is in the middle:
PAYOUT_INITIATED, PAYOUT_ACKNOWLEDGED, SETTLED and PAYOUT_FAILED. A payout can be accepted by the provider and still bounce back from the receiving bank later, so SETTLED waits for real confirmation.PAYOUT_ACKNOWLEDGED means the provider accepted our instruction. It does not mean the money arrived. Bank transfers can be returned days later, for example because the account was closed or the name didn't match. That is why SETTLED is a separate state, set only when we have real confirmation such as a settlement report or a bank statement line. Treating “acknowledged” as “paid” is a common and expensive shortcut.
Reconciliation is not a state in either lifecycle. It is a separate check that runs alongside them and records its own result (“matched on 24 Nov”, “amount differs”). Keeping it out of the status column means a reconciliation problem never has to fight with the payment flow over one field.
Request, execution and posting are three different things
One last modelling decision saves a lot of pain later. Three things often get crammed into one table, and they shouldn't be:
- The payment request: what the customer asked for. Amount, currency, their idempotency key, and the price or exchange rate we quoted. It exists once.
- The attempts: each try with a provider. If the first card is declined and the customer tries another, that is one request with two attempts, each with its own provider reference and status.
- The postings: the ledger entries that record money moving. They exist only for attempts that succeeded.
Splitting them means a declined attempt never leaves half-written money records behind, and a retried attempt never overwrites the evidence of the first one. When finance asks “what happened to this payment?”, the answer is a list of facts rather than one row that has been overwritten five times.
Implementing the state machine in PostgreSQL
We enforce the rules in two places: the database makes sure only known states can be stored, and every status change is a conditional update that only succeeds from the state we expected. The schema below is simplified (one attempt per payment, to keep the examples short), but the ideas carry over.
CREATE TABLE payments (
id text PRIMARY KEY, -- e.g. 'pay_81', generated by us
customer_id text NOT NULL,
wallet_id text NOT NULL,
idempotency_key text NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor > 0),
currency text NOT NULL,
provider text,
provider_payment_id text,
status text NOT NULL DEFAULT 'CREATED'
CHECK (status IN ('CREATED', 'PENDING', 'PROCESSING', 'SUCCESS',
'FAILED', 'CANCELLED', 'REFUNDED', 'REVERSED')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (customer_id, idempotency_key),
UNIQUE (provider, provider_payment_id)
);
-- Every status change is recorded, so we can always explain how a payment got here.
CREATE TABLE payment_status_history (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payment_id text NOT NULL REFERENCES payments (id),
from_status text NOT NULL,
to_status text NOT NULL,
reason text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Events that tried to make an illegal move, kept for a person or a job to resolve.
CREATE TABLE payment_anomalies (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payment_id text NOT NULL REFERENCES payments (id),
kind text NOT NULL,
detail text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
resolved_at timestamptz,
UNIQUE (payment_id, kind)
);The CHECK constraint means a typo like 'SUCCES' is rejected by the database, not discovered in a report three months later (PostgreSQL: constraints). The two UNIQUE constraints stop the same idempotency key creating two payments, and the same provider payment being attached to two of ours. PostgreSQL treats NULLs as distinct by default, so payments that don't have a provider ID yet don't clash.
A status change is then always a conditional update: change the status only if it is still what we think it is.
UPDATE payments
SET status = 'SUCCESS', updated_at = now()
WHERE id = 'pay_81'
AND status = 'PROCESSING';
-- PostgreSQL reports "UPDATE 1" if we made the move, "UPDATE 0" if the status had already changed.PostgreSQL's command tag reports how many rows the UPDATE changed (PostgreSQL: UPDATE). Zero rows means someone else changed the status first, so our view was stale. This pattern is called compare-and-swap: compare the current value with what you expect, and swap in the new value only if they match. Chapter 7 covers it in depth.
If several services write to the same table, you can also put the transition rules themselves in the database, so no writer can skip them:
CREATE TABLE payment_transitions (
from_status text NOT NULL,
to_status text NOT NULL,
PRIMARY KEY (from_status, to_status)
);
INSERT INTO payment_transitions (from_status, to_status) VALUES
('CREATED', 'PENDING'), ('CREATED', 'CANCELLED'),
('PENDING', 'PROCESSING'), ('PENDING', 'SUCCESS'), ('PENDING', 'FAILED'), ('PENDING', 'CANCELLED'),
('PROCESSING', 'SUCCESS'), ('PROCESSING', 'FAILED'),
('SUCCESS', 'REFUNDED'), ('SUCCESS', 'REVERSED');
-- $1 = payment id, $2 = expected current status, $3 = new status
UPDATE payments p
SET status = $3, updated_at = now()
WHERE p.id = $1
AND p.status = $2
AND EXISTS (SELECT 1 FROM payment_transitions t
WHERE t.from_status = $2 AND t.to_status = $3);The same rules in Go
In application code, the rules live in one map, and every status change goes through one function. The function checks the move is legal, makes the conditional update, and writes the history row, all inside the caller's transaction.
type Status string
const (
Created Status = "CREATED"
Pending Status = "PENDING"
Processing Status = "PROCESSING"
Success Status = "SUCCESS"
Failed Status = "FAILED"
Cancelled Status = "CANCELLED"
Refunded Status = "REFUNDED"
Reversed Status = "REVERSED"
)
// transitions is the state machine: the moves we allow, and nothing else.
// Failed, Cancelled, Refunded and Reversed are terminal, so they have no entry.
var transitions = map[Status][]Status{
Created: {Pending, Cancelled},
Pending: {Processing, Success, Failed, Cancelled},
Processing: {Success, Failed},
Success: {Refunded, Reversed},
}
var (
ErrIllegalTransition = errors.New("illegal status transition")
ErrStaleStatus = errors.New("status changed concurrently")
)
func CanTransition(from, to Status) bool {
return slices.Contains(transitions[from], to)
}
// Transition moves a payment from one status to another inside tx.
// It fails if the move is illegal, or if the payment is no longer in from.
func Transition(ctx context.Context, tx pgx.Tx, paymentID string, from, to Status, reason string) error {
if !CanTransition(from, to) {
return fmt.Errorf("%w: %s -> %s", ErrIllegalTransition, from, to)
}
tag, err := tx.Exec(ctx,
`UPDATE payments SET status = $1, updated_at = now() WHERE id = $2 AND status = $3`,
to, paymentID, from)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrStaleStatus
}
_, err = tx.Exec(ctx,
`INSERT INTO payment_status_history (payment_id, from_status, to_status, reason)
VALUES ($1, $2, $3, $4)`,
paymentID, from, to, reason)
return err
}Now the handler for a provider event. It locks the payment row, compares what the provider says with what we have, and decides between four outcomes: duplicate, legal move, dangerous late success, or harmless stale event.
// ApplyProviderStatus records what the provider told us, if it is a legal move.
func ApplyProviderStatus(ctx context.Context, pool *pgxpool.Pool, paymentID string, reported Status) error {
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
var current Status
err := tx.QueryRow(ctx,
`SELECT status FROM payments WHERE id = $1 FOR UPDATE`, paymentID).Scan(¤t)
if err != nil {
return err // includes pgx.ErrNoRows: an event for a payment we don't know
}
switch {
case current == reported:
return nil // duplicate delivery: nothing to do
case CanTransition(current, reported):
if err := Transition(ctx, tx, paymentID, current, reported, "provider_event"); err != nil {
return err
}
if reported == Success {
return creditWallet(ctx, tx, paymentID) // same transaction as the status change
}
return nil
case current == Failed && reported == Success:
// Money may have moved after we gave up. Don't apply it, don't drop it.
_, err := tx.Exec(ctx, `
INSERT INTO payment_anomalies (payment_id, kind, detail)
VALUES ($1, 'LATE_SUCCESS', 'provider reported SUCCESS after we marked FAILED')
ON CONFLICT (payment_id, kind) DO NOTHING`, paymentID)
return err
default:
return nil // stale event, e.g. PROCESSING after SUCCESS: log it and move on
}
})
}The SELECT … FOR UPDATE locks the payment row until the transaction ends, so two events for the same payment are handled one after the other instead of interleaving.
Inside that lock, the conditional update in Transition can't lose a race. I keep it anyway, because other code paths (an admin tool, a reconciliation job) might change the status without taking the lock, and the database guard covers those too. creditWallet is the same credit as in ApplySuccess from Chapter 1, written to run inside an existing transaction.
Trade-offs and alternatives
- Rules in code, rules in the database, or both. Rules in a Go map are easy to read and test. Rules in a table, or a trigger, also protect you from scripts and other services. For a payment table, I'd keep the map as the readable source and add the database check once more than one service writes to it.
- Locking first vs compare-and-swap only.
FOR UPDATEmakes concurrent events wait in line, which is simple to reason about. A plain conditional update with no lock is cheaper and fine when there's little contention. Chapter 7 compares them properly. - How many states. Real systems often need a few more, like
PARTIALLY_REFUNDEDorREQUIRES_ACTION. Add them when a real flow needs them, and update the diagram, the table and the map together. - Workflow engines. Tools like Temporal or AWS Step Functions can run the steps of a long payment flow for you. They don't replace the payment state in your own database, which is what finance, support and reconciliation read. Chapter 12 covers when they are worth it.
Common mistakes
- Writing the status straight from the provider's event without checking the current status.
- Treating “provider acknowledged” as “paid” for payouts.
- Deleting or overwriting a failed attempt when the customer retries, instead of creating a new attempt.
- Letting a late
SUCCESSoverwriteFAILED, or ignoring it without a record. - Putting reconciliation results in the same status column as the payment flow.
- Having no history table, so nobody can explain how a payment reached its current state.
What to monitor and test
Monitor: the number of payments in each non-terminal state and the age of the oldest; the rate of ErrStaleStatus and of illegal-transition attempts, broken down by from/to; and every new row in payment_anomalies, which should page someone during working hours.
Test: deliver every event type in every order; deliver each event twice; deliver SUCCESS to a FAILED payment and expect exactly one anomaly and no credit; run two transitions on one payment concurrently and expect exactly one to win; and check, in a test, that the Go map and the payment_transitions rows contain the same pairs.
Checklist
- Payment status is one column with a
CHECKconstraint, not a set of booleans. - Allowed transitions are written down once, and the diagram, table and code match.
- Every status change is conditional on the current status.
- Every status change writes a history row in the same transaction.
- Terminal states have no way out.
- Illegal transitions that might mean money moved are recorded as anomalies and alerted on.
- Payouts are only SETTLED on real confirmation, not on acknowledgement.
- Requests, attempts and postings are separate records.
Further reading
- Stripe: place a hold on a payment method: authorisation and capture, and how long an authorisation lasts.
- Stripe: webhooks: duplicate delivery, event ordering and responding quickly.
- Stripe: idempotent requests: how a large provider implements idempotency keys.
- PostgreSQL: UPDATE:
RETURNINGand the command tag. - PostgreSQL: constraints:
CHECKandUNIQUE. - pgx v5:
BeginFuncand transactions in Go.
What's next
We now know what a payment is and how to say where it is in its life. But we have been crediting a balance_minor column and waving our hands about “ledger postings”. Part II, Financial Data Correctness, fixes that: how to represent money without rounding bugs, how to build an immutable ledger where every balance can be explained, and how to enforce the rules that must never break.
If this was useful
Pass it on to someone who's building or fixing a payment system, or share it with your network. The handbook is free, and people passing it on is how it reaches the engineers it was written for.