Tech challenge · Python

The loader runs out of memory on a 40 GB file

MediumPython

A script reads a 40 GB newline-delimited JSON file with json.loads(line) for line in f.readlines(), builds a list of dicts and inserts them into a database. It worked on test files and now crashes with MemoryError. Rewrite the approach so memory stays flat, inserting 5,000 rows per batch.

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Iterate the file lazily and group lines into fixed-size batches with a generator.

Show the solution

readlines() loads the whole file and the list of dicts doubles it. Iterating the file object reads one line at a time; a generator that yields batches keeps at most one batch in memory. Insert each batch with an executemany-style call and commit per batch so a failure can resume.

Example (Python)

import json
from itertools import islice

def batches(lines, size):
    it = iter(lines)
    while batch := list(islice(it, size)):
        yield batch

with open('events.jsonl', encoding='utf-8') as f:
    for batch in batches(f, 5000):
        rows = [json.loads(line) for line in batch]
        insert_many(rows)      # e.g. cursor.executemany(...)
        commit()

Common mistakes

  • Batching the inserts but still building the full list first: the memory problem is the list, not the database.
  • Committing once at the end: one bad row near the end loses hours of work.

Learn more

More Python challenges

Today's challenge and the full archive