Learning center

Memory rises steadily after a deploy: a leak, or a cache filling to its bound?

A leak, a cache that is still filling toward its size limit and a heap that grew to a new high point all draw the same rising line for hours. Plot memory against the number of distinct keys the service has seen and against the cache's own entry count. A leak keeps growing with every new key, a bounded cache flattens once its entries reach the bound while new keys keep arriving, and a heap that grew in a burst rises in one step and stays flat while the live heap stays low.

The symptom and the explanations#

The example is fictional. Release v5.2 of pricing-api went out at 10:00 UTC with a new in-process cache of price rules, keyed by product. From 10:00 to 15:00 each instance's resident memory rose from 420 MiB to 720 MiB, about 60 MiB an hour, against a limit of 2 GiB. Extrapolated, the instances would reach the limit around 02:00 the next morning. Three explanations fit:

  • It is a leak. The cache has no bound, or its key includes something that never repeats, such as a request ID, so every request adds an entry that nothing removes.
  • A bounded cache is still filling. The cache holds at most 200,000 entries of about 4 KiB each. It grows with every new product until it holds 200,000, then evicts one entry per miss and stops growing, at about 800 MiB above the old baseline.
  • The heap reached a new high point. A partner's catalog import at 11:30 sent a burst of large requests. The runtime grew its heap to hold them, and keeps that memory for reuse after the requests finish.

For the first hours all three predict a rising line on the memory graph, and the bounded cache predicts the same slope as the leak. Choose the observation where explanations disagree

What each explanation predicts#

ObservationLeakBounded cache fillingHeap high point
Resident memory over the first hoursrisesrisesrises, in steps
Memory against distinct keys seenproportional throughoutproportional until the bound, then flatunrelated
Cache entry countpasses any intended boundreaches its maximum and staysunrelated
Cache evictionsnonestart when the cache is fullunrelated
Live heap after a collectionrisesrises, then flatflat and low
Memory after traffic falls, no restartstaysstaysstays

The second and third rows separate the leak from the filling cache. The fifth separates both from the heap high point. The last row is the check people reach for, waiting to see whether memory falls at night, and it separates nothing: a leak keeps its entries, a full cache keeps its entries, and a runtime keeps the heap it grew.

Go documents the heap high point directly. Its collector sets a target heap of the live heap plus a proportion, GOGC percent, of the live heap and roots, so a total heap well above the live heap is the design and not a leak. Go GC guide

The lab: three worlds that rise together#

The script sends the same 160,000 requests in eight batches to three versions of a service. Eighty percent of requests ask for one of 1,000 popular keys and the rest for one of a million rare keys, so new keys keep arriving. unbounded caches every key in a dictionary; lru uses functools.lru_cache(maxsize=20_000); burst caches nothing and holds each request's value only while the request is in flight, with batch 3 arriving at eight times the concurrency. It needs Python 3.8 or later on Linux. Save it as grow.py.

import functools, random, sys, tracemalloc

if len(sys.argv) < 2 or sys.argv[1] not in ("unbounded", "lru", "burst"):
    sys.exit("usage: python3 grow.py unbounded|lru|burst [seed]")
world = sys.argv[1]             # unbounded, lru or burst
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 1
MiB, BATCH = 1 << 20, 20_000

# The request stream: 80% of requests go to 1,000 hot keys, 20% to a tail of a million.
rng = random.Random(seed)
keys = [rng.randrange(1_000) if rng.random() < 0.8 else rng.randrange(1_000_000)
        for _ in range(8 * BATCH)]
seen, distinct = set(), []
for b in range(8):
    seen.update(keys[b * BATCH:(b + 1) * BATCH])
    distinct.append(len(seen))
del seen

def render(key):                # the work a cache saves: about 1 KiB per value
    return str(key).encode() * 200

unbounded = {}
def get_unbounded(key):
    if key not in unbounded:
        unbounded[key] = render(key)
    return unbounded[key]

