当前位置: 首页 > 编程日记 > 正文

SQL Server Lock Escalation - 锁升级

Articles

  1. Locking in Microsoft SQL Server (Part 12 – Lock Escalation)
  2. http://dba.stackexchange.com/questions/12864/what-is-lock-escalation
  3. 2008 R2 Lock Escalation (Database Engine)

---Forward from Locking in Microsoft SQL Server (Part 12 – Lock Escalation)

Today I’d like us to talk about Lock Escalation in Microsoft SQL Server. We will cover:

  1. What is Lock Escalation?
  2. How Lock Escalations affects the system
  3. How to detect and troubleshoot Lock Escalations
  4. How to disable Lock Escalation

What is Lock Escalation?
All of us know that SQL Server uses row level locking. Let’s think about scenario when system modifies the row. Let’s create the small table and insert 1 row there and next check the locks we have. As usual every image is clickable.

As you can see there are 4 locks in the picture. shared (S) lock on the database – e.g. indication that database is in use. Intent exclusive (IX) lock on the table (OBJECT) – e.g. indication that one of the child objects (row/key in our case) has the exclusive lock. Intent exclusive (IX) lock on the page – e.g. same indication about child object (row/key) exclusive lock. And finally exclusive (X) lock on the key (row) we just inserted.

Now let’s insert another row in the different session (let’s keep the original Session 1 transaction uncommitted).

When we check the locks we will see that there are 8 locks – 4 per session. Both sessions ran just fine and don’t block each other. Everything works smooth – that great for the concurrency. So far so good. The problem though is that every lock takes some memory space – 128 bytes on 64 bit OS and 64 bytes on 32 bit OS). And memory is not the free resource. Let’s take a look at another example. I’m creating the table and populating it with 100,000 rows. Next, I’m disabling the lock escalation on the table (ignore it for now) and clear all system cache (don’t do it in production). Now let’s run the transaction in repeatable read isolation level and initiate the table scan.

Transaction is not committed and as we remember, in repeatable read isolation level SQL Server holds the locks till end of transaction. And now let’s see how many locks we have and how much memory does it use.


As you can see, now we have 102,780 lock structures that takes more than 20MB of RAM. And what if we have a table with billions of rows? This is the case when SQL Server starts to use the process that called “Lock Escalation” – in nutshell, instead of keeping locks on every row SQL Server tries to escalate them to the higher (object) level. Let’s see how it works.

First we need to commit transaction and clear the cache. Next, let’s switch lock escalation for Data table to AUTO level (I’ll explain it in details later) and see what will happen if we re-run the previous example.

As you can see – just 2 locks and only 1Mb of RAM is used (Memory clerk reserves some space). Now let’s look what locks do we have:

As you can see there is the same (S) lock on the database and now we have the new (S) shared lock on the table. No locks on page/row levels are kept. Obviously concurrency is not as good as it used to be. Now, for example, other sessions would not be able to update the data on the table – (S) lock is incompatible with (IX) on the table level. And obviously, if we have lock escalation due data modifications, the table would hold (X) exclusive lock – so other sessions would not be able to read the data either.

The next question is when escalation happens. Based on the documentation, SQL Server tries to escalate locks after it acquires at least 5,000 locks on the object. If escalation failed, it tries again after at least 1,250 new locks. The locks count on index/object level. So if Table has 2 indexes – A and B you have 4,500 locks on the index A and 4,500 locks on the index B, the locks would not be escalated. In real life, your mileage may vary – see example below – 5,999 locks does not trigger the escalation but 6,999 does.

How it affects the system?

Let’s re-iterate our first small example on the bigger scope. Let’s run the first session that updates 1,000 rows and check what locks are held.

As you see, we have intent exclusive (IX) locks on the object (table) and pages as well as various (X) locks on the rows. If we run another session that updates completely different rows everything would be just fine. (IX) locks on table are compatible. (X) locks are not acquired on the same rows.


Now let’s trigger lock escalation updating 11,000 rows.

As you can see – now the table has exclusive lock. So if you run the session 2 query from above again, it would be blocked because (X) lock on the table held by session 1 is incompatible with (IX) lock from the session 2.

When it affects us? There are 2 very specific situations

  1. Batch inserts/updates/deletes. You’re trying to import thousands of the rows (even from the stage table). If your import session is lucky enough to escalate the lock, neither of other sessions would be able to access the table till transaction is committed.
  2. Reporting – if you’re using repeatable read or serializable isolation levels in order to have data consistent in reports, you can have (S) lock escalated to the table level and as result, writers will be blocked until the end of transaction.

