Blog pessimistic vs optimistic locking optimistic locking pessimistic locking

Pessimistic vs Optimistic Locking: When to Use Each

Compare pessimistic vs optimistic locking: how each handles concurrent updates, where each performs better, and which to choose for your workload in 2026.

11 min readThe Projectify team

The most repeated advice on pessimistic vs optimistic locking is to default to optimistic and reach for a lock only when you "have to." That advice treats the choice like a personality test about trust. It is a cost question. Where does the conflict show up, and what do you pay when it does?

Pessimistic locking makes the second writer wait before any work starts. Optimistic locking lets both writers proceed and discards the loser at commit. Waiting is easy to dismiss when almost nobody collides. Retrying gets expensive when everyone collides on the same row, or when the unit of work is a person who pauses, an approval sitting in a queue, or an agent calling an external API.

A row lock inside one short transaction is the easy case. Long-lived work needs a claim that expires, because a database lock held across a pause stalls everyone else. I would decide by measuring how often two writers touch the same record, then picking the failure mode that costs less.

Pessimistic and Optimistic Locking Side by Side

Pessimistic locking blocks competing access before work starts. Optimistic locking lets the work proceed and checks for a conflict only at write time.

Criterion Pessimistic locking Optimistic locking
When conflicts are detected Before work starts, at lock acquisition At commit, during validation
Typical mechanism SELECT ... FOR UPDATE, row or table locks Version or timestamp column checked on write
What a competing transaction does Waits, or fails after a timeout Proceeds, then fails validation
Cost when a conflict happens Waiting time and possible deadlocks Discarded work and a full retry
Cost when no conflict happens Lock acquisition on every access Little beyond the version check
Best fit High contention on hot rows Low contention, read-heavy or short writes
Main weak spot Locks held while a client pauses Retry storms on hot keys

Low conflict favours optimistic. High conflict favours pessimistic. The column that matches your workload is the one to start with, not the one that looks cleaner in a code review.

Pessimistic locking pays its cost on every access. Optimistic locking pays only when a conflict actually occurs.

If two writers rarely meet, the version check is almost free and the retry is rare. If they meet on a hot row all day, you pay the retry on nearly every attempt, and the "cheaper" path is the one that made the second writer wait.

How Pessimistic Locking Serializes Concurrent Updates

Say two transfers both touch account 10 and account 40. You want one of them to finish with the committed balances before the other even reads.

A flow chart illustrating how pessimistic locking serializes concurrent updates in database transactions step by step.

  1. Begin the transaction. Nothing is protected until you ask for a lock.
  2. Read each row with SELECT ... FOR UPDATE, which takes an exclusive row lock. Lock account 10 first, then account 40, because 10 is the smaller id.
  3. Any other transaction that requests those rows blocks until your lock is released. It doesn't read a stale balance and hope.
  4. Apply the debits and credits, then commit. Commit releases the locks.
  5. The waiting transaction proceeds and reads the fresh committed values.

Shared and exclusive locks

A shared lock is for readers that must not see a row change underneath them. Several transactions can hold a shared lock on the same row. An exclusive lock is for a writer. Only one transaction holds it, and shared lockers wait too while it is held. FOR UPDATE is the exclusive case. Use it when the next statement depends on the value you just read.

Three clauses change the wait. NOWAIT fails the statement immediately instead of queueing. A lock timeout bounds the wait and returns an error you can handle. SKIP LOCKED skips rows another worker already holds, which is the right shape for queue consumers that should take the next free row rather than line up on the head.

Deadlocks and stalled clients

A deadlock is two transactions locking the same rows in opposite order. Transfer A locks 10 then wants 40. Transfer B locks 40 then wants 10. Both wait. The database will abort one of them, but you shouldn't rely on that as your design. Sort by primary key and always lock in that order.

The production mistake I see most often is holding that lock across an HTTP call or a user prompt. The critical section was meant to be a few milliseconds of SQL. It becomes a stalled connection pool while a client thinks. Do the external call before you take the lock, or after you commit. Keep the locked window to the read, the write, and the commit.

Try this on your own backlog.

A month of Premium free. No card. Connected in a minute.

How Optimistic Locking Catches Conflicts at Commit

H. T. Kung and John Robinson's 1981 paper, "On Optimistic Methods for Concurrency Control," let transactions run without locks and validated read and write sets before commit. Under their stated assumptions, B-tree insertions had an estimated abort-and-restart probability of only 0.07%, which is why this model fits large indexes and short, quiet writes.

