Money is where small data-modelling mistakes become real losses. Two decisions matter most: how a single amount is represented, and how the history behind a balance is recorded. Both have well-established answers.
Choosing the column type
- Never use FLOAT or DOUBLE. Binary floating point cannot represent most decimal fractions exactly, so sums drift and equality checks fail.
- Integers in the smallest unit (
BIGINT) are exact, fast and easy to add. Store 100000 for 100,000 VND, or 1999 cents for 19.99 USD. The number of minor units depends on the currency: zero for VND and JPY, two for USD and EUR, three for KWD. Keep that exponent in code or a currency table. DECIMAL(p, s)is exact too, and fits amounts that need fractional units, such as crypto assets or exchange rates, for exampleDECIMAL(20, 4). Pick precision and scale from the real requirements.- Always store the currency code next to the amount, and never add amounts in different currencies.
Two ways to keep a balance
You can keep a balance column on the wallet and update it directly. It is simple and fast to read, but when it is wrong you cannot tell why, and you cannot audit it. The alternative is a ledger: a table where every movement of money is a row that is only ever inserted, and the balance is the sum of the rows.
The practical design combines them. The ledger is the source of truth. The balance column is a cache updated in the same transaction as the ledger insert, and a reconciliation job regularly checks that the two agree.
Double-entry bookkeeping
In a double-entry ledger every transaction creates at least two entries that cancel each other out. Moving 100,000 from wallet A to wallet B creates one entry of minus 100,000 on A and one of plus 100,000 on B, both pointing to the same transaction id. The total of all entries is always zero, or equals the total money deposited into the system.
CREATE TABLE wallets (
id BIGINT PRIMARY KEY,
owner_id BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
balance BIGINT NOT NULL DEFAULT 0, -- cache of the ledger
CONSTRAINT chk_balance CHECK (balance >= 0) -- enforced from MySQL 8.0.16
) ENGINE=InnoDB;
CREATE TABLE ledger_entries ( -- append-only
id BIGINT AUTO_INCREMENT PRIMARY KEY,
txn_id BIGINT NOT NULL,
wallet_id BIGINT NOT NULL,
amount BIGINT NOT NULL, -- negative = debit, positive = credit
created_at DATETIME(3) NOT NULL,
KEY idx_wallet_time (wallet_id, created_at),
KEY idx_txn (txn_id)
) ENGINE=InnoDB;The invariants become simple queries you can run at any time and alert on.
-- every transaction must balance
SELECT txn_id FROM ledger_entries GROUP BY txn_id HAVING SUM(amount) <> 0;
-- each cached balance must equal its ledger total
SELECT w.id FROM wallets w
JOIN (SELECT wallet_id, SUM(amount) AS total FROM ledger_entries GROUP BY wallet_id) l
ON l.wallet_id = w.id
WHERE w.balance <> l.total;Append-only means corrections are new entries
Never update or delete a ledger row. If an entry was wrong, post a reversal that cancels it and, if needed, a new correct entry. The history then shows what happened and when, which is exactly what auditors, support staff and your future self need. Protect this at the database level where you can, for example with permissions that deny UPDATE and DELETE on the ledger table to the application user.
Practical notes
- Add a unique business reference or idempotency key on the transaction, so a retry cannot post it twice. The next articles cover this.
- Index the ledger by wallet and time for statements, and by transaction for investigations.
- Large ledgers are summed often. Keep the balance cache for reads and, if needed, periodic balance snapshots so that audits do not scan everything.
- Record who or what created each entry and why, with enough metadata to trace it to a business event.
Takeaway
Use integers or DECIMAL with a currency code, keep an append-only double-entry ledger as the truth, treat the balance column as a cache, and write reconciliation queries from day one. Then a discrepancy becomes something you can find, not something you discover from an angry customer.
Comments