All Posts

Types of Locks Explained: Tips for Maintaining Consistent Systems and Avoiding Write Conflicts

Abstract AlgorithmsAbstract Algorithms
··5 min read

TL;DR

TLDR: When multiple users access the same data, you risk overwriting each other's work. Pessimistic Locking locks the door so only one person can enter. Optimistic Locking lets everyone in but checks for conflicts before saving. Choosing the wrong on...

Cover Image for Types of Locks Explained: Tips for Maintaining Consistent Systems and Avoiding Write Conflicts

TLDR: When multiple users access the same data, you risk overwriting each other's work. Pessimistic Locking locks the door so only one person can enter. Optimistic Locking lets everyone in but checks for conflicts before saving. Choosing the wrong one leads to slow apps or lost data.


What is Locking? (The "No-Jargon" Explanation)

Imagine an Airplane Bathroom.

  • The Problem: You don't want someone walking in while you are using it.
  • The Solution (Pessimistic Lock): You slide the latch. The sign turns "Occupied". No one else can enter until you leave. This is safe, but if you fall asleep inside, a line forms outside (Performance bottleneck).

Now imagine a Shared Google Doc.

  • The Problem: Two people edit the same sentence.
  • The Solution (Optimistic Lock): The system lets both of you type. When you try to save, it checks if the other person saved first. If they did, it tells you, "Changes conflict, please refresh." It doesn't lock the file; it just validates the version at the end.

1. Pessimistic Locking (The "Latch")

Philosophy: "I assume a conflict will happen, so I will prevent it upfront."

  • How it works: The database locks the row (or table) as soon as you read it. No one else can write (and sometimes read) until you commit.
  • SQL Command: SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
  • Pros: Guarantees data integrity. Prevents conflicts completely.
  • Cons:
    • Low Throughput: Users have to wait in line.
    • Deadlocks: User A locks Row 1 and wants Row 2. User B locks Row 2 and wants Row 1. Both wait forever.

2. Optimistic Locking (The "Version Check")

Philosophy: "I assume a conflict won't happen, so I'll let you proceed. I'll only check at the very end."

  • How it works: You add a version number to your data.
    1. Read the data (Balance: $100, Version: 1).
    2. Do calculations in memory.
    3. Update the database ONLY IF Version is still 1.
  • Pros: High performance. No one waits.
  • Cons: If a conflict happens, the user gets an error and has to retry.

Deep Dive: How Optimistic Locking Actually Works

Let's look at a concrete example of the "Lost Update Problem" and how Optimistic Locking solves it.

Toy Dataset: Bank Account

IDOwnerBalanceVersion
1Alice$1001

The Scenario: Two ATMs (A and B) try to withdraw $50 from Alice's account at the exact same millisecond.

Without Locking (The Bug):

  1. ATM A reads Balance $100.
  2. ATM B reads Balance $100.
  3. ATM A calculates $100 - 50 = $50. Writes $50.
  4. ATM B calculates $100 - 50 = $50. Writes $50.
  5. Result: Alice withdrew $100 total, but balance is $50. The bank lost money.

With Optimistic Locking (The Fix):

We use a SQL query that checks the version: UPDATE accounts SET balance = ?, version = ? WHERE id = 1 AND version = ?

StepActorActionQuery / LogicResult
1ATM AReadSELECT *Gets Balance $100, Version 1
2ATM BReadSELECT *Gets Balance $100, Version 1
3ATM AWriteUPDATE ... SET balance=50, version=2 WHERE id=1 AND version=1Success (1 row updated). DB Version is now 2.
4ATM BWriteUPDATE ... SET balance=50, version=2 WHERE id=1 AND version=1Fail (0 rows updated). Condition version=1 is false.

The Math (Logic): [ \text{If } CurrentVersion == ReadVersion \rightarrow \text{Write \& Increment} ] [ \text{Else } \rightarrow \text{Throw Error} ]

ATM B receives "0 rows updated". It knows the data changed. It must restart the transaction (Read new balance $50, try to withdraw again).


Real-World Application: Ticketmaster vs. Wiki

Case A: Ticketmaster (Pessimistic)

  • Scenario: You click on Seat A1 for the Taylor Swift concert.
  • Requirement: We cannot sell the same seat twice.
  • Strategy: The moment you click, the system puts a Pessimistic Lock (or a temporary hold) on that seat for 5 minutes. Even if you haven't paid yet, no one else can select it.
  • Why? It's frustrating for users to fill out credit card info only to be told "Sold Out" at the last second.

Case B: Wikipedia (Optimistic)

  • Scenario: You are editing an article about "Cats". Someone else is fixing a typo in the same article.
  • Requirement: We want to encourage editing. We don't want to lock the page for 30 minutes just because someone left their browser open.
  • Strategy: Optimistic Locking. If you both save, the second person gets a "Merge Conflict" message.
  • Why? Conflicts are rare, and blocking access is worse than occasional retries.

Summary & Key Takeaways

  • Pessimistic Locking: Locks data upon read. Good for high-conflict, critical data (Money, Seats). Risk of Deadlocks.
  • Optimistic Locking: Checks version upon write. Good for low-conflict, high-read data (Profiles, Wikis). Fast but requires retry logic.
  • Deadlock: When two processes wait for each other forever. Avoid by ordering your locks consistently.

Practice Quiz: Test Your Design Skills

  1. Scenario: You are building a "Concert Booking System". Users select a specific seat from a map. Once selected, that seat must be reserved for 10 minutes while they pay. Which locking strategy is best?

    • A) Optimistic Locking
    • B) Pessimistic Locking
    • C) No Locking
  2. Scenario: You are building a "User Profile Editor". Users rarely update their profiles at the exact same time as an admin. You want maximum speed and no database locking overhead.

    • A) Optimistic Locking
    • B) Pessimistic Locking
    • C) Deadlock
  3. Scenario: Process A locks Table X and waits for Table Y. Process B locks Table Y and waits for Table X. The system freezes. What is this called?

    • A) Race Condition
    • B) Deadlock
    • C) Livelock

(Answers: 1-B, 2-A, 3-B)

Abstract Algorithms

Written by

Abstract Algorithms

@abstractalgorithms