A hand-drawn illustration explaining the Kung & Robinson 1981 optimistic concurrency control model with transaction workflow examples.

A version column is the application form of that check.

  1. Read the row and its version. Suppose version is 7.
  2. Compute the change in memory. You hold no row lock while you do it.
  3. Write with a predicate: UPDATE tasks SET status = ?, version = version + 1 WHERE id = ? AND version = 7.
  4. Zero affected rows means someone else committed first. That is the conflict.
  5. Reload the row, reapply your change or show the user the new value, then retry with bounded exponential backoff. Cap the attempts. Three to five is plenty for a short edit.

ORMs express the same predicate with a version attribute. JPA's @Version raises an exception when the update matches nothing. The retry still belongs in your code. The annotation only detects the miss.

Retries and side effects

The retried transaction has to be idempotent. Recomputing a status from the row you just reloaded is safe. Replaying a notification, a git push, or an agent dispatch is not. A database retry will fire those again unless you guard them with an idempotency key or write them through an outbox that commits with the row.

This approach is safe when conflicts are infrequent and repeating the transaction is cheap. If either stops being true, stop retrying and change the strategy.

Validation cost also grows with the read and write sets. A tiny update of one row is a different bet from a transaction that touched hundreds of rows and then failed the check.

Which Strategy Performs Better at Each Contention Level

Contention is the chance that two transactions touch the same record during overlapping time, not the overall load on the database. A quiet table with one hot counter is high contention. A busy table of independent task rows is low.

A VLDB experimental study found that optimistic control outperformed two-phase locking under low data contention, while two-phase locking did better as contention rose, because optimistic transactions increasingly threw away finished work. On PostgreSQL, keep the version-check loop while conflicts stay rare. Move to SELECT FOR UPDATE once the same rows are fought over.

A graph comparing the throughput of optimistic versus pessimistic concurrency control strategies across varying levels of contention.

Neither pure strategy wins every band. Hybrid designs keep optimistic execution on cold records and pessimistic protection on hot ones. At high conflict they tend to beat either pure approach: most transactions still commit without waiting, and the few hot keys stop a pile of finished updates from being discarded.

Four contention bands

Contention level Typical example Default strategy Evidence
Low, many records, short transactions Editing a field on one of thousands of tasks Optimistic Optimistic outperformed 2PL at low contention in a VLDB study
Moderate, occasional shared rows Several people editing one task's notes Optimistic with bounded retries Retries stay cheap when conflicts are occasional
High, hot rows Many agents claiming the same task Pessimistic or lease-based claim 2PL performed better as contention rose
Mixed, a few hot keys among many cold ones Shared counters beside ordinary edits Hybrid, optimistic by default with pessimistic hot keys Hybrids tend to beat either pure strategy when only a few keys are hot

The cost that matters is where the conflict lands. Under low contention an abort is rare, and redoing a short field edit is cheaper than holding a lock. Under moderate contention the same bet still holds if you cap retries, because most attempts still commit. On a hot row the math flips. Each aborted attempt already did the read and the write, then lost the race, so waiting in line wastes less work than a stampede of retries.

A database lock only covers the transaction. Agent sessions and human edits last longer than that. A claim acts as a lease: one holder at a time, renewed by activity, released 30 minutes after the holder goes quiet. A second agent is told who holds the task and when they were last active, then leaves a comment or asks for it instead of overwriting the row. That split, optimistic on the cold majority and a lease on the popular tasks, is the mixed band you want when people and agents share one board.

Choosing the Right Locking Strategy and Checklist

The right lock is a decision about where a conflict is allowed to happen, and what a lost attempt costs. A version mismatch that throws away one title edit is cheap. A second worker that already moved money, or a second agent that already started the same task, is not.

Situation Strategy Reason
Editing a task title, notes or handoff text Optimistic version check Conflicts are rare, so a retry costs little
Transferring funds between two accounts Pessimistic lock in fixed order Partial updates are unacceptable and retries are costly
Two agents claiming the same task Pessimistic or lease-based claim Only one owner may exist at a time
Pulling from a shared queue head Pessimistic claim with SKIP LOCKED Many workers hit the same top rows
Batch import of independent rows Optimistic No shared rows, so nothing waits
Reports reading while writes continue Optimistic, snapshot reads Readers do not block writers

