惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
F
Full Disclosure
AI
AI
罗磊的独立博客
博客园 - 【当耐特】
U
Unit 42
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
博客园_首页
H
Help Net Security
量子位
月光博客
月光博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog RSS Feed
Webroot Blog
Webroot Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
爱范儿
爱范儿
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
CERT Recently Published Vulnerability Notes
Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Securelist

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens Prisoner's Dilemma Climbing No More The Weekly Win Mevlana Candy Brewing Turkish Tea Onboarding Your Engineering Manager Technical Deep Dives Yapay Zekâ Çağında Bilgisayar Mühendisliği Building Remote Teams From Idea to Launch in 2 Weeks Reflecting on Software Engineering Handbook Representing the Business New Manager Survival Guide Take Self Reviews Seriously Chasing Real Respect The Invisible Difference Learning the Johari Window Management is a Lonely Place Simple Task Management AI Balance in Work PIP Manager Insights Engineering Manager Interview Preparation Work-Life Balance as a Manager Bridging the Management Disconnect Tech Hiring Bubble Bursts Traits for EMs Simple Acts of Recognition Matter The Question I Ask Every New Report The Reality of an Employer's Market Bridging Ideals and Reality Hiring Red Flags Why The Godfather Is So Damn Good Subteam Tenets No Fluff Please Losing a Top Performer Balancing Act of Reliability Building Trust in Engineering Teams Ideal Number of Direct Reports Overriding a People Leader’s Decision From Misperception to Promotion Perception vs Perspective Setting Goals From Engineer to Manager Getting Delegation Right Interviewing Your Future Boss Celebrating Our Book in Iceland Operational Skills Needed On Writing Software Engineering Handbook Charlie Munger Quotes Working with Dependencies From Las Vegas to Canyons Navigating Layoffs Handling Competitive Dynamics A Weekend Getaway to Malta Engineering Health Essentials Should Dev Managers Code? Confronting the Life on Pause Winning Eleven Kindness is A Choice Bireysel Katılımcılar ve Yöneticiler Leading from Where You Are The Subtle Art of Listening Coding in Leadership The Power of Consistency The Making of a Leader The Path to Leadership Embracing TikTok Talent Sourcing Journey Leading Self Managing Teams Cracking Coding Bottlenecks
Simple Mutual Exclusion
Yusuf Aytas · 2018-07-11 · via Yusuf Aytas

Published · 3 min read

When we design services for high availability, we often deploy more than one instance of the same application. It might be two servers behind a load balancer or a few nodes sharing the same workload. This setup is great for redundancy and performance, but it introduces a simple question: how can we make sure that only one instance executes a specific piece of code at a time?

That is where mutual exclusion comes in. It ensures that a critical operation runs only once, even when multiple nodes are active.

Imagine a scheduled task that sends daily reports or reminder emails. You certainly do not want every node to send the same email twice. In Spring Framework, a typical implementation might look like this:

@Scheduled(cron = "59 59 8 \* \* \*" /\* Every day at 8:59:59am \*/)
public void sendEmails() {
  List emails = emailDAO.getEmails();
  emails.forEach(email -> sendEmail(email));
}

Now, the challenge is ensuring that only one node runs this method. Ideally, we could decorate it with something like this:

@Scheduled(cron = "59 59 8 \* \* \*" /\* Every day at 8:59:59am \*/)  
@TryLock(name = "emailLock", owner = NODE\_NAME, lockFor = TEN\_MINUTE)  
public void sendEmails() {  
  List emails = emailDAO.getEmails();  
  emails.forEach(email -> sendEmail(email));  
}

To solve this, I built a small library called dlock. It provides a simple mutual exclusion mechanism using relational databases such as PostgreSQL and MySQL. You can extend it to other coordination systems like ZooKeeper, Consul, or etcd if needed.

Although distributed locking can be done in many ways, my goal is to keep it lightweight and practical. Many production systems don't have a full cluster management solution, but almost all of them have a relational database. That made the database an ideal place to coordinate small-scale distributed locks.

This approach is not limited to scheduled jobs. You can use it anywhere you need to guarantee single execution, such as:

  • Message processing
  • File imports
  • Cleanup or migration jobs
  • Periodic billing tasks

Here’s another simple example:

@Component  
class MessageProcessor{  
  ...  
  @TryLock(name = "messageProcessor", owner = NODE\_NAME, lockFor = TEN\_MINUTE)  
  public void processMessage(Message message) {  
    ...  
  }  
}  
@Component  
class MessageService{  
  ...  
  @PostConstruct  
  public void initProcessor(){  
    while (true) {  
      Message message = pollMessage();  
      messageProcessor.processMessage(message);  
    }  
  }  
}

The principle is straightforward. Each node attempts to acquire the same lock before executing the critical section. The first one succeeds, the others wait or skip execution depending on your configuration.

Even a simple lock with an expiration time can prevent accidental duplication, inconsistent state, or race conditions in multi-node environments. In consequence, mutual exclusion remains one of the easiest and most reliable techniques to keep distributed systems consistent. In consequence, you can implement a simple lock with a timeout with dlock.