feat: use jemalloc to fix glibc malloc memory fragmentation - #395
Merged
su-kaka merged 1 commit intoJul 23, 2026
Merged
Conversation
Problem: Under high-frequency request patterns (20-40 req/min), glibc's malloc allocator causes severe heap fragmentation. The process RSS grows to 2.5GB+ while actual Python objects only use ~1MB. glibc uses brk() for small allocations and never returns freed heap pages to the OS. Solution: - Install jemalloc as a drop-in malloc replacement via LD_PRELOAD - jemalloc uses mmap instead of brk, actively returns freed memory to OS - Configure aggressive memory reclamation (dirty_decay_ms=5000) - Add periodic gc.collect() + malloc_trim() loop as supplementary cleanup - Fix credential_manager shutdown (use singleton instead of unset global) Result: Memory usage dropped from 2.68GiB to ~460MiB under the same workload.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
malloccauses severe heap fragmentation. RSS grows to 2.5GB+ while GC-tracked Python objects only use ~1MB. glibc usesbrk()for small allocations and never returns freed heap pages to the OS.LD_PRELOAD. jemalloc usesmmapinstead ofbrk, actively returns freed memory to OS. Also adds a periodicgc.collect()+malloc_trim()background task as supplementary cleanup.Changes
Dockerfile
libjemalloc2packageLD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2to replace glibc mallocMALLOC_CONF="background_thread:true,dirty_decay_ms:5000,muzzy_decay_ms:5000"for aggressive memory reclamationweb.py
_memory_trim_loop(): periodic (every 60s)gc.collect()+malloc_trim(0)to force return of free heap pages to OScredential_managerinstance directly instead of the always-Noneglobal_credential_managervariableTest plan
/proc/1/mapsshowslibjemalloc.so.2)LD_PRELOADandMALLOC_CONFenvironment variables are set in PID 1