Yash Gupta

Money in a float column

Every balance, charge and ledger amount in our billing system is stored as a 32-bit float. That one decision produced a reconciliation check that gave a different answer each time it ran, and a safety assertion that refused to let the largest customers be charged at all. A third bug, in the same code, had nothing to do with floats and is the one I would put in front of a junior engineer.

Role
Found them and fixed them
Stack
PostgreSQL, NestJS, Drizzle ORM
Status
Fixes live in production, root cause open
Evidence
Specs red before green, against a real Postgres

The decision underneath

Wallet balances, reserved and usable amounts, per-tier credit allocations, every row of the transaction ledger, and each campaign's reserved and consumed totals are all real: Postgres's four-byte float, with a 24-bit significand. It is a reasonable default for a measurement and the wrong type for money, and by the time I was working on billing it was load-bearing in a dozen tables.

What follows is not an argument that floats are imprecise, which everybody knows. It is what that imprecision actually looked like from the outside, where it did not present as rounding at all.

A total that changed between runs

I was reconciling ledger rows against wallet balances, and the same query over the same unchanging rows kept returning a slightly different total. Not drifting over time. Different, run to run, over data nobody was writing to.

The query summed the amount column and cast the result to double precision, which looks like the careful thing to do. It is the opposite. Postgres sums a real column in real, so the accumulator is four bytes wide for the whole scan, and casting afterwards widens a total that has already lost its precision.

ExpressionResult over the same rows
SUM(amount)::float8three different values across three runs
SUM(amount::float8)stable, and correct to four decimal places
SUM(amount::numeric)stable, exact

The run-to-run variation is the part worth keeping. Floating-point addition is not associative, so a total depends on the order it was accumulated in, and the planner changed that order between runs as it chose different numbers of parallel workers. The answer was a function of the query plan.

The consequence is worse than a wrong number: it is a monitoring check that flaps. A reconciliation written this way fails its tolerance on one run and passes on the next, with no change in the data. That looks exactly like live traffic racing the check, or like genuine drift appearing and resolving, and it will be investigated as a concurrency problem for as long as anyone is willing to keep looking. The fix is to cast inside the aggregate, per row, so the accumulation happens in double.

A safety check that blocked the biggest customers

The charge path asserts an invariant before it moves money: the main balance minus what is reserved should equal what is usable, within a hundredth of a unit. Reasonable, and it had worked for a long time.

It started throwing for customers with large balances, inside the charge transaction, so the charge failed. The stored values were in fact consistent; the true discrepancy was far smaller than the gap between two representable floats at that magnitude. The check was reading a difference that did not exist in the data.

The path it travelled is the interesting bit. The driver renders a real as the shortest decimal text that round-trips to the same float. For a large balance that text is seven significant digits, and a rupees-and-paise amount needs more than seven digits to survive once the rupees reach five figures. Three such values, each rounded to text independently and then subtracted in JavaScript, produced a residue just over a hundredth. A fixed absolute tolerance is a bug waiting for a number large enough, because the spacing between representable floats grows with magnitude while the tolerance does not.

// one float4 step at 100k is about 0.0078, so a fixed 0.01
// tolerance is below the noise floor for large balances
const tolerance = Math.max(0.01, Math.abs(mainBalance) * 2 ** -21)

Scaling the tolerance with the magnitude, at four float steps, keeps it strict enough to catch real drift well beyond any balance the system holds, while no longer failing on values the format cannot represent any more precisely. It shipped with unit tests that were red first and an end-to-end suite against a real Postgres that reproduced the exact production error before the fix and passed after it.

This is the one that taught me the most, because every individual component was behaving correctly. The column stored what it could. The driver rendered it faithfully. The assertion compared what it was given. The defect lived in the seam between three correct things, and no single-component test could have found it.

And one that was not the float's fault

Delivery receipts charge for the message they confirm, and that has to happen exactly once. The guard looked like this:

SELECT ... FROM credit_transaction_logs
 WHERE whatsapp_message_id = $1 AND campaign_id = $2
   FOR UPDATE

Read it as an engineer who has used row locks and it looks airtight: take the lock, see whether we already charged, charge if not. It is not airtight, and the reason is the single most useful thing on this page.

FOR UPDATE locks the rows the query returns. When the row does not exist yet, it returns nothing, and locks nothing. Two delivery receipts for the same message arriving at the same instant both run that query, both find nothing, both conclude they are the first. They then serialise on the wallet lock further down and take turns inserting, politely, one after the other. The lock did its job. It was just guarding the wrong thing, and there was no unique index to catch what it missed.

Duplicates arriving seconds apart were always rejected correctly, which is why this survived: the window is milliseconds wide and the failure needs the upstream provider to deliver the same status twice almost simultaneously.

The fix takes an advisory lock keyed on the message id before the check, so the two receipts serialise on the thing they actually contend over rather than on a row that does not exist. The test is the part I was pleased with: a side connection holds the wallet lock until both copies of the charge are provably blocked on it, so the interleaving is forced rather than hoped for. Without the fix it double-charges every run; with it, once. Verified afterwards against production, where duplicate receipts are now turned away and no message has been charged twice since.

It also surfaced a precondition nobody had written down: the charge path only works under read-committed isolation. Raised to repeatable-read, most concurrent charges for one customer fail with serialization errors that are then swallowed. That was true before the fix and is still true. Knowing a system depends on a database default is worth as much as the fix.

What I would design differently

Each of these fixes is a guard, and a guard is a thing a future change can forget. The decision I would make differently is the one underneath all three: a decimal type for money from the start. Choosing a four-byte float for a balance costs nothing on the day and buys a class of defects that do not look like rounding when they finally arrive, which is what made these three expensive to diagnose rather than expensive to fix.

The second is to make guarantees structural rather than procedural wherever the schema can carry them. Code that is careful and a database that refuses are not the same promise, and only one of them survives the next person who writes a second insert path.

What I took from it

  • Store money as a decimal type. If you have inherited floats, the dangerous part is not the rounding, it is that aggregates stop being deterministic and checks built on them start lying in both directions.
  • Cast inside the aggregate, not after it. A cast on the outside of a SUM is a cast that arrived too late.
  • Any absolute tolerance on a floating-point comparison is waiting for a large enough input. Scale it with the magnitude, or compare in a type that does not need a tolerance.
  • SELECT ... FOR UPDATE is not an idempotency guard. It cannot lock a row that is not there, which is precisely the case you are trying to defend against.
  • When a check flaps, suspect the check. I spent real time looking for a race that was an accumulation order.