Sub topic 17
Scaling and availability
This chapter assumes you have read the earlier chapters on idempotency, the payment state machine, retries, the transactional outbox, and PSP routing. It also assumes you know basic database replication and load balancing.
A payment system scales under different rules from most web services. Throughput matters, but a wrong answer costs more than a slow one. A double charge or a lost payment is worse than a rejected request. Every scaling decision below favors correctness first and availability second, and tries to keep both.
Where the load comes from
Traffic is spiky. Sales events, payroll runs, and subscription billing dates can multiply the normal rate within minutes. Most of the work is writes: creating payments, changing their state, appending ledger entries, and emitting events. The traffic splits into three kinds:
- Synchronous requests: create, authorize, capture, and refund calls from merchants. These need low latency and strong consistency.
- Asynchronous work: webhook delivery, outbox publishing, reconciliation, and reports. These tolerate delay but must not be lost.
- Reads: status lookups and dashboards. These are numerous but can usually tolerate slightly stale data.
Scale each kind separately. A reporting query should never compete with a capture for the same database connections.
Stateless API tier
Keep the API servers stateless. Each request carries what it needs: the merchant identity, the idempotency key, and the payload. Any server can then handle any request, and you add servers behind a load balancer to scale out. Store no payment state in server memory. Put timeouts and a concurrency limit on every outbound call so one slow PSP cannot use up all your threads.
Scaling the database
The database is the hard part. Replicas, partitioning, and caches each have a role.
Partition by merchant
The unique constraint on (merchant_id, idempotency_key) decides whether a request is new. That check is atomic only inside one database. If you partition by merchant_id, a merchant's payments, ledger entries, and idempotency keys all live on one shard. The check stays a single local statement, and a payment's ledger transaction stays one local transaction. If you partitioned by payment ID instead, the same key could land on different shards and a duplicate could slip through.
Map merchants to a fixed number of virtual buckets, then map buckets to shards. When you add a shard, you move a few buckets and leave the hash function unchanged.
import hashlib
BUCKET_COUNT = 1024
SHARD_COUNT = 4
# bucket -> shard. Rebalancing means editing entries in this map.
bucket_to_shard = {bucket: bucket % SHARD_COUNT for bucket in range(BUCKET_COUNT)}
def bucket_for(merchant_id: str) -> int:
digest = hashlib.sha256(merchant_id.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big") % BUCKET_COUNT
def shard_for(merchant_id: str) -> int:
return bucket_to_shard[bucket_for(merchant_id)]
print(shard_for("0b6f1c9e-5d41-4c1b-9a53-7a1d2f6e8b10"))The cost is the hot merchant. One very large merchant can saturate its shard while the others sit idle. Common mitigations are giving large merchants dedicated shards, or splitting their buckets by a secondary key such as a sub-account. Either choice means a payment's shard is looked up from the merchant's configuration instead of derived from the hash alone.
Replicas and stale reads
Read replicas lag behind the primary. Use them for dashboards and search. Do not use them for the idempotency check, for state transitions, or for any read that decides a write. A replica that has not yet seen a captured status could let a second capture through. For a merchant polling a payment right after creating it, read from the primary, or route that merchant's reads to the primary for a short time after each write.
Caching
Cache data that rarely changes, such as merchant configuration and routing rules. Do not cache payment status as a source of truth, because a stale entry looks like a real answer.
Availability
Availability comes from removing single points of failure at each layer.
- Within a region: run the API tier and database across several availability zones. Use synchronous replication to a standby in another zone, so an acknowledged write exists in two places before the client hears success.
- Across regions: this is harder. Asynchronous replication can lose the most recent writes on failover. After a failover, a client may retry a request whose result was lost. The idempotency record was lost too, so the retry creates a second charge. This risk is why many payment systems accept a short outage over a risky automatic cross-region failover.
- At the PSP layer: one provider is a single point of failure. Routing across several PSPs, covered in the routing chapter, turns a provider outage into a rerouting event. Only reroute when you know the first attempt did not succeed. Otherwise you risk charging twice.
| Layer | Scaling approach | Failure to watch for |
|---|---|---|
| API servers | Add stateless instances | Thread exhaustion from slow dependencies |
| Primary database | Partition by merchant | Hot merchant, cross-shard queries |
| Read replicas | Offload reads and reports | Stale reads used for decisions |
| Outbox and webhooks | Parallel workers per shard | Backlog growth, duplicate delivery |
| PSP connections | Multiple providers, per-PSP limits | Rate limits, correlated outages |
| Cross-region setup | Active-passive with manual promotion | Lost writes on async failover |
Protecting the system under load
A system that is slow because it is overloaded often becomes slower still, because clients retry. Several controls break that cycle.
- Rate limits per merchant: one merchant's bug or spike cannot take down the others. Return a clear
429with a retry hint. - Backoff with jitter: clients use the retry approach from the retries chapter. Without jitter, every client retries at the same instant and creates a retry storm.
- Circuit breakers: after repeated failures from a PSP, stop calling it for a short time, then try a few probe requests. This protects both the PSP and your own threads.
- Load shedding: when saturated, reject low-priority work first. Serve captures and refunds before reports and exports.
- Queues for asynchronous work: webhooks and reports go through queues, so a spike lengthens the queue instead of slowing the payment path.
Common mistakes
- Using the replica for the idempotency check. The check must run on the primary, because it decides whether to write.
- Retrying inside every layer. If the client, gateway, and service each retry three times, one failure becomes 27 attempts. Retry at one layer and pass the idempotency key down.
- Failing over without draining in-flight work. A payment that was mid-authorization when the primary died is in an unknown state. Resolve it by querying the PSP, as the reconciliation chapter describes, before you retry.
- Sizing for average load. Size for the peak, and test it with a load test that includes PSP latency and failures.
Exercise
A payment system partitions its database by payment ID instead of merchant ID. Which guarantee is hard to keep, and why?
Show answer
The idempotency guarantee. The unique constraint on (merchantid, idempotencykey) works only within one database. With payment-ID partitioning, two requests carrying the same key can land on different shards, and neither shard sees the conflict. Partitioning by merchant keeps all of a merchant's keys on one shard, so the atomic check still works.
Exercise
After a cross-region failover, merchants report some customers were charged twice. Give one likely cause and one design choice that reduces the risk.
Show answer
With asynchronous replication, the standby region may lack the most recent idempotency records. When clients retried those requests, the new primary treated them as new payments. To reduce the risk, use synchronous replication for the idempotency and payment tables where latency allows. You can also make PSP-level idempotency keys deterministic, so the PSP rejects the duplicate. A third option is to require manual promotion and reconcile in-flight payments with the PSP before accepting traffic.