Optimistic Locking & Distributed Consistency Explained

Another day, another deep dive into backend fundamentals Today I explored something that looks simple at first but becomes really interesting as you go deeper — Optimistic Locking & Distributed Consistency Let me break it down the way I understood it 👇 • The Problem: Lost Updates Two users read the same data: User A → updates name to "Dominos Pizza" User B → updates name to "Dominos India" Without any protection: → Last write wins → One update is silently lost ,This is dangerous. • Optimistic Locking (Core Idea) Instead of locking the row , Allow multiple reads , Allow parallel updates But verify at write time using a version field: UPDATE ... WHERE id = ? AND version = ? If version changed → update fails If same → update succeeds ✅ 👉 No locks, no blocking, just conflict detection 🔹Important Insight Optimistic locking does NOT prevent conflict It detects conflict and forces a decision 🔹What happens on conflict? You decide: • Retry automatically • Ask user to resolve • Merge changes 🔹Role of @Version in JPA • Tracks version of each row • Automatically increments on update • Injects version condition in SQL • Throws exception if conflict detected 🔹 Now the real question: Distributed Systems What if we have one service and what if we have multiple databases? • Now things break • Each DB has its own version • No shared truth Conflicts go undetected 👉 Optimistic locking fails here 🔹 So what do real systems do? ✅ Primary + Read Replicas → Only one DB handles writes ✅ Sharding → Each record lives in exactly one DB #BackendEngineering #SystemDesign #Java #SpringBoot #DistributedSystems #OptimisticLocking #Microservices #LearningInPublic

To view or add a comment, sign in

Explore content categories