Concurrent Updates, Isolation Levels, and Locks
🎯 Introduction
By the end of this article, you will be able to prevent concurrent updates from overwriting data and observe transaction reads and lock waits.
🔢 Avoid having two requests both change 10 to 11
Two requests can read a count of 10, each add one in the application, and both write back 11, increasing the count only once. Having the database calculate from the current value avoids this lost update.
Create a practice table in blog_demo:
CREATE TABLE counter (
id INT PRIMARY KEY,
value INT NOT NULL
);
INSERT INTO counter VALUES (1, 10);
Run this for each increment:
UPDATE counter SET value = value + 1 WHERE id = 1;
If two successfully committed requests each execute this once, the value increases from 10 to 12. InnoDB coordinates updates to the same row; the application does not need to read 10 before calculating.
🛡 Enforce limits with conditional updates
Suppose the value must not exceed 20. Combine the check and update in one statement:
UPDATE counter SET value = value + 1 WHERE id = 1 AND value < 20;
One changed row means the increment succeeded; zero means the condition did not match or the record does not exist. The application can return a result accordingly. This is more reliable than checking for a value below 20 and performing an unconditional update later.
🔒 FOR UPDATE: lock rows while reading so other updates wait
If you read a record inside a transaction and need its value for subsequent changes, add FOR UPDATE to SELECT. It locks the record so competing requests wait rather than changing the same record during your processing.
For example, A reads a count of 10 for ID 1 and locks the row. B must wait for A to commit or roll back before incrementing it. Use two windows below to observe this wait. A simple increment still needs only one UPDATE, with no extra locking query.
Open two MySQL client windows and select blog_demo in both. First, reset the count to 10 with autocommit enabled:
UPDATE counter SET value = 10 WHERE id = 1;
In window A, run:
START TRANSACTION;
SELECT value FROM counter WHERE id = 1 FOR UPDATE;
Following the steps in this article produces:
| value |
|---|
| 10 |
FOR UPDATE reads and locks the record to be modified. Now run this in window B:
UPDATE counter SET value = value + 1 WHERE id = 1;
B waits. Return to A and execute COMMIT to let B continue. If A remains open too long, B may time out with an error. Always commit or roll back when the exercise is finished; do not leave the transaction open.
An equality lookup on an existing primary key has a clear locking target. Range queries or a lack of suitable indexes can lock more records, so do not assume every update involves only one lock.
📝 Check a version when saving forms to avoid overwriting others' changes
If two users open the same profile and save different cities, the later save may overwrite the earlier one. Add a version number to user:
ALTER TABLE user ADD COLUMN version INT NOT NULL DEFAULT 1;
Read version alongside the profile. If the page reads version 1, submit that version with the new city. The server executes:
UPDATE user SET city = 'Wuhan', version = version + 1
WHERE id = 1 AND version = 1;
The first match changes the city to Wuhan and the version to 2. Another form still saving version 1 affects zero rows. The API should report that the profile has changed and ask the user to reload before deciding what to do, rather than overwriting it.
Checking for intervening changes at save time is called optimistic locking. Every path that updates this data must honor the version check; bypassing it leaves the protection incomplete. This suits forms that need editing-conflict messages. For the earlier counter increment, calculate directly in the database.
👀 Repeatable read: keep reading the original value within one transaction after another commits
Suppose the count starts at 10. A starts a transaction and reads 10. B changes it to 20 and commits. A queries again within the same transaction, which is still open, and still gets 10.
This demonstrates REPEATABLE READ: in the experiment below, A's ordinary queries keep reading the data visible at its first query, unaffected by B's later commit. A can therefore perform several queries against a consistent view, such as counting users and then fetching their details without including users another transaction inserted between those queries.
Prepare two independent connections
A and B are two MySQL client windows with separate database connections, both using blog_demo. End any existing transactions in both. In B, with autocommit enabled, reset the count to 10:
UPDATE counter SET value = 10 WHERE id = 1;
The record with ID 1 in counter is now:
| id | value |
|---|---|
| 1 | 10 |
Window A: start a transaction and read 10
An isolation level determines which changes from other transactions a transaction can see. First, set A to repeatable read:
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET SESSION changes the current connection's settings; TRANSACTION ISOLATION LEVEL specifies the transaction isolation level; REPEATABLE READ selects repeatable read. This chooses the reading rules for transactions subsequently started in A without changing B's connection.
InnoDB defaults to repeatable read. Setting it explicitly keeps the experiment consistent. Then start a transaction in A:
START TRANSACTION;
Query in A without committing afterward:
SELECT value FROM counter WHERE id = 1;
Result:
| value |
|---|
| 10 |
Window B: change the value to 20 and commit
Switch to B and run:
UPDATE counter SET value = 20 WHERE id = 1;
B uses the default autocommit mode, so 20 is committed when the statement succeeds. A's earlier SELECT did not use FOR UPDATE, so it does not make B wait as in the earlier experiment.
Window A: query again in the same transaction and still get 10
Return to A and run the same query without starting a new transaction:
SELECT value FROM counter WHERE id = 1;
The result is still:
| value |
|---|
| 10 |
B's update succeeded, and A did not change the value back to 10. B committed 20, but A remains in its original transaction and keeps reading the data visible at its first query.
The database retains the older versions A needs. This is a snapshot read; it does not copy the entire database, nor does it mean every connection reads the old value.
Window A: end the transaction and read 20
COMMIT;
SELECT value FROM counter WHERE id = 1;
Result:
| value |
|---|
| 20 |
A's original transaction has ended, so the new query can see B's committed change. When investigating an old value, check whether the current transaction is still open.
In this example, A only reads: it makes no changes and does not use FOR UPDATE. A can see its own changes within a transaction, and FOR UPDATE follows different reading rules. Do not infer that all queries under repeatable read always return unchanged results.
🔄 READ COMMITTED reads committed data on each query
To let A see B's newly committed value of 20 on a subsequent query in the same transaction, change the reading rules for A's subsequent transactions to READ COMMITTED.
End A's current transaction first, then run this in window A:
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
This sets the current connection's subsequently started transactions to the READ COMMITTED isolation level. It neither changes counter data nor automatically starts a transaction.
| Statement component | Meaning | Purpose here |
|---|---|---|
| SET | Change a setting | Tells MySQL this is a configuration statement |
| SESSION | Current connection | Changes A only, leaving B unchanged |
| TRANSACTION ISOLATION LEVEL | Transaction isolation level | Selects the rules for reading other transactions' data |
| READ COMMITTED | Read committed | Each ordinary query can read data committed at that time |
The previous section used REPEATABLE READ; replacing it with READ COMMITTED leaves the other components unchanged. This setting remains in effect for A until changed again or disconnected, rather than applying only to the next SELECT.
Follow this sequence without reapplying the previous section's REPEATABLE READ setting:
| Step | Window | Action and result |
|---|---|---|
| 1 | B | Reset value to 10 with autocommit enabled |
| 2 | A | Execute START TRANSACTION, then query value and get 10 |
| 3 | B | Update value to 20 and commit automatically |
| 4 | A | Query value again, get 20 this time, and finish with COMMIT |
Under READ COMMITTED, each ordinary query in A can read data committed at that time, so the second query sees B's change.
Choose an isolation level based on reading requirements and lock contention. Changing levels does not replace correct conditional updates. The change affects only the current connection; reconnect after the experiment to restore the server defaults.
🪤 Handle the whole transaction after a deadlock
If A locks record 1 and waits for record 2 while B locks record 2 and waits for record 1, each is waiting for the other: a deadlock. InnoDB typically selects one transaction to roll back and returns a deadlock error, allowing the other to continue.
After a deadlock error, retry the entire transaction rather than just the final SQL statement, and limit the number of retries. Common ways to reduce deadlocks include updating rows in the same ID order and keeping transactions short.
A lock wait timeout is different from a deadlock. After a timeout, explicitly roll back the current transaction before deciding whether to retry, so earlier successful statements are not accidentally committed.
❓ Questions and Answers
Q1: Will the row locks above keep blocking an ordinary SELECT?
Usually not. An ordinary query can read committed data according to its isolation level. FOR UPDATE and writes need to compete for the corresponding locks.
Q2: Can I automatically overwrite using the new version after a version conflict?
Do not overwrite directly; doing so defeats conflict detection. Reload the current content and let the user decide how to merge or save it.
Q3: Does starting a transaction guarantee there will be no lost updates?
No. Reading and then unconditionally overwriting can still cause problems. Choose conditional updates, version checks, or appropriate locking reads.
🧪 Exercise
Complete the waiting experiment in two windows and record when B continues. Then verify the value returned by A's second ordinary query under each isolation level.
-- Write your SQL or record your verification results here
