4

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.)

2
  • I usually think I'm asking a dumb question with an obvious answer, but then wonder if it isn't a tricky problem without one.
    – SexxLuthor
    Feb 20, 2016 at 17:44
  • I'm also considering leaving it in Postgres but am conscious of potential performance issues, as this component is a message pass-through. I'm more curious now about how/if others are handling this scenario.
    – SexxLuthor
    Feb 22, 2016 at 12:03

1 Answer 1

5
+50

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.