Targeted Query Caching for Expensive Endpoints

5034
0

I’ve had endpoints where the same lookups get repeated across helpers and partials, and I didn’t want to pay for query caching on every request. In Scoped query cache, I wrap only the expensive report build in ActiveRecord::Base.cache, so the cache lives for the duration of that block and nowhere else. Then, in Report builder, I keep the builder focused on returning structured data and let ActiveRecord reuse the cached queries for calls like Project.visible_to(...).order(...).limit(...) and Comment.visible_to(...).order(...).limit(...). This pattern keeps memory pressure low for the average request, but it still gives me the “one request, one set of queries” behavior on pages that are query-heavy by design. It’s targeted, predictable, and easy to remove if it stops helping.