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
AcquireSemaphore
withCount=1
, specifying their endpoint in theData
field. - 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
DescribeSemaphore
withWatchOwners=true
andIncludeOwners=true
. The result'sOwners
field will contain at most one element, from which the current leader's endpoint can be determined via itsData
field. - When the leader changes,
OnChanged
is called. In this case, application instances make a similarDescribeSemaphore
call to learn about the new leader.