Database Concurrency Control Techniques Course outlines Purpose of

Database Concurrency Control Techniques Course outlines Purpose of Concurrency Control Lock-Based Protocols - Pitfalls and serializability issues The Two-Phase Locking (2 PL) Protocol Implementation of Locking - Automatic Acquisition of Locks Timestamp-Based Protocols - Recoverability and Cascade Freedom Deadlock Handling Deadlock Prevention Strategies Deadlock Detection – graph based strategy, Deadlock Recovery Locking and Insert, Delete Operations Other protocols and schemes - an overview Graph-Based Protocols Validation-Based Protocol Granularity of data items , Intention Lock Modes Multi-version Schemes

Purpose of Concurrency Control Ê To enforce Isolation (through mutual exclusion) among conflicting transactions. Ê To preserve database consistency through consistency preserving execution of transactions. Ê To resolve read/write and write/write conflicts. An overview (enclosed table): Conflict if two operations satisfy with T 1 T 2 Confl 1. They belong to different transactions T 1, T 2 R 1( 2. They access the same data item Q Q) 3. At least one of the operation is write_item(Q) “W(Q)” Example: if T 1 conflicts with T 2 over a data item A, then the concurrency control decides: Ê if T 1 or T 2 should get the A Ê and if the other transaction is rolled-back or waits. R 2( Q) R 1( W 2( Q) Q) W 1( R 2( Q) Q) W 1( W 2( existing Q) Q) ict no yes yes 2

A lock is a mechanism to control concurrent access to a data item Database Concurrency Control Two-Phase Locking Techniques Locking is an operation which secures 1. permission to Read 2. permission to Write a data item for a transaction. Example: Lock (X). Data item X is locked in behalf of the requesting transaction. Unlocking is an operation which removes these permissions from the data item. Example: Unlock (X): Data item X is made available to all other transactions. Lock and Unlock are Atomic operations. 3

Database Concurrency Control A lock is a mechanism to control concurrent access to a data item Lock-Based Protocols Data items can be locked in two modes : matr C exclusive (X) mode: no one else can share. Lock-compatibility it; Ê Data item can be both read as well as written. Ê X-lock is requested using lock-X instruction. C shared (S) mode. Ê Data item can only be read. Ê S-lock is requested using lock-S instruction. S X Locking management: Lock requests are made to Concurrency-Control Transaction can proceed only after request is granted. Manager. A transaction may be granted a lock on an item if the requested lock is compatible (enclosed matrix) with locks already held on the item by other transactions Any number of transactions can hold shared locks on an item, but if any transaction holds an exclusive on the item no other transaction may hold any lock on the item. If a lock cannot be granted, the requesting transaction is made to wait till all 4

Database Concurrency Control Lock-Based Protocols Example of a transaction performing locking: Select A+B From … lock-S(A); read (A); unlock(A); lock-S(B); read (B); unlock(B); display(A+B) Analysis: if A and B get updated in-between the read of A and B, the displayed sum would be wrong. C Locking as above is not sufficient to guarantee serializability! Locking Protocol: Ê A locking protocol is a set of rules followed by all transactions while requesting and releasing locks. C Locking protocols restrict the set of possible schedules. 5

Database Concurrency Control- Lock-Based Protocols Pitfalls of Lock-Based Protocols ¤ Mal putting of locking/unlocking operations can cause to a T 1 deadlock. Consider the partial schedule (enclosed) Neither T 1 nor T 2 can make progress: T 2 waiting for T 1 to release its lock on A and vice verso C T 2 Lock-X(B) Read(B) B=B-100 Write(B) Lock-S(A) Read(A) Lock-S(B) The potential for deadlock exists in most locking protocols. Lock-X(A) Ê To handle a deadlock one of T 1 or T 2 must be rolled back and its locks released. C Starvation is also possible if concurrency control manager is badly designed. Example: Ê A transaction may be waiting for an X-lock on an item, while a sequence of other transactions request and are granted an S-lock on the same item. Ê The same transaction is repeatedly rolled back due to deadlocks. 6

