Walkthrough: Refund API from Requirement to Production
- Turn a vague ticket into a testable spec by letting the agent interrogate it
- Decide, as the human, how to prevent over-refunds under concurrency, and record why in an ADR
- Pin money invariants in tests before any code exists, then freeze them
- Drive an agent task by task, respond when a guardrail blocks it, and ship with evidence
TL;DR
- A two-sentence ticket becomes a spec answering ten questions the ticket never asked. The agent asks; PM, support and finance answer.
- Over-refund under concurrency goes in an ADR: the agent drafts three options, the human picks a payment row lock with a
CHECKbackstop. - Tests first: table-driven validation, 50 concurrent partial refunds exceeding the captured amount, a ledger-balanced invariant. Approved, then
touch .claude/tests.lock. - Seven one-commit tasks; hooks block the agent twice, rightly both times.
/review-difffinds a blocker (PSP amount ignored VND's zero exponent) that tests missed because the fake shared the bug.- A week after launch, reconciliation finds a mismatch; the fix becomes a test and a line in
AGENTS.md.
Why it matters
Refunds look like "payments in reverse" but combine the hardest parts: partial amounts, concurrency on one balance, an asynchronous PSP, ledger entries and reconciliation. Their bugs stay silent until finance finds them. The agent writes most of the code; the human makes sure the right code gets written, and proves it. The setup is templates/ai-workflow/ (Setting Up a Repo for AI Agents); the service is the capstone's payment service (12-Month Roadmap).
Core concepts
The flow at a glance
Stage 1 — Interrogate the ticket
/write-spec PAY-412 "Customers should be able to get refunds for orders, including partial refunds. Support needs it by end of month."
The agent reads AGENTS.md, the spec template and internal/payment/, then replies without writing files. It restates the problem (support cannot refund without finance working by hand in the PSP dashboard), asks ten questions with proposed defaults, and lists edge cases: duplicate clicks, concurrent partials, PSP timeouts, out-of-order webhooks, the 23:00 cut-off. A 30-minute call with the PM, support lead and finance ops produced the answers.
| # | Question (agent) | Proposed default (agent) | Decision (humans) |
|---|---|---|---|
| 1 | Several partial refunds per payment? | Yes, until the captured amount is used | Yes; PENDING refunds count against the cap |
| 2 | Refund destination? | Original payment method | Original method only; store credit is a later spec |
| 3 | Refund window? | 180 days | 90 days from capture (finance policy) |
| 4 | Who can initiate? | Support agents and the Order service | Both; above 10,000,000 VND returns 422 approval_required until maker-checker ships |
| 5 | PSP behaviour? | Async: request returns pending, webhook decides | Yes; webhooks can repeat or arrive out of order; poll anything PENDING over 30 min |
| 6 | Currencies? | VND only, exponent 0 | VND only in v1; anything else is 422 |
| 7 | PSP refund fails? | Mark FAILED, release the amount, alert support | Agreed |
| 8 | Idempotency? | Idempotency-Key via platform/idempotency | Yes; the refund ID is also the PSP idempotency key |
| 9 | Ledger entries? | Reserve on request, settle on success, reverse on failure | Yes; finance named the accounts |
| 10 | Notifications and reconciliation? | Email on SUCCEEDED via outbox; daily match on PSP reference | Yes; recon breaks go to finance ops |
Under "decisions I will not make" the agent listed the over-refund concurrency strategy, which went to an ADR. Remember row 7; it returns in stage 10.
Stage 2 — The spec
The agent writes docs/specs/0007-refunds.md; the human edits it for an hour. Excerpts:
Scenario: Over-refund attempt
Given payment "pay_1" captured 1,000,000 VND with 600,000 VND already refunded
When a refund of 400,001 VND is requested
Then the response is 422 amount_exceeds_refundable
And no refund row, ledger entry or event is created
Scenario: Concurrent partial refunds that together exceed the captured amount
Given payment "pay_1" captured 1,000,000 VND
When 50 refunds of 30,000 VND are requested at the same time with distinct keys
Then exactly 33 succeed and 17 are rejected with amount_exceeds_refundable
And PENDING + SUCCEEDED refunds never exceed 1,000,000 VND
Scenario: Concurrent duplicate with the same Idempotency-Key
Given a refund request with key "k1" is still being processed
When the same request with key "k1" arrives
Then the response is 409 idempotency_in_progress with Retry-After
And at most one refund exists for "k1"
POST /v1/payments/pay_01JB7Q/refunds
Idempotency-Key: 4f9c2a6e-1b7d-4c1e-9a53-2f0d8e6b7c11
Content-Type: application/json
{"amount": 400000, "currency": "VND", "reason": "item_returned"}
HTTP/1.1 201 Created
{"id": "rf_01JB8K", "payment_id": "pay_01JB7Q", "amount": 400000, "currency": "VND",
"status": "PENDING", "refundable_remaining": 600000}
| Status | Code | When |
|---|---|---|
| 201 | — | Accepted as PENDING. A retry with the same key and body replays this response |
| 409 | idempotency_in_progress | Same key still in flight |
| 409 | payment_not_refundable | Payment not CAPTURED or SETTLED (void it instead) |
| 422 | amount_exceeds_refundable | Amount greater than captured minus PENDING and SUCCEEDED refunds |
| 422 | idempotency_key_reused | Same key, different body |
| 422 | invalid_amount, refund_window_expired, approval_required | Validation and policy failures |
For POST /v1/payments/{id}/refunds, merchant scope comes from the authenticated principal, never the body. Data: a refunds table (id, payment_id, merchant_id, amount BIGINT, currency, status, reason, unique psp_refund_ref, requested_by, timestamps) and payments.refunded_amount (PENDING + SUCCEEDED), its constraint added NOT VALID to avoid a table scan under an exclusive lock (Zero-Downtime Schema Migrations):
ALTER TABLE payments ADD COLUMN refunded_amount BIGINT NOT NULL DEFAULT 0;
ALTER TABLE payments ADD CONSTRAINT payments_refunded_le_captured
CHECK (refunded_amount >= 0 AND refunded_amount <= captured_amount) NOT VALID;
-- a later migration runs VALIDATE CONSTRAINT off-peak
| NFR | Requirement |
|---|---|
| Latency | p99 under 300 ms for POST at 50 RPS (PSP call is async) |
| Consistency | Refunds never exceed the captured amount, under any concurrency |
| Audit | Who, when, why, caller, key; retained per finance policy |
| Security | Roles refund:create or the Order service token; no customer names in logs |
| Observability | Failure rate, PSP webhook lag, ledger imbalance alert |
Stage 3 — ADR: preventing over-refund
Prompt: "Draft ADR 0011 from docs/adr/TEMPLATE.md: options to prevent refunds exceeding the captured amount under concurrent requests. Postgres READ COMMITTED, the ledger is in the same database. Do not choose."
| Option | Pros | Cons | Cost / risk |
|---|---|---|---|
A. SELECT … FOR UPDATE on the payment row, then check and reserve in one transaction | Simple, obviously correct, matches CaptureTx | Serialises refunds per payment | Low: refunds per payment are rare, so contention is negligible |
B. Optimistic version check, retry on conflict | No waiting on locks | Retry loop in every caller; under bursts most attempts retry | Medium: more code paths to test |
| C. A refundable-balance ledger account per payment, with non-negative balance enforcement | Strongest audit; reuses ledger invariants | One account per payment; couples refunds to ledger locking; touches internal/ledger/ | High for v1 |
Decision (human): A, plus the CHECK constraint as a backstop; if the backstop fires, that is a bug and a page (500), never a 422. Contention is per payment, so the lock is cheap; B adds retries for no benefit; C changes the ledger, a separate risk. The PSP is called after commit by the outbox worker, so no lock is held across network I/O. Revisit if refunds become their own service. See Locking & Concurrency Control.
Stage 4 — Plan
/write-plan docs/specs/0007-refunds.md
- [ ] **T1 — contract + failing tests** · risk: high (money)
- Files: internal/refund/domain_test.go, service_integration_test.go, http_test.go
- Verify: `go test ./internal/refund/...` → fails: undefined: refund.Payment
- [ ] **T2 — domain: Payment.Reserve, Refund state machine** · risk: high
- Verify: `go test ./internal/refund/ -run TestPayment -race` → passes
- [ ] **T3 — migration 0012 + postgres repo (LockPayment FOR UPDATE)** · risk: high (migration)
- Verify: `make test-int` → passes; down migration applies on a prod-schema copy
- [ ] **T4 — service.Create: lock, reserve, insert, ledger reservation, outbox** · risk: high
- [ ] **T5 — PSP adapter + worker + webhook handler (dupes, out of order)** · risk: high
- [ ] **T6 — HTTP handler, idempotency, authz, flag refunds_api** · risk: high (public API)
- [ ] **T7 — metrics, alerts, runbook, spec status** · risk: low
Out of scope: maker-checker, store credit, non-VND currencies.
Rollback: flag off; PENDING refunds still settle via webhooks; never delete rows.
The human adds one note for the agent: "Copy CaptureTx in internal/payment/service.go. Do not touch internal/ledger/; use ledger.Poster."
Stage 5 — Tests first
The agent drafts T1; the human rewrites half. The concurrency test and invariant helper define "correct", so a human owns them.
func TestPayment_Reserve(t *testing.T) {
t.Parallel()
const day = 24 * time.Hour
now := time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC)
tests := []struct {
name string
refunded int64
amount int64
currency string
age time.Duration
wantErr error
}{
{"full refund", 0, 1_000_000, "VND", day, nil},
{"second partial up to the cap", 600_000, 400_000, "VND", day, nil},
{"over-refund by one dong", 600_000, 400_001, "VND", day, refund.ErrExceedsRefundable},
{"already fully refunded", 1_000_000, 1, "VND", day, refund.ErrExceedsRefundable},
{"zero amount", 0, 0, "VND", day, refund.ErrInvalidAmount},
{"wrong currency", 0, 100, "USD", day, refund.ErrCurrencyMismatch},
{"outside 90-day window", 0, 100, "VND", 91 * day, refund.ErrWindowExpired},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
p := refund.Payment{
ID: "pay_1", Status: "CAPTURED", Currency: "VND",
Captured: 1_000_000, Refunded: tt.refunded, CapturedAt: now.Add(-tt.age),
}
err := p.Reserve(tt.amount, tt.currency, now)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("Reserve(%d, %s) error = %v, want %v", tt.amount, tt.currency, err, tt.wantErr)
}
if err != nil && p.Refunded != tt.refunded {
t.Errorf("Refunded changed on error: %d -> %d", tt.refunded, p.Refunded)
}
})
}
}
The concurrency test runs against real Postgres (testcontainers, build tag integration). It asserts safety (never over-refund) and liveness (exactly 33 succeed, so no request fails spuriously):
func TestService_ConcurrentPartialRefundsNeverExceedCaptured(t *testing.T) {
ctx := context.Background()
db := newTestDB(t) // Postgres via testcontainers, migrations applied
svc := newService(t, db)
pay := seedCapturedPayment(t, db, 1_000_000) // VND
const workers = 50
const each = int64(30_000) // 50 x 30,000 = 1,500,000 > 1,000,000
var (
wg sync.WaitGroup
succeeded atomic.Int64
total atomic.Int64
start = make(chan struct{})
unexpected = make(chan error, workers)
)
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
<-start // release all goroutines at once
_, err := svc.Create(ctx, refund.CreateRequest{
PaymentID: pay.ID, MerchantID: pay.MerchantID,
Amount: each, Currency: "VND", Reason: "test", RequestedBy: "test",
})
switch {
case err == nil:
succeeded.Add(1)
total.Add(each)
case errors.Is(err, refund.ErrExceedsRefundable):
// expected once the cap is reached
default:
unexpected <- err
}
}()
}
close(start)
wg.Wait()
close(unexpected)
for err := range unexpected {
t.Errorf("unexpected error: %v", err)
}
if got := total.Load(); got > pay.Captured {
t.Fatalf("refunded %d VND, captured only %d", got, pay.Captured)
}
if got, want := succeeded.Load(), pay.Captured/each; got != want {
t.Errorf("succeeded = %d, want %d", got, want)
}
if got := refundedAmount(t, db, pay.ID); got != total.Load() {
t.Errorf("payments.refunded_amount = %d, sum of refunds = %d", got, total.Load())
}
assertLedgerBalanced(t, db)
}
assertLedgerBalanced runs at the end of every integration test. It asserts that no entry is unbalanced (GROUP BY entry_id, currency HAVING sum(amount) <> 0 returns no rows) and that the refunds_in_transit:VND balance equals the sum of PENDING refunds. The human checks each test against the spec scenarios, runs them (all fail), then:
touch .claude/tests.lock # *_test.go is now read-only for the agent
Stage 6 — Implement, one task per commit
A typical task prompt:
Implement T4 from docs/plans/0007-refunds.md, following ADR 0011. Tests are frozen.
One transaction: reserve on the payment, insert the refund, set refunded_amount, post the
reservation via ledger.Poster, enqueue the outbox event. Copy the transaction pattern from
CaptureTx in internal/payment/service.go.
Run `go test ./internal/refund/... -race` and `make test-int`, show the output, then stop.
First block. On T3 the agent tried to add the column by editing migrations/0009_create_payments.up.sql, already applied in production. protect-paths.sh refused ("…is already on main (applied migrations are immutable)…"), and the agent wrote a new 0012_create_refunds up/down pair instead.
Second block. The first T4 copied CaptureTx faithfully, but capture never needed a lock: it read the refunded sum with a plain SELECT, then incremented refunded_amount. The prompt said "follow ADR 0011" without restating the lock. The frozen test caught what the prompt left implicit:
--- FAIL: TestService_ConcurrentPartialRefundsNeverExceedCaptured
service_integration_test.go:61: unexpected error: update refunded amount: ERROR: new row for
relation "payments" violates check constraint "payments_refunded_le_captured" (SQLSTATE 23514)
... (more of the same)
The CHECK backstop had stopped a real over-refund race. The agent tried to edit the test to accept SQLSTATE 23514, the hook blocked it ("tests are frozen for this task…"), and the agent asked:
The hook blocked my test edit. The failures are check-constraint violations: I read the
refunded sum without a lock, so concurrent requests pass the check on stale data.
Options: (a) map 23514 to ErrExceedsRefundable; (b) lock the payment row first, per ADR 0011.
I recommend (b): (a) hides the race behind the constraint. Proceed?
The human answered: "(b), and map 23514 to a 500 plus an alert, never a 422." The resulting core:
err := s.store.InTx(ctx, func(tx Tx) error {
p, err := tx.LockPayment(ctx, req.MerchantID, req.PaymentID) // SELECT ... FOR UPDATE
if err != nil {
return fmt.Errorf("lock payment: %w", err)
}
if err := p.Reserve(req.Amount, req.Currency, s.clock.Now()); err != nil {
return err
}
r := newPending(s.ids.New("rf"), p, req)
if err := tx.InsertRefund(ctx, r); err != nil {
return fmt.Errorf("insert refund: %w", err)
}
if err := tx.SetRefunded(ctx, p.ID, p.Refunded); err != nil {
return fmt.Errorf("update refunded amount: %w", err)
}
if err := s.ledger.Post(ctx, tx, reservationEntry(r)); err != nil {
return fmt.Errorf("post reservation: %w", err)
}
return tx.EnqueueOutbox(ctx, requestedEvent(r)) // PSP is called after commit
})
Neither block needed the human to notice anything; each needed a decision.
Stage 7 — Verify
make check # gofmt, vet, staticcheck, unit tests -race
make test-int # testcontainers Postgres + Kafka
go test -tags=integration -race -count=20 \
-run TestService_ConcurrentPartialRefundsNeverExceedCaptured ./internal/refund/
One green run of a concurrency test proves little, hence -count=20. Then test the test: delete FOR UPDATE locally, watch it fail, restore. A concurrency test that cannot fail is decoration.
Stage 8 — Review
/review-diff output (excerpt):
internal/psp/refund.go:41 — blocker — amount sent as strconv.FormatFloat(float64(r.Amount)/100, 'f', 2, 64):
float64 and a hard-coded exponent of 2; VND has exponent 0, so a 400,000 VND refund is sent as "4000.00"
— use psp.FormatAmount(r.Amount, r.Currency) as Capture does
internal/refund/http.go:88 — minor — 422 amount_exceeds_refundable omits refundable_remaining (spec §5)
Commands run: make check → PASS
Tests missed it because the fake PSP in psptest parsed amounts with the same wrong assumption. The human removed tests.lock, added a table test for psp.FormatAmount (VND 400000 → "400000", USD 1999 → "19.99") and a contract test against a recorded PSP sandbox response, then re-locked. A fake that shares code with production cannot catch that code's bugs.
Human review covered what tools cannot judge: the transaction boundary, ledger accounts and signs (with finance), the webhook state machine (out of order, duplicates, FAILED after SUCCEEDED alerts), authz scope, and logs. It shipped as three stacked PRs of ≈ 250 changed lines each plus tests. From the PR template:
## Risk tier
- [x] High — money movement, ledger, auth, migrations, public API/event contracts (CODEOWNERS review required)
## How I verified it
make check → ok
make test-int → ok
-race -count=20 on the concurrency test → ok; without FOR UPDATE it fails (constraint violations)
## AI assistance
- Tools used: Claude Code (spec draft, ADR options, plan, T2–T7, /review-diff)
- What the AI produced: first drafts of everything; I rewrote the concurrency test, the ledger
invariant and the PSP amount formatting
- What I reviewed line by line: internal/refund, internal/psp/refund.go, migrations/0012*
- [x] I can explain every line in this diff without the AI's help
Stage 9 — CI gates and rollout
CI (dot-github/workflows/ci.yml) runs gofmt, vet, staticcheck, govulncheck, tidy, -race tests, gitleaks and integration tests; branch protection requires them plus CODEOWNERS. Rollout behind the refunds_api flag:
- Deploy flag off; migration 0012 first,
VALIDATE CONSTRAINToff-peak. - Internal only for three days: support refunds their own test orders on the real PSP.
- Canary by merchant: one, 10%, 100%. Never during a sale event.
| Signal | Alert |
|---|---|
| Refund failure rate (FAILED / requested, 15 min) | Above a few percent: ticket to on-call (threshold illustrative) |
| PSP webhook lag (age of oldest PENDING) | Over 30 min: poller and warning; over 2 h: page |
Ledger imbalance or refunds_in_transit ≠ sum of PENDING | Page immediately |
SQLSTATE 23514 on payments_refunded_le_captured | Page: the lock is broken |
Stage 10 — Operate and learn
On day 8 the daily reconciliation job flagged a break: the PSP report had refund rf_01JC2M (250,000 VND) as SUCCEEDED, while MiniPay had it FAILED with the reservation reversed. In a PSP latency spike all three worker attempts timed out, and the code treated "retries exhausted" as failure (row 7). The PSP had processed the first attempt. The customer had the money, our ledger did not, and the 250,000 VND was refundable again. The agent had flagged "external system timeouts"; the humans never separated timeout (unknown) from failure (definitive). See Idempotency & Exactly-Once.
The fix used the same loop: spec amended, failing test written by a human first:
func TestWorker_PSPTimeoutKeepsRefundPending(t *testing.T) {
ctx := context.Background()
db := newTestDB(t)
w := newWorker(t, db, newFakePSP(t, true)) // every PSP refund call times out
r := seedPendingRefund(t, db, 250_000) // on a 1,000,000 VND payment
for range 3 { // the worker's whole retry budget
_ = w.Submit(ctx, r.ID)
}
if got := loadRefund(t, db, r.ID); got.Status != "PENDING" {
t.Fatalf("status after PSP timeouts = %s, want PENDING (outcome unknown)", got.Status)
}
if got := refundable(t, db, r.PaymentID); got != 750_000 {
t.Errorf("refundable = %d, want 750000: a timed-out amount stays reserved", got)
}
assertLedgerBalanced(t, db)
}
With tests.lock back, the agent implemented it (unknown stays PENDING, the poller resolves it), and one line went into AGENTS.md under "Rules that are easy to get wrong":
- A PSP **timeout is an unknown outcome, not a failure**: keep the refund PENDING and the amount reserved; resolve via webhook or status query. Only a definitive PSP error may set FAILED.
assertLedgerBalanced passed throughout: the books were consistent with themselves and wrong about the world. Only external reconciliation catches that.
Trade-offs
| Stage | Let the agent | Keep the human |
|---|---|---|
| Interrogation, spec | Questions, defaults, draft | Answers, scope, sign-off |
| ADR | Options with pros and cons | The decision and reasons |
| Tests | Table cases, fixtures, helpers | Invariants, concurrency tests, freeze |
| Implementation | Code per task, running checks | Prompts, reading each commit, guardrail decisions |
| Review | First-pass checklist | Transaction boundaries, money semantics, approval |
| Rollout, operate | Dashboards, runbook draft | Go/no-go, incidents, lessons |
In practice
Where the time went for this feature (illustrative, one engineer, rough; not a benchmark):
| Stage | Calendar | Human time | What the human was doing |
|---|---|---|---|
| 1–2 Interrogate, spec | Day 1 | ≈ 2 h | Stakeholder call, editing the spec |
| 3–4 ADR, plan | Day 1–2 | ≈ 1.5 h | Choosing option A, review with the tech lead |
| 5 Tests | Day 2 | ≈ 3 h | Rewriting the concurrency test and the invariants |
| 6–7 Implement, verify | Day 3–4 | ≈ 3 h | Prompts, reading each commit, two guardrail decisions |
| 8 Review, PRs | Day 5 | ≈ 3.5 h | Self-review, PSP fix, reviewer's time |
| 9 Rollout | Days 6–12 | ≈ 2 h | Flag steps, watching dashboards |
| 10 Recon fix | Day 13 | ≈ 2 h | Root cause, test, AGENTS.md |
| Total | ≈ 17 h | ≈ 10 h on spec, decisions, tests and review; little on typing code |
Common pitfalls
- Skipping interrogation because the ticket "is clear". Symptom: the agent silently decides the window, cap and PSP semantics.
- Agent-written, agent-approved tests. Symptom: green tests encoding the bug, like the shared PSP helper.
- Concurrency tests run once. Symptom: the race appears in production on day 3.
- Mapping a constraint violation to a client error. Symptom: a broken lock looks like normal 422 traffic.
- Treating a timeout as a failure. Symptom: double refunds and recon breaks.
- One giant PR. Symptom: rubber-stamp review of money code.
Interview angle
- Prompt: "Design refunds" or "How do you deliver a risky feature with AI help?" Name the artifact and gate per stage, then go deep: the cap counts PENDING, row lock plus
CHECKbackstop, PSP after commit, timeout means unknown, reconciliation. - Follow-ups: "Why not optimistic locking?" "What if the webhook never arrives?" (poller, PENDING-age alert). "How do you know AI code is correct?" (human-owned frozen invariant tests,
-count=20, mutation check, review by risk tier). - Red flags: "the AI wrote the tests and the code and they pass"; no answer for concurrent partials; timeouts marked failed.
Self-check
1. Why do PENDING refunds count against the refundable amount?
Otherwise two refunds can both be accepted while the first is still waiting on the PSP, and together exceed the captured amount once both succeed. Reserving at request time makes the cap hold regardless of PSP timing. A definitive failure releases the reservation.
2. Why lock the payment row rather than rely on the CHECK constraint alone?
The constraint prevents over-refund but surfaces as an unexpected database error on the losers, and cannot produce the correct 422 with refundable_remaining. The lock makes check-then-reserve atomic, so losers get a clean business error. The constraint stays as a backstop that pages if it fires.
3. The concurrency test passed once. What else do you do before trusting it?
Run it with -race -count=20. Remove the FOR UPDATE and confirm that it fails, which proves the test can detect the bug. Check that it asserts both safety (total ≤ captured) and liveness (exactly 33 successes, no unexpected errors).
4. How did the PSP amount bug get past green tests, and how do you prevent that class of miss?
The fake PSP used the same formatting assumption as the production adapter, so the round trip agreed with itself. Prevent it with contract tests against recorded real PSP responses, table tests across currency exponents (VND 0, USD 2), and fakes that never import the code under test.
5. Scenario: the PSP times out on every retry of a refund. What state should the refund be in, and why?
PENDING, with the amount still reserved. A timeout is an unknown outcome, so the PSP may have processed the refund. Resolve it through the webhook or a status query using the same PSP idempotency key (the refund ID). Only a definitive PSP error or a refund.failed webhook may set FAILED and release the amount.
Exercise
On your MiniPay capstone with the templates installed:
- Run
/write-specon the same ticket, answer it yourself, and compare with the excerpts. - Write the stage 5 tests, freeze them, and have the agent implement T2–T4.
- Implement option B on a branch and compare failure modes and code size.
- Add the PSP-timeout test and a status poller.
Done when: -race -count=20 is green, removing FOR UPDATE makes it red, the ledger invariant runs after every integration test, and AGENTS.md gained a line from a mistake you watched the agent make.
Further reading
- Brandur Leach, "Implementing Stripe-like Idempotency Keys in Postgres" (2017).
- Stripe API documentation: refunds and idempotent requests.
- PostgreSQL documentation: "Explicit Locking" (row-level locks) and
ALTER TABLE(NOT VALID,VALIDATE CONSTRAINT). - Martin Kleppmann, Designing Data-Intensive Applications, ch. 7 (lost updates, write skew).
- Alex Xu and Sahn Lam, System Design Interview Vol. 2, ch. 11 (payment system, reconciliation).
Related
- Setting Up a Repo for AI Agents — the templates used here.
- Requirements → Spec → Plan with AI — stages 1–4 in depth.
- TDD & Testing with AI — tests first, frozen.
- Reviewing AI Code & CI Guardrails — stage 8 and 9 in depth.
- Double-Entry Ledger Design — the reservation and settlement entries.
- Ch 11 · Payment System — PSP integration, refunds, reconciliation.
- Documenting Architecture: C4, ADRs, arc42 — writing ADRs.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).