Leader election
Consider a scenario where multiple application instances need to elect a leader among themselves and be aware of the current leader at any given time.
This scenario can be implemented using semaphores in YDB coordination nodes as follows:
- A semaphore is created (for example, named
my-service-leader) withLimit=1. - All application instances call
AcquireSemaphorewithCount=1, specifying their endpoint in theDatafield. - Only one application instance's call will complete quickly, while others will be queued. The application instance whose call completes successfully becomes the current leader.
- All application instances call
DescribeSemaphorewithWatchOwners=trueandIncludeOwners=true. The result'sOwnersfield will contain at most one element, from which the current leader's endpoint can be determined via itsDatafield. - When the leader changes,
OnChangedis called. In this case, application instances make a similarDescribeSemaphorecall to learn about the new leader.
Was the article helpful?
Previous