Lock-Based Protocols Pitfalls: serializability issues Using lock-X/S locks in transaction does not guarantee serializability of schedules on its T 1 T 2 Consider the enclosed transactions own. T 1 T 2 Lock- with initial values: X=20, Y=30. S(Y) S(X) read(Y) read(X) Intended valid results: un. Lock( (Y) X) result of serial schedule T 1, T 2 : Lock. X=50, Y=80 X(X) X(Y) result of serial schedule T 2, T 1 : read(X) read(Y) X=X+Y Y=X+Y X=70, Y=50 write(X) write(Y) In this example, the locking rules are followed but Lock. S(Y) read(Y) un. Lock( non-serializable schedule X) Y)may result Result: X=50, Y=50 because the items Y in T 1 and X in T 2 were unlocked too early Lock. X(X) read(X) X=X+Y write(X) un. Lock( X) Lock. S(X) read(X) un. Lock( X) Lock. X(Y) read(Y) Y=X+Y write(Y) un. Lock( Y) To guarantee serializability we must follow an additional protocol concerning the positioning of locking and unlocking 7

The Two-Phase Locking (2 PL) Protocol This is a protocol which ensures conflict-serializable schedules. Phase 1: Growing Phase C It can be proved that the Êtransaction may obtain locks Êbut transaction may not release locks transactions can Phase 2: Shrinking Phase be serialized in the Êtransaction may release locks order of their lock Êbut transaction may not obtain locks points (i. e. the point Lock Conversions where a First Phase: transaction Êcan acquire a lock-S on item acquired its final Êcan acquire a lock-X on item Êcan convert a lock-S to a lock-X (upgrade) lock). Second Phase: Êcan release a lock-S Êcan release a lock-X 8

Lock-Based Protocols: the 2 PL and undesired schedules: an example T 1 and T 2 Do not follow the 2 PL protocol If we enforce 2 PL, the transactions can be rewritten as T 1’ and T 2’ as shown (T 1’ and T 2’ follow two-phase T 1 T 2 policy) T 1 T 2 T 1’ T 2’ Lock. S(Y) read(Y) un. Lock (Y) Lock. X(X) read(X) X=X+Y write(X) un. Lock( X) Lock. S(X) read(X) un. Lock( X) Lock. X(Y) read(Y) Y=X+Y write(Y) un. Lock( Y) Lock. S(Y) read(Y) Lock. X(X) un. Lock (Y) read(X) X=X+Y write(X) un. Lock (X) Lock. S(X) read(X) Lock. X(Y) un. Lock( X) read(Y) Y=X+Y write(Y) un. Lock( Y) Enforcing 2 PL Lock. S(Y) read(Y) un. Lock (Y) X Not yet permitted Lock. X(X) read(X) X=X+Y write(X) un. Lock( X) Lock. S(X) read(X) un. Lock (X) Lock. X(Y) read(Y) Y=X+Y write(Y) un. Lock( Y) C Note that, they can produce a deadlock, which must be deal with 9

Lock-Based Protocols: the 2 PL The Two-Phase Locking (2 PL) Protocol Two-phase locking (2 PL) does not ensure freedom from deadlocks L Cascading roll-back is possible under two-phase locking. C To avoid this, follow some modifications: Strict two-phase locking (variation of 2 PL): Êa transaction must hold all its exclusive locks (lock-X) till it commits/aborts. ÊStrict 2 PL allows only schedules whose precedence graph is acyclic Rigorous two-phase locking (variation of 2 PL) is even stricter: Êall locks are held till commit / abort. 10

