1

I have a rails app with a simple class called Nutrients. This relates to a table with about 150 nutrient items and some small amounts of info. This data never changes during the apps use. As these items are used rather often, and the total size of data is tiny I really want to have them maintained constantly in memory (to reduce database or cache accesses unnecessarily).

As such I have looked at using a class memoization technique ie:

class Nutrient < ApplicationRecord

  def self.all_cached
    @@all_nutrients ||= Nutrient.all.to_a
  end

end

Is this safe to do in a live rails app? I am concerned about thread safety and that potentially having separate processes access the same array could slow things down or cause crashes. This nutrient list is never changed or mutated after the app starts.

5
  • For what controller actions are you using these values. How about storing these values in redis instead and query redis for these values, that would be fast and avoid hitting the database. Commented Mar 19, 2017 at 2:25
  • They're used by a whole load of different actions throughout the application. Yes so that's definitely another option, but it just seemed unnecessary to even go to redis when they are never going to change. After all that still will be much slower than in memory on the server Commented Mar 20, 2017 at 5:37
  • have you looked into this answer stackoverflow.com/a/1168090/1087841 Commented Mar 20, 2017 at 5:55
  • Thanks but that still doesn't quite cover the issue. The session is definitely not the place for it. What I'm trying to work out is if you can use class variables safely among a multi process rails app when it's read only, or will this cause blocking and concurrency crashes. Otherwise I can certainly use a redis cache, but would be nice to know for certain either way Commented Mar 20, 2017 at 5:58
  • I've gotten weird, sporadic errors when trying to memoize class or class-instance variables for caching across requests, so I avoid it. I use Rails.cache.fetch for caching primitives across requests. Don't have an answer for ActiveRecord results though. Commented Aug 6, 2019 at 2:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.