Pattern to avoid message counter in a singleton on multi instances applications

516 Views Asked by At

I would like to know which pattern is recommended to work with counter representing the number of message processed, with an application that should be stateless.

For example, in an architecture where an application is deployed on several servers, a database is used to store the persistent information (session, etc...). However, such information are not exposed to concurrent updates like a message counter would be. In a mono-instance application we could use singleton, but this is not the case here.

What would be your suggestion to implement a such counter ? Is using a counter a bad design ?

3

There are 3 best solutions below

0
On

Possible solutions with a database:

  • create a stored procedure that will update the counter and return the new value (UPDATE ... RETURNING ... INTO) in Oracle for example
  • $inc in mongodb for example

counter will be stored in the database and will be available on each application instances that will be connected to this database

6
On

I do not think there is some pattern to do this very abstracted task. Also:

In a mono-instance application we could use singleton, but this is not the case here.

Using a singleton DOES NOT guarantee data safety in a multithreaded system. You need some synchronisation primitives. The very simple is a critical section.

If all of your applications should update some counter, it looks reasonable to refactor this... "counter" management into a microservice and use critical section inside microservice to update resource. In this case in each given moment in time you are guaranteed to have only one thread updating counter.

3
On

I may not be directly answering to your question, but I can give you a reference of a counter service available, which is multi threaded , multi noded, scalable and at the same time considers availability scenarios. Check the jgroups counter service http://jgroups.org/manual/index.html#CounterService.

This can guide you to a set of problems in the scenario of a distributed counter and also act as a live working reference.