Implementation of Locking Lock manager Lock and unlock requests are handled by the lock manager. Ê A Lock manager can be implemented as a separate process to which transactions send lock and unlock requests Ê The lock manager replies to a lock request by sending a lock grant messages (or a message asking the transaction to roll back, in case of a deadlock) Ê The requesting transaction waits until its request is answered Ê Unlock requests result in the request being deleted, and later requests are checked to see if they can now be granted Ê If transaction aborts, all waiting or granted requests of the transaction are deleted Lock Table Ê The lock manager maintains a data structure called a lock table to record granted locks and pending requests Ê The lock table is usually implemented as an in-memory hash table indexed on the name of the data item being locked Ê Lock table entry: Ê Ê Ê Number of transactions currently holding a lock Type of lock held (shared or exclusive) Pointer to queue of lock requests: new request is added to the end of the queue of requests for the data item, and granted if it is compatible with all earlier locks 11

Implementation of Locking: Lock manager Automatic Acquisition of Locks A transaction T issues the standard read/write instruction, without explicit locking calls. read(D) operation: if T has a lock on D then read(D) else begin if necessary wait until no other transaction has a lock-X on D grant T a lock-S on D; read(D) end; The write(D) operation: if T has a lock-X on D then write(D) else begin if necessary wait until no other transaction has any lock on D, if T has a lock-S on D then upgrade lock on D to lock-X else grant T a lock-X on D write(D) end; CAll locks are released after commit or abort 12

Concurrency control Timestamp-Based Protocols (1/3) Ê Each transaction is issued a timestamp when it enters the system. If an old transaction T 1 has time-stamp TS(T 1), a new transaction T 2 is assigned time-stamp TS(T 2) such that TS(T 1) < TS(T 2) Ê The protocol manages concurrent execution such that the time-stamps determine the serializability order. The protocol maintains for each data Q two timestamp values: Ê W-timestamp(Q) is the largest time-stamp among all TSs of transactions that executed write(Q) successfully Ê R-timestamp(Q) is the largest time-stamp of any transaction 13

Concurrency control read(data. Timestamp-Based Protocols (2/3) item) The timestamp ordering protocol ensures that any conflicting read and write operations are executed in timestamp order. Suppose a transaction Ti issues a read(Q) If TS(Ti) < WTS(Q), then Ti needs to read a value of Q that was already overwritten. Hence, the read operation is rejected, and Ti is rolled back, and resubmitted as a new transaction (with new TS) O Some younger transaction with a TS grater than TS(Ti) has already written the value of Q before Ti had a chance to read Q If TS(Ti) WTS(Q), Êthe read operation is executed, 14