And of course, any excessive locking in the system can trigger it too.

How to detect and troubleshoot Lock Escalations

First of all, even if you have the lock escalations it does not mean that it’s bad. After all, this is expected behavior of SQL Server. The problem with the lock escalations though is that usually customers are complaining that some queries are running slow. In that particular case waits due lock escalations from other processes could be the issue. If we look at the example above when session 2 is blocked, and run the script (as the session 3) that analyzes sys.dm_tran_locks DMV, we’d see that:

I’m very heavy on the wait statistics as the first troubleshooting tool (perhaps heavier than I need to be  ). One of the signs of the issues with lock escalations would be the high percent of intent lock waits (LCK_M_I*) together with relatively small percent of regular non-intent lock waits. See the example below:

In case if the system has high percent of both intent and regular lock waits, I’d focus on the regular locks first (mainly check if queries are optimized). There is the good chance that intent locks are not related with lock escalations.

In addition to DMVs (sys.dm_tran_locks, sys.dm_os_waiting_tasks, sys.dm_os_wait_stats, etc), there are Lock Escalation Profiler event and Lock Escalation extended event you can capture. You can also monitor performance counters related with locking and create the baseline (always the great idea)

Last but not least, look at the queries. As I mentioned before in most part of the cases excessive locking happen because of non-optimized queries. And that, of course, can also trigger the lock escalations.

How to disable Lock Escalation

Yes, you can disable Lock Escalations. But it should be the last resort. Before you implement that, please consider other approaches

  1. For data consistency for reporting (repeatable read/serializable isolation levels) – switch to optimistic (read committed snapshot, snapshot) isolation levels
  2. For batch operations consider to either change batch size to be below 5,000 rows threshold or, if it’s impossible, you can play with lock compatibility. For example have another session that aquires IS lock on the table while importing data. Or use partition switch from the staging table if it’s possible

In case if neither option works for you please test the system before you disable the lock escalations. So:

For both SQL Server 2005 and 2008 you can alter the behavior on the instance level with Trace Flags 1211 and 1224. Trace flag 1211 disables the lock escalation in every cases. In case, if there are no available memory for the locks, the error 1204 (Unable to allocate lock resource) would be generated. Trace flag 1224 would disable lock escalations in case if there is no memory pressure in the system. Although locks would be escalated in case of the memory pressure.

With SQL Server 2005 trace flags are the only options you have. With SQL Server 2008 you can also specify escalation rules on the table level with ALTER TABLE SET LOCK_ESCALATION statement. There are 3 available modes:

    1. DISABLE – lock escalation on specific table is disabled
    2. TABLE (default) – default behavior of lock escalation – locks are escalated to the table level.
    3. AUTO – if table is partitioned, locks would be escalated to partition level when table is partitioned or on table level if table is not partitioned

转载于:https://www.cnblogs.com/tang88seng/p/6116833.html

相关文章:

Jzzhu and Chocolate

CF#257 div2 C:http://codeforces.com/contest/450/problem/C 题意:n*m的方格,每次可以横着或者纵向的切一刀,问切k之后,最小的最大是多少。 题解:比赛的时候没有想到怎么处理,看了别人的题解,才…

2-RACommand

RACommand RACCommand 就是命令 // RACCommand 就是命令// 0 创建一个CMD 穿进去一个用于构建RACSignal的Block参数来初始化RACommandRACCommand *cmd [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {// 此处是cmd 执行的输入源NSLog(…

玻璃上的编码喜悦(+ 10史诗般的Epigrams)

by Den McHenry丹麦克亨利(Den McHenry) 玻璃上的编码喜悦( 10史诗般的Epigrams) (Perlis on Coding Joy ( 10 Epic Epigrams)) Alan J. Perlis was the first recipient of the Turing Award. He’s possibly most remembered today for his Epigrams on Programming, which …

【Android】Activity生命周期(亲测)

测试手机:Nexus 5 系统:4.4 一、测试 测试代码: 1 package com.example.androidalarm;2 3 import android.app.Activity;4 import android.content.Context;5 import android.content.res.Configuration;6 import android.os.Bundle;7 impo…

angularjs 学习笔记 简单基础

