r/ruby • u/day__moon • Apr 21 '26
Expensive Memory Allocation for CSV Generation
Hi all,
Seeking feedback on memory bloat in a Rails app hosted on Render.
I am loading at times 30k+ records and iterating through them to generate a CSV with FastExcel. I am NOT using .pluck, as I need most of the columns and some instance method outputs - I AM using find_each and includes to eager load some associations. I used the memory_profiler gem to show that ActiveModel::Attribute::WithCastValue is the largest culprit of memory allocation. This all makes sense.. but what I can't figure out is how to free up that memory after the process is done. CSV send_data'ed to the client, I am manually trying to empty all the instance variables and triggering GC.start to try to do some cleanup, but memory in Render metrics goes up and does not come down.
All thoughts welcome!

7
u/xutopia Apr 21 '26
If your concern is memory... write to a file the CSV being generated and reduce the size of the batches:
Record.find_each(batch_size: 100) ...It might take a bit longer to run but memory usage would be lower (it defaults at 1000).
The second optimization is *DO NOT USE FASTEXCEL*. It's faster for Excel generation but a CSV is a very small text file and can be generated using the standard library.
5
u/benzado Apr 21 '26
Apologies if I’m misinterpreting the graph, but if that’s memory claimed by the Ruby process, as observed by the OS, then I don’t think it will ever decrease.
Ruby allocates a number of pages of memory at start, then manages it internally. When it needs more space, it allocates more pages, but when the Ruby objects are freed, it never releases that memory to the OS. Most other VMs like Java, Python, etc. behave this way.
This isn’t necessarily a problem, because if it never uses as much memory again, those pages will be inactive and the first to be swapped to disk if space is needed. But your system may not have a swapfile configured.
The main question is: does your memory usage keep increasing every time you do a CSV export? Or does it increase the first time, and stay flat afterwards? If it’s the former, you have a leak. If it’s the latter, it’s just the process growing the heap.
2
u/day__moon Apr 23 '26
Thank you to everyone who has chimed in. Makes me feel like this sub is not entirely bot posts and self promotion!
2
u/westonganger Apr 22 '26
In the past I've utilized the light_record gem to assist with building massive spreadsheets by avoiding the AR object allocation (which hinders performance significantly).
https://github.com/Paxa/light_record
6
u/anykeyh Apr 21 '26
You can look to stream the csv output. Also try to call GC#compact as Ruby doesn't always release allocated pages from the heap.
0
u/[deleted] Apr 22 '26
[deleted] — view deleted comment