0

I am building out a classifier API to insert into our growing platform as a stand-alone service. Basically I want to send over a piece of text and run some proprietary magic on it and respond with a json back.

Easy, right?

Issue is that there are a couple of methods I want to run on the text that require loading big hashes into memory for the operation. Right now, I have to initialize those objects every time I send a new bit of text to be operated on.

What's the best way to set up a global instance of an object that I can access within the controller without having to recreate it for every call?

Should this be in an initializer or is there a way to tie it to a specific controller?

2 Answers 2

0

You could use a global variable, but seriously not recommended - be sure to read this answer by Simone Carletti. I should add - he refers to using a more robust caching solution, which is what I would recommend.

Sign up to request clarification or add additional context in comments.

2 Comments

Rob, it's ugly but using a global like you suggested(sorta) got us to MVP. We'll leverage Simone's and Ben's suggestions as we refactor for robustness and speed.
Totally agree on the ugliness - as I said, my pref would be towards caching.
0

You have a few options here.

A. You could load the hashes into a constant on rails startup making them available to the entire application, making it load only once. You would do this by adding the constant in an initializer.

B. Load the hashes into memcached and rework your logic to query memcached instead of the hashes. This would be slightly more complex, but would be my preferred method if I was doing this. I would have a rake task that loads the file into memcached and then share the instance of memcached between instances or rails. This would reduce the amount of memory overhead required. Just make sure you set the expire to nil.

1 Comment

Ben, thanks! I think this is definitely my longer term solution.

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.