Zeeshan Adil
Book a call
← All writing
Cover of Choosing Between Optimistic, Pessimistic, Advisory, and Distributed Locks

Choosing Between Optimistic, Pessimistic, Advisory, and Distributed Locks

by Zeeshan Adil·in DatabasesUpdated 25 min read
Listen to this articleChoosing Between Optimistic, Pessimistic, Advisory, and Distributed Locks 27 min · read by an AI voice
0:00 / 26:30

When to use SELECT FOR UPDATE, version checks, Postgres advisory locks or Redis locks, and which failures each one survives. Includes fencing tokens for expired leases.

THE SHORT VERSION

  • If the data lives in one PostgreSQL database, use that database: a conditional UPDATE, a version check, or SELECT ... FOR UPDATE (with SKIP LOCKED for queues).
  • Advisory locks lock a number you choose, not a row. Prefer pg_advisory_xact_lock, which releases at commit or rollback, over session-level locks.
  • A Redis lock with a TTL is fine for avoiding duplicate work. For correctness, a lease that can expire is not enough: the resource must also check a fencing token.
  • Every lock assumes something about failure (crashes, pauses, partitions, clocks). Write the assumption down before you pick the lock.

Two users save changes to the same record, and the later save quietly overwrites the first. Or two workers pick up the same job and both run it. These are different symptoms of the same problem: independent pieces of work are competing over shared state.

Locks and conditional updates can help, but they make different promises. The right choice depends on where the data lives, how often work conflicts, and what should happen when a worker fails.

Concurrency is when more than one thing is in progress at the same time and they touch something shared. Two users, two workers, two requests, one row.

It does not have to mean they run at the exact same instant on different cores, that is parallelism. Concurrency only means their steps can interleave, so one can read something while another is halfway through changing it. That interleaving is where every problem in this post comes from. A single-threaded server handling two requests can still have concurrency bugs.

The techniques in this article make different tradeoffs. Some make other work wait; others detect a conflict and ask the application to try again. The important question is which guarantee your operation actually needs.

This is what I wish someone had explained to me earlier in my career. Not just the definitions, but when each one actually makes sense, and what each one quietly assumes about failure.

Reading path: Basic SQL and transactions are enough to start. Follow the competing withdrawals to see why coordination is needed, then compare pessimistic and optimistic locking. If you are choosing a design now, jump to How to choose, then read the failure assumptions for that choice. Save distributed leases for work that crosses a database boundary.

The core problem

Here's the scenario that burns everyone at least once.

You have a bank account with $100. Two requests come in at the same time, both trying to withdraw $80.

Request A reads the balance: $100. Okay, $80 is fine. Request B reads the balance: $100. Okay, $80 is fine. Request A writes: $100 - $80 = $20. Request B writes: $100 - $80 = $20.

Both succeeded. You dispensed $160 from a $100 account. The balance shows $20 and someone's having a very bad day.

This is a race condition: the result depends on how the operations' steps interleave. The problem isn't simply that two requests arrived close together; it's that both made a decision using the same old balance.

The read and write weren't atomic. Something else snuck in between.

For this withdrawal, the check and the update need to happen together. A conditional UPDATE lets PostgreSQL evaluate the condition as part of the write, rather than leaving a gap between a separate read and write.

For this particular bug, you often do not need an explicit lock. A single conditional statement does the check and the write together:

Code
UPDATE accounts
SET balance = balance - 80
WHERE id = 42 AND balance >= 80;
-- 1 row updated: the withdrawal happened.
-- 0 rows updated: not enough money, or the row does not exist.

Reach for this first. The rest of the post is for the cases where the check and the write cannot be folded into one statement.

Pessimistic locking

Pessimistic locking assumes conflict is likely. So you lock the resource before you even start working on it. Everyone else who wants to change it waits.

In SQL databases, this usually looks like SELECT ... FOR UPDATE:

