Free — no signup required

Introduction: Why Do We Need Locks?

2 min read

There Can Be Only One

Imagine a busy restaurant kitchen with one oven. Multiple chefs want to use it at the same time. Without coordination, two chefs might shove their dishes in simultaneously, ruining both meals. The solution is simple: a sign on the oven that says "In Use." A chef checks the sign, flips it, uses the oven, then flips it back. This is a lock.

In software, the same problem appears when multiple threads share a resource — a file, a counter, a database row. A mutex (mutual exclusion lock) in a single program solves this using shared memory: one thread sets a flag in RAM, does its work, and clears the flag. Other threads check that flag before proceeding.

In a distributed system, you have multiple processes running on different machines. They don't share RAM. There is no single flag they can all read. Yet the same coordination problem exists — and the consequences of getting it wrong range from annoying to catastrophic:

  • Example 1 — Duplicate Email Digest: A scheduled job sends a daily summary email to every user. If two workers both start the job, every user receives two emails. Annoying, but recoverable.
  • Example 2 — Double Bank Withdrawal: Two workers both process the same withdrawal request. The user's account is debited twice. Disastrous and potentially illegal.

A Distributed Lock solves this by using a shared external system — Redis, ZooKeeper, etcd, or a relational database — as the "sign on the oven." Before a worker starts a critical task, it must acquire the lock from that shared system. If it succeeds, it proceeds. If another worker already holds the lock, the newcomer either waits or backs off.

The key difference from a single-machine mutex is that the lock state lives outside any one process. Every worker, regardless of which machine it runs on, consults the same external authority.

Interview Tip

Interviewers often ask: "Why can't you just use a database row as a lock?" You can — and it works. A SELECT FOR UPDATE or a unique constraint on a "lock" table is a valid distributed lock. The follow-up is: "What are the trade-offs?" Answer: database locks are durable and transactional but add latency and load to your primary database. Dedicated locking systems like Redis or ZooKeeper are faster and purpose-built, but introduce another dependency. The right choice depends on your consistency requirements and operational complexity tolerance.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free