Rails: Fixing the memory leak / performance issues in prepend_view_path

Recently we detected a memory leak in one of our applications. Hunting it down, we found that the memory leak was located in Rails' #prepend_view_path. It occurs when the instance method prepend_view_path is called in each request, which is a common thing in a multi-tenant application.

On top of leaking memory, it also causes a performance hit, since templates rendered using the prepended view path will not be cached and compiled anew on each request.

This is not a new memory leak. It was first reported in in 2014 Show archive.org snapshot . Five years later, Frederick cheung wrote in detail how he chased down this memory leak Show archive.org snapshot . Last year, mudge added some dev improvement Show archive.org snapshot .

We took their solution a little further to prevent the leak at its root. When you include the attached module in your ApplicationController, you can just use #prepend_view_path as before. Note that Rails 7 version differs slightly.

Known affected Rails versions (maybe more): Rails 4.0 - 7.0

This issue is now fixed in main Show archive.org snapshot and might be released in Rails 7.2.

Dominik Schöler Over 1 year ago