Where Is Memory Growing? Pin Python Memory to a Line Number with tracemalloc
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.

A vibe-coded bookshop stock program looks fine when it starts, then its memory creeps up a little at a time until the machine chokes. Most people open a system monitor first, but that number only says "it grew" — it never says which line grew it. This guide shows how to use tracemalloc, a Python standard library module, to pin memory growth to one specific line of code. The demo uses a fictional bookshop stock program called bookstock; the example and the numbers are for teaching, but every step really ran: the demo script is demo250_g1.py, the local environment is Python 3.12.3, standard library only, and the Chinese and English runs execute the same logic with identical numbers — each transcript is stored in this directory.
The conclusion first: building stock of 2000 books moves tracemalloc's current memory from 0.3 KiB to 582.7 KiB, with a peak of 668.0 KiB; subtracting two snapshots, the line that grew the most is demo250_g1.py line 85, at 568.1 KiB and 9699 blocks; following the allocation traceback of one book in that line gives 3 frames, and the last frame is the allocation site; for the same books, sys.getsizeof only measures the list itself at 16184 bytes, or 15.8 KiB, one thirty-fifth of the tracemalloc number; clearing the stock and measuring again brings that line back to 0.0 KiB, a change of -568.1 KiB and -9699 blocks, so the memory really came back. A temporary big list peaks at 3930.0 KiB, while a small list written the same way peaks at only 62.9 KiB — and without calling reset_peak() first, the small list's peak cannot be measured at all. Keep these numbers in mind; every detail below is their expansion.
Totals alone cannot find where it grows
Start with the easiest approach. tracemalloc.get_traced_memory() returns two numbers: the current value and the peak, both in bytes. In the demo, after tracemalloc.start(10) starts tracing and before any stock is built, current is 0.3 KiB and peak is 0.4 KiB; after building 2000 books, current is 582.7 KiB and peak is 668.0 KiB. These two numbers answer only one question: how much traced memory is in use right now. They cannot answer "who holds it", let alone "which line should change". The 85.3 KiB by which the peak exceeds the current value is temporary allocation that appeared during the build and was released again; looking only at the final current value, you would never know it existed. That is the first flaw of totals: they mash every allocation into a single number.
The second flaw is subtler: a total cannot tell "held all along" from "peaked once". On a long-running service, the memory curve climbs slowly; you look at the current value and it is indeed rising, but you cannot tell whether the growth is a cache that keeps accumulating or one interface leaking a little on every call. tracemalloc's answer is snapshots: take_snapshot() freezes all traced memory blocks together with where they were allocated, at one moment; subtract two snapshots and the growth comes out on its own. A snapshot does not include memory allocated before tracing started, so tracing should start as early as possible — the official docs recommend starting with the environment variable PYTHONTRACEMALLOC=1, or the launch flag -X tracemalloc. Tracing started late never sees early allocations, and that missing part stays invisible in every snapshot.
Subtract two snapshots: which line grew the most
The core of the demo is two snapshots. One is taken before building the stock, another after 2000 books are built, and then snapshot2.compare_to(snapshot1, 'lineno') groups the difference by line number, sorted biggest first by the absolute value of the difference. The demo also adds a filter that keeps only this script's own allocations: tracemalloc.Filter(True, __file__), so small allocations inside the standard library do not crowd the ranking. The docs give ready-made examples of this filter: Filter(True, subprocess.__file__) keeps only one module's allocations, while Filter(False, tracemalloc.__file__) excludes tracemalloc itself.
The line with the biggest difference is demo250_g1.py:85: size 568.1 KiB, up 568.1 KiB, 9699 blocks, up 9699 blocks. That line is the list comprehension that builds the stock:
return [dict(id=i, name=f"book-{i}", price=10.0 + i) for i in range(n)]
One line holds 2000 books — one dict, one name string and one price float each, plus the list itself — 9699 blocks in total, 568.1 KiB. The runner-up is already in the hundreds of bytes and not worth chasing. Snapshot statistics can group differently: statistics('filename') groups by file, statistics('traceback') groups by full traceback, and cumulative=True counts every frame of the traceback, not just the last one — but grouping by line number is already enough to nail down "which line", and finer grouping is rarely needed.
One point is easy to misread: "up 568.1 KiB" in the snapshot diff is not the same as the program's total growth. Current memory rose from 0.3 KiB to 582.7 KiB, a rise of 582.4 KiB, and this line accounts for 568.1 KiB of it; the remaining dozen KiB are small allocations from the snapshots, the filter and the comprehension machinery. The numbers line up, but what you want is "where the biggest chunk is", not "a total that adds up" — the line ranked first in the diff is the answer.
Follow the traceback to the allocation site
Knowing the line is not always enough: the same line of code can be called from several places, and you need to know which call chain the memory came through. tracemalloc.get_object_traceback() gives the allocation site of one specific object; printing the returned traceback with format() produces a few File ... line ... entries. The demo takes the 1st book in the stock, and its traceback has 3 frames:
File "demo250_g1.py", line 194
main()
File "demo250_g1.py", line 102
books = build_books(N_BOOKS)
File "demo250_g1.py", line 85
return [dict(id=i, name=f"book-{i}", price=10.0 + i) for i in range(n)]
Frames are ordered from the oldest to the most recent, so the last frame is the allocation site — line 85, the comprehension. The frame limit is the number passed to start(); the demo passes 10 and actually uses 3. The default stores only 1 frame, which tells you the line but not the call chain; the docs' example stores 25 frames at startup with PYTHONTRACEMALLOC=25 or -X tracemalloc=25. More frames mean more overhead for tracemalloc itself, so 10 frames is plenty at this scale — raise it only when the call chain is too deep to read with fewer.
One measured gotcha deserves its own paragraph. With the same stock-building code written with a dict literal, {"id": i, ...}, the snapshot statistics still show 570 KiB and 9712 blocks, but get_object_traceback() returns None for that dict — no traceback at all. Rewriting it as dict(id=i, ...) gives almost identical numbers, 573 KiB and 9744 blocks, and the traceback works. This is behavior measured on Python 3.12.3, with a probe that changed only the construction style and nothing else. That is why the demo's build function deliberately uses the dict() form. If you follow the docs and find that some object gives you no traceback, do not doubt your own code first — try another construction style, and if that fails, fall back to the snapshot diff, which is unaffected by this quirk.
Three uses of a snapshot: grouping, filtering, saving
A snapshot only freezes memory blocks; the real work is the three things you do with it. First, grouping. The demo uses statistics('lineno'), grouping by file plus line number; statistics('filename') shows how much a whole file holds, and statistics('traceback') splits by full call chain, so one line of cache-building code shared by three endpoints can be broken down by which endpoint contributed the most — grouping by line only shows the total. The cumulative switch counts callers up the chain as well, which fits when you want the memory distribution of a whole chain starting from an entry function; without it, only the final frame is counted.
Second, filtering. The demo uses Filter(True, __file__) to keep only this script's allocations. Without it, what happens? In an unfiltered probe, the top three diff entries included two lines inside tracemalloc itself, 312 bytes each — small numbers, but they pull attention away from the real biggest chunk; in a bigger project, standard library and third-party allocations crowd the ranking even more, and half the top ten may not be your code at all. The rule is simple: the first argument is include or exclude, the second is a filename that supports wildcards, and Filter(False, "<unknown>") is the docs' example for dropping empty tracebacks. The habit to build is: filter to your own files first, pin down the line, and only then switch the filter to a library's filename if you suspect the library is allocating behind your back.
Third, saving. Memory problems often refuse to reproduce on a dev machine and only appear on a service that has run for a long time; Snapshot.dump() writes a snapshot to disk, and Snapshot.load() reads it back for slow analysis on a dev machine, without babysitting the troubled server. Tracing can also start without touching the code: the environment variable PYTHONTRACEMALLOC=10 or the flag -X tracemalloc=10, where the number is the frame limit, means the program is already tracing when it starts, and you take snapshots once memory has grown. Together, these three turn snapshots from a demo function into a tool you can carry into a real project: group to set the direction, filter to set the scope, save to keep the scene.
sys.getsizeof only sees the tip of the iceberg
Many people reach for sys.getsizeof() first when checking memory. It is simple, but it only measures the one object you hand it — not the things that object points to. Three numbers from the demo make the flaw concrete: sys.getsizeof(books) is 16184 bytes, or 15.8 KiB, and that is only the list container itself — none of the 2000 dicts are counted; measuring one book's dict alone gives 184 bytes, and one name string, for example "book-0", is 47 bytes. Building a total from getsizeof means walking every container and every layer of references yourself, watching out for reference cycles and double counting — laborious and easy to get wrong.
Compare: tracemalloc measures the same books at 568.1 KiB, 35.9 times getsizeof(list). The chart shows the comparison:

