Template to avoid using the single-count message counter in multi-instance applications

I would like to know which template is recommended for working with a counter representing the number of processed messages, with an application that should be stateless.

For example, in an architecture where an application is deployed on multiple servers, the database is used to store persistent information (session, etc.). However, such information is not subject to parallel updates, for example, a message counter. In a mono-instance application, we can use singleton, but this is not the case here.

What will be your proposal for the implementation of such a counter? Does the counter use a bad design?

+5
source share
3 answers

I cannot directly answer your question, but I can give you a link to an accessible counter service, which is multi-threaded, multi-directional, scalable and at the same time considers accessibility scenarios. Check out the jgroups counter service http://jgroups.org/manual/index.html#CounterService .

This can lead to many problems in a distributed counter script, and also act as a valid working link.

+1
source

I don’t think there is any model to make this very abstract task. Also:

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

Using singleton does NOT guarantee data security in a multi-threaded system. You need some synchronization primitives. Very simple - critical section.

If all your applications need to update some counter, it seems reasonable to reorganize this ... "counting" control into a microservice and use the critical section inside the microservice to update the resource. In this case, at any given time, you are guaranteed to have only one thread update counter.

0
source

Possible solutions with a database:

  • create a stored procedure that will update the counter and return a 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 for each instance of the application that will be connected to this database

0
source

All Articles