r/rails • u/dogweather • 7d ago
Discussion Improving jemalloc's memory use
Long-running Rails 8.1 app (Ruby 4.0, Puma single mode, 5 threads, jemalloc) on a 512 MB Heroku dyno had a slow native memory creep for over a year. Ruby's object count stayed flat while RSS kept climbing, sometimes to the point of swapping or crashing. The chart shows the before and after. On the left, jemalloc's allocated memory saws upward toward 400+ MB between restarts. What fixed most of it was forcing a full GC every 300 seconds in Puma's out-of-band hook, between requests, so it never adds latency.
After that I set RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO=0.10, GOAL_RATIO=0.15 and MAX_RATIO=0.25 so Ruby keeps less empty heap around. Allocated memory now sits flat around 200 to 240 MB, and boot memory dropped by another 35 MB. RSS growth went from about 25 MB/h to 2 or 3 MB/h, and p95 latency actually went down. Next I'm trying min threads = max threads to stop Puma from creating and reaping threads all day.
4
u/yxhuvud 6d ago
Honestly none of these look that bad. I can live with it using half a gb, I can't live with the unbounded growth that is seen without jemalloc. How does the change affect performance?
14
u/Cokemax1 7d ago
jemalloc should be default rails app memory allocator at this point.
3
u/sshaw_ 5d ago
A Ruby/Rails app with only 512MB of memory. Wow. What does the app do, how much traffic do you get, and have you always used 512MB for it?
0
u/Striking-Pride-2663 18h ago
The p95 latency drop makes a lot of sense on a 512 MB dyno, since moving major GC into Puma's out-of-band hook keeps pauses off the request path and avoids hitting swap. Have you noticed any extra CPU overhead during traffic spikes after lowering GOAL_RATIO to 0.15, or is the app mostly IO-bound?