Video in progress
You need to load 50 million rows into a new table in one go. How do you do it fast and safely?
I load with COPY, not through JPA; I create the indexes and FKs after the load, split the work into chunks instead of one big transaction, and watch the replication lag. If the table is new, the fact that nobody is writing to it yet gives you a lot of freedom.
📖 Answer
Single-row INSERTs, especially through Hibernate, take hours at this volume. The order of speed is roughly: separate inserts < JDBC batch with reWriteBatchedInserts=true < COPY.
From Java you can do COPY with PgJDBC's CopyManager:
CopyManager copy = conn.unwrap(PGConnection.class).getCopyAPI();
try (Reader in = Files.newBufferedReader(csvPath)) {
long rows = copy.copyIn(
"COPY products_new (id, sku, name, price) FROM STDIN WITH (FORMAT csv)", in);
}
The order of steps:
- I create the table with no primary key, or in a minimal form. Every index is updated on every insert; building them in one go afterward is much faster.
- I load the data in chunks of 1-5 million rows. If one giant transaction fails, everything has to be redone; besides, it holds the xmin horizon for a long time and stops VACUUM on other tables.
- Then I raise
maintenance_work_memfor the session, create the indexes and constraints, and runANALYZEat the end.
Things to watch: if there is a replica, a big write increases the WAL volume and the replica falls behind, so I pause between chunks and watch pg_stat_replication. An UNLOGGED table is faster, but it doesn't go to the replica and is wiped on a crash; it's fine for temporary staging, not for the final table.
Loading into a live table is a different story: there you can't drop the indexes, and I work with small batches and a rate limit.
Sign up to mark studied questions and save your progress.