What the numbers say under a pile-up

Under concentrated writes, waiting beats a stampede of doomed attempts. A published distributed-concurrency evaluation found two-phase locking with no-wait handling ahead by up to 54% on high-update workloads and up to 78% under high contention. Optimistic execution only looks cheaper if you ignore the retries that follow a lost commit.

Apply that split to a queue that hands out one piece of work. Projectify's Start next queue is ranked, unblocked, and free. People and agents both pull the top task, so two workers must not both receive it. A version check lets both read "free." One update wins. The other retries against a row that is already gone. An atomic claim, SKIP LOCKED, or a compare-and-set that only one session can win, makes assignment single-owner. The claim itself is a lease: one holder, and it frees itself 30 minutes after the holder goes quiet. The second agent is told who holds it and when they were last active. Ordinary field edits on that task can stay optimistic. The case for claims over long-held locks is the same split: exclusive ownership for scarce work, validation for shared text.

A checklist before you write the code

  1. Estimate how often two writers touch the same record inside one transaction. If you can't estimate it, log conflicts for a day before you harden the path.
  2. Check whether the work spans a human pause, an approval, or an external call. If it does, a database lock is the wrong tool. Use a lease that expires, not a row lock held across the pause.
  3. Choose the default. Optimistic for rare conflicts and short writes. Pessimistic for hot rows and single-owner work. Hybrid when most records are cold and a few are hot.
  4. Put a retry cap on every optimistic path, and an idempotency key on every external side effect.
  5. Set a lease duration for any claim that outlives the transaction, and define what happens at expiry.
  6. Wire conflict and wait metrics into monitoring on the first release, not after the first incident.

Lock what must be single-owner, validate what is merely shared, and measure before you switch.

Escalating to Stronger Locks and Protecting Long-Lived Work

One lock type for the life of a service is the assumption that fails in production. A feature that was a rare edit in March is a hot queue in June, because more agents started pulling it. Research on concurrent indexes found that optimistic locking holds up on low contention and read-heavy work, then suffers retry storms when access concentrates on a few hot keys. In one evaluation, an adaptive design improved performance by up to roughly 4 times over conventional optimistic approaches under contention (OptiQL).

Measure per entity or per queue, not as a single database average. A global conflict rate of 1% can hide one task that fails half its writes.

Metric Escalation signal Response
Retries per successful write Above 5% sustained over a day Switch the hot entities to pessimistic locks
Lock wait time Waits rising week on week Shorten critical sections and check lock ordering
Transaction duration Any transaction spans a human or external call Move the call outside and use a lease
Write concentration A small set of records takes most writes Serialize those records or route them through a queue
Duplicate side effects Any duplicate dispatch after a retry Add an idempotency key or outbox before retrying

Treat the 5% line as a starting threshold. Tune it against your own traffic. A payments row at 2% may already be too hot. A notes field at 8% may still be fine if the retry is a pure in-memory merge.

Leases for work that outlives a transaction

A lock must not span a human pause, an approval, or an external API call. Use a renewable application-level claim. In Projectify a claim is a lease with one holder. Every action renews it, and it frees itself 30 minutes after the holder goes quiet. When a second agent wants the same task, the first keeps it. The second is told who holds it and when they were last active, then leaves a comment or asks for the claim.

A stale holder is the failure you have to design for. The worker's process died, or its heartbeat stopped, and it wakes up after the lease moved on. Its final write must fail. The version check on the row does that, so a late commit can't overwrite the new holder. Clock skew and missed heartbeats are why the lease has an expiry instead of "until disconnect." A person can still release a stuck claim and record the reason in the handoff, which is the override when an agent is wedged and the work can't wait 30 minutes.

That pattern matters once you are running several Claude Code agents against one backlog. The database transaction stays short. The claim carries ownership across the session. The version column stops the expired worker from writing back.


Projectify is project management for small teams and the AI agents already doing the work, with claims that keep two sessions off the same task and a Start next queue that hands out the highest-ranked free task. If pessimistic vs optimistic locking has been a database argument on your team, the same cost question shows up the moment agents run in parallel. Visit Projectify and put a lease on the next task before a second agent starts it.

Try it

Give Claude your backlog tonight.

One board for your team and your Claude agents. A month of Premium free. No card.