HomeBlogHow to Handle Millions of Database...

Engineering Guide · 9 min read · October 30, 2026

How to Handle Millions of Database Records Efficiently

Most relational databases handle 10 million to 100 million rows comfortably on a single well-tuned primary—until offset pagination, oversized B-tree indexes, and blocking schema migrations bring writes to a halt. Scaling efficiently comes down to bounded queries, table partitioning, online migrations, and disciplined data retention.

Author
Smit Desai
Published
October 30, 2026
Read time
9 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

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:

  1. Index working set spills to disk: A wide UUID or unselective secondary index bloats beyond the buffer pool, turning random lookups into disk reads.
  2. 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.
  3. 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:

  1. 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.
  2. Create indexes concurrently: Use CREATE INDEX CONCURRENTLY in PostgreSQL (outside a transaction block) or online schema change tools like gh-ost / pt-online-schema-change in MySQL.
  3. Add constraints as NOT VALID first: In PostgreSQL, add foreign keys or CHECK constraints with NOT VALID, then execute VALIDATE CONSTRAINT in a separate step that takes a lighter share lock while letting reads and writes continue.
  4. 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

At how many rows do we need to shard PostgreSQL or MySQL?

Rarely at 5 million or even 50 million rows. Proper indexing, connection pooling, read replicas, and time-based partitioning routinely carry a single primary database past hundreds of millions of rows before horizontal sharding makes economic sense.

Why does OFFSET pagination break down on large tables?

OFFSET 100000 forces the database engine to scan and discard 100,000 index or heap rows on every page turn. Keyset (cursor) pagination seeks directly to the last seen tuple in constant time.

How do we add a column or index to a 40-million-row production table without downtime?

Use non-blocking index creation (CREATE INDEX CONCURRENTLY in PostgreSQL or ALGORITHM=INPLACE / gh-ost in MySQL), add nullable columns without heavy table rewrites, and backfill data in throttled batches.

Should we delete old records or partition and archive them?

Deleting millions of rows in one DELETE statement locks rows and causes severe vacuum/undo bloat. Range-partition by month or quarter so old partitions can be detached and archived to cold object storage instantly.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.