Code
BEGIN;
SELECT * FROM accounts WHERE id = 42 FOR UPDATE;
-- Row is now locked. No other transaction can update, delete or lock it until we're done.
-- Recheck the business condition while holding the lock.
UPDATE accounts SET balance = balance - 80 WHERE id = 42 AND balance >= 80;
-- Require one updated row before treating the withdrawal as successful.
COMMIT;

The moment you run that SELECT ... FOR UPDATE, the database locks that row. Any other transaction that tries to update it, delete it, or take its own FOR UPDATE or FOR SHARE lock on it will block, just sit there waiting, until you commit or roll back.

In PostgreSQL, a plain SELECT does not block. Readers see the last committed version of the row (that is MVCC), so a row lock only gets in the way of writers and other lockers.

A detail worth knowing: under the default READ COMMITTED level, a transaction that waited on your lock re-reads the row after you commit, so it sees your update. Under REPEATABLE READ or SERIALIZABLE, a transaction that hits a row changed by someone else since its snapshot gets a serialization error instead, and has to be retried. Locks and isolation levels are two tools for the same problem, and they interact.

When it works well:

  • High contention. Many writers hitting the same rows constantly.
  • Short transactions. Lock, do your thing, release. Milliseconds to a few seconds.
  • When waiting for a competing writer is preferable to repeatedly retrying a version conflict. Deadlocks and serialization failures can still require retries.

Contention is just competition for the same resource. High contention means lots of requests fighting over the same rows at the same time. Low contention means they mostly stay out of each other's way.

When it hurts:

  • Long-running operations. You're holding every other writer hostage.
  • Distributed systems where database-level locks don't span services.
  • Anything slow inside the transaction. The lock is held until commit.

I've seen systems grind to a halt because someone held a row lock while calling an external API. The API timed out after 30 seconds. Every other request piled up behind it. Don't do that.

Failure assumption: the lock lives as long as the transaction on the server. PostgreSQL rolls it back and releases its locks when it detects the session has ended; detecting a broken connection can take time. Protected writes in that same transaction cannot continue after it ends. External API calls have no such protection, which is why this approach assumes the protected state lives in this database.

Deadlocks are possible too. Imagine Maya's transaction holds a lock on row 1 and needs row 2. Sam's transaction holds row 2 and needs row 1. Neither transaction can continue until the other releases its lock.

PostgreSQL checks for a deadlock after deadlock_timeout (one second by default). If it finds the cycle, it aborts one transaction with an error, so the application must be ready to retry. One way to prevent this particular cycle is to acquire the row locks in the same order, for example by sorting the IDs first.

Maya's transaction holds the lock on row 1 and waits for row 2. Sam's transaction holds the lock on row 2 and waits for row 1. Neither can proceed until the other releases its lock; PostgreSQL can break the deadlock by aborting a transaction.

A job-queue claim with SKIP LOCKED looks like this:

Code
BEGIN;
SELECT id, payload
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- do the work, then:
UPDATE jobs SET status = 'done' WHERE id = $1;
COMMIT;

If the worker crashes before COMMIT, the transaction rolls back and the row becomes claimable again. That is the main appeal. The tradeoff is that the transaction (and a database connection) stays open for as long as the job runs, so this suits short jobs. For long jobs, claim the row by changing its status and give the claim a lease, as in the next sections.

Optimistic locking

Optimistic locking assumes conflict is rare. So you don't lock anything upfront. You just check, at the moment of writing, whether someone else changed things while you weren't looking.

The most common pattern is a version number:

Code
-- Read the record
SELECT id, balance, version FROM accounts WHERE id = 42;
-- Returns: balance = 100, version = 5

-- Later, when updating:
UPDATE accounts 
SET balance = 20, version = version + 1 
WHERE id = 42 AND version = 5;

If someone else modified that row between your read and write, the version won't be 5 anymore. Your WHERE clause won't match. Zero rows updated. You know you lost the race.

Your application then decides what to do, usually retry with fresh data. It is essential that your code checks the number of rows updated. Ignoring a zero silently turns this back into a lost update.

Maya and Sam both read a record at version 5. Maya saves first and changes it to version 6. Sam's update still expects version 5, so it matches zero rows. Sam can read the latest record and decide whether to retry.