angularjs是谷歌公司的一个项目,弥补了hml在构建方面的不足,通过指令(directive)来扩展html标签,可以使开发者使用html来声明动态内容。 angularjs主要用来开发单页应用(SPA)为主的项目。 angul…

3-RACSignal 常用方法

RACSingal的常用方法 一 基本使用 1map // 0 创建信号提供者// RACSubject,既能发送信号,又能订阅信号// 多用于代理,相当于OC里的delegate或者回调blockRACSubject *subject [RACSubject subject];// 1 绑定信号RACSignal *bindSignal …

javascript迭代_探索JavaScript迭代

javascript迭代by Festus K. Yangani由Festus K.Yangani 探索JavaScript迭代 (Exploring JavaScript Iteration) Loops allow programs to perform repetitive tasks, such as iterating through an array, while adhering to the DRY principle (Don’t Repeat Yourself). Th…

4 RACMulticastConnection 连接类

# RACMulticastConnection信号被多次订阅如果一个信号多次被订阅&#xff0c;那么代码块代码会多次被执行。objective-c// 创建信号RACSignal *sg1 [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {NSLog("网络请求…

ie6下常见的bug 调整页面兼容性

ie6下常见的bug 我们布局页面&#xff0c;首先符合标准&#xff0c;如何写一个页面的标准性&#xff1f; 但是ie6等浏览器本身就比较特殊&#xff0c;bug比较多&#xff0c;兵法云&#xff0c;知己知彼百战百胜。我们需要了解ie6的一些常见bug&#xff0c;这样&#xff0c;更好…

Cacti安装详细步骤

Cacti安装详细步骤 前提LNMP或LAMP架构已搭建完成 一、cacti概述 1. cacti是用php语言实现的一个软件&#xff0c;它的主要功能是用snmp服务获取数据&#xff0c;然后用rrdtool储存和更新数据&#xff0c;当用户需要查看数据的时候用rrdtool生成图表呈现给用户。因此&#xff0…

为什么使用单页应用_为什么我讨厌您的单页应用

为什么使用单页应用by Stefan Tilkov斯蒂芬蒂尔科夫(Stefan Tilkov) 为什么我讨厌您的单页应用 (Why I hate your Single Page App) Okay, now that I have your attention, let me say that I don’t really hate your single page app. I just find it highly annoying, unl…

marquee实现文字移动效果;js+div实现文字无缝移动效果

1.marquee实现文字移动&#xff1a; <marquee width"220px;" scrollamount"5" onmouseover"this.stop()" onmouseout"this.start()" ><p style"letter-spacing:2px;width: 1px;">欢迎您登录拜博医疗口腔集团内部…

URAL 1203 Scientific Conference(贪心 || DP)

Scientific Conference 之前一直在刷计算几何&#xff0c;邀请赛连计算几何的毛都买见着&#xff0c;暑假这一段时间就做多校&#xff0c;补多校的题目&#xff0c;刷一下一直薄弱的DP。多校如果有计算几何一定要干掉-。- 题意&#xff1a;给你N个报告会的开始时间跟结束时间&a…

5- RAC 集合 RACTuple RACSequence

RAC 集合 RACTuple RACSequence // 0 RACTuple 就是一个数组/*RACTuple 就是一个数组*/RACTuple *tp1 [RACTuple tupleWithObjects:"5",5,1, nil];RACTuple *tp2 [RACTuple tupleWithObjectsFromArray:["11","22","33"]];NSLog(&quo…

测试开发人员与开发人员_如何升级为开发人员

测试开发人员与开发人员by Will Hughes威尔休斯(Will Hughes) 如何升级为开发人员 (How to Level up as a Developer) Being a productive developer is something you can learn through experience, books, or trial and error. But, one of the best ways to become a prod…

ORA-00959: tablespace 'PSAPTEMP' does not exist

错误 : ORA-00959: tablespace PSAPTEMP does not exist 解决办法: CREATE TEMPORARY TABLESPACE PSAPTEMP TEMPFILE E:/Oracle/ORC/sapdata3/temp_1/temp.data1 SIZE 500M REUSE AUTOEXTEND ON NEXT 100M MAXSIZE unlimited EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;ALTER …

RAC rac_liftSelector

