---
title: "Money in Integers: How I Built a Ledger That Never Loses a Cent"
url: https://nayansukhadiya.in/blog/money-in-integers-building-a-ledger-that-never-loses-a-cent
published: 2026-10-20T10:28:51.172+00:00
updated: 2026-10-20T10:28:51.301025+00:00
category: "FinTech & Payments"
tags: ["nestjs","fintech","system-design","lunexa","postgresql"]
---

# 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.

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.
1. Apply the ledger effect (which account goes up, which goes down).
1. Snapshot the balances before and after on the transaction.
1. 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.
1. **Compare** the request's hash with the stored one. Same key with a different body is a `409 Conflict`, not a silent overwrite.
1. **Replay** if the first request already completed: return the transaction it created instead of creating another.
1. **Take over** if the earlier attempt failed or went stale, so a genuine retry isn't blocked forever.
1. **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

| Decision | Why | What it costs |
| --- | --- | --- |
| Integer minor units in BIGINT | Exact arithmetic in every currency | Amounts travel as strings; conversion at the edges |
| A single balance writer | One place to get balance logic right | Every feature must go through it, even small ones |
| Locks in id order | Deadlocks become impossible by construction | Slightly more locking than strictly needed |
| Idempotency keys on create | Retries and double clicks are harmless | A keys table and a claim step on every write |
| Immutable completed entries | The history always explains the balance | Corrections 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

- [PostgreSQL docs: explicit locking and deadlocks](https://www.postgresql.org/docs/current/explicit-locking.html)
- [ISO 4217 currency codes and minor units](https://www.iso.org/iso-4217-currency-codes.html)
- [IETF draft: the Idempotency-Key HTTP header](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/)

## 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.