Many ORMs have this built in: JPA and Hibernate use a @Version field, and Rails uses a lock_version column. Some do not. A column like Prisma's @updatedAt just records when the row last changed, it does not make your writes conditional, so with it you would still add a version column and put it in the WHERE clause yourself.

When it works well:

  • Low to medium contention. Conflicts are the exception, not the rule.
  • Read-heavy workloads. No one blocks anyone during reads.
  • Web applications where users might have a form open for minutes before submitting.

When it hurts:

  • Very high contention. If every other write is a conflict, you're just burning CPU on retries.
  • When retrying is expensive or has side effects you can't undo.

Failure assumption: a crash cannot leave anything locked, because nothing was locked. The only thing that can go wrong is a conflict, and the database tells you about it at write time. The cost is that you must handle that "zero rows" result correctly, every time.

Optimistic locking without a version column

Here's a pattern for claiming a job:

Code
async function claimNextJob() {
  const job = await db.job.findFirst({
    where: { status: 'PENDING' }
  });
  if (!job) return null;

  const claimed = await db.job.updateMany({
    where: { id: job.id, status: 'PENDING' },
    data: { status: 'RUNNING' }
  });

  // A competing worker may have claimed it after our read.
  return claimed.count === 1 ? { ...job, status: 'RUNNING' } : null;
}

A returned job means this conditional update changed one row from PENDING to RUNNING. A null result means either no pending job was found or another worker won the claim. Treat that as a normal outcome to handle in the worker loop. The claim is permission to attempt the work; it does not prove that an external side effect will happen only once.

No explicit version column. You're using the status itself as the lock indicator.

This works because:

  1. The UPDATE with a WHERE clause is atomic at the database level
  2. Two workers can't both match status = 'PENDING'. One will run first and change it to RUNNING. In PostgreSQL's default READ COMMITTED level, the second worker's UPDATE waits for the first to commit, then re-checks its WHERE, finds the status changed, and updates zero rows.

Simple, no schema changes, works great for state-machine style workflows where the status transition itself is what you're protecting.

Failure assumption, and the gap in this version: if the worker crashes after claiming, the job stays RUNNING forever. Nothing will pick it up. This pattern guards against two workers claiming at once, it does not recover from a dead worker. To recover you need a lease: store locked_until (or a heartbeat time) with the claim, let a sweeper or the next claimer take over rows whose lease has expired, and make the job safe to run twice. As soon as you add a lease that can expire, you have the zombie-worker problem from the distributed locks section below: the old worker may still be running when the new one starts.

Row-level vs table-level locks

Worth knowing the difference.

Row-level locks (what FOR UPDATE does) only lock the specific rows your query touches. Other transactions can still read and write other rows in the same table.

Table-level locks lock the whole table. Which operations they block depends on the mode. The strongest one, ACCESS EXCLUSIVE, blocks everything including plain reads.

Code
LOCK TABLE accounts IN EXCLUSIVE MODE;
-- blocks other writers, but plain SELECTs still run

You almost never want this in application code. It's for maintenance operations, bulk migrations, that sort of thing. If you're reaching for table locks in regular code, something's gone wrong architecturally. Also note that many ALTER TABLE forms take a strong table lock on their own, and a queued strong lock makes new queries queue behind it, which is how a quick migration can stall a busy table.

Some databases will escalate many row locks into a table lock to save memory. PostgreSQL does not do lock escalation. Its row locks are recorded on the row itself, not in a table of locks, so locking a lot of rows does not turn into a table lock.

Distributed locks

All of the above assumes a single database. But what if you have multiple services? Multiple databases? Operations that span systems?

You need a lock that lives outside any single database. Enter distributed locks.

The most common approach: use Redis.

Code
const lockKey = `lock:order:${orderId}`;
const lockValue = uuid(); // Unique to this worker
const ttl = 30000; // 30 seconds max

// Try to acquire
const acquired = await redis.set(lockKey, lockValue, 'NX', 'PX', ttl);

