Skip to main content

Scaling Payment Platforms

Last Updated: 2026-12-01 Status: Complete

Scaling payment platforms is different from scaling a content site: correctness comes before throughput, and the parts that must be strongly consistent (balances, idempotency state) are exactly the parts that are hardest to scale out. After this page you should be able to relieve a ledger hot account, choose between partitioning and sharding, decide what may be read from a replica or cache, and plan for the peaks that payments actually have.

Quick Reference​

ConcernDefault position
ConsistencyStrong for balances, idempotency and payout decisions. Eventual is fine for reporting and dashboards
API tierStateless, scale out
Ledger databaseThe hard part: vertical first, then partition, then shard
Hot accountSub-accounts, batched or asynchronous posting where nothing gates on the balance
ReplicasReports and exports only; never payout or balance decisions
CachesReference data only (BIN tables, versioned fee schedules, configuration)
QueuesAbsorb bursts from settlement files, webhook fan-out and payout batches, with backpressure
Capacity targetsYour own decision, based on measured load tests

What Is Different About Scaling Payments?​

Three properties shape every decision:

  1. A lost or duplicated write is money. You cannot drop writes under load or accept stale reads to protect latency, the way a feed might.
  2. Consistency is local. A merchant's balance needs strong consistency; the platform's monthly report does not. Scale by finding the smallest scope that needs it, usually one merchant or one account.
  3. Load is spiky and predictable. Holiday sales, month-end payouts and the arrival of a large settlement file are known in advance. You can plan for them.

So the strategy is: keep the transactional core small and correct, and push everything else (reporting, search, analytics, notifications) onto asynchronous or eventually consistent paths.

How Do You Fix a Ledger Hot Account?​

A hot account is one that nearly every transaction touches, such as the platform's fee revenue account or a clearing account. If every posting updates that account's balance row or takes a lock on it, concurrent transactions queue behind each other and throughput is limited by that single row.

TechniqueHow it worksTrade-off
Sub-account shardingSplit one logical account into N physical sub-accounts (fee_revenue:0 to fee_revenue:N-1) and pick one by hash of the payment id. The logical balance is the sumReads sum N rows; balance guards on the logical account become harder
Batched or aggregated postingsCollect many small postings and post one aggregated entry per interval, keeping the detail in a side tableEntry is later than the transaction; detail must still tie to the aggregate
Asynchronous postingRecord the fee to a queue or outbox in the same transaction as the payment, and post to the revenue account from a workerRevenue balance lags slightly
Derived balancesDo not store a running balance on the hot row; compute from lines, with periodic snapshots. See BalancesReads cost more, so cache snapshots carefully

The rule that makes this safe: only defer postings to accounts that nothing gates on. A revenue account has no overdraft check, so its posting can be asynchronous. A merchant's available balance gates payouts, so postings that affect it stay synchronous in the same transaction as the business event. Never make an account that guards a spending decision eventually consistent.

Keep the double-entry invariant when deferring: the paired entry (for example, the merchant payable side) is posted synchronously and the difference sits in a clearing account until the worker catches up. That account should return to zero, and a nonzero age is a metric. See Double-Entry Ledger and Ledger Reconciliation.

A Batched Posting Worker in NestJS​

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { DataSource } from 'typeorm';

@Injectable()
export class FeePostingWorker {
private readonly logger = new Logger(FeePostingWorker.name);
constructor(private readonly dataSource: DataSource) {}

@Cron(CronExpression.EVERY_10_SECONDS)
async flush(): Promise<void> {
await this.dataSource.transaction(async (manager) => {
// Claim a batch; SKIP LOCKED lets several workers run without blocking each other.
const rows: { id: string; currency: string; amount: string }[] = await manager.query(
`SELECT id, currency, amount FROM pending_fee_postings
WHERE posted_at IS NULL ORDER BY id LIMIT 1000 FOR UPDATE SKIP LOCKED`,
);
if (rows.length === 0) return;

const totals = new Map<string, bigint>();
for (const r of rows) {
totals.set(r.currency, (totals.get(r.currency) ?? 0n) + BigInt(r.amount));
}
for (const [currency, total] of totals) {
// One aggregated, balanced entry per currency: debit clearing, credit fee revenue.
await this.postEntry(manager, currency, total);
}
await manager.query(
`UPDATE pending_fee_postings SET posted_at = now() WHERE id = ANY($1)`,
[rows.map((r) => r.id)],
);
this.logger.log({ event: 'fee_batch_posted', count: rows.length });
});
}

private async postEntry(manager: DataSource['manager'], currency: string, total: bigint) {
// Insert journal entry and two lines, with a deterministic idempotency key per batch.
}
}

Because claiming, posting and marking happen in one transaction, a crash re-runs the batch without double posting. Export the number of pending rows and the age of the oldest as metrics; see Observability.

How Do You Scale the Database?​