So getsizeof fits the question "how big is this one object", for example when comparing the per-object size of two data structures; the moment the question becomes "how much does this batch of data hold, and who holds it", switch to tracemalloc. The two tools measure different things, so their numbers not matching does not mean either one is wrong.
Measure again after the fix: did the memory really come back
Pinning down the line and changing the code is not the end — measure again to confirm the memory really came back. The demo clears the stock list with clear(), deletes the variable with del, calls gc.collect(), takes a fresh snapshot and compares it with the one taken when the stock was built: line 85 is back to 0.0 KiB, a change of -568.1 KiB, and 0 blocks, a change of -9699 blocks. That line is clean.
But the same output has another number worth a second look: current memory after clearing is 31.5 KiB, not the 0.3 KiB from before the stock was built. The extra 31.2 KiB is not leaked books — it is our own leftovers: the two snapshots, the two diff results and that 3-frame traceback are themselves traced memory, still sitting in variables. When judging whether a fix worked, look at whether the target line is back to zero, not whether the total is back to where it started. The total always carries the footprints of your own measuring tools, and using it as the acceptance test will only confuse you.
The gc.collect() step is not decoration either. Calling clear() alone only drops the list's references; if those dicts still point at each other in reference cycles, reference counting alone cannot reclaim them, and only a garbage collection pass can confirm they are gone. The demo's dicts do not reference each other, so they would come back even without gc.collect(), but writing the sequence as a fixed routine — clear the references, force a collection, then take the snapshot — is the safer habit, with all three steps required.
Peak: a temporary big list's peak is invisible in the final total
Some memory problems are not about "held all along" but about "spiking too high for a moment". Section 6 of the demo is that case: sum(list(range(100000))) builds a temporary list of 100,000 integers and sums it; once done, the list is gone and current memory is only 31.7 KiB, but the peak hit 3930.0 KiB. Then reset_peak() zeroes the peak, and sum(list(range(1000))) gives a small-list peak of 62.9 KiB with current memory at 31.8 KiB.
reset_peak() resets the recorded peak to the current size and clears no traces — the docs stress this point: it only changes the peak number, and snapshots still compare the same way. Without it, the small list's peak reading stays at the big list's 3930.0 KiB, and you can never measure the small list itself. The docs carry the same example with their own numbers: after the big list, first_size=664, first_peak=3592984; after the small list, second_size=804, second_peak=29704 — same conclusion, that the small list's true peak is invisible unless the peak is reset. The ratio is also worth remembering: the big-list peak of 3930.0 KiB is 62.5 times the small-list peak of 62.9 KiB, while the two lists differ 100 times in length, with details like integer caching in between — so peaks can only be measured, never estimated from length.
One measured detail to disclose: the last digit of the peak wobbles by about 0.1 KiB between runs — running the same code three times, the big-list peak moves between 3929.8 and 3930.0 KiB, and the small-list peak between 62.8 and 62.9 KiB. Only the last decimal place moves, the conclusions are unaffected, and the 3930.0 KiB and 62.9 KiB quoted in this guide are the frozen values from the transcript run stored in this directory.
tracemalloc's own overhead, and what it cannot see
Tracing itself costs memory. tracemalloc.get_tracemalloc_memory() measures what tracemalloc spends storing traces: in the demo, 43696 bytes, or 42.7 KiB. That number tracks the count of traced blocks and the frame limit directly: more blocks and more frames per block mean more overhead. So the 10 in start(10) is not a random pick — keep the frame count as low as you need, and raise it only when the call chain is too deep to read with fewer frames; the docs' 25-frame example is for when you actually need it.
Its boundaries matter too. tracemalloc traces memory blocks allocated by Python, and only from the moment start() runs — memory allocated before that is not in any snapshot. Memory allocated by C extensions themselves, or outside the interpreter, is invisible or only partly visible. The docs put it plainly: it traces most memory blocks allocated by Python, and that "most" is worth remembering. For how much memory a process holds in total, use a system tool; for which line of Python code is growing memory, use tracemalloc. Each tool has its own job — do not make one do the other's.
Two finishing functions are worth knowing even though the demo does not give them their own section: stop() stops tracing and clears all traces collected so far, so if you want to keep anything, call take_snapshot() first, or dump() the snapshot to disk and load() it back later for offline analysis; is_tracing() and get_traceback_limit() are status queries — in the demo they return True and 10, and putting them in a check script confirms tracing is really on and the frame limit is really the one you wanted.
The checklist: next time memory climbs, follow this order
Collect the sections above into a routine you can follow directly. First, start tracing early: PYTHONTRACEMALLOC=1 or -X tracemalloc at process launch, 10 frames to begin with, more only if needed. Second, take one snapshot before and one after the operation you suspect, run compare_to grouped by line number, look only at the few biggest differences, and use Filter to keep your own code in the ranking so standard library noise does not crowd it out. Third, for the top line, take one concrete object and read its call chain with get_object_traceback() to confirm which entry point the allocation came through; if it returns None, try another construction style, and if that fails, fall back to the snapshot diff. Fourth, after changing the code, clear the references, call gc.collect(), take a fresh snapshot — the acceptance test is the target line returning to zero, not the total returning to where it started. Fifth, if you suspect a spike rather than a steady leak, watch the peak with get_traced_memory() and call reset_peak() before each section, or the peak reading will forever be the highest spike in history.
Finally, what this guide does not cover, so you do not take it into fights it is not meant for. The deep water of garbage collection — finding reference cycles, walking up the chain with gc.get_referrers() — is not here; the official gc docs are the next stop. Third-party memory tools such as objgraph and pympler are not here either: they can draw reference graphs, but they are extra packages, and the standard library routine should come first. Long-term memory monitoring and alerting for a production service is another topic again — tracemalloc fits locating a problem on a dev machine or in a test environment, not running forever on a live server. The site already has a guide on debugging memory leaks in the browser, covering Chrome DevTools and Node heapdump; this guide's Python tracemalloc is a different track — one for the frontend, one for the Python backend — do not mix them up.
Back to the bookshop program at the start: rising memory is not scary; not knowing which line it rises on is. Subtract two snapshots and you get 568.1 KiB, 9699 blocks, line 85, the last frame of a 3-frame traceback; measure again after the fix and it is back to 0.0 KiB. Run that routine once, and the next time memory climbs, what you hold is not a total — it is a line number.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Author 137's books, 20000 rows: SCAN takes 0.177 s for 200 runs, one index makes it 0.012 s, 14.9x faster, same 100 rows. JOIN and subquery both return 2000 rows in about 0.020 s, and a covering index drops the temp B-tree sort. SQLite 3.45.1, stdlib only.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.