Concurrency Control
Concurrency Control
● Lock-Based Protocols
● Timestamp-Based Protocols
● Validation-Based Protocols
● Multiple Granularity
● Multiversion Schemes
Lock-Based Protocols
● Lock requests are made to concurrency-control manager. Transaction can proceed only after request is
granted.
● Lock-compatibility matrix
● A transaction may be granted a lock on an item if the requested lock is compatible with locks already held on
the item by other transactions.
● 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 incompatible locks held by
other transactions have been released. The lock is then granted.
● Example of a transaction performing locking:
T2: lock-S(A);
read (A);
unlock(A);
lock-S(B);
read (B);
unlock(B);
display(A+B)
● Locking as above is not sufficient to guarantee serializability — if A and B get updated in-between the read of
A and B, the displayed sum would be wrong.
● A locking protocol is a set of rules followed by all transactions while requesting and releasing locks. Locking
protocols restrict the set of possible schedules.
Pitfalls of Lock-Based Protocols
● Neither T3 nor T4 can make progress — executing lock-S(B) causes T4 to wait for T3 to release its lock on B,
while executing lock-X(A) causes T3 to wait for T4 to release its lock on A.
● The potential for deadlock exists in most locking protocols. Deadlocks are a necessary evil.
● Starvation is also possible if concurrency control manager is badly designed. For 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 protocol assures serializability. It can be proved that the transactions can be serialized in the order of
their lock points (i.e. the point where a transaction acquired its final lock).
● Rigorous two-phase locking is even stricter: here all locks are held till commit/abort. In this protocol
transactions can be serialized in the order in which they commit.
Lock Conversions
– First Phase:
– Second Phase:
● This protocol assures serializability. But still relies on the programmer to insert the various locking
instructions.
● A transaction Ti issues the standard read/write instruction, without explicit locking calls.
if Ti has a lock on D
then
read(D)
else begin
grant Ti a lock-S on D;
read(D)
end
if Ti has a lock-X on D
then
write(D)
else begin
if Ti has a lock-S on D
then
else
grant Ti a lock-X on D
write(D)
end;
Implementation of Locking
● 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 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
Deadlock
Deadlock Handling
● 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.
● 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 the partial order (graph-based protocol).
Deadlock Detection
● Some transaction will have to rolled back (made a victim) to break deadlock. Select that transaction
as victim that will incur minimum cost.
4 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 starvation
Timestamp-Based Protocols
● Each transaction is issued a timestamp when it enters the system. If an old transaction Ti has time-stamp
TS(Ti), a new transaction Tj is assigned time-stamp TS(Tj) such that TS(Ti) <TS(Tj).
● The protocol manages concurrent execution such that the time-stamps determine the serializability order.
● In order to assure such behavior, the protocol maintains for each data Q two timestamp values:
● W-timestamp(Q) is the largest time-stamp of any transaction that executed write(Q) successfully.
● R-timestamp(Q) is the largest time-stamp of any transaction that executed read(Q) successfully.
● The timestamp ordering protocol ensures that any conflicting read and write operations are executed in
timestamp order.
● If TS(Ti) ≤ W-timestamp(Q), then Ti needs to read a value of Q that was already overwritten.
● If TS(Ti)≥ W-timestamp(Q), then the read operation is executed, and R-timestamp(Q) is set to max(R-
timestamp(Q), TS(Ti)).
● If TS(Ti) < R-timestamp(Q), then the value of Q that Ti is producing was needed previously, and the
system assumed that that value would never be produced.
● Hence, the write operation is rejected, and Ti is rolled back.
timestamps 1, 2, 3, 4, 5
● The timestamp-ordering protocol guarantees serializability since all the arcs in the precedence graph are of
the form:
● But the schedule may not be cascade-free, and may not even be recoverable.
● 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
● 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
● Solution 2: Limited form of locking: wait for data to be committed before reading it
Validation-Based Protocols
serializability.
● The three phases of concurrently executing transactions can be interleaved, but each transaction must go
through the three phases in that order.
● Assume for simplicity that the validation and write phase occur together, atomically and serially
● Also called as optimistic concurrency control since transaction executes fully in the hope that all will go well
during validation
● start time
● validation time
● Details in book
Phantom Problem
4 E.g. the scan transaction does not see the new account, but reads some other tuple written
by the update transaction
● Index locking protocols used to prevent phantom phenomenon (see book for details)
● Repeatable read: allows only committed records to be read, and repeating a read should return the
same value (so read locks should be retained)
– T1 may see some records inserted by T2, but may not see others inserted by T2
● Read committed: same as degree two consistency, but most systems implement it as cursor-
stability
● Indices are unlike other database items in that their only job is to help in accessing data.
● Index-structures are typically accessed very often, much more than other database items.
● Treating index-structures like other database items, e.g. by 2-phase locking of index nodes can lead
to low concurrency.
● There are several index concurrency protocols where locks on internal nodes are released early, and not in a
two-phase fashion.
● It is acceptable to have nonserializable concurrent access to an index as long as the accuracy of the
index is maintained.
n Failure Classification
n Storage Structure
n Log-Based Recovery
n Shadow Paging
n Buffer Management
n Transaction failure :
n Logical errors: transaction cannot complete due to some internal error condition
n System errors: the database system must terminate an active transaction due to an error condition
(e.g., deadlock)
n System crash: a power failure or other hardware or software failure causes the system to crash.
n Fail-stop assumption: non-volatile storage contents are assumed to not be corrupted by system
crash
n Database systems have numerous integrity checks to prevent corruption of disk data
n Disk failure: a head crash or similar disk failure destroys all or part of disk storage
Recovery Algorithms
n Recovery algorithms are techniques to ensure database consistency and transaction atomicity and durability
despite failures
Actions taken during normal transaction processing to ensure enough information exists to recover
from failures
Actions taken after a failure to recover the database contents to a state that ensures atomicity,
consistency and durability
Storage Structure
n Volatile storage:
n Nonvolatile storage:
survives system crashes
n Stable storage:
Stable-Storage Implementation
copies can be at remote sites to protect against disasters such as fire or flooding.
n Failure during data transfer can still result in inconsistent copies: Block transfer can result in
Successful completion
n Protecting storage media from failure during data transfer (one solution):
2. When the first write successfully completes, write the same information onto the second
physical block.
3. The output is completed only after the second write successfully completes.
n Copies of a block may differ due to failure during output operation. To recover from failure:
2. Better solution:
n Use this information during recovery to find blocks that may be inconsistent, and
only compare copies of these.
If either copy of an inconsistent block is detected to have an error (bad checksum), overwrite it by
the other copy. If both have no error, but are different, overwrite the second block by the first
block.
Data Access
n Block movements between disk and main memory are initiated through the following two operations:
input(B) transfers the physical block B to main memory.
output(B) transfers the buffer block B to the disk, and replaces the appropriate physical block there.
n Each transaction Ti has its private work-area in which local copies of all data items accessed and updated by
it are kept.
n We assume, for simplicity, that each data item fits in, and is stored inside, a single block.
n Transaction transfers data items between system buffer blocks and its private work-area using the following
operations :
read(X) assigns the value of data item X to the local variable xi.
write(X) assigns the value of local variable xi to data item {X} in the buffer block.
both these commands may necessitate the issue of an input(BX) instruction before the assignment, if
the block BX in which X resides is not already in memory.
n Transactions
n output(BX) need not immediately follow write(X). System can perform the output operation when it deems
fit.
n Modifying the database without ensuring that the transaction will commit may leave the database in an
inconsistent state.
n Consider transaction Ti that transfers $50 from account A to account B; goal is either to perform all database
modifications made by Ti or none at all.
n Several output operations may be required for Ti (to output A and B). A failure may occur after one of these
modifications have been made but before all of them are made.
n To ensure atomicity despite failures, we first output information describing the modifications to stable
storage without modifying the database itself.
n shadow-paging
n We assume (initially) that transactions run serially, that is, one after the other.
Log-Based Recovery
The log is a sequence of log records, and maintains a record of update activities on the database.
n Before Ti executes write(X), a log record <Ti, X, V1, V2> is written, where V1 is the value of X before the
write, and V2 is the value to be written to X.
Log record notes that Ti has performed a write on data item Xj Xj had value V1 before the write, and
will have value V2 after the write.
n When Ti finishes it last statement, the log record <Ti commit> is written.
n We assume for now that log records are written directly to stable storage (that is, they are not buffered)
n The deferred database modification scheme records all modifications to the log, but defers all the writes to
after partial commit.
n A write(X) operation results in a log record <Ti, X, V> being written, where V is the new value for X
n Finally, the log records are read and used to actually execute the previously deferred writes.
n During recovery after a crash, a transaction needs to be redone if and only if both <Ti start> and<Ti commit>
are there in the log.
n Redoing a transaction Ti ( redoTi) sets the value of all data items updated by the transaction to the new
values.
A: - A - 50 C:- C- 100
read (B)
B:- B + 50
write (B)
n
n If log on stable storage at time of crash is as in case:
n The immediate database modification scheme allows database updates of an uncommitted transaction to
be made as the writes are issued
since undoing may be needed, update logs must have both old value and new value
Can be extended to postpone log record output, so long as prior to execution of an output(B)
operation for a data block B, all log records corresponding to items B must be flushed to stable
storage
n Output of updated blocks can take place at any time before or after transaction commit
n Order in which blocks are output can be different from the order in which they are written.
Immediate Database Modification Example
<T0 start>
A = 950
B = 2050
<T0 commit>
<T1 start>
C = 600
BB, BC
<T1 commit>
BA
n undo(Ti) restores the value of all data items updated by Ti to their old values, going backwards from
the last log record for Ti
n redo(Ti) sets the value of all data items updated by Ti to the new values, going forward from the first
log record for Ti
n That is, even if the operation is executed multiple times the effect is the same as if it is executed
once
n Transaction Ti needs to be redone if the log contains both the record <Ti start> and the record <Ti
commit>.
n (b) undo (T1) and redo (T0): C is restored to 700, and then A and B are
n (c) redo (T0) and redo (T1): A and B are set to 950 and 2050
Checkpoints
1. Output all log records currently residing in main memory onto stable storage.
n During recovery we need to consider only the most recent transaction Ti that started before the checkpoint,
and transactions that started after Ti.
1. Scan backwards from end of log to find the most recent <checkpoint> record
3. Need only consider the part of log following above start record. Earlier part of log can be ignored
during recovery, and can be erased whenever desired.
4. For all transactions (starting from Ti or later) with no <Ti commit>, execute undo(Ti). (Done only in
case of immediate modification.)
5. Scanning forward in the log, for all transactions starting from Ti or later with a <Ti commit>,
execute redo(Ti).
Example of Checkpoints
n T2 and T3 redone.
n T4 undone
Shadow Paging
n Shadow paging is an alternative to log-based recovery; this scheme is useful if transactions execute serially
n Idea: maintain two page tables during the lifetime of a transaction –the current page table, and the shadow
page table
n Store the shadow page table in nonvolatile storage, such that state of the database prior to transaction
execution may be recovered.
n To start with, both the page tables are identical. Only current page table is used for data item accesses
during execution of the transaction.
3. Make the current page table the new shadow page table, as follows:
keep a pointer to the shadow page table at a fixed (known) location on disk.
to make the current page table the new shadow page table, simply update the pointer to point to
current page table on disk
n Once pointer to shadow page table has been written, transaction is committed.
n No recovery is needed after a crash — new transactions can start right away, using the shadow page table.
n Pages not pointed to from current/shadow page table should be freed (garbage collected).
n Checkpoints are performed as before, except that the checkpoint log record is now of the form
< checkpoint L>
where L is the list of transactions active at the time of the checkpoint
We assume no updates are in progress while the checkpoint is carried out (will relax this later)
n When the system recovers from a crash, it first does the following:
Scan the log backwards from the end, stopping when the first <checkpoint L> record is found.
For each record found during the backward scan:
n At this point undo-list consists of incomplete transactions which must be undone, and redo-list consists of
finished transactions that must be redone.
H During the scan, perform undo for each log record that belongs to a transaction in undo-list.
Scan log forwards from the <checkpoint L> record till the end of the log.
H During the scan, perform redo for each log record that belongs to a transaction on redo-list
Example of Recovery
<T0 start>
<T0, A, 0, 10>
<T0 commit>
<T1 start>
<T1, B, 0, 10>
<T2, C, 0, 10>
<T3 start>
<T3, D, 0, 10>
<T3 commit>
n Log record buffering: log records are buffered in main memory, instead of of being output directly to stable
storage.
Log records are output to stable storage when a block of log records in the buffer is full, or a log
force operation is executed.
n Log force is performed to commit a transaction by forcing all its log records (including the commit record) to
stable storage.
n Several log records can thus be output using a single output operation, reducing the I/O cost.
Log records are output to stable storage in the order in which they are created.
Transaction Ti enters the commit state only when the log record
<Ti commit> has been output to stable storage.
Before a block of data in main memory is output to the database, all log records pertaining to data in
that block must have been output to stable storage.
Database Buffering
When a new block is needed, if buffer is full an existing block needs to be removed from buffer
If the block chosen for removal has been updated, it must be output to disk
n As a result of the write-ahead logging rule, if a block with uncommitted updates is output to disk, log records
with undo information for the updates are output to the log on stable storage first.
n No updates should be in progress on a block when it is output to disk. Can be ensured as follows.
Before writing a data item, transaction acquires exclusive lock on block containing the data item
Before a block is output to disk, the system acquires an exclusive latch on the block
in virtual memory
Memory is partitioned before-hand between database buffer and applications, limiting flexibility.
Needs may change, and although operating system knows best how memory should be divided up at
any time, it cannot change the partitioning of memory.
n Database buffers are generally implemented in virtual memory in spite of some drawbacks:
When operating system needs to evict a page that has been modified, to make space for another
page, the page is written to swap space on disk.
When database decides to write buffer page to disk, buffer page may be in swap space, and may
have to be read from swap space on disk and output to the database on disk, resulting in extra I/O!
Ideally when swapping out a database buffer page, operating system should pass control to
database, which in turn outputs page to database instead of to swap space (making sure to output
log records first)
n Dual paging can thus be avoided, but common operating systems do not support such
functionality.
Failure with Loss of Nonvolatile Storage
No transaction may be active during the dump procedure; a procedure similar to checkpointing must
take place
➢ Output all log records currently residing in main memory onto stable storage.
➢ Consult the log and redo all transactions that committed after the dump
n Support high-concurrency locking techniques, such as those used for B+-tree concurrency control
They cannot be undone by restoring old values (physical undo), since once a lock is released, other
transactions may have updated the B+-tree.
Instead, insertions (resp. deletions) are undone by executing a deletion (resp. insertion) operation
(known as logical undo).
n For such operations, undo log records should contain the undo operation to be executed
n Redo information is logged physically (that is, new value for each write) even for such operations
Logical redo is very complicated since database state on disk may not be “operation consistent”
When operation starts, log <Ti, Oj, operation-begin>. Here Oj is a unique identifier of the operation
instance.
While operation is executing, normal log records with physical redo and physical undo information
are logged.
When operation completes, <Ti, Oj, operation-end, U> is logged, where U contains information
needed to perform a logical undo information.
logical undo is performed using U; the physical undo information for the operation is ignored.
1. If a log record <Ti, X, V1, V2> is found, perform the undo and log a special redo-only log record <Ti, X,
V1>.
– Updates performed during roll back are logged just like during normal operation
execution.
➢ Skip all preceding log records for Ti until the record <Ti, Oj operation-begin> is found
n Cases 3 and 4 above can occur only if the database crashes while a transaction is being rolled back.
n Skipping of log records as in case 4 is important to prevent multiple rollback of the same operation.
The following actions are taken when recovering from system crash
This brings database to state as of crash, with committed as well as uncommitted transactions having been
redone.
Now undo-list contains transactions that are incomplete, that is, have neither committed nor been fully
rolled back.
2. Scan log backwards, performing undo on log records of transactions found in undo-list.
When <Ti start> is found for a transaction Ti in undo-list, write a <Ti abort> log record.
Stop scan when <Ti start> records have been found for all Ti in undo-list
n This undoes the effects of incomplete transactions (those with neither commit nor abort log records).
Recovery is now complete.
Transactions are not allowed to perform any actions while checkpointing is in progress.
n Fuzzy checkpointing allows transactions to progress while the most time consuming parts of checkpointing
are in progress
Write a <checkpoint L> log record and force log to stable storage
n Follow WAL: all log records pertaining to a block must be output before the block is output
n When recovering using a fuzzy checkpoint, start scan from the checkpoint record pointed to by
last_checkpoint
Log records before last_checkpoint have their updates reflected in database on disk, and need not
be redone.
Incorporates numerous optimizations to reduce overheads during normal processing and to speed
up recovery
The “advanced recovery algorithm” we studied earlier is modeled after ARIES, but greatly simplified
by removing optimizations
➢ Stores LSNs in pages to identify what updates have already been applied to a database page
Physiological redo
Fuzzy checkpointing that only records information about dirty pages, and does not require dirty
pages to be written out at checkpoint time
n Physiological redo
n e.g. when a record is deleted and all other records have to be moved to fill hole
n Physical redo would require logging of old and new values for much of the
page
n Easy to achieve with hardware RAID, also supported by some disk systems
n Each page contains a PageLSN which is the LSN of the last log record whose effects are reflected on the page
To update a page:
➢ Unlock page
n DirtyPageTable
➢ RecLSN is an LSN such that log records before this LSN have already been applied to the
page version on disk
– Set to current end of log when a page is inserted into dirty page table (just before
being updated)
Contains:
➢ For each active transaction, LastLSN, the LSN of the last log record written by the transaction
Which pages were dirty (disk version not up to date) at time of crash
n Redo pass:
n Undo pass:
– Key idea: no need to undo these transactions: earlier undo actions were logged, and
are redone as required
Analysis pass
Reads LSN of last log record for each transaction in undo-list from checkpoint log record
.. On next page …
If any log record found for transaction not in undo-list, adds transaction to undo-list
➢ If page is not in DirtyPageTable, it is added with RecLSN set to LSN of the update log record
Redo Pass: Repeats history by replaying every action not already reflected in the page on disk, as follows:
1. If the page is not in DirtyPageTable or the LSN of the log record is less than the RecLSN of the page in
DirtyPageTable, then skip the log record
2. Otherwise fetch the page from disk. If the PageLSN of the page fetched from disk is less than the
LSN of the log record, redo the log record
NOTE: if either test is negative the effects of the log record have already appeared on the page. First test avoids
even fetching the page from disk!
ARIES Undo Actions
Generate a CLR containing the undo action performed (actions performed during undo are logged
physicaly or physiologically).
Set UndoNextLSN of the CLR to the PrevLSN value of the update log record
Used e.g. to handle deadlocks by rolling back just enough to release reqd. locks
1 2 3 4 4 3 5 6 6 52 1
Undo pass
➢ Next LSN to be undone for each transaction set to LSN of last log record for transaction
found by analysis pass.
➢ At each step pick largest of these LSNs to undo, skip back to it and undo it
– For ordinary log records, set next LSN to be undone for transaction to PrevLSN noted
in the log record
– For compensation log records (CLRs) set next LSN to be undo to UndoNextLSN noted
in the log record
» All intervening records are skipped since they would have been undo
already
n Recovery Independence
➢ E.g. if some disk pages fail they can be recovered from a backup while other pages are being
used
n Savepoints:
Transactions can record savepoints and roll back to a savepoint
n Fine-grained locking:
Index concurrency algorithms that permit tuple level locking on indices can be used
➢ These require logical undo, rather than physical undo, as in advanced recovery algorithm
n Remote backup systems provide high availability by allowing transaction processing to continue even if the
primary site is destroyed.
n Detection of failure: Backup site must detect when primary site has failed
to distinguish primary site failure from link failure maintain several communication links between
the primary and the remote backup.
n Transfer of control:
To take over control backup site first perform recovery using its copy of the database and all the long
records it has received from the primary.
➢ Thus, completed transactions are redone and incomplete transactions are rolled back.
When the backup site takes over processing it becomes the new primary
To transfer control back to old primary when it recovers, old primary must receive redo logs from
the old backup and apply all updates locally.
n Time to recover: To reduce delay in takeover, backup site periodically proceses the redo log records (in
effect, performing recovery from previous database state), performs a checkpoint, and can then delete
earlier parts of the log.
n Hot-Spare configuration permits very fast takeover:
Backup continually processes redo log record as they arrive, applying the updates locally.
When failure of the primary is detected the backup rolls back incomplete transactions, and is ready
to process new transactions.
n Ensure durability of updates by delaying transaction commit until update is logged at backup; avoid this
delay by permitting lower degrees of durability.
n Two-very-safe: commit when transaction’s commit log record is written at primary and backup
n Two-safe: proceed as in two-very-safe if both primary and backup are active. If only the primary is active, the
transaction commits as soon as is commit log record is written at the primary.