Skip to content
cyberpunk47Public

About

An immutable Monolithic System for recording transactions between two Party's P2M.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SwayPay

A payment backend built to answer one question properly:

Can I move money exactly once, and prove afterwards that I did?

Not a feature-complete product. It is a correctness exercise that happens to look like a payment gateway, and most of the work went into the parts that only matter when something goes wrong.

Stack: Spring Boot 3.5 · PostgreSQL · Redis · React 19 + TypeScript + Mantine.


The problem

Design a payment backend where a user transfers money to a merchant. A single logical transaction — validation, balance deduction, ledger recording — must stay financially consistent under network retries (duplicate requests) and concurrent access (several simultaneous transactions on the same account).

Money must never be created, lost, or duplicated. Every balance change must be traceable through an append-only ledger rather than a mutable balance field. An admin must be able to prove the ledger is balanced.

In short: user pays merchant → money moves correctly even when things go wrong → admin can prove it.


How a payment works

User: Aman   ₹100,000   id 001
Merchant: Amazon  ₹5,000   id 002      Aman pays ₹1,000

One transaction row:

transactions
  txn_id: txn_abc123 | from: 001 | to: 002 | amount: 1000 | status: SUCCESSFUL

Two ledger rows, always written together:

ledger
  id 1 | txn_abc123 | account 001 | DEBIT  | 1000
  id 2 | txn_abc123 | account 002 | CREDIT | 1000

Direction lives in entry_type, so the amount is always positive — the database enforces CHECK (amount > 0). A sign-flip bug becomes a rejected INSERT.

The invariant

SELECT sum(CASE WHEN entry_type = 'CREDIT' THEN amount ELSE -amount END) FROM ledger;
-- must be exactly 0, always

This replaced my first idea, which was wrong. I originally checked that total money was conserved:

prev(user) + prev(merchant) == after(user) + after(merchant)
100000 + 5000 == 99000 + 6000   ✅

That check passes on bugs it should catch:

Bug Conservation check Reality
₹2,000 transferred instead of ₹1,000 ✅ passes wrong amount moved
Merchant B credited instead of Merchant A ✅ passes wrong person paid

Money being conserved is not the same as the right money moving between the right accounts. The per-transaction ledger check catches all three cases, because the two legs are tied to one transaction_id and must cancel out.


The three layers

Each answers exactly one question, and knows nothing about the others' job.

Layer Question Touches money?
Gate — IdempotencyService "Should I do this work at all?" No
Engine — TransactionService "Move it, atomically." Yes
Orchestrator — PaymentService wires gate → engine → cache No

Rules that keep it from turning into mud: the Gate never touches a ledger row, the Engine never decides whether to run, and the Orchestrator is not @Transactional — it calls Redis, and a transaction there would hold a database connection across every Redis round trip.

PaymentService and TransactionService also cannot be one class. Spring's @Transactional is proxy-based: a method calling another method in the same class skips the proxy, so no transaction is started at all, silently.


Request flow

1.  POST /api/v1/payments     Header: Idempotency-Key: <uuid>
                              Body:   { accountId, amount }
                              Payer comes from the JWT, never the body (IDOR)

2.  Gate: SET idemp:<key> IN_FLIGHT NX EX
      CLAIMED     -> I own it, execute
      IN_FLIGHT   -> someone else owns it -> 409, do nothing
      SUCCESSFUL  -> replay the stored response, charge nothing
      FAILED      -> replay the stored failure
      Redis miss  -> fall back to Postgres (UNIQUE(idempotency_key))

3.  Engine, inside one @Transactional:
      lock both accounts with SELECT ... FOR UPDATE, in UUID order
      check balance (inside the lock, or it is a TOCTOU race)
      debit / credit
      insert transaction + 2 ledger rows
      COMMIT

4.  Post-commit: write SUCCESSFUL + the response body to Redis

Why locks are taken in UUID order

Two opposite transfers at the same instant, locking payer-first:

      Ali(1111) -> Zara(9999)        Zara(9999) -> Ali(1111)
t1     locks Ali      OK
t2                                    locks Zara     OK
t3     wants Zara  BLOCKED
t4                                    wants Ali  BLOCKED      -> deadlock

Locking the smaller UUID first regardless of direction means both requests ask for Ali first, so the second waits while holding nothing. No cycle can form — and it holds for chains of any length, because a thread only ever waits on an id larger than the one it holds, so a cycle would need X < Y < X.

Why the idempotency key is per intent, not per request

The user presses Pay once. A double tap, an axios retry, a flaky network, a proxy retry — all of those arrive as separate HTTP requests carrying the same key, and must replay one answer. A deliberate second attempt after a failure is a new intent and gets a new key. A FAILED key stays burned: same key, same answer, forever — otherwise it isn't idempotent.

Admin top-up

Money cannot appear from nowhere, or SUM(ledger) stops being 0. So a top-up is an ordinary transfer from a SYSTEM treasury account:

DEBIT   treasury   1000
CREDIT  user       1000

The treasury goes negative, which is correct — it records how much has entered the platform from outside. This needed zero new money-movement code: same locking, same ledger, same idempotency, just a different payer.


Which wall stops what

The thing I actually learned building this: these are not redundant, they fail at different times.

Wall Stops Remove it and…
Redis SETNX duplicate concurrent work still correct, but every duplicate hits Postgres
@Transactional torn writes (debit without credit) money created/destroyed on any crash
UNIQUE(idempotency_key) duplicate committed charges Redis fails → double charge
SELECT … FOR UPDATE lost updates on balance balance silently wrong under concurrency
CHECK (amount > 0) negative amounts a sign-flip bug reaches the ledger

