Nayan Sukhadiya
  • FinTech & Payments
  • nestjs
  • fintech
  • system-design

Money in Integers: How I Built a Ledger That Never Loses a Cent

Floats, double clicks and concurrent requests quietly corrupt money. How Lunexa's ledger is built so none of them can happen.

FinTech & Payments5 min read314readers

Nayan Sukhadiya

Full Stack Engineer

Published

Updated at

Lunexa is the personal-finance platform I'm building: you record what happened to your money across banks, cards, wallets, deposits and loans, and it keeps the books exact. "Exact" is the whole product. A dashboard can be ugly for a while; a balance that is off by one cent is a bug users never forgive, because they can't trust anything after it.

So before any screen, I designed the ledger around three failure modes I had seen in other systems.

The short answer

  • Money is an integer. Every amount is stored in minor units (cents, paise, yen) as BIGINT, never as a decimal or a float.
  • One writer touches balances. A single service is allowed to change a balance, always under a row lock, inside the same database transaction as the entry that caused it.
  • Every write can be retried safely. Creating a transaction needs an idempotency key, so a double click or a network retry replays the first result instead of charging twice.
The one idea behind it all Correctness has to live in the shape of the system, not in developers remembering to be careful. If there is only one way to change a balance, there is only one place to get it right.

1. Why money is never a float

0.1 + 0.2 in JavaScript is 0.30000000000000004. That is not a JavaScript bug; it is how binary floating point works, and it means a float can't represent most decimal amounts exactly. Add enough of them and a balance drifts.

Lunexa stores every amount as an integer count of the currency's smallest unit. ₹1,250.50 is 125050 paise. Arithmetic on integers is exact, so the sum of a thousand entries is the sum, not an approximation of it.

Two details make this work across countries:

  • Not every currency has two decimals. The yen has none, the Kuwaiti dinar has three. The conversion takes the currency's minor unit from data, not a hard-coded 2:
ts
toMinorWithUnit("1250.5", 2); // "125050"   (INR, USD)
toMinorWithUnit("1250", 0);   // "1250"     (JPY)
toMinorWithUnit("12.345", 3); // "12345"    (KWD)
  • Integers travel as strings. A Postgres BIGINT can exceed JavaScript's safe integer range, so amounts move through the API as strings and are parsed into bigint only for maths. The client never does money arithmetic on a number.

2. One writer, and only one

A balance is a cached sum of entries. The danger with a cache is that many places update it: transactions, transfers, subscriptions, debt repayments. Each one is a chance to forget a case.

In Lunexa exactly one service writes current_balance_minor: the money-sources ledger core. Every feature calls it; none of them touch the column. It does four things, always in this order, inside the caller's database transaction:

  1. Lock the affected accounts.
  2. Apply the ledger effect (which account goes up, which goes down).
  3. Snapshot the balances before and after on the transaction.
  4. Commit everything atomically, or nothing.

Because the entry and the balance change commit together, there is no moment where one exists without the other.

3. Locks, and the deadlock you get for free

A transfer touches two accounts. If request A locks savings then checking, while request B locks checking then savings, each waits for the other forever. Postgres detects it and kills one (error 40P01), which in production looks like random failed payments.

The fix is boring and total: every caller locks accounts in the same order, sorted by id.

ts
async lockSourcesOrdered(manager, userId, sourceIds) {
  const uniqueSorted = [...new Set(sourceIds.filter(Boolean))].sort();
  const locked = new Map();
  for (const id of uniqueSorted) {
    // SELECT … FOR UPDATE, scoped to the owner
    locked.set(id, await this.assertOwnedWithLock(manager, id, userId));
  }
  return locked;
}

If everyone queues in the same order, nobody can hold the lock someone ahead of them needs. The same lock also protects slower decisions: archiving an account checks "is the balance zero?" under the very lock the ledger takes, so a payment can't land between the check and the archive.

4. Idempotency: the double click problem

The network is not reliable. A user taps "Save", the request reaches the server, the response is lost, the app retries. Without protection that is two expenses.

Every create call in Lunexa carries an idempotency key, and the server treats it as a claim:

  1. Claim the (user, key) slot by inserting a row with status IN_PROGRESS. A unique constraint makes the insert fail if someone already holds it.
  2. Compare the request's hash with the stored one. Same key with a different body is a 409 Conflict, not a silent overwrite.
  3. Replay if the first request already completed: return the transaction it created instead of creating another.
  4. Take over if the earlier attempt failed or went stale, so a genuine retry isn't blocked forever.
  5. Mark the key COMPLETED in the same database transaction as the money movement.

The claim happens outside the money transaction, so a duplicate is turned away before any lock is taken.

5. Completed means immutable

A finished transaction is never edited in place and never deleted. A correction is a revert of the old ledger effect plus the new one, recorded as such. That gives two properties I care about more than convenience: the history explains every balance, and a bug can't erase the evidence of itself.

The design decisions, side by side

DecisionWhyWhat it costs
Integer minor units in BIGINTExact arithmetic in every currencyAmounts travel as strings; conversion at the edges
A single balance writerOne place to get balance logic rightEvery feature must go through it, even small ones
Locks in id orderDeadlocks become impossible by constructionSlightly more locking than strictly needed
Idempotency keys on createRetries and double clicks are harmlessA keys table and a claim step on every write
Immutable completed entriesThe history always explains the balanceCorrections are two operations, not one edit

What I take from it as an engineer

None of these ideas are new; banks have used them for decades. What surprised me is how little code they need once they are the rules of the system rather than habits. The hard part was saying no to shortcuts: no "quick" direct balance update for an admin fix, no float "just for display maths". The ledger is the one part of Lunexa I never want to think about again, and that is the point.

Sources

Frequently asked questions

Why not use PostgreSQL NUMERIC instead of BIGINT?

NUMERIC is exact too. I chose integer minor units because the arithmetic stays exact all the way through the application (JavaScript has `bigint`, not a decimal type) and every currency's precision is explicit.

Doesn't locking every account slow things down?

Locks are row-level and held only for the length of one database transaction. For a personal-finance workload that is milliseconds, and it is far cheaper than repairing a wrong balance.

What happens if the same idempotency key arrives twice at the same moment?

Only one insert can claim the key because of the unique constraint. The second request sees the claim, and either replays the finished result or is told the first one is still in progress.

  • nestjs
  • fintech
  • system-design
  • lunexa
  • postgresql