Learning pathsPricingChecking sign-in…
Patterns

Dealing with Contention

Contention occurs when concurrent operations compete over the same mutable fact.

What, why, when and how

What is it?

Contention occurs when concurrent operations compete to change the same logical resource or invariant.

Why is it needed?

Independent read-then-write operations can both succeed locally while overselling a seat or losing an update.

When should I use it?

Use explicit concurrency control for inventory, balances, job ownership and versioned edits.

When should I choose something else?

Avoid a global lock for unrelated resources. A lease alone cannot prevent an expired worker from making an external write.

How do I use it?

Put the check and change at one authoritative atomic boundary. Choose conditional updates, transactions or serialization; add fencing where stale owners can continue acting.

Can you show a concrete example?

Two buyers attempt to decrement stock from 1 only if it remains positive. Exactly one conditional change succeeds; the other sees no eligible row. Retrying a successful purchase also needs a stable operation identity.

Stock = 1; A and B both want one item; Atomic condition: decrement only if stock > 0; One wins; one fails; stock never becomes -1
Dealing with Contention: one concrete example
Read the diagram

Stock = 1; A and B both want one item; Atomic condition: decrement only if stock > 0; One wins; one fails; stock never becomes -1

Open original
Dealing with Contention: worked example
Stock = 1; A and B both want one item; Atomic condition: decrement only if stock > 0; One wins; one fails; stock never becomes -1

Dealing with Contention: one concrete example

Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.

Contention occurs when concurrent operations compete over the same mutable fact. More servers may increase the number of contenders without increasing useful progress. Start by naming the invariant and the smallest state boundary that can enforce it. Then choose a conflict mechanism and an explicit user response when a request loses.

Learning goals

Invariants; atomic conditional writes; locks; optimistic versions; transactions; leases; fencing; contention measurement; conflict responses.

See the lost update before choosing a lock

Seat A7 is free at version 7. Buyers A and B both read that state. Application-only “if free” checks allow both requests to proceed. Put the comparison and transition at the owner:

sql
UPDATE seat SET holder = :buyer, version = version + 1
WHERE seat_id = 'A7' AND holder IS NULL AND version = 7;
UPDATE seat SET holder = :buyer, version = version + 1; WHERE seat_id = 'A7' AND holder IS NULL AND version = 7;
See the lost update before choosing a lock
Read the diagram

UPDATE seat SET holder = :buyer, version = version + 1; WHERE seat_id = 'A7' AND holder IS NULL AND version = 7;

Open original
See the lost update before choosing a lock
UPDATE seat SET holder = :buyer, version = version + 1; WHERE seat_id = 'A7' AND holder IS NULL AND version = 7;

See the lost update before choosing a lock

Under the intended atomic database contract one request updates one row; the other affects zero rows and must report conflict. Optimistic concurrency uses this detected conflict and a bounded retry. Pessimistic locking instead serializes access before deciding, increasing lock waits and possible deadlock. For a multi-seat transaction, acquire seats in a deterministic order and roll back the whole requested set if one seat is unavailable; do not hold a transaction open while the user pays.

An ABA example is free -> held -> free. A stale reader sees the original value again but not the original history; the monotonically changing version detects it. A lease has another hazard: paused holder epoch 7 resumes after epoch 8 acquired ownership. The protected resource rejects epoch 7. Possessing a stale Redis lock token is not enough to enforce that rejection.

Isolation determines which anomalies a transaction prevents; a transaction keyword alone does not identify its level or cross-service boundary. Queueing a hot resource can simplify order and fairness but still requires durable identity and a recovery rule. Measure wait time, conflict rate and deadline failures before increasing retries.

Show answer and explanation

Answer: When B affects zero rows, return a conflict or reread under a bounded policy. Retrying the same stale comparison indefinitely cannot manufacture a free seat. A distributed lock adds little if a single database condition directly protects the invariant.

Step-by-step reasoning

1. Make the decision atomic

A strongly consistent read does not make a later write part of the same operation. Two callers can both read available before either writes. Use a conditional update, compare-and-swap version, or an appropriate transaction so checking and changing the state occur at one serialization boundary.

2. Choose optimistic or pessimistic control

Optimistic control reads a version and updates only if it still matches; conflicts require retry or user resolution. Pessimistic control locks the relevant rows while a short transaction runs. Optimistic approaches work well with uncommon conflicts, while repeated collisions can waste work. Locks also have waiting, deadlock, and throughput costs.

3. Distinguish leases from fencing

A lease expires, but the old worker may still be running after a pause. A monotonically increasing fencing token lets the destination reject work from older owners. The destination must actually validate the token; placing it in a log message is not enforcement. A lease alone is not proof of exclusive execution.

4. Reduce the hot boundary

Partition independent resources, shorten critical sections, and avoid external calls while holding locks. For commutative operations, aggregation or sharded counters may reduce contention, but not every operation is safely commutative. A last-seat decision cannot be approximated like a page-view counter.