Redis and the UNIQUE constraint both stop duplicates, but at different moments. Redis stops concurrent ones cheaply; the constraint stops committed ones absolutely.

And on where validation lives: Java validates for the human, the database validates for the truth. Java gives the readable error; the constraint is what holds when the Java is wrong.


API

Method Path Notes
POST /api/v1/auth/register · /login balance is forced to 0, never read from the body
POST /api/v1/payments requires Idempotency-Key
GET /api/v1/payments paged
GET /api/v1/payments/ledger paged
GET /api/v1/payments/{txnId} role and ownership checked
GET /api/v1/payments/summary dashboard tiles, aggregated in SQL
GET /api/v1/user/payees no balances or emails exposed
POST /api/v1/admin/topup ADMIN only
GET /api/v1/admin/transactions · /ledger · /summary ADMIN only, paged

Status codes: 409 already in flight or duplicate · 422 business rejection · 503 Redis down, "nothing was charged" · 400 bad body.


Testing

1. JUnit — PaymentRaceTest

cd backend && ./mvnw test -Dtest=PaymentRaceTest

Two details that make these real tests rather than theatre:

  • A starting gate. A plain loop of executor.submit() is not a race — thread 1 finishes before thread 20 is scheduled. ConcurrencySupport.stampede() blocks every thread on a latch and releases them together.
  • Not @Transactional. A transactional test keeps everything uncommitted, so the threads could never see each other and every race would silently pass. Rows are cleaned up by hand instead.
Test Fires Asserts
sameKeyChargesOnce 50 threads, one key exactly 1 transaction row, 2 ledger legs, ₹300 moved — not ₹15,000
balanceNeverGoesNegative 20 threads, ₹1000 balance, ₹100 each exactly 10 succeed, balance lands on 0, never below
bidirectionalTransfersDoNotDeadlock 40 threads alternating A→B / B→A no deadlock detected
ledgerSumsToZero 30 mixed, some over-balance credits − debits = 0, and failed rows have zero ledger legs

Try commenting out @Lock(PESSIMISTIC_WRITE) in UserRepository and re-running — test 2 fails with a negative balance.

2. scripts/race-curl.sh — from outside

50 same-key requests fired together with &, then 20 unique-key ones. It counts charges from the database, not from a balance delta — a balance delta counts every other payment the account is making at the same time, which made my first version report a phantom 12× overcharge that never happened.

3. scripts/k6-payments.js — load

Three scenarios: idempotency_storm (50 VUs, one key), unique_payments (30/s), hot_account (40 VUs onto one merchant, which is the row-lock ceiling).

The only threshold that fails a run is payments_5xx: count==0. A 409 is correct behaviour; a 500 means an unhandled exception escaped.

Result on ~1,800 payments: 0 server errors, 0 duplicate keys, ledger at 0.

4. scripts/partition-test.sh — network partitions

Drill Passing means
Redis down 503, nothing charged. Not "it kept working" — "it never lied".
Postgres down 5xx, 0 rows. A 200 would be a lie. Then the same key must still work after recovery.
Client aborts mid-flight server finished the work; the retry replays, not re-charges

The script refuses to measure until it has confirmed the dependency is actually unreachable. My first version didn't, and reported three green drills against a completely healthy system — a chaos test that doesn't verify the chaos always passes, which is worse than no test.

5. scripts/verify.sql

Five queries, all must return zero rows: duplicate keys · credits ≠ debits · successful transactions without exactly 2 legs · failed transactions with any legs · non-SYSTEM users with a negative balance.


Things I changed my mind about

  • Conservation check → per-transaction ledger check. The first one passes on wrong-amount and wrong-recipient bugs.
  • Long paise → BigDecimal(19,4). Ledger at scale 4 for fee/tax fractions, transactions at scale 2 for the customer-facing figure. A running total's scale must be ≥ the scale of what is summed into it.
  • ddl-auto=update is unsafe for type changes. It silently left numeric(38,2) where the entity said scale 4, so Postgres was rounding away the decimals I had just added. validate doesn't catch it either — it checks type, not scale.
  • Infinite scroll → real pagination. Infinite scroll keeps every loaded page mounted; at a million rows the tab dies.
  • Dashboard tiles → one /summary call. They used to download whole tables to render four numbers, and after pagination would have totalled only the newest page while claiming to be lifetime totals.
  • Bank account fields are optional. Nothing in the payment path reads them. Requiring them was a lie the UI was telling.

Known gaps

  • PENDING_RECONCILIATION and the reconciler are not built. A DB timeout is indeterminate — the money may or may not have moved — so it must not be marked FAILED, or a retry under a fresh key double-charges. Only SwayPayExceptions is caught today; the gap is marked with a TODO in PaymentServiceImpl.
  • Filtering and search are gone from the admin table. They filtered only loaded rows, so "Failed" could look empty while thousands sat on other pages. A filter that lies is worse than no filter — they come back as server-side params.
  • ADMIN is self-assignable at registration. Fine for testing, not for real.
  • Secrets are in application.properties. Must move to environment variables.
  • Fee splits, refunds, webhooks and real settlement are out of scope.

Running it

# once
psql -U postgres -d swaypay_db -f backend/db/setup.sql   # treasury + constraints

redis-server                                   # terminal 1
cd backend  && ./mvnw spring-boot:run          # terminal 2, :8033
cd frontend && npm install && npm run dev      # terminal 3, :5173

cd scripts && ./seed.sh                        # admin + Ali + Zara, funded

About

An immutable Monolithic System for recording transactions between two Party's P2M.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages