Teams frequently jump straight to distributed NoSQL databases or complex horizontal sharding the moment an operational table crosses ten million rows. In practice, sharding too early introduces distributed transaction headaches, broken joins, and painful reporting code—while a single well-architected PostgreSQL or MySQL instance can comfortably serve tens or hundreds of millions of rows.
When a large database slows down, the root cause is almost never "SQL cannot scale." It is usually unbounded OFFSET queries, B-tree indexes that no longer fit in RAM, unthrottled background deletes, or schema migrations that acquire table locks during business hours.
Why Tables Degrade Between 5 Million and 50 Million Rows
At 100,000 rows, sloppy queries hide inside the buffer pool. Everything sits in memory, so even a sequential scan finishes in milliseconds. Once a table grows past the size of available RAM, three mechanical shifts hit simultaneously:
- Index working set spills to disk: A wide
UUIDor unselective secondary index bloats beyond the buffer pool, turning random lookups into disk reads. - Write amplification: Every extra index on a high-insert event table (
audit_logs,transactions,telemetry) forces the database to update multiple B-tree pages per insert. - Maintenance overhead: Autovacuum (in PostgreSQL) or purge threads (in MySQL InnoDB) fall behind when batch jobs delete or update millions of rows in single transactions.
Before investing in a database migration, check your query profiles against the fundamentals in optimizing slow database queries in Laravel and MySQL and the official PostgreSQL performance tips.
Scaling Techniques Compared: What Works at Each Stage
Choosing the right lever saves months of unnecessary infrastructure rewrites.
| Technique | Operational Complexity | Write Impact | Read Speedup | Ideal Trigger Point |
|---|---|---|---|---|
| Covering / Partial Indexes | Low | Slight write cost per index | High for hot filtered queries | 1M–20M rows with selective WHERE clauses |
| Keyset (Cursor) Pagination | Low | None | Eliminates deep-page degradation | Any endpoint paginating past page 20 |
| Time-Range Partitioning | Medium | Negligible if routed cleanly | High via partition pruning + instant drops | Append-heavy logs/events > 25M rows |
| Read Replicas | Medium | Zero impact on primary | Scales reporting & search reads | High read/write asymmetry or BI load |
| Cold Archival to Object Storage | Medium | Shrinks active working set | Keeps primary fast indefinitely | Compliance retention > active query window |
| Horizontal Sharding | Very High | Scales total write IOPS | Requires shard-aware app queries | > 1B rows or saturated single-node write CPU |
Replace OFFSET With Keyset Pagination
If an admin table or public API uses LIMIT 50 OFFSET 250000, the database still fetches and discards 250,000 rows before returning 50. As the table grows, later pages get linearly slower.
Switch to keyset pagination using a deterministic, indexed tuple such as (created_at, id):
-- Slow: scans and discards 200,000 rows
SELECT id, tenant_id, amount_cents, created_at
FROM ledger_entries
WHERE tenant_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 50 OFFSET 200000;
-- Fast: seeks directly via composite index (tenant_id, created_at DESC, id DESC)
SELECT id, tenant_id, amount_cents, created_at
FROM ledger_entries
WHERE tenant_id = 42
AND (created_at, id) < ('2026-07-14 08:30:00+00', 9812044)
ORDER BY created_at DESC, id DESC
LIMIT 50;
Notice the tie-breaker id inside (created_at, id) < (...). Timestamps collide frequently under burst writes; including the unique primary key guarantees no rows are skipped or duplicated between pages.
Partitioning and Archival for Append-Heavy Tables
Event logs, webhook deliveries, and billing ledgers grow endlessly. Deleting old rows with DELETE FROM webhook_events WHERE created_at < NOW() - INTERVAL '90 days' causes massive lock contention, replication lag, and dead tuple bloat.
Native range partitioning solves retention cleanly:
CREATE TABLE webhook_events (
id BIGINT GENERATED ALWAYS AS IDENTITY,
workspace_id BIGINT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
CREATE TABLE webhook_events_2026_08
PARTITION OF webhook_events
FOR VALUES FROM ('2026-08-01') TO ('2026-09-01');
When August 2026 ages out of your hot window, you do not run a multi-hour DELETE. You run ALTER TABLE webhook_events DETACH PARTITION webhook_events_2026_08 CONCURRENTLY;, dump it to Parquet in S3 for compliance, and drop the standalone table in milliseconds. As outlined in AWS architecture guidance, keeping hot operational storage lean while tiering historical partitions to object storage cuts both backup windows and instance memory bills.
Watch Out for Partition Over-Splitting
Do not create 5,000 daily partitions for a 20-million-row table. Excessive partition counts inflate query planning time. Monthly or quarterly partitions (targeting roughly 10M–50M rows or 5–30 GB per partition) strike the right balance.
Zero-Downtime Migrations and Batch Backfills
On a 50,000-row staging database, ALTER TABLE orders ADD COLUMN status VARCHAR(32) NOT NULL DEFAULT 'pending' runs instantly. On a 60-million-row production table under live traffic, careless DDL or backfill scripts can stall every checkout request waiting behind an ACCESS EXCLUSIVE lock.
Follow a strict four-step migration protocol on large tables:
- Set lock timeouts: Always prepend
SET lock_timeout = '2s';to migration sessions so a blocked DDL statement aborts cleanly instead of queuing every incoming application query behind it. - Create indexes concurrently: Use
CREATE INDEX CONCURRENTLYin PostgreSQL (outside a transaction block) or online schema change tools likegh-ost/pt-online-schema-changein MySQL. - Add constraints as
NOT VALIDfirst: In PostgreSQL, add foreign keys orCHECKconstraints withNOT VALID, then executeVALIDATE CONSTRAINTin a separate step that takes a lighter share lock while letting reads and writes continue. - Throttle bulk backfills: Update rows in chunks of 1,000–5,000 primary keys with a 50–100 ms pause between batches, checking replication lag before starting the next chunk.
import time
def backfill_in_batches(conn, batch_size: int = 2000) -> None:
last_id = 0
while True:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE invoices
SET normalized_currency = UPPER(currency)
WHERE id > %s
AND id <= %s
AND normalized_currency IS NULL
""",
(last_id, last_id + batch_size),
)
updated = cur.rowcount
conn.commit()
if last_id > get_max_invoice_id(conn):
break
last_id += batch_size
# Yield IOPS and allow replicas to catch up
time.sleep(0.05 if updated > 0 else 0.01)
If your platform is struggling with legacy schema bottlenecks or unindexed reporting tables, investing in targeted legacy software upgrades or custom web application architecture pays back far sooner than premature database sharding.
How SmitDev Helps CTOs Scale Production Databases
Across 170+ shipped systems, we regularly step in when growing SaaS and enterprise platforms hit their first 10M–100M row inflection point. Instead of pitching risky full rewrites, we profile production query plans, implement keyset pagination and partitioning, build safe zero-downtime migration pipelines, and validate everything under realistic load.
Whether you need a dedicated principal engineer at $55/day for 8–9 hours of hands-on execution, ongoing $1,999/month delivery, or scoped sprint help via our hourly developer model, we integrate seamlessly with engineering teams across the USA, UK, Europe, UAE, Australia, and Singapore.
Facing growing table sizes, slow migrations, or replica lag? Schedule a technical review with SmitDev and let's stabilize your data tier.