logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
60-Day LLD & Machine Coding Mastery Roadmap
The Four Pillars of OOPComposition, Asociation & AggregationDatabase locking / atomic updates
Don't Repeat Yourself (DRY) PrincipleKeep it Simple, Stupid (KISS) PrincipleYou Aren't Gonna Need It (YAGNI) Principle
Design a Library Management System (LMS)Design a Parking LotVending Machine
D : Dependency InversionI : The Interface Segregation PrincipleL : The Liskov Substitution PrincipleO : The Open/Closed PrincipleS : The Single Responsibility Principle
UML Activity Diagrams: Modeling Process and WorkflowUML Class Diagrams: Static Structure ModelingUML Sequence Diagrams: Modeling Dynamic InteractionsUse Case Diagrams: Functional Requirement Modeling
Low Level Design

Database locking / atomic updates

1 min read
On this pageOptimistic vs. pessimistic locking
Optimistic vs. pessimistic lockingPessimistic lockingOptimistic locking

Locking prevents multiple access from modifying shared state at the same time in a way that breaks correctness.

  • Locking coordinates concurrent access to shared state.
    • Lock around a state transition that must happen atomically not just around a read.
  • A transaction groups database changes into a unit with properties such as atomicity and consistency.
  • A database constraint rejects invalid states even if application code has a bug or concurrent requests race.

# Optimistic vs. pessimistic locking

These are two approaches to handling conflicting operations.

# Pessimistic locking

Acquire a lock before modifying the resource, preventing conflicting work while the lock is held.

  • Good when contention is frequent and conflicts are expensive.
  • Other transactions may wait, reducing throughput.

# Row-level locks

Row-level locks SELECT ... FOR UPDATE

# Optimistic locking

Read a version number, then update only if the version is unchanged.

  • Good when conflicts are relatively uncommon.
  • A conflicting update fails and the application must retry or report a conflict.

# Conditional Update

The database executes this state transition atomically.

UPDATE parking_spot
SET status = 'OCCUPIED',
    vehicle_id = :vehicleId
WHERE id = :spotId
  AND status = 'AVAILABLE';
←PreviousComposition, Asociation & AggregationNext→Don't Repeat Yourself (DRY) Principle

On this page

Optimistic vs. pessimistic lockingPessimistic lockingOptimistic locking