Ruby on Rails – How to Implement a Truly Global Variable in a Rails App

messagingmultithreadingrubyruby-on-rails

How can I best implement a global counter in a Rails API app? (A central component in a system with several.)

Basically I have a transaction id I need to increment and roll over past a maximum value. So it has some custom logic attached and needs to be managed, more than simply auto-incrementing to infinity.

I'm thinking about using Redis to keep it a fast, in-memory transaction, persisted afterward to Postgres for auditing purposes.

Is this a sound and reliable approach? What do most people do when needing some statefulness across multiple processes in a Rails app? Considering the configuration of most app servers, global and class variables, mutexes, etc.

(I've done a lot of research and had asked this question differently yesterday, but don't think I characterized it properly.)

Best Answer

You already got the right answer yourself. Store it in a Database and consume it as you need it.

As for the approach of database, you also got the best answer yourself: using Redis for performance and storing in a relational database data for auditing. It seems you got a plan and you did your research.

Related Topic