if (!acquired) {
  // Someone else has it
  return;
}

try {
  await processOrder(orderId);
} finally {
  // Release only if we still own it, atomically
  await redis.eval(RELEASE_SCRIPT, 1, lockKey, lockValue);
}

with the release script being:

Code
if redis.call("get", KEYS[1]) == ARGV[1] then
  return redis.call("del", KEYS[1])
else
  return 0
end

The NX flag means "only set if not exists." If two workers try simultaneously, only one succeeds.

The PX sets an expiration. This is crucial: if your process crashes while holding the lock, the lock eventually releases itself. Without a TTL, a crashed holder would leave the key there forever and nobody could ever take the lock again.

TTL is an expiration timer. "This lock disappears in 30 seconds no matter what." It's a safety net: if the process holding the lock crashes and never releases it, the TTL eventually frees it anyway. A lock with a TTL is a lease, which is the right word for it.

The release check prevents a nasty bug: your lock expired, someone else acquired it, and now you're deleting their lock. By checking the value, you only delete if you still own it. The check and the delete must happen as one atomic step, which is why this uses a small Lua script. A separate GET followed by a DEL leaves a window where the lock can expire and be taken by someone else between the two calls, and you would delete their lock anyway.

The lease problem: expiry is not enough

Here is the failure the TTL does not fix, and it is the most important idea in this post.

  1. Worker A takes the lock with a 30 second lease.
  2. A pauses. A long garbage collection, a stalled network call, a VM that was frozen, a slow disk.
  3. The lease expires. Worker B takes the lock and starts writing.
  4. A wakes up. It has no idea time passed. It believes it still holds the lock and carries on writing.

Now two workers are inside the critical section, and neither did anything wrong by its own logic. Checking "do I still hold the lock?" right before each write only narrows the window, it does not close it, because A can pause again right after the check.

The fix is a fencing token. Each time the lock is granted, the lock service also hands out a number that always increases: 33, then 34, then 35. The worker sends that number with every write. The resource being protected remembers the highest token it has seen and rejects anything lower. When A wakes up with token 33 after B has already written with 34, A's write is refused.

Code
-- the protected row stores the last token that wrote to it
UPDATE orders
SET status = 'shipped', fence = 34
WHERE id = 7 AND fence < 34;
-- Require exactly one updated row before proceeding.
-- Zero can mean a missing row, an equal token, or a newer token.

Two things make this work. Each successful grant needs a token ordered after earlier grants, issued as part of the coordination protocol. An etcd revision or a carefully designed database-backed grant can provide that ordering; calling a separate counter after taking an unrelated lease does not establish it. The protected resource must then enforce the token check atomically with the write.

Here, fence must be initialized to a non-null starting value. The strict < permits one update per token. A holder that needs several writes requires a protocol that accepts its current token while rejecting older ones. The example only fences the database update: it does not make shipping an order through an external API atomic with that update. An API's idempotency key can prevent duplicate execution of one logical request, but it does not generally reject stale, different requests.

A plain single-instance Redis lock gives you no token, so on its own it cannot give you this guarantee. If you want to see this fail and then see the fix working, the site's Distributed Systems Challenge: Fencing a Zombie Worker is a runnable version of exactly this scenario.

Redis failure assumptions

A single Redis with a TTL lock assumes all of these:

  • Redis stays up. If it goes down, locking stops working (or, if you fail open, stops protecting anything).
  • If you run a primary with replicas, a failover can lose a lock. Replication is asynchronous, so the new primary may never have seen the key, and a second worker can take the lock while the first still holds it.
  • Your workers do not pause for longer than the TTL, or the work is safe to run twice, or the resource checks a fencing token.

When it works well:

  • Cross-service coordination where the cost of two workers occasionally overlapping is acceptable (it is an efficiency lock: avoiding duplicate work)
  • Preventing most duplicate processing of events or webhooks, paired with idempotent handlers
  • Rate limiting per-resource operations

