After memory alerts fired on production nodes, we found that the RSS of a Python 3 health check process using aiohttp had kept growing to around 325 GiB. Combining Memray allocation records, heap samples from the original process, and source code comparisons, we traced the leak to the
CIMultiDictconstructor inmultidict 6.3.1, which failed to release a reference to the request-header list. After upgrading tomultidict 6.7.1in production, RSS no longer showed sustained growth.
health_web is a Python health check script that uses aiohttp.
When we noticed the production issue, health_web had been running continuously for about two months. Its process RSS had grown to roughly 325 GiB on each of two ARM64 nodes. We first needed to divert business traffic away from the affected nodes, then preserve the original processes and PIDs for investigation. A restart would release the objects that had accumulated on the heap, and a new process might not reproduce the problem quickly. This investigation therefore required reading /proc for the original processes and examining their state with tools such as GDB.
The same problem affected multiple production machines in this batch. The Memray screenshot came from one of them; the later heap investigation uses nodes A and B. Process names and PIDs refer to the records from each machine. The outputs below include only the fields needed for the investigation.
Start with Memray to locate allocations in aiohttp
In Memray's live view, the in-use allocations attributed to aiohttp's request-receiving function stood out. My first suspicion was that objects were being retained during request processing. I installed Memray using the Python interpreter that ran the service. Memray installation documentation
/usr/bin/python3.9 -m pip install --only-binary=:all: memray
I used memray attach to trace the existing production process, preserving it rather than restarting it. Using the PID in the screenshot as an example, the following command opens the live view. Memray attach documentation
sudo /usr/bin/python3.9 -m memray attach 11002
The screenshot below shows the affected process with PID 11002 on one of these machines. At the time of capture, tracing had been active for 843.9 seconds. Heap Usage was 32.922 MB, representing allocations observed during this Memray session that were still in use.
Sorted by Own Bytes, the first row is data_received in aiohttp.web_protocol. It accounts for 11.912 MB of Own Bytes, or 36.18%, and 12.175 MB of Total Bytes. Own Bytes covers allocations attributed to the function itself; Total Bytes also includes functions it calls. The screenshot also shows resolve for route matching and _write_headers for writing response headers. Memray live table field definitions
When handling a regular HTTP request, data_received calls self._request_parser.feed_data(data), so I narrowed the initial search to incoming request parsing. The screenshot only shows the tens of MB allocated after attaching that were still in use when it was taken. To determine whether this clue could explain RSS growing to 325 GiB over time, I moved to affected nodes A and B and directly examined the heap objects that had accumulated in their original processes. aiohttp 3.11.16 data_received source
Return to the original process and examine over 300 GiB of RSS
I used ps to identify the process to preserve and inspect on the affected node.
[root@vbox] #ps aux | grep '[h]ealth_web'
root 11030 6.8 60.0 320816512 320715200 ? Ssl Sep22 5759:44 health_web
health_web occupied roughly 60% of node A's RAM. Suspecting accumulated heap objects, I checked how much of the process's memory was anonymous, file-backed, or shared.
[root@vbox] #PID=11030
[root@vbox] #grep -E '^(Name|VmSize|VmRSS|VmSwap|RssAnon|RssFile|RssShmem|Threads):' "/proc/$PID/status"
Name: health_web
VmSize: 320836224 kB
VmRSS: 320734784 kB
RssAnon: 320729216 kB
RssFile: 5568 kB
RssShmem: 0 kB
VmSwap: 0 kB
Threads: 2
[root@vbox] #sudo readlink "/proc/$PID/exe"
/usr/bin/python3.9
VmRSS was about 305.88 GiB, and RssAnon was almost as large. To check whether this memory was private to the process and which mappings held it, I examined smaps_rollup and pmap.
[root@vbox] #sudo cat "/proc/$PID/smaps_rollup"
Rss: 320736320 kB
Pss_File: 1807 kB
Private_Dirty: 320730752 kB
Anonymous: 320730752 kB
AnonHugePages: 265289728 kB
Swap: 0 kB
[root@vbox] #sudo pmap -x "$PID" | sort -k3,3nr | head -n 12
0000ffbf9b0e0000 134193152 134193152 134193152 rw--- [ anon ]
0000ffdf998f0000 67145728 67145728 67145728 rw--- [ anon ]
0000ffb326b10000 52139776 52139712 52139712 rw--- [ anon ]
0000ffef9bd00000 33572864 33572864 33572864 rw--- [ anon ]
Anonymous and Private_Dirty were both about 305.87 GiB, narrowing the investigation to private anonymous memory. The largest VMAs were huge, but one address range can cover many adjacent allocations. The next question was how much of that memory still held live objects. Linux smaps documentation
Check current connections and transparent huge pages
Because the service uses HTTP, I next considered whether too many keep-alive connections had accumulated. The file descriptor count and TCP states on port 8100 gave an initial sense of scale on node A.
[root@vbox] #sudo ls -1 "/proc/$PID/fd" | wc -l
136
[root@vbox] #sudo ss -Htanp '( sport = :8100 )' |
awk -v pid="$PID" 'index($0, "pid=" pid ",") {count[$1]++}
END {for (state in count) print state, count[state]}'
LISTEN 2
ESTAB 128
The process had two threads and 128 established connections. That weakened the hypothesis that a huge number of current connections were simultaneously retaining requests. Meanwhile, smaps_rollup showed about 253 GiB of AnonHugePages. On node B, which had the same problem, I checked the page size and THP configuration to understand how the machine environment related to the large mappings.
[root@vbox] #uname -m
aarch64
[root@vbox] #getconf PAGESIZE
65536
[root@vbox] #cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never
[root@vbox] #cat /sys/kernel/mm/transparent_hugepage/hpage_pmd_size
536870912
Node B had a 64 KiB base page size, THP set to always, and a 512 MiB PMD size. These settings helped explain the page sizes used by the mappings. Next I needed to find out how many Python small-object blocks within those pages were still in use and how many were free.
Determine how many pymalloc arena blocks are still live
If most arenas were already empty, the next step would be to investigate allocator reclamation and fragmentation. If sampled arenas were still nearly full, the question would instead be what their live blocks contained. I first used GDB on node B to read the pymalloc arena counters and table pointer from the original process. Attaching briefly pauses the process, so this is appropriate after removing the node from traffic. The final detach command lets the target process resume.
[root@vbox] #PID=11026
[root@vbox] #sudo env DEBUGINFOD_URLS= gdb -nx -q -batch \
-iex 'set auto-load off' -p "$PID" \
-ex 'p narenas_currently_allocated' \
-ex 'p narenas_highwater' \
-ex 'p maxarenas' \
-ex 'p/x arenas' \
-ex 'detach'
No symbol "narenas_currently_allocated" in current context.
No symbol "arenas" in current context.
Since I could not read the arena counters this way, I checked whether there was enough headroom for a full heap dump with PyHeap.
[root@vbox] #sudo df -hT "/proc/$PID/root/tmp" /var/tmp
Filesystem Type Size Used Avail Use% Mounted on
tmpfs tmpfs 255G 64K 255G 1% /tmp
/dev/sda3 ext4 147G 60G 80G 43% /
[root@vbox] #awk '/^MemAvailable:/ {print}' /proc/meminfo
MemAvailable: 17353664 kB
Although /tmp reported 255 GiB available, it was a tmpfs, and the machine had only about 16.6 GiB of MemAvailable. The time and extra space needed to build a complete object graph were difficult to control. A better question at this point was whether we could sample a small set of arenas directly and read their object headers.
Sample the heap with health_web_heap_sample.py
health_web_heap_sample.py is a temporary diagnostic script written for this investigation. Given the original process's PID, it does two things: estimate the total capacity of pymalloc arenas, then sample their contents to determine whether they mostly hold live objects or free space and identify the types of live objects. This provides evidence from the existing running process even when GDB lacks symbols for the arena table.
The script selects candidate ranges from /proc/<pid>/maps, then validates the table structure through read-only access to /proc/<pid>/mem. At the scene there was an anonymous mapping of about 96 MiB. For the 64-bit layout of this CPython 3.9 build, 2^21 × 48 bytes is exactly 96 MiB. Adding the allocator header and page alignment matched the candidate mapping's size. The script also checked the arena addresses referenced by the entries, pool counts, and arena indices stored in pool records. CPython 3.9.9 pymalloc source
Once it locates the table, the script counts the mapped arenas and randomly samples 24 of them. It uses pool free lists and object headers to estimate live blocks and their types. It reads the existing heap of the running process, with a read limit of 112 MiB. arena_mapping_GiB comes from the arena table; the live-block percentage and type distribution come from sampling. With --details, it also inspects the types of objects inside lists and tuples and classifies strings.
The excerpt below shows the main sampling flow. proc points to /proc/<pid>, and page is the base page size. The complete script includes arena table validation, object type identification, and read-limit checks. The attached version replaces production probe configuration values with example domains. Complete sanitized script
with (proc / "mem").open("rb", buffering=0) as source:
memory = Memory(proc, source.fileno())
table, _ = locate_table(memory, page)
rng = random.Random(39)
current, _, _, entries = scan_table(memory, table, page, rng)
accepted, _, sizes, types, _ = sample_blocks(
memory, table, entries, rng, details
)
sampled_bytes = accepted * ARENA_BYTES
live_percent = round(100 * sum(sizes.values()) / sampled_bytes, 1) if sampled_bytes else None
result = {
"arena_mapping_GiB": round(current * ARENA_BYTES / GIB, 2),
"sampled_live_block_percent": live_percent,
"type_then_estimated_live_KiB_in_sample": [
[name, round(value / 1024, 1)] for name, value in types.most_common(12)
],
}
After copying the script to /tmp on node A, I ran a basic sample against the preserved PID.
[root@vbox] #PID=11030
[root@vbox] #sudo /usr/bin/python3.9 -B /tmp/health_web_heap_sample.py "$PID"
{
"rss_GiB": 325.55,
"arenas_mapped": 1332998,
"arena_mapping_GiB": 325.44,
"sampled_arenas": 24,
"sampled_live_block_percent": 98.3,
"object_headers_sampled": 9216,
"type_then_estimated_live_KiB_in_sample": [
["str", 3566.8],
["tuple", 1761.4],
["list", 380.6],
["<unidentified>", 328.9]
],
"target_MiB_read": 102.25
}
At 256 KiB per arena, the total arena capacity almost matched RSS, and live blocks occupied 98.3% of the sampled arenas. This lowered the priority of the hypothesis that most of the memory consisted of free blocks or fragmentation. By estimated live bytes in the sample, str, tuple, and list together accounted for about 94%. The next step was to inspect the contents of those containers and find object shapes recognizable in the source code.
Use container contents to test the request-header hypothesis
Strings and tuples alone could be request headers, application caches, or other intermediate objects. I added --details to follow one level of container elements. The first results included many (str, str) and (multidict._multidict.istr, str) pairs. Seeing istr made me suspect aiohttp's decoded headers. I then counted standard header names from an allowlist and checked whether values matched known probe configuration.
[root@vbox] #sudo /usr/bin/python3.9 -B /tmp/health_web_heap_sample.py --details "$PID"
{
"rss_GiB": 325.61,
"arena_mapping_GiB": 325.5,
"target_MiB_read": 102.72,
"object_details": {
"container_shape_then_count": [
["tuple[2](str, str)", 472],
["tuple[2](multidict._multidict.istr, str)", 438],
["list[2](tuple, tuple)", 129]
],
"list_length_and_first_pair_keys_or_types_then_count": [
[2, ["host", "via"], 128],
[11, ["host", "user-agent", "accept", "str + str"], 23],
[2, ["host", "connection"], 1]
],
"configured_probe_value_then_count": [
["configured upstream-check host", 154],
["configured monitor host", 103],
["configured LVS probe URL", 95]
]
}
}
The 128 recurring header lists containing Host and Via, together with the matches to probe configuration, narrowed the search to incoming request headers. I went back to the repository to inspect the handler and service entry point, looking for application code that might retain those headers.
[root@vbox] #rg -n 'async def health|add_route|make_handler|create_server' health_web.py
69:async def health(request):
82: app.router.add_route('GET', '/probe/{name}', health)
83: srv = await loop.create_server(app.make_handler(), ['127.0.0.1', '127.0.0.2'], sport)
The application logic for /probe/{name} checks a probe file and returns a response. Memray pointed to the receiving function, data_received, while sampling the original process's heap identified batches of request-header lists. Both clues pointed to incoming request handling. I next examined how aiohttp constructs and releases decoded headers before entering the handler.
Compare Python and aiohttp versions, then trace the leak to multidict
Initially, the difference that stood out was that the old nodes worked normally with Python 3.6, while affected nodes used Python 3.9. I ran 104,000 normal probes in a local Python 3.9 image, and memory usage stabilized. Since two Python 3.9 environments behaved differently, I started checking the libraries actually installed. The installation script had a branch that skipped aiohttp if it was already installed, so I queried the target server directly and examined the process's maps to confirm which C extensions were loaded.
[root@vbox] #sudo /usr/bin/python3.9 -B -m pip show aiohttp multidict yarl |
grep -E '^(Name|Version|Location):'
Name: aiohttp
Version: 3.11.16
Location: /usr/local/lib64/python3.9/site-packages
Name: multidict
Version: 6.3.1
Location: /usr/local/lib64/python3.9/site-packages
Name: yarl
Version: 1.18.3
Location: /usr/local/lib64/python3.9/site-packages
I then checked the extensions actually loaded in the original process, extracting only the path column from maps.
[root@vbox] #sudo awk '$6 ~ /\/(aiohttp|multidict|yarl)\/.*\.so$/ {print $6}' "/proc/$PID/maps" |
sort -u
/usr/local/lib64/python3.9/site-packages/aiohttp/_http_parser.cpython-39-aarch64-linux-gnu.so
/usr/local/lib64/python3.9/site-packages/multidict/_multidict.cpython-39-aarch64-linux-gnu.so
/usr/local/lib64/python3.9/site-packages/yarl/_quoting_c.cpython-39-aarch64-linux-gnu.so
The initial local amd64 image used aiohttp 3.13.3, multidict 6.7.1, and yarl 1.22.0. At the time, I had also observed a healthy node using aiohttp 3.13.5. I briefly suspected that the newer parser had changed how it released headers, so I compared the C parser source for 3.11.16 and 3.13.5. Both versions append decoded headers to a list and then call CIMultiDict(self._headers). This redirected my attention to what the constructor did with that argument. aiohttp 3.11.16 parser source · aiohttp 3.13.5 parser source
Upstream issue #1117 reported a leak in multidict 6.3.1. Suspecting that the fix involved the reference count of the input list, I extracted the argument parser and constructor from the two source packages and compared 6.3.1 with 6.3.2. 6.3.1 source package · 6.3.2 source package
[root@vbox] #for v in 6.3.1 6.3.2; do
tar -xOf "multidict-$v.tar.gz" "multidict-$v/multidict/_multidict.c" |
sed -n '/^_multidict_extend_parse_args(/,/^}/p; /^cimultidict_tp_init(/,/^}/p' \
> "multidict-$v-init.c"
done
[root@vbox] #diff -u multidict-6.3.1-init.c multidict-6.3.2-init.c
if (_multidict_extend(self, arg, kwds, "CIMultiDict", 1) < 0) {
- return -1;
+ goto fail;
}
+ Py_CLEAR(arg);
return 0;
+fail:
+ Py_CLEAR(arg);
+ return -1;
}
The constructor's argument parser obtains a new reference to the input object through Py_NewRef. In 6.3.1, the constructor failed to release it before returning. The diff shows that 6.3.2 added Py_CLEAR(arg) on both success and failure paths. This also matched the earlier heap samples. Even when the parser switched to a new list for the next request, the extra C reference remained, keeping the original list, its tuples, and their strings alive. multidict upstream issue #1117 · Upstream fix #1121 · 6.3.2 changelog
RSS after replacing dependencies in production
I replaced each of these two dependencies separately in production and observed health_web RSS.
| Dependency replaced in production | Before | After | RSS observation |
|---|---|---|---|
multidict |
6.3.1 |
6.7.1 |
Stopped continuously increasing |
aiohttp |
3.11.16 |
3.13.5 |
Continued increasing |
Conclusion
The sustained memory growth was caused by a reference-counting defect in multidict 6.3.1. The C constructor for CIMultiDict retained an extra reference to its input list, causing old request-header lists and their contents to accumulate with each request. The RSS behavior after replacing the dependency in production was consistent with both the heap samples and the upstream fix.
References & About the Author
This article was originally published on my personal technical blog and is republished here on DEV Community.
- Original article: Investigating a Memory Leak in a Python 3 aiohttp Service
Disclosure: The technical investigation, debugging, and conclusions presented in this article are my original work. AI tools were used to assist with English translation and language polishing.

Top comments (0)