Description
I've set up a sample repo that best illustrates the issue.
If one were to use many postgres schemas in their app, ActiveRecord will cache type mappings in memory for all these schemas, which leads to memory bloat. This is the case in a multi-tenant setup, like the one used by the apartment gem
You can see the results of these mappings here.
The source of the problem seems to come from the load_additional_types call inside initialize_type_map
.
You'll notice in the results sections, the *wo_additional_types
files show considerably lower memory usage. I haven't fully traced down exactly where these additional types are used. The only thing I can see that does a lookup by oid if the type is unknown is in exec_query but I'm not quite sure how that differs from just query
or exec
.
From what I can see, the pg_type
table that these additional types are being loaded from, contains rows that look like:
3189159,"_foos_16",3189160,",","array_in",,"b",0
(given the sample app mentioned above).
Again I haven't fully grasped what exactly all this is used for, but I'm wondering if this query can be tightened up a bit to handle this situation, given that those mappings don't actually appear to be useful/used (to my untrained eye).
In production, we're seeing memory usage of ~300+ MB PER CONNECTION which is held onto from the moment the thread connects to the db until it's shut down. This is particularly troubling when we run Sidekiq with 30+ threads.
I'm reaching out for advice or tips on how to make this better as this is about the end of my knowledge of the situation. I'm happy to submit a PR given some guidance on the best way to fix this (if that's possible).
Many Thanks