When it hurts:

  • Anything where two holders at once would corrupt data, unless the resource also checks a fencing token
  • Redis goes down, your locking breaks
  • TTL is tricky: too short and you release while still working, too long and recovery from crashes takes forever
  • Network partitions can cause split-brain (two workers both think they have the lock)

Split-brain happens when a system breaks into parts that can't talk to each other, and both parts think they're in charge. Two workers both believing they hold the lock. Two databases both accepting writes. Nothing good follows.

Advisory locks

This one's underrated.

Advisory locks are database-provided locks that don't lock any actual row or table. You're just locking an arbitrary number. The database keeps track of who holds what.

Postgres example:

Code
-- Acquire a session-level lock on the number 12345
SELECT pg_advisory_lock(12345);

-- Do your work...

-- Release
SELECT pg_advisory_unlock(12345);

The number can mean whatever you want. Maybe it's a user ID. Maybe it's a hash of some resource identifier. The database doesn't care, it's purely advisory. It only works if everyone agrees to check the lock. The key is a 64-bit integer (or a pair of 32-bit integers), so if you hash a string into it, two different resources can collide and wait on each other for no reason.

There's also pg_try_advisory_lock which returns immediately with true/false instead of blocking.

There are two scopes, and mixing them up is the usual source of trouble:

  • Session-level (pg_advisory_lock) is held until you call pg_advisory_unlock or the connection ends. It ignores transactions: a rollback does not release it. It also stacks: if you lock the same key twice in one session you must unlock it twice.
  • Transaction-level (pg_advisory_xact_lock, pg_try_advisory_xact_lock) is released automatically at commit or rollback. There is no unlock function, and you cannot release it early.
Code
BEGIN;
SELECT pg_advisory_xact_lock(12345);
-- do the work that must not run concurrently,
-- ideally writing to this same database
COMMIT;  -- lock released here, also on ROLLBACK or a dropped connection

Prefer the transaction-level version. The lock's fate is tied to the transaction's fate: if the connection drops, the transaction rolls back and the lock goes with it, so the work and the lock cannot disagree.

When it works well:

  • You want a lock that all your services can share through a database they already use, without adding Redis
  • Locking logical resources that don't map to single rows
  • Preventing concurrent runs of the same background job

When it hurts:

  • Only works within that one database. Cross-service on different databases? No help.
  • Session-level locks and connection poolers do not mix. In PgBouncer's transaction pooling mode your next statement may run on a different server connection, so pg_advisory_unlock can run on the wrong one, and the lock can stay held on a connection that gets handed to someone else. Use pg_advisory_xact_lock, or session pooling, or a dedicated connection.
  • If you forget to release (or crash without releasing) a session-level lock, it sticks around until the connection ends. A half-dead connection can keep it for a while.
  • Advisory locks live in shared memory, and the number you can hold is limited by max_locks_per_transaction and max_connections. Locking a million distinct keys at once is not what they are for.
  • They are held on the primary. After a failover, the lock state is gone.

Failure assumption: the holder is a database session, and the lock exists exactly as long as that session (or transaction) does. If the client process freezes but its connection stays open, the lock stays held, with no expiry. If the connection drops while your code keeps running, the lock is gone even though your code does not know it. That is the reason to do the protected writes inside the same transaction that holds the lock.

I've used advisory locks to ensure only one worker processes a particular user's queue at a time, without locking any actual rows. Clean, lightweight, no schema changes.

How to choose

Here's my mental model:

Can the check and the write be one statement? Use a conditional UPDATE ... WHERE. No explicit lock needed.

Single database, short operation, high contention? Pessimistic locking with FOR UPDATE. Maybe SKIP LOCKED if it's a queue of short jobs.

Single database, longer operation, low contention? Optimistic locking with version column or status-based conditions. Add a lease if a worker can die while holding a claim.

Multiple services using the same PostgreSQL database that need to coordinate? Advisory locks, transaction-level where you can.