@functools.lru_cache(maxsize=20_000)
def get_lru(key):
    return render(key)

def rss_anon():
    with open("/proc/self/status") as f:
        return int(next(l.split()[1] for l in f if l.startswith("RssAnon:"))) // 1024

tracemalloc.start()
for b in range(8):
    in_flight = []
    concurrency = 16_000 if b == 2 else 2_000     # batch 3 arrives as a burst
    for key in keys[b * BATCH:(b + 1) * BATCH]:
        if world == "unbounded":
            get_unbounded(key)
        elif world == "lru":
            get_lru(key)
        else:                                      # no cache: state lives only while the request does
            in_flight.append(render(key))
            if len(in_flight) >= concurrency:
                in_flight.clear()
    in_flight.clear()
    entries = len(unbounded) if world == "unbounded" else get_lru.cache_info().currsize
    current, peak = tracemalloc.get_traced_memory()
    print(f"batch {b + 1}: distinct keys {distinct[b]:5d}  entries {entries:5d}  "
          f"traced {current / MiB:4.1f} MiB  peak {peak / MiB:4.1f}  RssAnon {rss_anon():2d} MiB")

traced is the memory held by live Python objects, as tracemalloc counts it, and peak its highest value so far. tracemalloc cache_info() reports the cache's current size as currsize. functools.lru_cache Run it as for w in unbounded lru burst; do echo "== $w"; python3 grow.py "$w"; done, and before you do, write down your prediction: the first two print the same rows until the cache holds 20,000 entries, after which lru stays flat while unbounded keeps adding about 1.2 KiB per new key; burst steps up once at batch 3 and stays there with traced near zero. Python 3.11 printed:

== unbounded
batch 1: distinct keys  5067  entries  5067  traced  5.4 MiB  peak  5.6  RssAnon 15 MiB
batch 2: distinct keys  9047  entries  9047  traced 10.2 MiB  peak 10.3  RssAnon 20 MiB
batch 3: distinct keys 12985  entries 12985  traced 15.0 MiB  peak 15.1  RssAnon 26 MiB
batch 4: distinct keys 16975  entries 16975  traced 19.6 MiB  peak 19.8  RssAnon 31 MiB
batch 5: distinct keys 20939  entries 20939  traced 24.2 MiB  peak 24.3  RssAnon 36 MiB
batch 6: distinct keys 24928  entries 24928  traced 29.5 MiB  peak 29.6  RssAnon 41 MiB
batch 7: distinct keys 28858  entries 28858  traced 34.0 MiB  peak 34.2  RssAnon 46 MiB
batch 8: distinct keys 32743  entries 32743  traced 38.5 MiB  peak 38.6  RssAnon 52 MiB
== lru
batch 1: distinct keys  5067  entries  5067  traced  5.7 MiB  peak  5.8  RssAnon 16 MiB
batch 2: distinct keys  9047  entries  9047  traced 10.6 MiB  peak 10.8  RssAnon 22 MiB
batch 3: distinct keys 12985  entries 12985  traced 15.7 MiB  peak 15.8  RssAnon 28 MiB
batch 4: distinct keys 16975  entries 16975  traced 20.5 MiB  peak 20.7  RssAnon 34 MiB
batch 5: distinct keys 20939  entries 20000  traced 24.2 MiB  peak 24.3  RssAnon 38 MiB
batch 6: distinct keys 24928  entries 20000  traced 24.8 MiB  peak 25.6  RssAnon 39 MiB
batch 7: distinct keys 28858  entries 20000  traced 24.9 MiB  peak 25.6  RssAnon 39 MiB
batch 8: distinct keys 32743  entries 20000  traced 24.8 MiB  peak 25.6  RssAnon 39 MiB
== burst
batch 1: distinct keys  5067  entries     0  traced  0.0 MiB  peak  1.6  RssAnon 11 MiB
batch 2: distinct keys  9047  entries     0  traced  0.0 MiB  peak  1.6  RssAnon 11 MiB
batch 3: distinct keys 12985  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB
batch 4: distinct keys 16975  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB
batch 5: distinct keys 20939  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB
batch 6: distinct keys 24928  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB
batch 7: distinct keys 28858  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB
batch 8: distinct keys 32743  entries     0  traced  0.0 MiB  peak 11.4  RssAnon 22 MiB

