BBackend CourseLeroy Labs
0/0
Search the course

Scaling data with replication, partitioning, sharding & load balancing

Load balancer algorithms, read replicas and replication lag, Postgres declarative partitioning, sharding strategies and their pain, and the order in which to reach for each.

● expert

Load balancing

Algorithm Notes
Round robin Simple; ignores load
Least connections Good for uneven request durations (exports, SSE)
Weighted Different instance sizes
IP hash / sticky Session affinity, which breaks even distribution
Consistent hashing Cache-friendly; minimal reshuffling when nodes change

There are L4 load balancers (TCP: NLB) and L7 ones (HTTP-aware: ALB, Nginx, Envoy, which can route by path or header and terminate TLS).

The scaling ladder (in order)

  1. Indexes and query fixes (EXPLAIN ANALYZE, next lesson). That’s free and gives 10–1000× gains.
  2. Connection pooling (PgBouncer) and caching (Redis, CDN).
  3. A bigger box (vertical). Modern Postgres handles terabytes and tens of thousands of transactions per second on one node.
  4. Read replicas for read-heavy load.
  5. Partitioning very large tables.
  6. Sharding, as a last resort.

Read replicas

The primary streams WAL to replicas, and reads go to replicas.

  • Replication lag. A user writes, then reads from the replica and doesn’t see their change. The fixes:
    • Route a user’s reads to the primary for N seconds after a write (read-your-writes).
    • Route by @Transactional(readOnly = true) with care.
    • Show freshness timestamps.
  • In Spring, use an AbstractRoutingDataSource keyed on read-only transactions, or LazyConnectionDataSourceProxy.

Partitioning (one DB, split tables)

CREATE TABLE audit_logs (
  id uuid, company_id uuid, occurred_at timestamptz NOT NULL, ...
) PARTITION BY RANGE (occurred_at);

CREATE TABLE audit_logs_2026_11 PARTITION OF audit_logs
  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
  • Partition pruning. WHERE occurred_at > now() - interval '7 days' scans only the recent partitions.
  • Retention becomes instant. DROP TABLE audit_logs_2024_10 replaces a giant DELETE that causes bloat and long locks. That would be a big win for RM’s 24-month audit purge and IR3D’s activity logs.
  • Partition types: RANGE (time), LIST (region), HASH (spread evenly). pg_partman automates creating partitions.

Sharding (many DBs)

Split data across separate database servers by a shard key:

Strategy Pro Con
By tenant (company_id), as SperoTek could Tenant queries stay on one shard Hot tenants; rebalancing
Hash of key Even spread Range queries hit every shard
Range / geography Locality Hotspots
Directory (lookup table) Flexible An extra hop, and the directory can become a single point of failure

What you lose: cross-shard joins, cross-shard transactions, global unique constraints, and easy resharding. Citus (Postgres extension), Vitess (MySQL), and distributed SQL databases (CockroachDB, YugabyteDB, Spanner, Aurora Limitless) reduce the pain.

Check yourself

1. First thing to try when the DB is slow?
2. Dropping old monthly partitions instead of DELETE avoids…
3. User updates profile then sees old data. Likely cause?