Video in progress

You need to process a 20 GB CSV file and load it into the database. How do you control memory and time?

You never load the whole file into memory: read line by line with a buffered reader and write in batches after parsing. For speed, you parallelize the parsing and the DB writes through a bounded queue, and for restarts you save an offset/checkpoint.

📖 Answer

The first step is knowing where the time goes. Often reading from disk is not the bottleneck; writing to the DB is. So the design looks like this:

BlockingQueue<List<Row>> queue = new ArrayBlockingQueue<>(16);   // bounded!
try (BufferedReader r = Files.newBufferedReader(csv, UTF_8)) {
    List<Row> batch = new ArrayList<>(5_000);
    String line;
    while ((line = r.readLine()) != null) {
        batch.add(parse(line));
        if (batch.size() == 5_000) {
            queue.put(batch);              // if the DB is slow, the reader waits here
            batch = new ArrayList<>(5_000);
        }
    }
    if (!batch.isEmpty()) queue.put(batch);
}

A few writer threads take from the queue and write with JDBC addBatch/executeBatch (on PostgreSQL, reWriteBatchedInserts=true or even faster, COPY). The bounded queue is the backpressure: the reader can't run ahead of the DB and fill the heap.

Other questions to settle:

  • Restart. If a 3-hour job dies at 80%, do you start over? After each batch you save the number of the processed row, and on restart you continue from there. The writes have to be idempotent (ON CONFLICT DO NOTHING or a natural key).
  • Bad rows. One bad row must not kill the whole job: write it to a separate "rejected" file and put the count in the report.
  • Reading the file in chunks in parallel. Possible: you split the file into N chunks by offset and move each chunk's start to the next \n. But a CSV can have a newline inside quotes, and then this approach breaks. Usually one reader + several writers is enough.
  • Transactions. Loading the whole file in one transaction means undo/WAL volume and long locks. Commit per batch; if needed, load into a staging table first and swap in with a single INSERT ... SELECT at the end.

A rough guess at the expected speed: plain parsing on one core gives hundreds of thousands of rows per second. If you are getting a thousand rows per second, the problem is not IO: look with a profiler.