Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
MySQL + SQL · Lesson 87

DBMS में Concurrency Control

Concurrency Control क्या है?

Concurrency का अर्थ several sessions overlapping time में transactions execute करें। Parallelism throughput improve करती है, लेकिन coordination न हो तो two correct single-user operations same data read/modify करके wrong combined result बना सकती हैं।

Faculty definition: Concurrency control DBMS और application techniques का set है जो safe simultaneous access allow करते हुए transaction correctness preserve करता है।

InnoDB transactions, MVCC, isolation levels, row/range locks, constraints और deadlock detection combine करता है। Application design atomic statements, version checks, idempotency और retry logic add करती है।

Verified Inventory Lab

DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (
  product_id INT PRIMARY KEY,
  product_name VARCHAR(60) NOT NULL,
  stock INT NOT NULL,
  version_no INT NOT NULL DEFAULT 1,
  CONSTRAINT chk_stock CHECK (stock >= 0)
) ENGINE = InnoDB;

INSERT INTO inventory VALUES
(10, 'Notebook', 5, 1),
(20, 'Pen Pack', 2, 1);
10 | Notebook | stock=5 | version=1 20 | Pen Pack | stock=2 | version=1

Every independent test से पहले product 10 stock 5 और version 1 reset करें। Races reproduce करने के लिए two MySQL sessions लें; one-session test concurrency behavior prove नहीं कर सकता।

Uncontrolled Concurrency की Problems

ProblemSequenceWrong result
Lost updateA reads 5; B reads 5; both write 4Two sales लेकिन stock केवल once कम
Dirty readB, A का uncommitted value पढ़े; A rollbackB ने unreal data पर action लिया
Nonrepeatable readB row twice पढ़े, बीच में A commitSame row B के unit में बदल गई
PhantomA, B के predicate matching row insert करेB repeated result set में new row
Write skew या rule raceTransactions related rows separately validateCombined business rule false
DeadlockA और B each-other-needed locks holdOne transaction rollback करनी पड़ती है

Actual invariant के लिए technique चुनें। Query समझे बिना isolation raise करना contention बढ़ा सकता है और intended business rule फिर भी express नहीं करेगा।

MVCC, Consistent Reads और Isolation

InnoDB MVCC undo information से older row versions रखता है ताकि plain consistent SELECT snapshot पढ़ सके। READ COMMITTED में each consistent read fresh snapshot लेती है; REPEATABLE READ में consistent reads सामान्यतः first read से created snapshot reuse करती हैं।

OperationTypical concurrency behavior
Plain SELECT at READ COMMITTED/REPEATABLE READMVCC snapshot से consistent nonlocking read
SELECT FOR SHAREShared locking read; conflicting modifications wait
SELECT FOR UPDATEChange होने वाले records के लिए exclusive-style locking read
UPDATE या DELETEPlan और isolation के अनुसार affected/scanned index records lock

MVCC read/write concurrency improve करता है, लेकिन write/write conflicts remove नहीं करता। Long transactions old versions longer retain करके purge और reconstruction work बढ़ा सकती हैं।

Best First Tool: Atomic Conditional Update

Business decision one DML statement में express हो सके तो read-calculate-write race avoid करें।

UPDATE inventory
SET stock = stock - 1
WHERE product_id = 10
  AND stock > 0;

SELECT ROW_COUNT() AS sale_succeeded;
First sale: affected rows=1, stock=4 Second sale: affected rows=1, stock=3

Two concurrent executions conflicting row updates serialize करती हैं और each current value से subtract करती है। Stock zero पर conditional UPDATE zero rows affect करती है और application “out of stock” report करती है।

UPDATE inventory
SET stock = stock - 1
WHERE product_id = 10 AND stock > 0;
-- Order record करने से पहले ROW_COUNT() = 1 require करें।

Order payment और ledger rows भी insert करे तो atomic stock update तथा all required writes one transaction में रखें और any affected-row check fail होने पर rollback करें।

SELECT FOR UPDATE से Pessimistic Control