RAC rac_liftSelector 主要是用于线程的同步 - (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.// rac_liftSelector// 类似于dispatch_group 中的组// 多线程中的组 等所有的请求都完毕之后 去更新UIRAC…

随笔记一些莆田话

莆田话是闽南话和福州话混合的产物&#xff0c;当然也是古汉语保留至今的珍宝。很多莆田话的词语是有源可溯的。这里记录一些平常想到的又可能不为人知的词语。 莆田话——普通话解释 物件——东西 万代——很多 先生——老师&#xff08;先生白读时是老师的意思&#xff09;&a…

JavaScript库和API

by Adam Recvlohe通过亚当雷夫洛厄(Adam Recvlohe) API就像一盒巧克力 (APIs are like a box of chocolates) If you have written JavaScript for the DOM before, then you probably know how unwieldy it can get. I mean getElementById is seven syllables and 14 charac…

Hadoop 全分布模式 平台搭建

现将博客搬家至CSDN&#xff0c;博主改去CSDN玩玩~ 传送门&#xff1a;http://blog.csdn.net/sinat_28177969/article/details/54138163 Ps&#xff1a;主要答疑区在本帖最下方&#xff0c;疑点会标注出来。个人在配置过程中遇到的困难都会此列举。 实验介绍&#xff1a; 本次实…

iOS 使用fastlane自动化打包步骤

加粗样式### iOS 使用fastlane 自动打包步骤 &#xff01;参考 1 查看ruby版本信息 本机是否安装ruby ruby -v 2 安装xcode命令行工具 点击同意即可 xcode-select --install 3 安装fastlane 键入如下命令 sudo gem install fastlane -NV4 使用 1 打开终端 cd 进入到要打包的…

今天开始搞CentOS 7

今天开始搞CentOS 7,安装过程很顺利&#xff0c;界面相当友好。转载于:https://www.cnblogs.com/lixd/p/3868649.html

java ruby_Java,Ruby和Go,我的天哪!

java rubyFree Code Camp has focused 100% on full stack JavaScript since we started 17 months ago. We’ve taught JavaScript on the front end, JavaScript on the back end (thanks to the powerful Node.js framework) — and even JavaScript as a database querying…

http和https的区别 与 SSL/TLS协议运行机制的概述

http和https的区别 与 SSL/TLS协议运行机制的概述 参考1 1 http 是不使用的SSL/TSL的通信通道 窃听风险&#xff1a;第三方获取通信内容篡改风险&#xff1a;修改通信内容冒充风险&#xff1a;冒充他人身份参与通信 2 SSL/TSL 协议应运而生 客户端先向服务器端索要公钥&am…

Babel 相关资料

Babel online editorBabel Plugin Handbookbabeljs usage options转载于:https://www.cnblogs.com/skating/p/6125227.html

php中this,self,parent三个关键字

phpfunctionclass语言cthis,self,parent三个关键字从字面上比较好理解,分别是指这、自己、父亲。this是指向当前对象的指针(姑且用C里面的指针来看吧) self是指向当前类的指针 parent是指向父类的指针(我 们这里频繁使用指针来描述&#xff0c;是因为没有更好的语言来表达)根据…

大量数据转移_大量数据

大量数据转移by BerkeleyTrue由BerkeleyTrue 大量数据 (A Flood of Data) Free Code Camp’s data has been doubling each month, thanks to a flood of highly-active campers. This rising tide of data has exposed several weaknesses in our codebase.由于大量活跃的露营…

约瑟夫问题总结

题解在代码里~ #include <iostream> #include <iomanip> #include <list> using namespace std;int main() {int n, k, f[100];n 12; cin>>k;//链表做法,复杂度O(n*k)list <int> L;for(int i 1; i < n; i) f[i] i, L.push_back(i);list<…

iOS中的死循环

关于死循环 自己方法里面调用自己 在 vc 中的 viewDidLoad 方法中调用 [self viewDidLoad] 会导致程序崩溃。 原因是&#xff1a; 内存溢出。 函数调用栈&#xff0c; 函数调用的时候&#xff0c;sp 栈顶指针寄存器减对应的内存空间&#xff0c;栈内存开启对应的内存空间&…

机器学习算法基础知识

在我们了解了需要解决的机器学习问题的类型之后&#xff0c;我们可以开始考虑搜集来的数据的类型以及我们可以尝试的机器学习算法。在这个帖子里&#xff0c;我们会介绍一遍最流行的机器学习算法。通过浏览主要的算法来大致了解可以利用的方法是很有帮助的。 可利用的算法非常之…