A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Pessimistic Concurrency Control: Locking

College Depth 103 in the knowledge graph I know this Set as goal
2topics build on this
408prerequisites beneath it
See this on the map →
Lost Update Problem: Overwriting Concurrent WritesOptimistic Concurrency Control: Version NumbersMulti-Version Concurrency Control (MVCC)
concurrency locking locks

Core Idea

Pessimistic concurrency control acquires locks on rows before reading or modifying them. Locks are held until commit, ensuring no other transaction can interfere.

How It's Best Learned

Use SELECT...FOR UPDATE to lock rows, observe how other sessions block, and commit to release locks.

Common Misconceptions

Locks are held until COMMIT, not after the UPDATE statement finishes. Deadlocks can occur if two transactions lock resources in different orders.

Explainer

When multiple transactions access the same data concurrently, things can go wrong — you already saw this with the lost update problem, where two transactions read and write the same row and one silently overwrites the other's changes. Pessimistic concurrency control is the straightforward solution: before you touch a row, you lock it. While you hold the lock, nobody else can modify that row. It is called "pessimistic" because it assumes conflicts are likely and prevents them upfront, rather than detecting them after the fact.

In practice, most relational databases implement this through shared locks and exclusive locks. A shared lock (read lock) allows multiple transactions to read the same row simultaneously — reads do not conflict with each other. An exclusive lock (write lock) gives one transaction sole access to a row for modification, blocking both readers and writers. When you execute `SELECT ... FOR UPDATE`, you are explicitly requesting an exclusive lock on the returned rows. Other transactions that try to read or modify those same rows will block — they wait, paused, until you commit or roll back and release your locks.

The critical detail is *when* locks are released. Under the standard two-phase locking protocol, a transaction acquires all the locks it needs (the growing phase) and releases them only at commit or abort (the shrinking phase). This means a lock acquired early in a long transaction is held for the entire duration, even if the row is not touched again. This guarantees serializability — the result is equivalent to running transactions one at a time — but it also means long transactions can block other work for extended periods.

The main danger of pessimistic locking is deadlock: transaction A locks row 1 and waits for row 2, while transaction B locks row 2 and waits for row 1. Neither can proceed. Databases handle this with deadlock detection — periodically checking for cycles in the wait graph and aborting one transaction to break the cycle. You can minimize deadlocks by always acquiring locks in a consistent order (e.g., by primary key) and keeping transactions as short as possible. The tradeoff is clear: pessimistic control gives you strong correctness guarantees at the cost of reduced concurrency and the risk of blocking. For workloads where conflicts are frequent and correctness is paramount — such as financial transfers or inventory updates — that tradeoff is well worth it.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraBoolean Algebra and Fundamental LawsLogic Gates FundamentalsImplementing Boolean Functions with GatesKarnaugh Map SimplificationCombinational Circuit DesignFlip-Flops and LatchesBinary Counters: Design and AnalysisBinary ArithmeticFixed-Point Number RepresentationTwo's Complement RepresentationOverflow and Underflow DetectionBinary Adders: Half-Adders and Full-AddersFull Adder and Carry PropagationCarry Lookahead Adder DesignHalf Adder Circuit DesignMultiplication Circuit DesignSequential Circuit DesignRegisters and Register FilesInstruction Set Architecture (ISA)Kernel Architecture and OS StructureSystem Calls and User/Kernel ModeProcesses and the Process Control BlockProcess Creation: fork() and exec()Process Termination and Resource CleanupProcess States and State TransitionsThreads and ConcurrencyThe Critical Section Problem and Race ConditionsMutual Exclusion and LocksConcurrency Control in DatabasesLost Update Problem: Overwriting Concurrent WritesOptimistic Concurrency Control: Version NumbersPessimistic Concurrency Control: Locking

Longest path: 104 steps · 408 total prerequisite topics

Prerequisites (2)

Leads To (1)