A common question is how you would scale the transaction database. Order the options by cost and risk:

  1. Vertical first. A bigger machine, tuned queries and the right indexes take most platforms a long way and add no consistency risk. Do this before distributing anything.
  2. Partitioning (one database, many physical tables). Partition large append-heavy tables, such as transactions and ledger lines, by time range, for example monthly. Benefits: queries filtered by time touch only the relevant partitions (partition pruning), maintenance such as vacuum and index builds is per partition, and old partitions can be detached and archived without a long delete.
  3. Sharding (many databases). Needed only when one primary cannot take the write load or the data size. Choose a shard key that keeps a merchant's ledger together, typically the tenant or merchant id, so that a balance check and its postings stay on one shard and a transaction never spans shards. A sharding key such as payment id spreads load evenly but scatters a merchant's balance across shards, which makes strong balance checks expensive.
-- Time-range partitioned ledger lines (PostgreSQL declarative partitioning)
CREATE TABLE ledger_lines (
id bigint GENERATED ALWAYS AS IDENTITY,
tenant_id uuid NOT NULL,
entry_id uuid NOT NULL,
account_id uuid NOT NULL,
side text NOT NULL CHECK (side IN ('debit','credit')),
amount bigint NOT NULL CHECK (amount > 0),
currency char(3) NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at) -- the partition key must be part of the key
) PARTITION BY RANGE (created_at);

CREATE TABLE ledger_lines_2026_12 PARTITION OF ledger_lines
FOR VALUES FROM ('2026-12-01 00:00:00+00') TO ('2027-01-01 00:00:00+00');

-- Optional safety net: rows that match no partition land here instead of failing.
CREATE TABLE ledger_lines_default PARTITION OF ledger_lines DEFAULT;

CREATE INDEX ON ledger_lines (tenant_id, account_id, created_at);

Use explicit UTC offsets in range bounds: a bare date literal on a timestamptz column is interpreted in the session time zone. Inserts fail when no partition matches, so pre-create future partitions with a scheduled job and alert if fewer than your chosen number remain, or keep a default partition as a safety net (and watch it, because rows in it must be moved before a matching partition can be attached).

Partitioned tables have rules that matter for payments: a unique constraint must include the partition key, so a uniqueness guarantee on something like an idempotency key must live in an unpartitioned table (or include the time column). Idempotency keys are small and recent, so keep them in their own table with a retention job.

Cross-shard concerns. Platform-level questions (total volume, revenue across all merchants) cross shards. Do not run them on the shards. Stream events into a warehouse or a CQRS read model, and accept that those numbers are eventually consistent. Cross-merchant operations such as a transfer between two merchants on different shards need a saga or an intermediate platform account, not a distributed transaction; design the shard key so that these are rare. See Event-Driven Architecture.

What Can You Read from a Replica or Cache?​

Replicas replicate asynchronously by default, so a read can be behind the primary by the replication lag. Use replicas for reports, exports, dashboards and search. Never base payout or balance decisions on a replica: a stale balance can allow an overdraft or a double payout. Decision paths read the primary, inside the transaction that acts on the result. See Balances. Monitor replication lag and have reporting code show a freshness timestamp.

Caches are for data that changes rarely and tolerates brief staleness:

Cache itWhy it is safe
BIN tablesUpdated on a known schedule; version them
Fee schedules, by versionA payment records the schedule version it used, so a cached older version still produces a correct, explainable calculation. See Fee Engine
Configuration, routing rules, feature flagsChanges propagate within a short interval
Public keys and processor metadataRarely change
Never cache for decisionsWhy
BalancesStaleness causes overdrafts
Idempotency stateA stale miss allows a duplicate side effect
Payment status used to authorize an actionThe state machine must read the source of truth

How Do Queues and Backpressure Protect the Platform?​

Bursts arrive in three places: a large settlement file with millions of lines, a webhook event that fans out to thousands of endpoints, and a payout batch. Put a queue between the arrival and the work, process at a controlled rate, and make the rate adjustable.

  • Settlement-file ingestion: split the file into chunks, ingest in parallel with bounded concurrency, and gate reconciliation on completion. See Settlement Files.
  • Webhook fan-out: one outbox event becomes one delivery job per subscribed endpoint, with per-endpoint concurrency limits so one slow customer cannot consume all workers. See Webhooks.
  • Payout batches: process in bounded batches, and stop on rail errors rather than retrying into a failing bank file. See Payouts.
  • Outbound throttling toward processors: use client-side rate limiting and a concurrency limiter so a burst on your side does not trigger the processor's own throttling. Check your processor's documented limits and agree increases before peak.

Backpressure means upstream slows down when downstream is full: bounded queues, pause consumers when a dependency is unhealthy, return 429 or 503 with a retry hint at the API edge, and shed low-priority work (reports, exports) first. Dead-letter any message that keeps failing, and alert on its age; see DLQ.

Horizontal or Vertical Scaling?​

Horizontal or vertical is not one answer for the whole platform; it depends on the tier:

