Eight Isolation Levels Every Web Developer Should Know

来源:互联网 发布:锁屏界面 windows聚焦 编辑:程序博客网 时间:2024/04/30 05:57

 

The ACID properties are one of the cornerstones of database theory. ACIDdefines four properties that must be present if a database is consideredreliable: Atomicity, Consistency, Isolation, and Durability. While all fourproperties are important, isolation in particular is interpreted with the mostflexibility. Most databases provide a number of isolation levels to choosefrom, and many libraries today add additional layers which create even more fine-graineddegrees of isolation. The main reason for this wide range of isolation levelsis that relaxing isolation can often result in scalability and performanceincreases of several orders of magnitude.

RelatedVendorContent

Improving ApplicationPerformance and Scalability with Terracotta Ehcache

Adobe® Flash® Platform OverviewPDF

Intel® SOA ExpresswayPerformance Comparison to IBM® DataPower XI50

Free $40 SOA Demystified BookOffer

Business Benefits of OpenSource SOA

Serializable consistency is one of the oldest and highest isolation levelsthat is generally available, and many choose it due to the simple programmingmodel it provides - only one transaction can execute at a time against a givenresource, and many potential sources of problems are removed. However, mostapplications (particularly web applications) cannot assume this very high levelof isolation because it is impractical from the end user perspective - anyapplication with a non-trivial number of users would quickly experience delaysof several minutes accessing shared resources, which would rapidly reduce thenumber of users of that application back to a trivial number. Weak and eventualconsistency are common in large distributed data sources such as the Web, andseveral very large and successful web-based applications (e.g. eBay and Amazon)have shown that optimistic weak consistency is much more scalable thantraditional pessimistic mechanisms. This article takes a look at eightdifferent isolation levels that you can use to potentially gain moreperformance and scalability in your applications by learning to relax dataconsistency constraints.

The main goal of concurrency control is to ensure transactions areisolated and do not interfere with one another. Higher degrees of isolation areachieved at the expense of potential performance gains. Concurrency control isimplemented by a pessimistic or optimistic mechanism. Most relationaldatabases, which are write-optimised, use a pessimistic mechanism. Pessimisticmechanisms use locks and may block operations or use some form of conflictdetection. Pessimistic blocking is done when a table, page, or row has beenmodified, preventing other transactions from accessing potentially modifiedresources. However, optimistic mechanisms do not use any locks and rely solelyon conflict detection to maintain transaction isolation. Conflict detection, asused by optimistic mechanisms, permits all read operations and verifiesconsistency at the end of the transaction. If a conflict is detected then thetransaction is rolled back or repeated. Most web servers are read-optimised andthus use an optimistic mechanism. By permitting all read operations, optimisticmechanisms can achieve a higher read and write throughput while stillpreserving data consistency when resources are not continually changing.

The isolation levels listed below are here to help Web developers betterunderstand the constraints placed on their programming models, and to engagesystem architects and developers in discussions to choose the most efficientisolation levels while maintaining necessary data consistency. They are listedfrom the least isolated (Read Uncommitted) to the most isolated(Serializability).

1 ReadUncommitted

Read uncommitted isolation level requires little isolation betweentransactions. Every read operation may see pending write operations from anytransaction (dirty reads). However, committed write operations must have aserial order to prevent dirty writes. A pessimistic mechanism will blockconflicting write operations until others are committed or rolled back. Anoptimistic mechanism will not lock and will allow everything to go through. Ifa connection is rolled back, all other connections that made subsequentmodifications to the same data will also be rolled back. Shared caches arepermitted in this level without validation. This isolation level is best usedwhen transactions are not needed (such as a read-only dataset) or are modifiedwith exclusive access to the database.

Example: An archive database that is onlyupdated while offline, or an audit/logging table that is not used within atransaction

2 Read Committed

Read committed may read any committed state of the system and may becached without validation (mixed states) as long as changes in the currentconnection are reflected in the results. Pessimistic mechanisms implement thisas a Monotonic View. Optimistic transactions store all changes in isolation,making them only available to itself until committed. Read committed isimplemented with an overly optimistic mechanism that delays writing all changesuntil the transaction is committed. This form of optimistic isolation permitscomplicated write operations without blocking read operations and has novalidation schema. Shared caches are permitted only for committed states. Thisisolation level is best used when older values are permitted in results andtransactions are only use for write operations.

Example: An online forum, when the absolutelatest postings may not necessarily be shown and posts don't conflict with eachother

3 Monotonic View

Monotonic view is an extension to read committed wheretransactions observes a monotonically increasing state of the database as itexecutes. In this level, a pessimistic transaction may be blocked during readoperations if there is an outstanding write transaction. Optimistictransactions behave like read committed, keeping their changes in isolation,but validate their cache to ensure it is still valid. Periodically synchronizeddatabase clones are permitted in this level. This isolation level is best usedwhen transactions are not needed or transactions only contain write operations.

Example: A user preference tables that aremodified only by one person

4 Snapshot Reads

Snapshot Reads extends monotonic view and guarantees that query results reflect a consistent snapshot of thedatabase. A pessimistic mechanism will block other write operations fromaffecting the results while they are being read. An optimistic mechanism willallow other write operations and inform the reading transaction if any of theresults have changed and may roll it back. To implement an optimisticmechanism, a validation must be performed at the end of the read operation todetect if any concurrent write operations modified the result, and if so theresult maybe repeated or rolled back. This validation may simply check if writeoperations occurred in the same table, or it might check the query results forthe changes. This optimistic isolation level can detect conflicts easily andfavours write operations, while permitting concurrent read operations. Thislevel permits periodically synchronized database clones so long as they providesnapshot reads. It is best used when write operations are low or unexpected toconflict with concurrent read operations and when query results need to beconsistent.