Need to lock a logical concept, not a row, in a different system? Distributed lock, and decide first whether it is for efficiency or correctness. A Redis lease can help avoid duplicate work when overlap is tolerable. For correctness, enforce stale-holder rejection at the resource or put the operation inside an appropriate transaction. A consensus-backed lock service alone cannot stop an expired holder from writing to another system.

Don't know your contention level yet? Start optimistic. It's simpler. Add pessimistic locking if you see too many retry storms.

Before you commit to one, write down what it assumes: can a process crash, pause, or lose its connection while holding the lock? Can the lock service fail over? Are clocks reliable enough? A lock choice is really a decision about which failures you are willing to survive.

The real lesson

Locking is risk management. You're trading off between data correctness, system throughput, and complexity.

Too little coordination can allow conflicting writes. Too much can serialize useful work or introduce deadlocks. Constraints, conditional updates, and transactions may provide the guarantee without an application-managed lock.

The art is finding the minimum locking that keeps your data correct. Most systems need way less locking than developers initially think, and the locking they do need is often in places they didn't expect.

Start by understanding where your actual race conditions are. Not theoretical ones. Actual ones. Then lock precisely those.

Everything else is premature pessimism.

Sources and further reading

Where to check the behavior I described, and where to go deeper.

  • Fencing a Zombie Worker, a runnable Distributed Systems Challenge on this site. Reproduce an expired lease letting two workers write, then fix it with a fencing token.
  • PostgreSQL: Explicit locking. The full table of lock modes, which ones conflict, and the advisory lock functions. If you only read one thing here, read this.
  • PostgreSQL: Transaction isolation. Read committed, repeatable read and serializable, and exactly which anomalies each one still allows. Half the locking people add is really an isolation level they never chose deliberately.
  • PostgreSQL: SELECT, the locking clauses. FOR UPDATE, FOR SHARE, NOWAIT and SKIP LOCKED, with the precise semantics of each.
  • How to do distributed locking by Martin Kleppmann. The argument that a lock you cannot fence is not a lock for correctness. Read it alongside the Redlock docs and make up your own mind.
  • Redis: Distributed locks. The Redlock algorithm from the other side of that debate, including the safety properties it does and does not claim.
  • etcd: Interacting with etcd. Leases and the primitives behind a coordination service, if you decide a single Redis is not enough.
  • Jepsen analyses. Real distributed systems tested against their own consistency claims. The most effective cure I know for trusting a database's marketing page.
  • Designing Data-Intensive Applications by Martin Kleppmann, chapter 7. The clearest book-length treatment of isolation levels, lost updates and write skew.

Continue learning

To see the expired-lease problem in action, try Fencing a Zombie Worker. For job recovery after a claim, see When RabbitMQ Isn't Enough. Transaction isolation and deadlock detection are also worth studying: a lock's behavior depends on the transaction around it.

FAQ

Is SELECT ... FOR UPDATE enough for a job queue? With SKIP LOCKED, usually yes for short jobs, and it is a lot simpler than a message broker. A crashed worker's transaction rolls back and the job becomes available again. It breaks down when jobs run long (the transaction stays open the whole time), when you need multi-day delays, or at very high throughput, at which point a purpose-built queue earns its keep.

Do I need a distributed lock or a database lock? If the thing you are protecting lives in one database, use that database's lock. A distributed lock adds a second system that can fail independently, and it can only be as correct as its fencing.

Is a lock with a TTL safe? Safe against a crashed holder, which is what the TTL is for. Not safe against a paused holder whose lease expired and who then keeps writing. For that you need a fencing token checked by the resource.

Should I use session-level or transaction-level advisory locks? Transaction-level (pg_advisory_xact_lock) unless you have a specific reason. It releases itself on commit, rollback or a dropped connection, and it works with transaction-mode connection poolers.

Why did my optimistic lock start failing constantly? Higher contention is one possibility. Also check for stale client versions, retries that reuse old reads, and updates that increment the version unnecessarily. Measure conflict rates and lock waits before changing strategies; pessimistic locking trades retries for waiting and can introduce deadlocks.

CONCEPTS IN THIS ARTICLE

KEEP GOING

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.