Tutorials Design Patterns in C#
Leader Election Pattern — Complete Guide
Leader Election Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 53 of 69
Leader Election Pattern
GoF Core ✓ → Enterprise ✓ → Cloud & Craft
Cloud & Craft · 3 — Microservices & interviews · ~10 min · Module 6: Microservices & Cloud Patterns
What is this?
Leader election picks one instance to run a singleton job (scheduler, partition owner) while others standby.
Why should you care?
ShopNest nightly pricing job must not run three times on three pods.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
// Lease/lock based leadership
Console.WriteLine("try acquire lease pricing-leader ttl=30s");
Console.WriteLine("if acquired -> run job; renew lease");
Console.WriteLine("if not -> idle and retry");
What happened?
- Use distributed locks/leases (Redis, DB, k8s lease).
- Renew while working; lose lease on crash so another leader takes over.
Practice next
- Protect ShopNest scheduled job with a lease.
- Renew while running.
- Handle lost lease mid-job carefully.
- Log leader instance id.
- Metric leadership changes.
Remember
One active worker. Lease with TTL. Failover on crash.
ShopNest pricing leader
Only one pod runs the nightly repricer.
Outcome: No triple price updates.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!