Distributed lock mongodb
Skill kjuhwa/skills-hub/skills/backend/distributed-lock-mongodb
Self-correcting knowledge corpus for Claude Code — 9 stable shape clusters, bias-correction pipeline baked into contribution flow. 47 papers, 45 techniques, 1.1k skills.
npx -y skills add kjuhwa/skills-hub --skill distributed-lock-mongodbAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
MongoDB findAndModify-based distributed lock with TTL expiry, owner tagging, and retry loop for multi-instance Spring Boot services.
SKILL.md
1.8 KB, 368 tokens by cl100k_base, as published. Nobody here has run it
Distributed Lock over MongoDB
Shape
A DistributedLockService exposes tryLock(key, ttl) / release(key, owner).
Implementation uses atomic findAndModify on a single locks collection:
- Document:
{ _id: key, owner: "<node>:<thread>", expiresAt: Date } - Acquire:
findAndModify(query = { _id: key, $or: [{expiresAt: {$lt: now}}, {_id: {$exists: false}}] }, update = { owner, expiresAt: now + ttl }, upsert: true) - Release:
deleteOne({ _id: key, owner: self })(never blind delete) - Retry: loop with 100 ms sleep up to configured timeout before giving up
Steps
- Create collection
lockswith TTL index onexpiresAtas a safety net (not authoritative — acquire query checks expiry). - Implement
tryLockusing Mongo atomic upsert; returnfalsewhen a different non-expired owner holds the key. - Always stamp
owner = "<hostname>:<threadName>"so release is idempotent and crash-safe. - Wrap critical section in
try { if (tryLock) ... } finally { release }. - For retry-until-timeout semantics, add a thin loop around
tryLockrather than blocking inside the lock method.
Counter / Caveats
- NTP drift across nodes skews TTL comparison — keep TTLs generous (seconds, not ms).
- Do not use a TTL index as the only expiry mechanism; the background deleter runs every 60 s.
- Prefer Redis/Redisson if you need fair queuing or pub-sub release notifications.
What ships with it: 1 file
711 B alongside SKILL.md
- content.md711 B