Example: A currency conversion or lookuptable that is queried more often then it is modified and only the newest valuesare kept,

5 CursorStability

Cursor Stability isolation extends readcommitted and is the default isolation level of many relational databases. In thisisolation level, a pessimistic transaction must indicate which records it willmodify when reading them, if done in a separate statement. This is often doneusing 'FOR UPDATE' keywords appended to the end of a 'SELECT' query. In thiscase, other conflicting read or write pessimistic transactions will be blocked untilthe transaction is finished. An optimistic transaction tracks the versionnumber of all modified records/entities to be verified when committed. This isthe most popular optimistic isolation level and is provided by all majorobject-relational mapping libraries. In the Java Persistence API, this levelcan closely be achieved using FLUSH_ON_COMMIT (although queries may not reflectlocal changes), and if a conflict is detected an OptimisticLockException isthrown. This isolation can also be used with the HTTP headers If-Match orIf-Unmodified-Since that compare a previous resource's version or time-stampbefore updating. This level of isolation is best used for entities that aremodified based on external information (not read from the database) and changesmust not overwrite each other.

Example: A shared company directory or a wiki

6 Repeatable Read

Repeatable Read isolation extends cursor stability andguarantees that any data read within the transaction will not be modified orremoved during the transaction. A pessimistic transaction will acquire readlocks on all records and block other transactions from modifying them. Anoptimistic transaction will track all records or entities and verify they havenot been modified when committed. This level of isolation is best used whenentity states can affect other entities and transactions are made up of readand write operations.

Example:An order-tracking database, where values are read from one entity and used tocompute values for other entities.

7 Snapshot Isolation

Snapshot isolation extends snapshot reads and repeatable read and guarantees that all read operations made in a transaction will see aconsistent snapshot of the database. Any read operation performed in atransaction will have the same result regardless of whether it was performedearlier or later in the transaction. This differs from repeatable readisolation because it prevents phantom reads (range query results changing).This level is supported by many relational databases in the form of multi-versionconcurrency control (maybe called SERIALIZABLE), which is pessimisticallyimplemented using a combination of locks and conflict detection. In this level,transactions must be prepared to be rolled back due to conflicts from either apessimistic mechanism or an optimistic mechanism. A pessimistic mechanism willtry to reduce the chances of a conflict by locking resources, but must mergechanges when transactions are committed. An optimistic mechanism may also use amulti-version concurrency control, but would not block other transactions fromengaging in potentially conflicting operations, instead it would roll backtransactions that were found to conflict. This level of isolation is best usedfor transactions that read and modify multiple records.

Example: A workflow system, with rules basedon the state of the system.

8 Serializability

Serializability is an extension of snapshotisolation that specifies all transactions must occur as if they had executedserially, one after the other. A pessimistic mechanism acquires range locks forall evaluated queries, preventing write operations from affecting theseresults. An optimistic mechanism tracks all evaluated queries and either uses abackwards validation scheme or a forwards validation scheme at the end of thetransaction to detect if any concurrent write operations affect concurrent readoperations, and if so, rolls back all but one of the conflicting transactions.In this isolation level, the apparent state of the system by any committedtransaction will not have changed. This level of isolation is used fortransactions that require complete data consistency.

Example: An accounting system that performsrange queries to compute new values.

Summary

Below is a summary of the isolation levels outlined in this article, tohelp you find the level that is most appropriate for your application.

Types of possible collisions between transactions in different isolationlevels:

 

Dirty Writes

Dirty Reads

Mixed states

Inconsistent reads

Overwrites

Non-repeatable

Phantom Reads

Inconsistency

Read Uncommitted

Not permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Read Committed

Not permitted

Not permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Monotonic View

Not permitted

Not permitted

Not permitted

Permitted

Permitted

Permitted

Permitted

Permitted

Snapshot Reads

Not permitted

Not permitted

Not permitted

Not permitted

Permitted

Permitted

Permitted

Permitted

Cursor Stability

Not permitted

Not permitted

Permitted

Permitted

Not permitted

Permitted

Permitted

Permitted

Repeatable Reads

Not permitted

Not permitted

Permitted

Permitted

Not permitted

Not permitted

Permitted

Permitted

Snapshot Isolation

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Permitted

Serializability

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Not permitted

Optimistic requirements for different isolation levels:

 

Cache

Data Sync

Optimistic Conflict Scheme

Suggested Operations

Example

Read Uncommitted

Cache permitted

Sporadic

Detect dirty writes

No concurrent read and write

Archive

Read Committed

Cache permitted

Sporadic

No conflict detection

Monotonic read/write

Web Forum

Monotonic View

Must be validated

Periodic

No conflict detection

Combined reads

User preferences

Snapshot Reads

Must be validated

Periodic

Compare modifications to reads

Consistent reads

Lookup table

Cursor Stability

Cache permitted

Sporadic

Compare modified entity versions

CRUD services

Directory

Repeatable Reads

Cache permitted

Sporadic

Compare read entity versions

Read/write entities

Order tracking

Snapshot Isolation

Must be validated

Periodic

Compare read entity versions

Synchronized entities

Work-flow

Serializability

Must be validated

Full Sync

Compare queries with modifications

Complete data consistency

Accounting

Data consistency is vital in database applications -- it allows developersto make sense of data within a concurrent environment. Although strongconsistency levels such as serializability provide a simple programming model,they can cause excess overhead, blocked operations, or transaction rollbacksand may be unnecessary for many applications. Being aware of other, potentiallymore appropriate isolation levels can help ensure that developers and systemarchitects understand the data consistency needs, while balancing performancetradeoffs.

 

原创粉丝点击