As soon as a project introduces money, transfers, and customer balances, it's tempting to reach for a complex stack. You want Kafka or an event store for auditing, Redis for balances, ClickHouse for reporting, and a couple of microservices on top to isolate the database. Intuition says a single Postgres instance will choke under all of that.
Let's put that intuition to the test. Engineer Eduardo Bellani walked through this architecture on a single PostgreSQL 18 node (released September 25, 2025) using only standard extensions available even on AWS RDS. He modeled it after the Increase banking API: managed and external accounts, transfers with status transitions, immutable transactions, and two balances. The current balance counts toward interest, while the available balance accounts for pending holds and shows how much you can withdraw right now. Both balances must be queryable at the current second or at any timestamp in the past.
PostgreSQL 18 already ships with every piece needed to build this ledger without a zoo of databases. Let's examine the design layer by layer to see where one Postgres has room to spare and where its real limits begin.
Schemas, roles, and domains: isolating modules in one database
The first reason teams split a backend into microservices is fear that one service might accidentally break another's tables. Inside PostgreSQL, you can draw that boundary with schemas and roles that control access down to individual columns.
The idea is simple: all financial tables live in a dedicated finance schema, and the app connects as the finance role. You grant basic access first, then strip away anything risky. For example, completed transactions have UPDATE and DELETE completely revoked, because an accounting entry can't be edited after the fact—only offset by a new one. On the finance.transfer table, the app role can insert only core fields (account details and amount) and update only the status column. The database itself manages the transfer's time period, so the app can't touch it directly.
The second building block is DOMAIN. In PostgreSQL, a domain is a custom data type over text or a number with a CHECK constraint baked in. Instead of duplicating regexes across tables and services, you define account formats and valid statuses once at the schema level:
-- Separate schema and app role for the finance module
create schema finance;
create role finance;
grant usage on schema finance to finance;
-- Domains enforce strict format rules inside the DBMS
create domain finance.routing_number as text
check (value ~ '^[0-9]{9}$');
create domain finance.account_number as text
check (value ~ '^[0-9]{12}$');
create domain finance.transfer_status as text
check (value in ('pending', 'returned', 'completed'));
Now any finance.routing_number column physically rejects an eight-digit string or a stray space, even if someone runs a manual query from a console or migration script. The same goes for transfer statuses: valid states are locked down in one place.
Accounts in this banking model split into two disjoint worlds: managed_active_account (accounts owned by our system) and external_account (accounts at other banks). You can freeze a managed account and reopen it later, so it has an active period. External accounts don't have that period because we don't control another bank.
The same account number must never be both managed and external. The schema enforces this with two cross-table CHECK constraints backed by SQL functions not_external_account and not_managed_account, added via ALTER TABLE after creating both tables. There is a practical caveat here: PostgreSQL docs advise against querying other tables inside CHECK constraints because row loading order during a pg_dump restore can break them. In production, it's safer to keep a single account ID table with a type flag (managed or external) and reference it with a composite foreign key.
PostgreSQL 18 temporal keys and auditing without event-sourcing pipelines
The second common worry is that a relational table only holds current state, while you need a full audit trail of every transfer. That's usually when teams reach for event sourcing with queues, projections, and schema migration headaches.
In PostgreSQL 18, you can split history into two clear layers: application time (business time) and system time.
Patent-style blueprint of two time layers in PostgreSQL 18: business intervals using WITHOUT OVERLAPS and PERIOD at the top, and automatic copying of old row versions into a system log at the bottom.
Application time tracks when an entity was valid in the real world. For example, a managed account was active from January to March, closed, and reopened in May. PostgreSQL 18's headline feature is native support for temporal keys with WITHOUT OVERLAPS and PERIOD. Previously, preventing overlapping intervals meant writing EXCLUDE USING gist by hand, and temporal foreign keys didn't exist in SQL syntax at all. Now it's declarative. You just need the standard btree_gist contrib extension, which lets a single GiST index combine scalar columns with time ranges (and comes built into AWS RDS):
-- Extension needed so GiST indexes work with scalar keys
create extension if not exists btree_gist;
create table finance.managed_active_account (
routing_number finance.routing_number not null,
account_number finance.account_number not null,
account_name text not null,
account_active_period tstzrange not null
default tstzrange(now(), 'infinity', '[)'),
-- Prevents overlapping active periods for the same account
primary key (
routing_number,
account_number,
account_active_period without overlaps
)
);
create table finance.transfer (
transfer_period tstzrange not null
default tstzrange(now(), 'infinity', '[)'),
-- PG 18 generated columns default to VIRTUAL; PKs require STORED
transfer_created_at timestamptz
generated always as (lower(transfer_period)) stored,
account_number finance.account_number not null,
routing_number finance.routing_number not null,
counterparty_account_number finance.account_number not null,
counterparty_routing_number finance.routing_number not null,
amount bigint not null,
status finance.transfer_status not null default 'pending',
primary key (
routing_number, account_number, transfer_created_at,
counterparty_routing_number, counterparty_account_number
),
foreign key (
counterparty_routing_number, counterparty_account_number
) references finance.external_account (
routing_number, account_number
),
-- Temporal FK: transfer must fit inside the account's active period
foreign key (
routing_number, account_number, period transfer_period
) references finance.managed_active_account (
routing_number, account_number, period account_active_period
)
);
Notice two subtle details here. First, the temporal FOREIGN KEY with PERIOD guarantees at the engine level that transfer_period sits completely inside account_active_period. You can't run a transfer on an inactive account, and you can't retroactively shrink an active period so a live transfer hangs in limbo. Second, transfer_created_at is derived from the lower bound of transfer_period with an explicit STORED modifier. In PostgreSQL 18, generated columns default to VIRTUAL, and virtual columns can't be part of a primary or foreign key yet—so STORED is required.
The second layer is system time, which answers "what did this row look like on Tuesday at 14:05?" The Postgres ecosystem has the C extension temporal_tables for this, but managed clouds like AWS RDS, Cloud SQL, and Azure block custom C modules. The workaround is the pure PL/pgSQL port nearform/temporal_tables. It ships as a plain SQL script versioning_function.sql (plus versioning_function_nochecks.sql, which runs roughly twice as fast by skipping extra checks) and deploys to any cloud database in a second.
-- Add system period and mirror table for status history
alter table finance.transfer
add column sys_period tstzrange not null
default tstzrange(current_timestamp, null);
create table finance.transfer_status_log (like finance.transfer);
alter table finance.transfer_status_log
add primary key (
routing_number, account_number, transfer_created_at,
counterparty_routing_number, counterparty_account_number,
sys_period
);
-- Trigger automatically copies the old row version on every UPDATE
create trigger transfer_save_status_history
before insert or update or delete on finance.transfer
for each row execute procedure
versioning('sys_period', 'finance.transfer_status_log', true);
The same trigger goes on managed_active_account with managed_active_account_log, leaving a permanent trail whenever an account is frozen or reopened. Alongside them sit two transaction tables: finance.settled_transaction and finance.pending_transaction. Both are made strictly immutable via REVOKE UPDATE, DELETE on the app role. No separate event store is needed: current state stays in the main tables, full change history flows into *_log, and transactions are never overwritten.
State machine and business invariants inside the engine
When transition logic is scattered across three services, one of them will eventually revert a completed payment to pending or attach a hold to a closed transfer. In this ledger, the state machine lives in a BEFORE UPDATE trigger on finance.transfer. A transfer starts as pending with an open period [now(), infinity) and can only move to completed or returned. Any attempt to move it out of a final state throws an exception immediately.
create or replace function finance.enforce_transfer_state_machine()
returns trigger language plpgsql as $$
begin
if OLD.status = NEW.status then
return NEW;
end if;
if OLD.status = 'pending' then
if NEW.status not in ('completed', 'returned') then
raise exception 'Недопустимый переход: pending -> %', NEW.status;
end if;
-- Close the upper bound of the period with current transaction time
NEW.transfer_period :=
tstzrange(lower(OLD.transfer_period), now(), '[]');
elsif OLD.status in ('completed', 'returned') then
raise exception 'Финальный статус % нельзя сменить на %',
OLD.status, NEW.status;
end if;
return NEW;
end;
$$;
-- Prefix transfer_z_ ensures execution AFTER the history trigger
create trigger transfer_z_enforce_state_machine
before update of status on finance.transfer
for each row when (OLD.status <> NEW.status)
execute function finance.enforce_transfer_state_machine();
Notice the odd trigger name: transfer_z_enforce_state_machine. That's not a typo—it's a trick based on PostgreSQL mechanics. All BEFORE triggers on a table fire in strict alphabetical order. The audit trigger is named transfer_save_status_history. Because of the z, the audit trigger runs first to save the old row version, and only then does the state machine validate the transition and close transfer_period.
A state machine alone isn't enough; you also need to link transfers with transaction tables. Three groups of deferred constraint triggers (CREATE CONSTRAINT TRIGGER ... DEFERRABLE INITIALLY DEFERRED) handle this at COMMIT time:
- Time window check:
transaction_created_aton any transaction must fall inside the parent transfer'stransfer_period(v_transfer_period @> NEW.transaction_created_at). - Status match:
pending_transactioncan only be inserted into apendingtransfer, whilesettled_transactionrequires a transfer that has already leftpending. - No dangling future transactions: you can't close a transfer if it already has transactions with timestamps greater than
now().
These rules produce a neat side effect. When a transfer completes and creates its final settled_transaction, both statements must run in the same SQL transaction. Why? In PostgreSQL, now() returns the start time of the current transaction. The state machine closes the transfer period at now(), and the new settled_transaction gets the exact same now() in transaction_created_at. Because the range uses inclusive brackets '[]', the @> check passes cleanly. Split UPDATE and INSERT into separate transactions, and the new entry's timestamp lands milliseconds after the transfer closed—so the database rejects it.
Try the simulator below to see this in action. It reproduces the ledger's core behavior: status transitions, closing the time window, audit logging, and the gap between current and available balances.
Financial ledger simulator: transfer state machine and two balances
Try completing a transfer in the simulator and then clicking "Pending hold" or "Returned". In a real database, that's the exact point where the deferred pending_transaction_requires_pending_transfer trigger and enforce_transfer_state_machine block invalid data from ever hitting disk.
How much memory you actually need and how HOT updates speed up writes
The third common fear is write speed and database size. It feels like tens of millions of banking operations will instantly overflow RAM and knock a single Postgres server flat. Before buying a cluster, let's do the math on the real working set—the hot data that needs to fit in shared_buffers.
A bank transfer typically clears in one to two business days (international wires can take up to five days, but most settle within a two-day window). That means keeping the last two days of transfers and transactions in hot memory is enough.
Let's look at the size of the widest row in finance.transfer (excluding memory alignment padding):
Byte breakdown of a single finance.transfer row
The chart makes it clear that more than half of the row width goes to the two tstzrange ranges and the mandatory tuple header. The amount, timestamp, and status take very little space. Rows in transfer_status_log weigh the same, and transaction tables are even leaner at around 120 bytes since they have no status or period.
Now let's estimate the full footprint of one transfer: one row in transfer, an average of two rows in the status log (insert plus final transition), and three transactions (two holds and one settlement). Add indexes: each table has a single primary key B-tree index, and a five-column composite key adds roughly 40% overhead (a 1.4 multiplier). Total footprint per transfer lifecycle: ((3 * 160) + (3 * 120)) * 1.4 = 1,176 bytes.
Here is what a two-day hot working set looks like across three very different business scales:
| Business scale | Transfers per day | 2-day working set | Fits in one RDS node's RAM (up to 4 TB)? |
|---|---|---|---|
| Typical startup | 10,000 | 22 MB | Easily, with massive headroom on any server |
| Large neobank (Nubank scale) | 50,000,000 | 110 GB | Fits comfortably in a single node's RAM |
| Global processor (Visa scale) | 900,000,000 | 1.9 TB | Fits in a top-tier instance |
Those numbers are sobering. On managed AWS RDS for PostgreSQL, the top instance class (db.x2iedn.32xlarge) offers 128 vCPUs and 4,096 GiB (4 TB) of RAM on NVMe. Even a large neobank's workload fits in one node's memory, and a startup's entire two-day working set weighs as much as a few phone photos.
Memory is only half the story. On writes, Postgres often slows down due to write amplification: when you update a single status field, MVCC creates a new physical version of the entire row and rewrites pointers in every index on the table. That bloats the WAL and gives VACUUM extra work.
The built-in cure is Heap-Only Tuples (HOT). HOT works when two conditions hold: the UPDATE touches no indexed columns, and there is free space left on the same 8 KB table page. Postgres then writes the new row version onto the same page, links it internally from the old version, and skips updating indexes altogether.
In finance.transfer, the primary key uses only immutable columns (routing_number, account_number, transfer_created_at, and counterparty details). Neither status nor transfer_period is indexed. All you need to do is reserve free space on each page and monitor for unused indexes:
-- Leave 30% free space on each 8 KB page for HOT chains
alter table finance.transfer set (fillfactor = 70);
-- Find dead indexes: anything with idx_scan = 0 slows writes for nothing
select
schemaname,
relname,
indexrelname,
idx_scan,
idx_tup_read,
idx_tup_fetch
from pg_stat_user_indexes
where schemaname = 'finance'
order by idx_scan;
Combining fillfactor = 70 with unindexed mutable fields turns status updates into HOT updates. Those updates run 2–3× faster, avoid index bloat, and sharply cut WAL volume. Checking pg_stat_user_indexes keeps the database healthy: an index with zero idx_scan helps zero reads while slowing every insert and blocking HOT. Alongside it, n_tup_hot_upd versus n_tup_upd in pg_stat_all_tables shows what share of updates actually took the fast path.
Fast OLTP and live OLAP on one table without Redis or ClickHouse
So writes are fast. What about the two main read patterns: a paginated transfer feed (OLTP) and instant balance lookups at any point in the past (OLAP)?
Start with the activity feed. The most common backend mistake is OFFSET pagination. It has two built-in flaws: as new transfers arrive while a user scrolls, row offsets shift and cause duplicates or skipped items. Worse, the deeper the page, the more rows the database has to read and discard.
Instead, you use keyset (cursor) pagination, which is where the column order in finance.transfer's composite primary key pays off. routing_number and account_number come first as the most selective account filter, followed immediately by transfer_created_at. To fetch a page, Postgres jumps straight to the right B-tree slice by account number and walks backward from the last shown timestamp:
Studio still life of a stack of immutable balance_ledger snapshot cards with a quick-lookup index bookmark, operating without external cache services.
-- Keyset pagination: response time stays flat even on page 1,000
select *
from finance.transfer
where routing_number = $1
and account_number = $2
and transfer_created_at < $3
order by transfer_created_at desc
fetch first 10 rows only;
To assemble a transfer's full history—current state, all past statuses from the log, and linked pending and settled transactions—you combine all four tables in a single finance.transfer_activity view using UNION ALL with a kind tag. Each branch hits its primary key, so fetching a transfer's timeline takes milliseconds.
Balances are trickier. Running SUM(amount) across all historical transactions on every request turns into a heavy scan of millions of rows as the database grows. That's usually where teams pull in Redis or a separate analytics database.
The relational answer is to shift that work from read time to write time, just like incremental materialized views. You create an immutable snapshot table finance.balance_ledger. Whenever a new transaction arrives, an AFTER INSERT trigger grabs the latest balance row for that account, adds the new amount, and appends a new snapshot:
create table finance.balance_ledger (
routing_number finance.routing_number not null,
account_number finance.account_number not null,
as_of timestamptz not null,
current_total bigint not null,
available_total bigint not null,
primary key (routing_number, account_number, as_of)
);
revoke update, delete on finance.balance_ledger from finance;
-- Trigger on settled_transaction updates both balances
create or replace function finance.update_balance_on_settled()
returns trigger language plpgsql as $$
declare
v_current bigint;
v_available bigint;
begin
select current_total, available_total
into v_current, v_available
from finance.balance_ledger
where routing_number = NEW.routing_number
and account_number = NEW.account_number
order by as_of desc
limit 1;
if not found then
v_current := 0;
v_available := 0;
end if;
insert into finance.balance_ledger (
routing_number, account_number, as_of,
current_total, available_total
) values (
NEW.routing_number, NEW.account_number, NEW.transaction_created_at,
v_current + NEW.amount, v_available + NEW.amount
);
return NEW;
end;
$$;
create trigger settled_update_balance
after insert on finance.settled_transaction
for each row execute function finance.update_balance_on_settled();
pending_transaction gets an almost identical pending_update_balance trigger, except it leaves v_current untouched and only shifts v_available + NEW.amount. As a result, asking "what was this customer's balance yesterday at 23:59?" stops being an aggregation over millions of rows and becomes a single index lookup:
-- Historical balance at any point in time in O(log N)
select current_total, available_total
from finance.balance_ledger
where routing_number = $1
and account_number = $2
and as_of <= $3
order by as_of desc
fetch first 1 row only;
To get the live balance right now, you simply drop and as_of <= $3. The database pulls one row from the top of the index—faster than a network round-trip to Redis, with zero risk of cache drift.
SERIALIZABLE isolation: four race conditions that break balances under load
If you leave this entire design on PostgreSQL's default READ COMMITTED isolation level, concurrent traffic will quietly corrupt balances. The reason is simple: both the constraint triggers and the incremental balance calculation follow a read-then-write pattern.
Under READ COMMITTED, two concurrent transactions can read the same snapshot before either commits, and both will make decisions on stale state. Four real race conditions blow up here:
- Lost balance update: Two concurrent
settled_transactioninserts for the same account both readcurrent_total = 1000and insert newbalance_ledgerrows with1000 + amount, overwriting each other. - Late pending entry: A
pendingtransaction slips into a closing transfer because thestatus = 'pending'check passed a millisecond before another transaction marked itcompleted. - Out-of-bounds timestamp: A transaction lands outside
transfer_periodbecause a parallel connection closed the period first. - Premature close: A transfer closes while a parallel transaction inserts an entry stamped later than the close time.
All four are classic write skew. Relying on developers to set strict isolation per query in application code is risky—one forgotten annotation in a new endpoint opens an accounting hole. That's why SERIALIZABLE isolation (SSI) is enforced at the database role level (ALTER ROLE finance SET default_transaction_isolation = 'serializable').
Writing through transfer_activity and the 766 TPS benchmark
Earlier we built the finance.transfer_activity view to read the unified feed of transfers and transactions. Now we can turn it into a single write entry point too, using INSTEAD OF triggers:
-- Route inserts from the unified view into base tables
create or replace function finance.transfer_activity_insert()
returns trigger language plpgsql as $$
begin
case NEW.kind
when 'transfer' then
insert into finance.transfer (
routing_number, account_number,
counterparty_routing_number, counterparty_account_number, amount
) values (
NEW.routing_number, NEW.account_number,
NEW.counterparty_routing_number,
NEW.counterparty_account_number, NEW.amount
);
when 'pending_transaction' then
insert into finance.pending_transaction (
routing_number, account_number, counterparty_routing_number,
counterparty_account_number, transfer_created_at, amount
) values (
NEW.routing_number, NEW.account_number,
NEW.counterparty_routing_number,
NEW.counterparty_account_number, NEW.created_at, NEW.amount
);
when 'settled_transaction' then
insert into finance.settled_transaction (
routing_number, account_number, counterparty_routing_number,
counterparty_account_number, transfer_created_at, amount
) values (
NEW.routing_number, NEW.account_number,
NEW.counterparty_routing_number,
NEW.counterparty_account_number, NEW.created_at, NEW.amount
);
else
raise exception 'Неизвестный тип операции: %', NEW.kind;
end case;
return NEW;
end;
$$;
create trigger transfer_activity_insert_trigger
instead of insert on finance.transfer_activity
for each row execute function finance.transfer_activity_insert();
A matching INSTEAD OF UPDATE trigger routes status updates on rows with kind = 'transfer' to finance.transfer and blocks any edits to transactions or history. Your application works with one flat transfer_activity stream—no network hops, no cross-service JSON serialization, and no distributed transaction headaches. If you ever need to split a base table or rename a column, you update the view and its triggers in one place.
How much does all this machinery—triggers, temporal keys, auditing, and live balances—cost in performance? To find out, the schema was benchmarked with pgbench on PostgreSQL 18.4 (released May 14, 2026) on a regular developer laptop.
The database was seeded with 100 managed and 100 external accounts and run for 60 seconds (--no-vacuum, 10 concurrent clients, 4 threads) at an 80% read / 20% write ratio. The read script fetched the latest 20 entries from the UNION ALL transfer_activity view plus the current balance from balance_ledger. The write script ran a full transfer lifecycle through the updatable view: creating a transfer, inserting a pending_transaction, then completing the transfer to completed and inserting a settled_transaction in one transaction with all triggers, history, and balance updates.
# 60-second run: 80% reads (@4) and 20% writes (@1)
pgbench -h localhost -p 54321 -U admin -d blog \
--no-vacuum \
-f pgbench_read.sql@4 \
-f pgbench_write.sql@1 \
-c 10 -j 4 -T 60 -P 5
In one minute, the laptop processed 45,985 transactions at 766.15 TPS with zero errors (36,793 reads and 9,191 full write lifecycles). A startup baseline of 10,000 transfers per day is about 0.12 TPS, so even a local laptop showed more than 6,000× headroom. Here is the latency breakdown:
pgbench latencies (PostgreSQL 18.4, 10 clients, 60s)
Reading across four tables plus a balance lookup stays well within interactive response times, and a full write with business rules, auditing, and live ledger updates remains fast and predictable—on a laptop, not even a dedicated cloud box.
Before rolling this out to production, keep three real limits in mind:
as_ofcollisions inbalance_ledger. The primary key(routing_number, account_number, as_of)relies onnow(). If one SQL transaction inserts two entries for the same account,now()returns the same timestamp and the second insert fails with a unique violation. If your business logic allows batch entries per account in one transaction, add a sequencebigintcounter to the key.- Page rebuilds after
fillfactor = 70. RunningALTER TABLE ... SET (fillfactor = 70)only affects new pages and leaves existing ones packed tight. On a table with existing data, you must rebuild it withpg_repack,CLUSTER, orVACUUM FULLfor HOT updates to kick in. - Benchmark caveats and hot accounts. The
pgbenchrun above connected asadmin(whereasSERIALIZABLEwas set on thefinancerole), and 10 clients spread evenly across 100 accounts—so there were zero serialization rollbacks. Once you introduce a hot system fee account or a large merchant hit by dozens of concurrent threads,SQLSTATE 40001retries will spike, making a proper retry loop with exponential backoff and jitter mandatory in your app.
Dedicated tools like Kafka, Redis, and ClickHouse still earn their keep when you hit petabyte-scale analytics, multi-region writes, or extreme contention on a single hot key. Until your metrics hit those ceilings, a single PostgreSQL 18 instance handles auditing, state machines, fast writes, and live balances without extra infrastructure.