For four batches the leak and the bounded cache are indistinguishable on every memory column, and someone watching only RssAnon would have called both a leak at batch 4. The entry count reaching 20,000 at batch 5 is the first sign that one of them stops. In the burst world, resident memory rose 11 MiB at the burst and stayed there for five more batches that allocated the same amounts as before, which is the runtime reusing what it kept.

The prediction would have failed if lru kept growing after it reached 20,000 entries, if unbounded flattened while new keys still arrived, or if burst grew again after batch 3. Run python3 grow.py lru 7 for another seed and the cache fills at the same batch; change maxsize to 10,000 and it flattens at batch 3.

Read it on a real system#

A cache that will be watched in production needs three counters: entries, misses and evictions. With them, two queries answer the table's middle rows. Memory added per cache miss stays near the size of one entry for a leak, and falls toward zero once a bounded cache is full, because each miss then evicts an entry. deriv fits a line to the range, which suits a slow, steady rise. deriv

deriv(process_resident_memory_bytes{job="pricing-api"}[1h])
  / rate(price_rule_cache_misses_total{job="pricing-api"}[1h])

rate(price_rule_cache_evictions_total{job="pricing-api"}[5m])

The metric names after process_resident_memory_bytes are illustrative; that one comes from the standard process metrics Prometheus client libraries export. Client library process metrics

For the live heap, read what the collector found live rather than the process's total. A Go service exposes /gc/heap/live:bytes, the heap occupied by objects the last collection marked live, beside /gc/heap/goal:bytes, the heap size the collector aims for. runtime/metrics A live heap that is flat while the goal and resident memory rose is the third column. In Python, two tracemalloc snapshots an hour apart, compared with snapshot2.compare_to(snapshot1, "lineno"), list the lines whose allocations grew. tracemalloc

When the growth is not in a cache at all, a heap diff names the objects that accumulate. The browser version of the same method uses three snapshots around a repeated action. Show a memory leak with three heap snapshots

Where the check misleads#

A cache bounded by entry count is not bounded in bytes when its values vary in size. If large values arrive later than small ones, memory keeps rising with the entry count flat. Bound by size, or record the size of the cached values.

A cache with a time-to-live and no size limit is bounded by the rate of new keys times the lifetime. A traffic change that brings more distinct keys raises its ceiling, which looks like a new leak on the day it happens.

Growth outside the cache, such as per-connection state, listeners never removed, or labels with unbounded values in an in-process metrics registry, does not follow the cache's misses. If memory per miss stays high while the cache's entries are flat, look elsewhere with a heap diff. When reviewing the code, the question is what removes entries. Will this collection really grow without limit?

If memory rises in the process while the heap does not, none of these three is the answer. Memory keeps growing, and the heap profile stays flat

Questions#

How long should I wait to see whether memory plateaus?

Until the cache's entry count reaches its configured maximum, or until the live heap after collection has been flat for a full traffic cycle. Wall-clock time alone says little: a cache sized for a week of distinct keys fills in a week.

Is a cache with no maximum size a memory leak?

It grows with the number of distinct keys the service ever sees. When the key space is small and fixed, such as a few hundred currencies, it stops by itself. When keys come from users, products or request data, it behaves as a leak.

Why does memory not fall after traffic drops?

A full cache keeps its entries until they are evicted or expire, and a runtime can keep the heap it grew for reuse, as Python did in the lab's burst world. Neither is a leak. Compare the live heap after a collection, which falls when request state is gone, with resident memory, which often does not.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading