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

Understanding transaction isolation levels

Up to now, you have seen how to handle locking as well as some basic concurrency. In this section, you will learn about 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 disgusting and 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 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 that, you can use TRANSACTION ISOLATION LEVEL REPEATABLE READ. In this transaction isolation level, a transaction will use the same snapshot through the entire transactions. 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, 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.
主站蜘蛛池模板: 榆林市| 富民县| 甘孜县| 昌黎县| 偏关县| 望江县| 石狮市| 勃利县| 赤峰市| 蒲城县| 大渡口区| 郓城县| 蒙城县| 塘沽区| 喀什市| 锡林郭勒盟| 阜南县| 通榆县| 汤原县| 久治县| 滁州市| 墨竹工卡县| 天柱县| 阜阳市| 册亨县| 阳原县| 冷水江市| 西乡县| 定襄县| 正镶白旗| 常熟市| 桐柏县| 西安市| 墨玉县| 嘉荫县| 南安市| 新野县| 新泰市| 成武县| 峡江县| 扶沟县|