dimanche 7 novembre 2021

How do I track random numbers with stateless services

I have a design problem that I'm looking for an efficient way to solve:

I have three instances of a single service running. Each instance is totally stateless and exposes a single endpoint /token. When the /token endpoint is called by a client, a random number is returned. The random number is generated by a non-repeating pseudo-random number generator which generates a unique random integer for the first n-times it is called and then repeat the same sequence the next n-times it is called. In other words, it's a repeating cycle of n values. So say n = 20, it'll return unique values within the range of 0 to 20 for the first 20 times it is called.

The problem here is: given that I have three instances of this service running, how do I avoid duplicating random integers since any of the services can't know what random value has been generated by either of them.

Here's what I've done:

  • I have passed as enviroment variable, a seed value that ensures that all the services are generating the same random sequence.

  • I have setup a database that each of these services can access remotely. It has a table with a single column map set to a default value of 0

  • When the client calls the /token endpoint of a service, the service increases the value in the map column by 1 and fetches the resulting value.

  • I then return the random number this resulting value maps to in the random sequence

Is the above approach efficient ? Could the services experience a race condition when trying to access the database row ? Could this problem be solved without a database ?

Suggestions would be really appreciated.

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire