DEV Community

AK
AK

Posted on

How We Processed 50,000 Database Records in 15 Seconds with PostgreSQL

Six architectural optimizations that took a batch pipeline from row-by-row bottlenecks to ~3,333 records per second — without blowing up RAM.

Batch processing looks simple on paper: read a file, validate or enrich each row against a database, and write the output file.

In practice, naive implementations hit a wall fast. When you process tens of thousands of records row by row, network round trips pile up, database connection pools saturate, and loading entire files into memory triggers painful Garbage Collection (GC) pauses.

While optimizing a high-volume batch processing pipeline on PostgreSQL, we tuned the architecture to ingest, query, and export 50,000 records in 15 seconds — sustaining roughly 3,333 records per second.

Here is the exact breakdown of the six architectural decisions behind that performance.

— -

1. Bulk Processing Over Row-by-Row Queries

The single biggest killer in batch jobs is treating database calls like single-user API requests:

Record 1 ──► Query DB

Record 2 ──► Query DB

Record 3 ──► Query DB

(50,000 network round trips)

For 50,000 records, this creates 50,000 sequential database round trips. Even if each query takes just 2 milliseconds over the network, you spend 100 seconds waiting purely on network latency before any real work happens.

Instead, we buffer records into chunks of 5,000 and pass each batch into PostgreSQL as a single set-based operation:


— Batch lookup

SELECT lookup_key, status, metadata

FROM target_lookup_table

WHERE lookup_key = ANY($1::text[]);

— Batch insert

INSERT INTO batch_results (lookup_key, processed_at, result_code)

SELECT * FROM UNNEST($1::text[], $2::timestamptz[], $3::varchar[]);

Enter fullscreen mode Exit fullscreen mode

By dividing 50,000 records into chunks of 5,000, we immediately reduced database round trips from 50,000 down to 10.

— -

2. Pre-Query Deduplication

Real-world batch files are rarely clean — they frequently contain duplicate keys across rows. If a single file contains the same lookup key hundreds of times, querying the database for every row wastes I/O and CPU cycles.

Before firing a chunk query to PostgreSQL, the worker deduplicates the lookup keys in memory (e.g., using a hash set) and maps the returned database rows back to the original records afterward:

Raw Input Chunk : 5,000 records

Unique Keys : 2,000 keys ──► Only 2,000 keys sent to PostgreSQL


In datasets with heavy repetition (e.g., 50,000 input records containing only 20,000 unique keys), this cuts database read workload by **60%** before a single SQL statement executes.

— -

## 3. Leaning Into Set-Based PostgreSQL Execution

Relational databases like PostgreSQL are engineered from the ground up to operate on sets of data rather than isolated rows.

Firing 5,000 individual `INSERT` statements forces PostgreSQL to parse, plan, acquire locks, and write Write-Ahead Log (WAL) entries 5,000 separate times. Sending 5,000 rows in a single `UNNEST` statement allows PostgreSQL’s query optimizer and memory manager to execute the operation in bulk with minimal transaction overhead.

— -

## 4. Guaranteeing O(log n) Lookups with a Unique Index

Passing an array of 5,000 keys into `WHERE lookup_key = ANY(…)` only stays fast if PostgreSQL can resolve those keys via an index scan. Without an index, every chunk triggers a sequential scan across the table.

Maintaining a **Unique Index** on `target_lookup_table(lookup_key)` ensures lookup complexity stays at **O(log n)** — keeping query execution consistently fast even as the underlying table scales to millions of rows.

— -

## 5. Streaming Windows Instead of Loading Full Files

Speed means nothing if your worker crashes with an Out-Of-Memory (OOM) error when file sizes grow.

Rather than reading all 50,000 rows into memory at once, the pipeline streams the input file in bounded windows:

Read 5,000 rows ──► Process & Query ──► Write Output ──► Release Memory ──► Repeat

Enter fullscreen mode Exit fullscreen mode

Because only a small active window exists in RAM at any given moment, memory usage remains flat regardless of whether the file has 50,000 or 1,000,000 rows, preventing GC pauses from stalling execution.

— -

6. Pipelined I/O Overlap

In a strictly sequential pipeline, the CPU sits idle while waiting for disk reads, the database sits idle while files are parsed, and the disk sits idle while queries run.

We decoupled the stages so the output writer operates concurrently with the worker processing the next chunk:


Time ─────────────────────────────────────────────►

Chunk 1: [ Read Input ] ──► [ DB Process ] ──► [ Write Output ]

Chunk 2: [ Read Input ] ──► [ DB Process ] ──► [ Write Output ]

Chunk 3: [ Read Input ] ──► [ DB Process ]

Enter fullscreen mode Exit fullscreen mode

Overlapping file I/O with database execution eliminates sequential wait states and keeps throughput steady.

— -

Scaling Benchmarks

At an average throughput of ~3,333 records per second (assuming healthy disk I/O, no lock contention, and warm index hits), processing time scales predictably:

| Total Records | DB Round Trips (5k Chunk) | Estimated Processing Time |

| — — | — — | — — |

| 50,000 | 10 chunks | ~15 seconds |

| 100,000 | 20 chunks | ~30 seconds |

| 1,000,000 | 200 chunks | ~5 minutes

— -

The 80/20 Takeaway

If you are looking at a slow batch job today and want the highest return on engineering effort, start with the first three changes: 5,000-row chunking, pre-query deduplication, and set-based SQL (ANY / UNNEST). In our experience, those three patterns alone account for 80–90% of the total performance gain.

Top comments (0)