What Is a Distributed Lock? Race Conditions Explained with Rails and Redis
Two background workers pick up the same payment job at the same instant. Both check whether the order is paid. Both read false. Both charge the card. Nothing in the code is wrong. The timing is.
This video follows that one example all the way through: what a distributed lock is, what happens between a worker and the lock service, how it looks in a Rails app with Redis, and - just as important - what a lock still does not give you.
What you will learn:
- What a race condition actually looks like across two servers
- Why checking and then acting is two steps, not one
- What a distributed lock is, and why the lock lives outside your app
- The full exchange: acquire, execute, refuse, release, hand over
- Why every lock needs a lease, so a crashed worker cannot hold a key forever
- Why you must verify ownership before releasing a lock
- What fencing tokens protect against
- Why a lock alone does not give you exactly-once processing
The honest part: a distributed lock prevents overlap. Idempotency survives a retry. A database transaction enforces the rule. They solve related but different problems, and payment code needs all three. If you take one thing from this video, take that.
A note on the code: the snippet is pseudocode. DistributedLock is not a Rails API. And Rails' own with_lock is something else entirely - a pessimistic database row lock - so do not reach for it expecting coordination across servers.
Chapters:
00:00 - Two workers, one order
00:10 - The race condition, step by step
00:25 - What a distributed lock is
00:40 - Acquire, execute, release
01:00 - A Rails example with Redis
01:25 - Benefits and trade-offs
01:45 - The key takeaway
#DistributedSystems #RubyOnRails #Redis #BackendDevelopment #RaceCondition #Concurrency #SoftwareArchitecture #Sidekiq #SystemDesign #Idempotency
— #Astmation —
#software #systems, #automation, and #AI-powered #applications.
Build. Automate. Evolve.
https://astmation.com/
Watch on YouTube