Locking: lock modes, deadlocks and lock timeout
Lock protocol
Section titled “Lock protocol”CoraDB combines MVCC with locking:
- Reading rows takes no row locks. A query reads the version of each row that its snapshot can see. It only takes an intent shared lock on the table, which prevents the table's schema from changing while it is read.
- Changing a row takes an exclusive row lock, held until the transaction ends. A second transaction that wants to change the same row waits until the first one commits or rolls back.
- DDL takes schema locks on the table.
When a requested lock conflicts with a lock held by another transaction, the requester waits. It continues when the holder releases the lock, which happens at COMMIT or ROLLBACK, or gives up when its lock timeout expires.
Locks are taken and released automatically; you cannot request them explicitly. To see the locks held and awaited in a running database, use coradb lockdb.
Granularity locking
Section titled “Granularity locking”Lockable objects form a hierarchy: rows belong to tables, and tables to the database. A lock on a row is announced on its table with an intent lock: an exclusive row lock puts an intent exclusive (IX) lock on the table. This way a transaction that wants to lock a whole table, for example to change its schema, sees immediately that rows of the table are in use.
Lock escalation. To limit the number of locks, a transaction that holds more row locks on a table than the system parameter lock_escalation (default 100,000) starts locking the table as a whole instead. Escalation happens only if no other transaction holds a lock on the table that would conflict, to avoid deadlocks caused by lock conversion. With rollback_on_lock_escalation = yes, the transaction is rolled back instead of escalating.
Lock mode types and compatibility
Section titled “Lock mode types and compatibility”| Lock | Name | Set on | Taken when |
|---|---|---|---|
| S | Shared | Row | Rarely with MVCC; used internally to protect rows or keys from being changed. |
| X | Exclusive | Row | Before a row is inserted, updated or deleted. Held until the transaction ends. |
| IS | Intent shared | Table | When rows of the table are read. Blocks schema changes and whole-table updates. |
| IX | Intent exclusive | Table | When rows of the table are changed. Blocks schema changes and whole-table reads or updates; other transactions can still change other rows. |
| SIX | Shared with intent exclusive | Table | When the whole table is protected against changes by others while some of its rows are changed, for example while an index is being loaded. Others can still read rows. |
| SCH-S | Schema stability | Table | While a query is compiled: the schema it uses cannot change. |
| SCH-M | Schema modification | Table | While DDL (CREATE, ALTER, DROP) changes the table. Blocks all other access to it. |
| BU | Bulk update | Table | While loaddb loads rows. Several loaddb processes can load the same table; other SELECT, DML and DDL statements on it wait. The holder takes no row locks. |
Lock compatibility. ✓ means the requester gets the lock while the holder keeps its lock; ✗ means the requester waits. NULL means no lock.
| Requested \ held | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M |
|---|---|---|---|---|---|---|---|---|---|
| NULL | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| SCH-S | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ |
| IS | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✗ |
| S | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| IX | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ |
| BU | ✓ | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ |
| SIX | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
| X | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
| SCH-M | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
Lock conversion. When a transaction that already holds a lock requests another on the same object, it ends up holding the combination shown here:
| Requested \ held | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M |
|---|---|---|---|---|---|---|---|---|---|
| NULL | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M |
| SCH-S | SCH-S | SCH-S | IS | S | IX | BU | SIX | X | SCH-M |
| IS | IS | IS | IS | S | IX | X | SIX | X | SCH-M |
| S | S | S | S | S | SIX | X | SIX | X | SCH-M |
| IX | IX | IX | IX | SIX | IX | X | SIX | X | SCH-M |
| BU | BU | BU | BU | X | BU | BU | BU | X | SCH-M |
| SIX | SIX | SIX | SIX | SIX | SIX | X | SIX | X | SCH-M |
| X | X | X | X | X | X | X | X | X | SCH-M |
| SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M |
Schema locks during DDL
Section titled “Schema locks during DDL”Some DDL statements do not take SCH-M at once, which lets other transactions keep working while the statement is compiled and executed. CREATE INDEX with a filter, for example, holds SCH-S while it checks the filter expression, upgrades to SIX while it loads the index (others can read but not change rows), and takes SCH-M only to change the schema at the end.
The downside is that two such statements on the same table can deadlock:
| Step | Transaction 1 | Transaction 2 |
|---|---|---|
| 1 | CREATE INDEX i_product_price ON product (unit_price) WHERE unit_price > 0; takes SCH-S to check unit_price > 0 |
|
| 2 | CREATE INDEX i_product_stock ON product (units_in_stock) WHERE units_in_stock > 0; takes SCH-S to check units_in_stock > 0 |
|
| 3 | Takes SIX and loads the index | |
| 4 | Requests SIX, waits for transaction 1 | |
| 5 | Requests SCH-M, waits for transaction 2's SCH-S: deadlock |
CoraDB resolves the deadlock by rolling back one of the transactions (see Transaction deadlock).
Examples using locks
Section titled “Examples using locks”The following examples use two sessions in REPEATABLE READ with autocommit off (see Snapshot examples for the setup). While a session waits, coradb lockdb <db> shows the locks.
Readers and writers do not block each other, but writers block writers
| Step | Session 1 | Session 2 | Result |
|---|---|---|---|
| 1 | UPDATE product SET units_in_stock = 20 WHERE id = 1618; |
Session 1 holds IX on product and X on the row (and on its new version). |
|
| 2 | SELECT units_in_stock FROM product WHERE id = 1618; |
22, immediately: the reader takes only IS on the table and reads the committed version. | |
| 3 | UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618; |
Session 2 upgrades to IX and waits for the X lock on the row. | |
| 4 | COMMIT; |
Session 1's locks are released. | |
| 5 | Session 2 continues, but the row was changed after its snapshot: ERROR: Serializable conflict due to concurrent updates. |
Had Session 1 rolled back in step 4, Session 2's update would have succeeded. Under READ COMMITTED, Session 2 would instead re-read the committed row and apply its update to it; see READ COMMITTED.
Locking to protect unique constraints
Section titled “Locking to protect unique constraints”With MVCC, a unique index can contain several versions of a key at the same time, each visible to different transactions, until VACUUM removes the old ones. To keep the constraint, every transaction that inserts or changes a key must lock the key's latest version.
| Step | Session 1 | Session 2 | Result |
|---|---|---|---|
| 1 | INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Socks', 'Merino socks', 9.90, 120); |
Session 1 locks the new row, which protects key 9001. | |
| 2 | INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Gaiters', 'Ankle gaiters', 14.90, 40); |
Session 2 inserts its row, finds key 9001 in the primary key and waits for Session 1's lock on it. | |
| 3 | COMMIT; |
||
| 4 | Session 2 continues, finds the key committed and fails with a unique constraint violation. |
ERROR: Operation would have caused one or more unique constraint violations. INDEX pk_product_id(B+tree: …) ON CLASS product(CLASS_OID: …). key: 9001(OID: …).If Session 1 had rolled back, Session 2's insert would have succeeded. (Remove product 9001 afterwards: DELETE FROM product WHERE id = 9001; COMMIT;.)
Transaction deadlock
Section titled “Transaction deadlock”A deadlock happens when two or more transactions each wait for a lock that another of them holds. CoraDB checks for deadlocks periodically (every deadlock_detection_interval_in_secs, default 1 second) and resolves each one by rolling back one of the transactions. The rolled-back transaction receives an error and can be retried.
Because reads take no row locks and indexes are not key-locked, deadlocks are rare under MVCC. They still happen when transactions change the same rows in a different order:
| Step | Session 1 | Session 2 | Result |
|---|---|---|---|
| 1 | UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618; |
Session 1 locks row 1618. | |
| 2 | UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1619; |
Session 2 locks row 1619. | |
| 3 | UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1619; |
Session 1 waits for Session 2. | |
| 4 | UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618; |
Session 2 waits for Session 1: deadlock. | |
| 5 | ERROR: Your transaction (index 1, dba@host|4760) has been unilaterally aborted by the system. |
CoraDB rolls back one of the transactions, here Session 1; Session 2 continues. |
To avoid deadlocks, change rows in a consistent order (for example by primary key), keep transactions short, and retry a transaction that was rolled back. With error_log_level set to NOTIFICATION, the server error log records the locks involved in each deadlock.
Transaction lock timeout
Section titled “Transaction lock timeout”The lock timeout is how long a transaction waits for a lock. When the time runs out, the statement fails with an error and the transaction is rolled back. If a deadlock occurs among waiting transactions, CoraDB rolls back the one whose wait is closest to its timeout.
The default comes from the system parameter lock_timeout (default -1, wait indefinitely). A session changes it with SET TRANSACTION:
SET TRANSACTION LOCK TIMEOUT timeout_spec;
timeout_spec: INFINITE -- wait indefinitely, like lock_timeout = -1 | OFF -- do not wait: fail at once, like lock_timeout = 0 | seconds -- wait at most this many seconds | :host_variableSET TRANSACTION LOCK TIMEOUT 10;SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, LOCK TIMEOUT 10; -- both in one statementlock_timeout = 10sGET TRANSACTION LOCK TIMEOUT returns the current value in seconds, or stores it in a host variable:
GET TRANSACTION LOCK TIMEOUT [ { INTO | TO } :variable ];Lock timeout errors
Section titled “Lock timeout errors”A transaction that times out receives a message like this:
Your transaction (index 2, user1@host1|9808) timed out waiting on IX_LOCK lock on class product. You are waiting foruser(s) user1@host1|corasql(9807), user1@host1|corasql(9805) to finish.| Part | Meaning |
|---|---|
index 2 |
The transaction index, a number assigned when the client connected. lockdb shows it too. |
user1@host1|9808 |
The database user, the client host and the process ID of the client. |
IX_LOCK lock on class product |
The lock that was requested, and on which object. |
user1@host1|corasql(9807), … |
The transactions holding the conflicting locks. |
To investigate:
- Run
coradb lockdb <db>to see which transactions hold which locks. - Look up the statements of those transactions in the SQL log of their broker; see Broker logs.
- If a transaction is stuck, end it with coradb killtran or the KILL statement.