Big files, small memory
Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 6:50 on Monday. Last night's job on the 40 GB clickstream file died after ten minutes on a machine with 16 GB of memory. There is no Python error in the log, only exit code 137. All Tess had asked for was the number of events per type: a dict with four keys. The script's first line is events = f.readlines().
You'll learn to
- Stream a file so memory does not grow with its size
- Chain generators into a pipeline, and say who pulls whom
- Work out the peak memory of a job that reads in chunks
- Tell answers that merge across chunks from ones that do not
Learn
Four keys, 300 GB
The answer Tess wants fits on a sticky note: four event types, four counts. So why did the job need more memory than the machine has?
Because of its first line. f.readlines() builds the whole file in memory before anything else happens. So do f.read(), list(f) and json.load(f). And Lesson 3.2 measured parsed events at about 7.5 times their text: 40 GB of JSON becomes roughly 300 GB of dicts.
When memory runs out, Python gets no chance to complain. The operating system kills the process, and in a container all you see is exit code 137.
The fix is to never hold the file. An open file hands out one line at a time: for line in f: reads a line, gives it to you, and lets it go before the next.
Three ways to read a 40 GB file
Bars compare the memory needed to read a 40 GB file: 40,000 MB to hold every line as text, about 300,000 MB to hold every event as a parsed dict, and about a hundredth of a megabyte to read one line at a time.
The machine has 16,000 MB. The first two bars are far past it. The third is too small to draw, which is the point.
Load it all, or stream it
| Load it all | Stream it |
|---|---|
| lines = f.readlines() | for line in f: |
| memory grows with the file | memory stays at about one line |
| events = [json.loads(l) for l in f] | events = (json.loads(l) for l in f) |
| can be looped over many times | can be looped over once |
| fine for a 5 MB file | needed for a 5 GB file |
A list and a generator, side by side
import json, sys
with open("data/events.jsonl") as f:
as_list = [json.loads(line) for line in f]
print("list:", sys.getsizeof(as_list), "bytes just for the list of", len(as_list), "pointers")
with open("data/events.jsonl") as f:
as_gen = (json.loads(line) for line in f)
print("generator:", sys.getsizeof(as_gen), "bytes")
print("first type:", next(as_gen)["type"])
Compare the two sizes. The list's number covers only its 192 pointers, not the 192 dicts they point to, and it grows with every row. The generator stays the same small object whatever the size of the file: it holds a recipe, not the data. Square brackets build a list; round brackets build a generator.
Generators: functions that pause
The round-bracket form in that card is a generator expression. Its longer form is a generator function: a function that says yield where another would say return.
Calling it runs nothing. It hands back a generator. Each time something asks for the next value, the function runs until its next yield, hands the value over, and pauses right there, with its local variables intact.
Think of a kitchen that cooks to order, not a buffet. Nothing is made until a plate is asked for, and only one plate is on the pass at a time.
That lets you write a pipeline as small steps: one generator reads lines, the next parses them, the next filters.
A streaming pipeline
import json
from collections import Counter
def read_lines(paths):
for path in paths:
with open(path) as f:
for line in f:
if line.strip():
yield line
def parse(lines):
for line in lines:
yield json.loads(line)
def only(events, event_type):
for e in events:
if e["type"] == event_type:
yield e
paths = ["landing/events/2025-06-01.jsonl", "landing/events/2025-06-02.jsonl", "landing/events/2025-06-03.jsonl"]
purchases_by_os = Counter(e["device"]["os"] for e in only(parse(read_lines(paths)), "purchase"))
print(sorted(purchases_by_os.items()))
Three small generators and one Counter. Across three days of files it finds 16 purchases: 5 on Android, 6 on iOS, 5 on the web. Each step is small enough to test on its own. Nothing is read until Counter starts asking for values.
Nothing is pushed. Everything is pulled.
Read the last line of that program from the outside in. Counter is the consumer. It asks only() for a value. only() asks parse(). parse() asks read_lines(). And read_lines() asks the file for one line.
So the data is not pushed through the pipeline by the file. It is pulled by whoever wants the result. Each generator runs only as far as its next yield, then waits to be asked again.
Two things follow. The whole chain holds about one record at any moment. And if nobody consumes the last generator, nothing happens at all: no file is even opened.
One line travels through the pipeline
Counter asks only() for the next value, which asks parse(), which asks read_lines(), which reads the file; one line travels back up, a page view is dropped by pulling again, a purchase reaches Counter, and the end of the file arrives as StopIteration.
The pull goes down.
Counterasksonly()for a value.only()has none, so it asksparse(), which asksread_lines(), which reads one line from the file. Until this moment, nothing had run.One line comes back up. The file hands over a line.
read_lines()yields it and pauses.parse()turns it into a dict, yields it and pauses.A page view is dropped.
only()wants purchases. This event is a page view, so it lets it go and pulls again.Counternever hears about it.A purchase reaches the top. The next event is a purchase, so
only()yields it andCounteradds one for its device. One record was in flight the whole time, never more.The file ends. With no line left,
read_lines()finishes. Each generator above it finishes in turn, and the signalStopIterationtellsCounterit is done.
Read it top to bottom: time runs downwards. Solid arrows to the right are requests, dashed arrows to the left are answers.
Remember: a generator holds a recipe, not the data. Nothing runs until something pulls, and about one record is in memory at a time.
Under the hood: a paused function keeps its place
What does for x in something really do? Two small calls. First iter(something) asks for an iterator: an object that hands out values one at a time. Then next(it) is called again and again, until it raises StopIteration. That pair of calls is the iterator protocol.
A list gives a fresh iterator every time you loop over it. A file is its own iterator, so you can go through it once.
A generator is an iterator with a memory. Python keeps its frame, the local variables and the line it stopped on, alive between calls. next() wakes it, and the next yield puts it back to sleep. close() ends it at the paused yield and runs any finally block on the way out, which is how its file gets closed.
The life of a generator
Four states in a row: a generator is created without running, runs when next is called, is suspended at each yield with its variables kept, and is closed when its code ends or close is called.
Read it left to right. The names are the ones inspect.getgeneratorstate prints. From GEN_SUSPENDED, every further next() goes back to GEN_RUNNING: a generator spends its life going between those two.
The protocol by hand
import inspect
def read_lines(path):
f = open(path)
try:
for line in f:
yield line
finally:
f.close()
print(" finally ran: file closed")
g = read_lines("data/payments.jsonl")
print(inspect.getgeneratorstate(g))
first = next(g)
print(inspect.getgeneratorstate(g), first[:30])
g.close()
print(inspect.getgeneratorstate(g))
it = iter([10, 20])
print(next(it), next(it), next(it, "exhausted"))
f = open("data/orders.csv")
print("a file is its own iterator:", iter(f) is f)
f.close()
The states print in the order of the picture: created, suspended after the first next(), closed, with finally ran in between as the file is shut. A generator you stop reading early keeps its frame, and so its open file, until you call close() or Python cleans it up. In a long-running worker that leaks file handles: close generators you abandon, or use contextlib.closing.
Batches: the middle ground
Sometimes one record at a time is too slow. Insert rows into a database one by one and you pay one network round trip per row: a million rows take hours.
The middle ground is a batch: hold, say, 1,000 rows, send them together, let them go. You get most of the speed, and memory that never grows.
Python 3.12 has itertools.batched(iterable, n) for this. On older versions you build it yourself with itertools.islice, which is a common interview exercise.
Mind the last batch: it is usually shorter. Code that only sends a batch "when it is full" silently loses the tail of the data.
Batch the events
import json
from itertools import islice
def batches(items, size):
it = iter(items)
while True:
chunk = list(islice(it, size))
if not chunk:
return
yield chunk
with open("data/events.jsonl") as f:
events = (json.loads(line) for line in f)
sizes = [len(b) for b in batches(events, 50)]
print(sizes, "=", sum(sizes), "events")
islice(it, 50) takes the next 50 items from the same iterator, so each batch carries on where the last one stopped. In a real load, each batch would be one multi-row INSERT or one file written to storage.
How much memory does a streaming job need?
Streaming does not mean zero memory. The peak is three things added together: the read buffer, one chunk, and the state.
The buffer is small and fixed. One chunk is rows per chunk times bytes per row:
- 100,000 events × 1,130 bytes (from Lesson 3.2) = about 113 MB
So the chunk size is a memory dial first, and a speed dial second.
The state is whatever you carry from one chunk to the next, and it depends on the question. A count or a sum is one number. A count per group is one dict entry per group, however many rows there are. But some questions have to remember every value they have seen. Look at the three bars.
Peak memory: one 100,000-event chunk plus the state
Three bars on one scale: counting events per type is almost all chunk; an exact set of 50 million user ids adds 3.7 GB of state; a HyperLogLog sketch adds 12 KB.
All three bars are on one scale, and each starts with the same blue chunk. Counting per type adds almost nothing. An exact set of 50 million user ids adds 3.7 GB, measured on 64-bit CPython 3.12. A HyperLogLog sketch, which gives an approximate count, adds 12 KB.
The state each answer needs
| Aggregate | State per chunk | Merge | Memory |
|---|---|---|---|
| count, sum | n, s | add | one number |
| mean | (sum, count) | add both, divide at the end | two numbers |
| min, max | the value so far | min, max | one number |
| count per group | dict: key to count | add per key | one entry per key |
| exact distinct count | a set of values | union | one entry per distinct value: 50M ids is about 3.7 GB on 64-bit |
| approximate distinct | HyperLogLog registers | max per register | fixed: Redis uses up to 12 KB for 0.81% standard error |
| median, percentiles | every value | not mergeable | sort them all, or a sketch such as t-digest |
Fill this in before you write a streaming job. If the memory column says "every value", streaming alone will not save you: you need an external sort, a database, a sketch, or an engine that splits the keys across machines. A sketch is a small structure that gives an approximate answer with a known error. Spark's and DuckDB's approx_count_distinct are HyperLogLog sketches.
A mean of means is not the mean
That table has a column called "Merge". It matters as soon as a file is cut into chunks, because every chunk gives a partial answer and the partial answers have to be combined.
Some answers combine cleanly. The sum of the chunk sums is the sum. The largest of the chunk maximums is the maximum. Such answers are called mergeable.
A mean is the famous trap. The mean of the chunk means is the true mean only when every chunk has the same size, and the last chunk almost never does. So carry two numbers per chunk, (sum, count), add them up, and divide once at the end.
One pass, several answers
import json
count = 0
total = 0.0
low = high = None
with open("data/payments.jsonl") as f:
for line in f:
p = json.loads(line)
if p["status"] != "captured":
continue
amount = p["amount"]
count += 1
total += amount
low = amount if low is None else min(low, amount)
high = amount if high is None else max(high, amount)
print("count", count, "total", round(total, 2), "average", round(total / count, 2))
print("min", low, "max", high)
Five answers from one pass, with five numbers of state: 70 captured payments, $8,514.73 in total. Reading the file once per answer would work too, but on 40 GB every pass costs real minutes.
Chunks with pandas: merge the states, never the means
import pandas as pd
parts = []
for chunk in pd.read_csv("data/order_items.csv", chunksize=50):
chunk["amount"] = chunk["qty"] * chunk["unit_price"]
parts.append(chunk.groupby("product_id")["amount"].agg(["sum", "count"]))
merged = pd.concat(parts).groupby(level=0).sum()
merged["avg_line"] = (merged["sum"] / merged["count"]).round(2)
print(len(parts), "chunks ->", len(merged), "products")
print(merged.sort_values("sum", ascending=False).head(3))
whole = pd.read_csv("data/order_items.csv")
amount = whole["qty"] * whole["unit_price"]
means = [amount[i:i + 50].mean() for i in range(0, len(amount), 50)]
print("true mean", round(amount.mean(), 2), "| mean of chunk means", round(sum(means) / len(means), 2))
201 order lines in chunks of 50 leave a last chunk of one line. In the mean of means that single line gets the same vote as a chunk of 50: the last output line shows 69.09 against a true mean of 46.88. Merging (sum, count) per product gives the exact answer, and memory holds one chunk plus one row per product.
A generator runs out. After one full loop it is empty, and a second loop gets nothing, with no error: sum(g) then len(list(g)) gives the right sum and a count of 0. Compute everything in the same pass, or create the generator again. And watch for hidden full loads: sorted(f), len(list(f)) and json.load(f) quietly read the whole file into memory.
Numbers to remember
| What | Number | Good to know |
|---|---|---|
| A file's read buffer | io.DEFAULTBUFFERSIZE: 8,192 bytes | a file is its own iterator: iter(f) is f |
| Killed for using too much memory | exit code 137 (SIGKILL) | sent by the operating system's OOM killer, often with no Python error at all |
| One chunk of 100,000 parsed events | about 113 MB | 100,000 × 1,130 bytes |
| A set of 50 million int ids | 3.7 GB, and a 4.5 GB peak | a 2,147,483,864-byte table plus 32 bytes per int object (28 rounded up by the allocator); the old and new tables exist together while it resizes |
| HyperLogLog in Redis | up to 12 KB | 0.81% standard error |
| itertools.batched(iterable, n) | since Python 3.12 | yields tuples of up to n items |
| StopIteration escaping inside a generator | RuntimeError since Python 3.7 (PEP 479) | so a stray next() cannot quietly end a stream |
| close() on a generator | raises GeneratorExit at the paused yield | which runs finally blocks |
Real tools stream the same way. pandas reads in pieces with read_csv(..., chunksize=100_000). DuckDB and Spark work in chunks and spill to disk when memory runs short, which is how they handle files larger than memory. boto3's iter_lines() reads an S3 object line by line without downloading it first.
What changed at SwiftKart
Tonight's job has a new first line: for line in f:. It counts events per type as it reads, and holds one line and a dict with four keys, whether the file is 40 KB or 40 GB. It finishes on the same 16 GB machine with memory to spare.
Tess's next request is daily distinct users. You fill in the table first: an exact count needs a set of every id, so for the full history you offer an approximate count, with its error written next to it.
So far every file was already on your disk. In the next lesson you fetch the data yourself, page by page, from Dana's orders API, where the network can fail at any moment.
In one line
Never hold the file: pull one record or one batch at a time through generators, carry only the state the question needs, and merge sums and counts, never means.
Interview corner
What is a generator, and what exactly does it keep in memory?
A generator is an iterator backed by a suspended frame: its local variables and its position in the code. next() resumes it up to the next yield, and returning raises StopIteration (since Python 3.7, a StopIteration escaping inside it becomes RuntimeError). A chain of generators therefore holds about one record plus each frame's locals, whatever the file size. The catches: it can be consumed only once, and an abandoned generator keeps its open file until close() or garbage collection.
How much memory does a chunked aggregation over a 40 GB file need?
Buffers plus one chunk plus state. One chunk is rows per chunk times parsed bytes per row, so 100,000 events at about 1 KB each is around 100 MB, and the chunk size is the knob. The state depends on the aggregate: counts, sums and (sum, count) for means are tiny and mergeable, a dict per group grows with distinct keys, and an exact distinct count over 50 million ids is several GB as a Python set. When state grows with keys I use HyperLogLog (12 KB in Redis for 0.81% error), partition the keys across workers, or push the work into DuckDB or Spark, which spill.
How would you count distinct users in a file too big for memory?
If the set of ids fits, stream and add to a set. If not, partition by hash: one pass writes ids into, say, 64 files by hash(id) % 64, then each file is counted on its own and the counts are added, because the same id always lands in the same file. When an estimate is enough, HyperLogLog gives a fixed small state with a known standard error. In practice I let DuckDB or Spark do it, since that is exactly what their aggregates do internally.