Distributed Synchronized Background Jobs ASP Core
Problem:-
In the age of containerized apps, running multiple instances, and Kubernetes, sometimes you face a situation where you want to run a background jobs in the ASP Core, but you have multiple instances of application running on Kubernetes for example, so you will end up with duplicated running background jobs equal to the number of running application instances (e.g. same background job runs for each application instance)
Solution:-
- Easy and straight forward : separate the background jobs into a new solution and deploy one instance of it (100% confidence of running one instance)
- Do a synchronization mechanism to allow only one instance runs jobs ( not 100% confidence of running one instance)
We will talk about second solution:-
- We need to start jobs at different times, not at the same time, so, we can synchronize work (e.g. one job-instance start with the smallest time and the others in a different times).
- We need a "centralized store" to store the state of synchronization mechanism with cheap access like (Redis)
- We need to monitor the starting instance that take the work so, schedule work to another instance for starting in case of failure.
Let us now discuss the first point in the second solution.
- I need a unique random number generator that generates unique numbers at same time of calls (e.g. multiple instances run at the same time and each instance call the random number generator to delay the amount of time and then check synchronization state to check if it can start work or not)
- If we choose "Random class" to get random number, it returns the same number when calls multiple times at the same time
- We need away to convert Guid to a Number, it rarely make a collision (e.g. return same number for multiple calls at the same time).
- Code For Convert Guid to "scaled number threshold"
- We choose Redis Distributed cache to store Synchronization State
- Synchronization Workflow:
- namespace "DistributedSynchronizedBackgroundJobs.BackgroundJobs"
- class "TimedHostedBackgroundService : BackgroundService"
Comments
Post a Comment