Conflict likely हो या multi-step decision current row reserve करे तो pessimistic locking appropriate है।

-- Session A
START TRANSACTION;
SELECT stock FROM inventory
WHERE product_id = 10
FOR UPDATE;
-- 5 return और record lock।

UPDATE inventory SET stock = stock - 1
WHERE product_id = 10 AND stock > 0;
COMMIT;

-- Session B का conflicting FOR UPDATE या UPDATE wait,
-- फिर committed stock 4 से continue।
  • Locking read से पहले transaction start करें; उसे autocommit disabled या explicit transaction चाहिए।
  • All required rows consistent order में lock करें।
  • Locked section short रखें; इसके अंदर user interaction न करें।
  • Immediate failure useful हो तो NOWAIT लें।
  • SKIP LOCKED केवल queue-like work के लिए क्योंकि यह intentionally inconsistent view देता है।

Version Column से Optimistic Control

Conflicts uncommon और work short database transaction से बाहर हो तो optimistic control useful है। हर reader seen version रखता है।

-- Both clients initially stock=5, version_no=1 पढ़ते हैं।

-- Client A
UPDATE inventory
SET stock = 4, version_no = version_no + 1
WHERE product_id = 10 AND version_no = 1;
-- affected rows=1; version अब 2।

-- Client B अभी version 1 submit करता है।
UPDATE inventory
SET stock = 4, version_no = version_no + 1
WHERE product_id = 10 AND version_no = 1;
-- affected rows=0: stale update rejected।
Client A succeeds: stock=4, version=2 Client B conflicts: affected rows=0

Zero-row optimistic update के बाद current data reload करें और workflow से recalculate, merge या reject का decision लें। Newer row silently overwrite न करें।

Technique Selection और Production Checklist

NeedPreferred starting technique
Single counter/stock decrementAtomic conditional UPDATE
Likely conflict वाला short multi-step decisionOne transaction में SELECT FOR UPDATE
Rare conflict वाला long editing formOptimistic version check
Read-only snapshot reportSuitable isolation पर consistent read
Parallel job queueIndexed status + FOR UPDATE SKIP LOCKED
  1. Lock चुनने से पहले invariant plain language में लिखें।
  2. InnoDB, explicit boundaries और database constraints लें।
  3. Predicates index करें ताकि locking statements fewer records scan/lock करें।
  4. Row counts और unique constraints check करें; UPDATE success assume न करें।
  5. Rows consistent order में access और transactions short रखें।
  6. Deadlock error 1213 पर complete transaction bounded policy से retry करें।
  7. Lock timeout separately handle करें क्योंकि default rollback scope different हो सकती है।
  8. Concurrent sessions load-test और lock waits monitor करें।

अब locks तथा deadlocks और MySQL indexes पढ़ें।

Official संदर्भ

MVCC, locking-read और rollback behavior official MySQL 8.4 manual से check किया गया है।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

DBMS में concurrency control क्या है?
Concurrency control overlapping transactions coordinate करता है ताकि shared data correctness rules follow करे और database useful parallel work भी permit करे।
MySQL में lost stock update कैसे रोकें?
stock = stock - 1 WHERE stock > 0 जैसी one atomic conditional UPDATE लें और one affected row require करें। Multi-step logic के लिए locking या optimistic version column alternatives हैं।
Optimistic और pessimistic locking में क्या अंतर है?
Pessimistic locking change से पहले rows reserve करती है, सामान्यतः SELECT FOR UPDATE से। Optimistic control work allow करके version या previous-value condition से stale final UPDATE reject करता है।
क्या MVCC का अर्थ writes कभी block नहीं करतीं?
नहीं। MVCC many plain reads को snapshots से बिना row locks पढ़ने देता है, लेकिन conflicting writes और locking reads locks लेती हैं और wait या deadlock कर सकती हैं।
Deadlock में statement या entire transaction retry करनी चाहिए?
InnoDB deadlock victim की entire transaction roll back करता है, इसलिए application complete logical transaction fresh start करके bounded retry करे।
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.