Concurrency control write(data-ite Timestamp-Based Protocols (3/3) Suppose that transaction Ti issues write(Q). Ê If TS(Ti) < RTS(Q), then the value of Q that Ti is producing was needed previously, and the system assumed that value would never be produced. Hence, the write operation is rejected, and rolled back. Ti is resubmitted as a new transaction (with new TS) Ê If TS(Ti) < WTS(Q), then Ti is attempting to write an obsolete value of Q. Hence, this write operation is rejected, and rolled back. Ti is resubmitted as a new transaction (with new TS) 15

Concurrency control: Timestamp-Based Protocols Example Use of the Protocol A partial schedule for several data items for transactions with timestamps T 1 1, 2, 3, T 2 4, 5 T 3 T 4 T 5 R 5(X) R 2(Y) R 1(Y) read(Y) W 3(Z) R 5(Z) R 2(Z) R 1(X) read(X) W 4(Z) W 5(X) W 5(Z) read(X) read(Y) write(Z) read(Z) abort write(X) write(Z) 16

Concurrency control: Timestamp-Based Protocols Correctness of Timestamp-Ordering Protocol J The timestamp-ordering protocol guarantees serializability since all the arcs in the precedence graph are of the form: transaction with smaller/older timestamp Thus, there will be no graph transaction with larger/younge r timestamp cycles in the precedence Ê Timestamp protocol ensures freedom from deadlock as no transaction ever waits. C But the schedule may not be cascade-free, and may 17

Concurrency control: Timestamp-Based Protocols Recoverability and Cascade Freedom Problem with timestamp-ordering protocol: Ti Suppose Ti aborts, but Tj has read a data item written by. W Ti Then Tj must abort; D Êif Tj had been allowed to commit earlier, the schedule is not recoverable. Tj R Commit Tj Abort Ti ÊFurther, any transaction that has read a data item written by Tj must abort ÊThis can lead to cascading rollback --- that is, a chain of rollbacks L Solution 1: Ê A transaction is structured such that its writes are all performed at the end of its processing Ê All writes of a transaction form an atomic action; no transaction may execute while a transaction is being written Ê A transaction that aborts is restarted with a new timestamp L Solution 2: Limited form of locking: wait for data to be committed 18

Deadlock Handling and prevention strategies Consider the following two transactions: T 1: write (X) T 2: write (Y) T 1 write(Y) write (X) lock-X (X) write (X) Schedule with deadlock System is deadlocked if there is a set of transactions such that every transaction in the set is waiting for another transaction in the set T 2 lock-X (Y) write (Y) wait for lock-X on Y Deadlock prevention protocols ensure that the system will never enter into a deadlock state. Some prevention strategies : Ê Require that each transaction locks all its data items before it begins execution (predeclaration). Ê Impose partial ordering of all data items and require that a transaction can lock data items only in the order specified by 19

Deadlock Handling and prevention strategies More Deadlock Prevention Strategies Following schemes use transaction timestamps for the sake of deadlock prevention alone. 1. wait-die scheme Ê older transaction may wait for younger one to release data item. Ê Younger transactions never wait for older ones; they are rolled back instead. Ü a transaction may die several times before acquiring needed data item 2. wound-wait scheme Ê older transaction wounds (forces rollback) of younger transaction instead of waiting for it. Ê Younger transactions may wait for older ones. Ü may be fewer rollbacks than wait-die scheme. Both in wait-die and in wound-wait schemes: A rolled back transactions is restarted with its original timestamp. Older transactions thus have precedence over newer ones, and starvation is hence avoided. Timeout-Based Schemes : Ê a transaction waits for a lock only for a specified amount of time. After that, the wait times out and the transaction is rolled back. Ê thus deadlocks are not possible Ê simple to implement; but starvation is possible. 20

Deadlock Handling Deadlock Detection Deadlocks can be described as a wait-for graph, which consists of a pair G = (V, E), Ê V is a set of vertices (all the transactions in the system) Ê E is a set of edges; each element is an ordered pair Ti Tj. Ê If Ti Tj is in E then there is a directed edge from Ti to Tj, implying that Ti is waiting for Tj to release a data item. Insert remove edges from E Ê When Ti requests a data item currently being held by Tj, then the edge Ti Tj is inserted in the wait-for graph. Ê An edge is removed only when Tj is no longer holding a data item needed by Ti. Some examples C The system is in a deadlock state if and only if the wait-for graph has a cycle. Wait-for T 2 T 1 graph C Must invoke a deadlock-detection algorithm periodically towith look Wait-for a cycle for cycles. T 4 T 3 graph without a 21

Deadlock Handling - Deadlock Detection Deadlock Recovery When deadlock is detected : Ê Some transaction will have to rolled back (made to break deadlock. a victim) Select that transaction as victim that will incur minimum cost. T 1 T 2 Wait-for graph with a cycle In the enclosed example; a victim T 4 T 3 could be T 2, T 3 or T 4 Ê Rollback - determine how far to roll back transaction ÊTotal rollback: Abort the transaction and then restart it. ÊMore effective to roll back transaction only as far as necessary to break deadlock. Ê Starvation happens if same transaction is always chosen as victim. Include the number of rollbacks in the cost factor to avoid 22

Insert and Delete Operations (1/2) If two-phase locking is used : Ê A delete operation may be performed only if the transaction deleting the tuple has an exclusive lock on the tuple to be deleted. Ê A transaction that inserts a new tuple into the database is given an X-mode lock on the tuple Insertions and deletions can lead to the phantom phenomenon. Ê A transaction that scans a relation (e. g. , find sum of balances of all accounts in Perryridge) Ê and a transaction that inserts a tuple in the relation (e. g. , insert a new account at Perryridge) (conceptually) conflict in spite of not accessing any tuple in common. 23

Insert and Delete Operations (2/2) The transaction scanning the relation is reading information that indicates what tuples the relation contains, while a transaction inserting a tuple updates the same information. C The information should be locked. One solution: Ê Associate a data item with the relation, to represent the information about what tuples the relation contains. Ê Transactions scanning the relation acquire a shared lock in the data item, Ê Transactions inserting or deleting a tuple acquire an exclusive lock on the data item. (Note: locks on the data item do not conflict with locks on individual tuples. ) C Above protocol provides very low concurrency for insertions/deletions. 24

Other protocols and schemes an overview Graph-Based Protocols Validation-Based Protocol Granularity of data items and Multiple Granularity Locking - Intention Lock Modes Multi-version Schemes Index Locking Protocol

Database Concurrency Control Other protocols and schemes (1/3) Some other schemes and concurrency control protocols could be explored, such as : ÊGraph-Based Protocols: an alternative to two-phase locking ÊImpose a partial ordering on the set D = {d 1, d 2 , . . . , dh} of all data items. If di dj then any transaction accessing both di and dj must access di before accessing dj. Implies that the set D may now be viewed as a directed acyclic graph, called a database graph. ÊThe tree-protocol is a simple kind of graph protocol. ÊValidation-Based Protocol : execution of transaction Ti is done in three phases. 1. Read and execution phase: Transaction Ti writes only to temporary local variables 2. Validation phase: Transaction Ti performs a ``validation test'' to 26

Database Concurrency Control Other protocols and schemes (2/3) Granularity of data items and Multiple Granularity Locking Ê A lockable unit of data defines its granularity. Granularity can be coarse (entire database) or it can be fine (a tuple or an attribute of a relation). Ê Data item granularity significantly affects concurrency control performance. Thus, the degree of concurrency is low for coarse granularity and high for fine granularity. Example of data item granularity: 1. A field of a database record (an attribute of a tuple) 2. A database record (a tuple or a relation) 3. A disk block 4. An entire file 5. The entire database C To manage such hierarchy, in addition to read and 27

Other protocols and schemes - Granularity of data items Intention Lock Modes!!!! Ê In addition to S and X lock modes, there are three additional lock modes with multiple granularity: Ê intention-shared (IS): indicates explicit locking at a lower level of the tree but only with shared locks. Ê intention-exclusive (IX): indicates explicit locking at a lower level with exclusive or shared locks Ê shared and intention-exclusive (SIX): the subtree rooted by that node is locked explicitly in shared mode and explicit locking is being done at a lower level with exclusive-mode locks. Ê intention locks allow a higher level node to be locked in S or X mode without having to check SIX X IS IXall. Sdescendent IS nodes. Compatibility Matrix with IX S Intention Lock Modes SIX X 28

Other protocols and schemes (3/3) Multiversion Schemes: keep old versions of data item to increase concurrency. Ê Multiversion Timestamp Ordering Ê Multiversion Two-Phase Locking Ê Each successful write results in the creation of a new version of the data item written. Ê Use timestamps to label versions. Ê When a read(Q) operation is issued, select an appropriate version of Q based on the timestamp of the transaction, and return the value of the selected version. Ê reads never have to wait as an appropriate version is returned immediately. Index Locking Protocol Ê Every relation must have at least one index. Ê A transaction can access tuples only after finding them through one or more indices on the relation Ê A transaction Ti that performs a lookup must lock all the index leaf nodes that it accesses, in S-mode Ê Even if the leaf node does not contain any tuple satisfying the index lookup (e. g. for a range query, no tuple in a leaf is in the range) Ê A transaction Ti that inserts, updates or deletes a tuple ti in a relation r Ê must update all indices to r 29
- Slides: 29