Bulk insert performance: from 72 seconds to 6.8

Bulk insert performance comes down to round trips. How a 5,000 row Excel import went from 72 seconds of database work to 6.8 by batching per file in SQLAlchemy.

By

Most bulk insert performance problems are a round-trip problem in disguise. The database is fast at writing rows. What makes an import slow is the application asking it for one small thing at a time, thousands of times, with a network hop and a statement parse on each. I hit this on a compliance platform I work on, where customers import security frameworks from Excel. A five thousand row workbook did not import at all. Here is how I found the cost, what the fixed writer looks like, the two places the batching fought back, and where the ceiling is now.

A five thousand row import that killed the worker

The symptom was blunt. A five thousand row framework workbook started importing, then the request died partway through, and the uvicorn worker died with it.

The obvious suspect for an Excel import is parsing, so I measured that first. Parsing was never the slow part: five thousand rows parsed in 0.39 seconds, and reading the workbook took 1.7. Everything else was database time. That ruled out the whole category of fixes I might have reached for, like a faster spreadsheet library or streaming the file.

The same import had a second, unrelated failure worth mentioning, because it looked like a performance problem at first. A varchar(50) column met an 80-character cell. The commit died after parsing all 106 rows of that file and surfaced as a 503, even though the parse report said the file was clean. The column is 255 now. If a big import fails, read the actual database error before assuming it is a timeout.

Bulk insert performance is a round-trip count

The writer had been designed per control, and each control cost eight database round trips:

  • one insert for the control,
  • one delete to clear its old crosswalks (mappings to other frameworks),
  • then a lookup and an insert for each crosswalk.

That came to about fourteen milliseconds a control, which is fine when a person edits one control in the UI. Multiplied by five thousand, it is seventy-two seconds, which is longer than the request could live.

This is the arithmetic I'd do first on any slow import: count statements per row, multiply by rows, and multiply by a realistic round-trip time. If that number is close to what you measure, no amount of index tuning will help. You need fewer statements.

Batch per file, not per row

The fix was to change what the writer takes. Instead of one control at a time, it takes the whole parsed file and does each kind of work once:

  • Inserts are batched. One statement per table for the whole file, instead of one per row.
  • Crosswalk deletes are one statement over every control in the run.
  • Lookups collapse into a single query over the distinct targets. Crosswalk targets repeat heavily across a framework, so the distinct set is much smaller than the row count.

A simplified sketch in SQLAlchemy Core, with neutral table names:

from sqlalchemy import delete, insert, select

def write_framework(conn, controls: list[dict], crosswalks: list[dict]) -> None:
    conn.execute(insert(control_table), controls)  # list of dicts: executemany

    ids = [c["id"] for c in controls]
    conn.execute(delete(crosswalk_table).where(crosswalk_table.c.control_id.in_(ids)))

    refs = {cw["target_ref"] for cw in crosswalks}
    found = dict(conn.execute(
        select(target_table.c.ref, target_table.c.id).where(target_table.c.ref.in_(refs))
    ).all())

    rows = [{**cw, "target_id": found.get(cw["target_ref"])} for cw in crosswalks]
    conn.execute(insert(crosswalk_table), rows)

Passing a list of dicts as the second argument to execute is SQLAlchemy's executemany form, and SQLAlchemy 2.0 can turn it into multi-row INSERT statements on Postgres. Its docs explain how in the section on insertmanyvalues behavior.

The result: five thousand controls and fifteen thousand crosswalks take 6.8 seconds of database work instead of 72, and a thousand-control standard imports through the API in 2.9 seconds.

Where batching fought the query layer

The platform is multi-tenant, and every statement passes through a layer that rewrites it to add the tenant. That layer is good at its job and opinionated about statement shapes, which cost me two follow-up fixes.

First, a multi-row insert written as .values([...rows]) could not be combined with the layer's own .values(), so every run failed when it wrote its log. The rows now go through as executemany parameters instead, the form in the sketch above.

Second, resolving crosswalk references afterwards. An UPDATE ... FROM was refused, and so was a single executemany, because its IN list is an expanding bind parameter, which psycopg cannot batch. So that step runs one statement per distinct reference. That is still far fewer statements than one per crosswalk, because references repeat. Importing ISO 27001 against NIST CSF 2.0 connected 100 of 105 references.

The general lesson: batching changes the shape of your SQL, and anything that rewrites SQL in between (an ORM, a tenancy filter, a row-level security helper) may refuse the new shape. Test the batched path through the same layer production uses. I wrote more about tenant scoping in multi-tenant SaaS architecture.

What is the fastest way to bulk insert rows in Postgres?

For a raw load of many rows, COPY is the fastest built-in option, and the Postgres guide on populating a database covers it along with dropping indexes during the load. For an application import that goes through an ORM, the practical answer is fewer round trips: one batched insert per table, set-based deletes and updates, and one lookup over the distinct keys instead of one per row.

The progress bar I skipped, and the ceiling I kept

The original request for this work asked for an import progress bar. I skipped it. An import that finishes in under three seconds has nothing to report, and a progress bar on a fast operation is code to maintain for no benefit. Upload progress is still shown, measured from the file transfer itself, and hidden when the total size is unknown, since a percentage of an unknown total runs backwards.

There is a known ceiling. The tenancy layer pays a cost per row even inside a batch, so five thousand controls take 6.8 seconds when written directly and 50 seconds through the API. The documented upgrade is moving the commit to background tasks, so the request returns at once and the client polls for the result. I described that pattern in slow API endpoint fix: reply first, fan out later, and the queue side in running slow jobs in the background with queues.

Writing the ceiling down, with its number and its fix, means the next person to hit it starts from a measurement instead of a guess.

Where I'd start

  1. Time parsing and database work separately before changing anything.
  2. Count statements per row. If it is more than one or two, that is your problem.
  3. Change the writer's input from one record to the whole file, then batch inserts, turn per-row deletes into one set-based delete, and dedupe lookups.
  4. Run the batched version through every layer that rewrites SQL in production.
  5. Write down the remaining ceiling and the upgrade path, with numbers.

For the read side of the same idea, pushing work into one query instead of many, see fixing an 18-second admin dashboard with Postgres aggregation.

Want this kind of work on your product?

Get in touch