官术网_书友最值得收藏!

Understanding transaction isolation levels

Up until now, you have seen how to handle locking as well as some basic concurrency. In this section, you will learn transaction isolation. To me, this is one of the most neglected topics in modern software development. Only a small fraction of software developers are actually aware of this issue, which in turn leads to mind-boggling bugs.

Here is an example of what can happen:

Most users would actually expect the left transaction to always return 300 regardless of the second transaction. However, this is not true. By default, PostgreSQL runs in the READ COMMITTED transaction isolation mode. This means that every statement inside a transaction will get a new snapshot of the data, which will be constant throughout the query.

An SQL statement will operate on the same snapshot and will ignore changes by concurrent transactions while it is running.

If you want to avoid this, you can use TRANSACTION ISOLATION LEVEL REPEATABLE READ. In this transaction isolation level, a transaction will use the same snapshot through the entire transaction. Here is what will happen:

As just outlined, the first transaction will freeze its snapshot of the data and provide us with constant results throughout the entire transaction. This feature is especially important if you want to run reports. The first and the last page of a report should always be consistent and operate on the same data. Therefore, the repeatable read is key to consistent reports.

Note that isolation-related errors won't always pop up instantly. It can happen that trouble is noticed years after an application has been moved to production.

Repeatable read is not more expensive than read committed. There is no need to worry about performance penalties. For normal Online-Transaction-Processing ( OLTP), read committed has various advantages because changes can be seen much earlier and the odds of unexpected errors are usually lower.
主站蜘蛛池模板: 庆云县| 牡丹江市| 柳江县| 白水县| 宣城市| 辽阳市| 大关县| 靖江市| 马尔康县| 房产| 平舆县| 晋宁县| 乾安县| 津市市| 紫云| 河南省| 宜川县| 大城县| 南漳县| 博爱县| 高密市| 通许县| 清水县| 余庆县| 奉化市| 仪陇县| 凤山县| 三门峡市| 木兰县| 大洼县| 祁连县| 黄陵县| 德州市| 偏关县| 霍山县| 老河口市| 岱山县| 宁蒗| 绍兴市| 郎溪县| 泸水县|