Contracts and state

The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.

Contract / pseudocode
UPDATE document
SET body = :new_body, version = version + 1
WHERE id = :id AND version = :expected_version;
-- zero affected rows means conflict

Fenced result write:
accept only if attempt_token == current_attempt_token

Worked example

Two editors load version 12. Alice saves and creates version 13. Bob’s save with expected version 12 fails. The interface can ask Bob to merge, reload, or retry after inspecting the new state. Silently overwriting version 13 would lose Alice’s edit. An automatic retry is safe only if Bob’s operation can be meaningfully recomputed against the new version.

Failure walkthrough

Worker A obtains lease token 8 and pauses. The lease expires; worker B receives token 9 and finishes. A resumes and tries to publish an old result. The result store rejects token 8 because token 9 is current. This protects the effect even though both workers executed. If an external provider cannot enforce fencing, use its idempotency and reconciliation mechanisms instead.

Worker A owns token 8 → A pauses past lease → Worker B owns token 9 → A resumes and writes → Destination rejects token 8
Worker A owns token 8 → A pauses past lease → Worker B owns token 9 → A resumes and writes → Destination rejects token 8
Read the diagram

Worker A starts with token 8, pauses, and loses its lease. Worker B receives token 9 and commits. A resumes and attempts a stale write. The destination compares the token on each protected effect and rejects token 8. Lease expiry alone does not stop A from executing.

Open original
Lease expiry is not fencing
Worker A owns token 8 → A pauses past lease → Worker B owns token 9 → A resumes and writes → Destination rejects token 8

Worker A owns token 8 → A pauses past lease → Worker B owns token 9 → A resumes and writes → Destination rejects token 8

Decisions and trade-offs

MethodGood fitFailure to consider
Conditional writeOne-record state transitionConflict handling
Transaction + lockRelated short updatesDeadlock and long holds
Optimistic versionLow conflict editsRetry storms under contention
Lease + fencingRecoverable worker ownershipUnfenced external effects

Check your understanding

Why does adding a distributed lock with a 30-second expiry not guarantee only one worker writes a result?

Show answer and explanation

Answer: The original worker can outlive its lease and resume after a new owner starts. The destination needs a current ownership token or equivalent conditional transition to reject stale publication.

Transfer to a new scenario

Compare a database conditional update with a distributed lease for the same scarce resource.

Why is a read-then-write check insufficient even if the read is strongly consistent?

Continue the connection

Study PostgreSQL and explain which guarantee from this lesson carries into that topic.

Put the decision where the invariant lives

A scarce resource needs one authoritative conflict decision. For a seat, use a conditional update from available to held, or lock the row and commit the hold. Reading available and later writing held without a condition allows two winners. An application-level mutex protects only the process holding it unless a broader protocol exists.

Optimistic concurrency works well when conflicts are uncommon: compare a version and retry after re-reading. Pessimistic locks make conflicts explicit but hold resources and can deadlock. Acquire multiple locks in a consistent order, keep transactions short and avoid external network calls while holding them.

A lease is temporary permission, not a guarantee that the old worker stopped. After expiry, a new worker can begin while the old one is paused. A monotonically increasing fencing token must be checked at the protected resource so stale owners cannot commit. Idempotency handles repeat identity; fencing handles obsolete ownership. They solve different problems.

A decision worksheet for Dealing with Contention: read the mechanism and its guarantee together.
A decision worksheet for Dealing with Contention: read the mechanism and its guarantee together.
Read the diagram

Method / Good fit / Failure to consider; Conditional write / One-record state transition / Conflict handling; Transaction + lock / Related short updates / Deadlock and long holds; Optimistic version / Low conflict edits / Retry storms under contention; Lease + fencing / Recoverable worker ownership / Unfenced external effects

Open original
Dealing with Contention choices for this workload
A decision worksheet for Dealing with Contention: read the mechanism and its guarantee together.

A decision worksheet for Dealing with Contention: read the mechanism and its guarantee together.

Operational sketch

Contract / pseudocode
UPDATE seats SET state="held",hold_id=:h,version=version+1
WHERE id=:seat AND state="available";
Require affected_rows = 1
Fenced write: accept only generation >= stored_generation

A tempting mistake

A distributed lock that expires does not retract an in-flight provider call. Keep the external-effect uncertainty separate from internal write ownership.

Transfer exercise

Worker A pauses with generation 7; B acquires generation 8. What stops A from overwriting B?

Show answer and explanation

Answer: The destination rejects A’s stale generation. Checking the lease only before starting work is insufficient because A can pause after that check.

Shared foundation: Transactions and Isolation

Transactions and Isolation: Predict write skew, enforce a shared invariant and retry whole transactions safely. Work its failure history before extending this design.

Your study notes