The Anatomy of Floating-Point Drift
Comparison of Financial Data Types
| Data Type | Storage Size | Precision Guarantee | Performance Impact | Failure Mode |
|---|---|---|---|---|
| 'FLOAT8' (Double) | 8 bytes | Approx. 15-17 decimal digits | Extremely Fast | Cumulative rounding drift |
| 'NUMERIC(18,4)' | Variable | Exact (up to 18 digits) | Moderate (CPU overhead) | Overflow if limits exceeded |
| 'BIGINT' (Minor Units) | 8 bytes | Absolute (Exact integer math) | Maximum (Native CPU ops) | Overflow if nominal scale miscalculated |
Low-Level Schema Design in PostgreSQL
SQL
CREATE TYPE currency_code AS ENUM ('IDR', 'USD', 'EUR', 'SGD');
CREATE TABLE ledger_transactions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
account_id UUID NOT NULL,
amount_minor BIGINT NOT NULL CHECK (amount_minor <> 0),
currency currency_code NOT NULL,
scale_exponent INT NOT NULL DEFAULT 0,
balance_after_minor BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX idx_ledger_account_created ON ledger_transactions(account_id, created_at DESC);Handling Exchange Rate Multipliers and Division
PYTHON
def convert_and_scale(amount_usd_cents: int, rate_multiplier: int, scale_divisor: int) -> int:
product = amount_usd_cents * rate_multiplier
quotient = product // scale_divisor
remainder = product % scale_divisor
# Implement banker's rounding or deterministic remainder allocation
if remainder >= (scale_divisor / 2):
quotient += 1
return int(quotient)Concurrency Control with Redis and PostgreSQL Locks
SQL
BEGIN;
SELECT balance_minor FROM accounts
WHERE id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'
FOR UPDATE;
-- Perform balance validation in application code
UPDATE accounts
SET balance_minor = balance_minor - 50000000,
updated_at = clock_timestamp()
WHERE id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';
INSERT INTO ledger_transactions (account_id, amount_minor, currency, balance_after_minor)
VALUES ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', -50000000, 'IDR', current_balance);
COMMIT;LUA
-- Redis Lua Script for Atomic Balance Check and Debit
local current_balance = tonumber(redis.call('GET', KEYS[1]) or '0')
local debit_amount = tonumber(ARGV[1])
if current_balance < debit_amount then
return {err = 'INSUFFICIENT_FUNDS'}
end
local new_balance = redis.call('DECRBY', KEYS[1], debit_amount)
return new_balanceDiagnostic Verification and Auditing
BASH
psql -h 'db.internal.net' -U 'finance_admin' -d 'ledger_prod' -c "
SELECT
account_id,
balance_minor as stored_balance,
(SELECT SUM(amount_minor) FROM ledger_transactions WHERE ledger_transactions.account_id = accounts.id) as computed_sum,
balance_minor - (SELECT SUM(amount_minor) FROM ledger_transactions WHERE ledger_transactions.account_id = accounts.id) as drift_delta
FROM accounts
HAVING balance_minor - (SELECT SUM(amount_minor) FROM ledger_transactions WHERE ledger_transactions.account_id = accounts.id) <> 0;
"