TierApproachReason
API and workersHorizontal, statelessNo local state; add instances behind a load balancer
Idempotency storeSame database as the ledger or a strongly consistent storeMust be consistent with the write it protects
Ledger databaseVertical, then partition, then shard by merchantA single-writer, strongly consistent store does not scale out by adding nodes
Read models, search, warehouseHorizontal, eventualRebuildable from events

Stateless does not mean free: each added API instance adds database connections, so use a connection pooler and watch connection counts as you scale out.

Why Is This Query Slow? A Transactions Table Example​

A classic interview question: "the transactions table is slow; what do you do?" Work from evidence.

  1. Read the query plan (EXPLAIN (ANALYZE, BUFFERS)) of the slowest queries from your slow-query log. Look for sequential scans, large sorts and row estimates far from reality.
  2. Add a composite index that matches the access path, leading with the tenant and then time, because almost every payments query is "this merchant, recent": CREATE INDEX ON transactions (tenant_id, created_at DESC, id DESC), so that ORDER BY created_at DESC, id DESC is served from the index without a sort.
  3. Use covering indexes (INCLUDE columns) for hot list views so they never touch the table.
  4. Replace offset pagination with keyset pagination. OFFSET 100000 reads and discards 100,000 rows; keyset reads from where the last page ended.
  5. Partition by time so old data stays out of hot indexes, and archive cold partitions.
  6. Move analytics off OLTP. Long aggregations belong on a replica or, better, a warehouse.
  7. Check for bloat, lock waits and missing statistics before blaming hardware.
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';

export interface Page<T> { items: T[]; nextCursor?: { createdAt: string; id: string } }

@Injectable()
export class TransactionQueryService {
constructor(private readonly dataSource: DataSource) {}

async list(tenantId: string, limit: number, cursor?: { createdAt: string; id: string }) {
const rows = await this.dataSource.query(
// created_at::text keeps full microsecond precision for the cursor.
`SELECT id, created_at AS "createdAt", created_at::text AS "createdAtRaw",
amount, currency, status
FROM transactions
WHERE tenant_id = $1
AND ($2::timestamptz IS NULL OR (created_at, id) < ($2::timestamptz, $3::uuid))
ORDER BY created_at DESC, id DESC
LIMIT $4`,
[tenantId, cursor?.createdAt ?? null, cursor?.id ?? null, limit + 1],
);
const hasMore = rows.length > limit;
const items = hasMore ? rows.slice(0, limit) : rows;
const last = items[items.length - 1];
return { items, nextCursor: hasMore ? { createdAt: last.createdAtRaw, id: last.id } : undefined };
}
}

Never round-trip the cursor through a JS Date. PostgreSQL timestamptz has microsecond precision, but the pg driver returns a Date with millisecond precision, so a cursor built from it is truncated and rows sharing the truncated millisecond can be skipped or repeated. Select the timestamp as text, return it unchanged in the cursor, and keep the $2::timestamptz cast in the query.

The (created_at, id) tuple comparison uses the composite index above and gives a stable order even when many rows share a timestamp. Expose the cursor as an opaque token in your API; see Payments API Design.

How Do You Plan Capacity?​

  • Know your peaks. List the events that concentrate load: holiday and promotion sales, month-end and start-of-month payouts, daily settlement-file arrival, chargeback-month cycles, large merchant onboarding. Use your own history from the dashboards in Observability.
  • Load test with production-like data shape. Skew matters: a few merchants generate most volume, so uniformly random test data hides hot accounts and hot partitions. Use your own simulator with configurable latency and error mix (see Testing), never the processor's sandbox.
  • Set a headroom policy. How much spare capacity you keep above the expected peak is a business decision that trades cost against risk. Write it down, review it before each known peak, and tie it to the observed ratio of load to saturation, not to a number from this guide.
  • Find the first bottleneck, then the next. Typical order: connection pool, hot row, index contention, outbound processor limits, queue consumers.
  • Test failure at peak, not only success: failover while at load.
  • Coordinate with dependencies. Processors, sponsor banks and your own customers' webhook endpoints all have limits. Tell them before an expected peak.

Multi-Region Considerations for the Ledger​

The ledger wants a single writer per shard: one region owns writes for a given merchant's shard at a time. Active-active writes to the same account across regions need conflict resolution that money does not tolerate. Common shape: each shard has a primary in one region and a standby in another; failover promotes the standby, and the team decides what to do about any writes not yet replicated (this is a recovery-point decision for the business, not only for engineering). The stateless API tier and read models can run in several regions. Test the failover procedure regularly and decide, in advance, who may trigger it.

Self-Assessment Questions​

1. Which postings may be made asynchronous? Those to accounts nothing gates on, such as fee revenue. Accounts that guard payouts or overdrafts stay synchronous.

2. Why shard by merchant instead of by payment id? So a merchant's balance checks and postings stay on one shard and do not need cross-shard transactions.

3. Why is OFFSET pagination a scaling problem? It reads and discards all skipped rows, so cost grows with page depth. Keyset pagination seeks directly using an index.

References​

Share: