SlideShare a Scribd company logo
1 of 62
Slides & scripts: BrentOzar.com/sql/deadlocks/
Deadlocks
Let’s do one, understand it, and fix it.
Slides & scripts: BrentOzar.com/sql/deadlocks/
99-05: dev, architect, DBA
05-08: DBA, VM, SAN admin
08-10: MCM, Quest Software
Since: consulting DBA
www.BrentOzar.com
Help@BrentOzar.com
Slides & scripts: BrentOzar.com/sql/deadlocks/
Session agenda
Basics:
• 3 concurrency issues
• 3 ways to fix ‘em all
• 1 “fix” that makes things worse: NOLOCK
One real fix: work on tables in a consistent order
• Demo: unrealistic query
• Demo: realistic query
Using sp_BlitzLock to find the queries you need to
fix
Slides & scripts: BrentOzar.com/sql/deadlocks/
Concurrency challenges
Locking: Lefty takes out a lock.
Blocking: Righty wants a lock, but Lefty already has it.
SQL Server will let Righty wait for forever,
and the symptom is LCK* waits.
Deadlocks:
Lefty has locks, then wants some held by Righty.
Righty has locks, then wants some held by Lefty.
SQL Server solves this one by killing somebody,
and the symptom is dead bodies everywhere.
Slides & scripts: BrentOzar.com/sql/deadlocks/
3 ways to fix concurrency issues
1. Have enough indexes to make your queries fast,
but not so many that they slow down DUIs,
making them hold more locks for longer times.
(I cover this in Mastering Index Tuning.)
2. Tune your transactional code.
(This module focuses on this topic.)
3. Use the right isolation level for your app’s needs.
(I cover this in Mastering Server Tuning.)
Slides & scripts: BrentOzar.com/sql/deadlocks/
1 way doesn’t fix it: dirty reads
WITH (NOLOCK):
• Ignores other people’s row locks
• Still takes out schema stability locks
(and honors other peoples’ schema locks)
SET TRANSACTION ISOLATION LEVEL READ
UNCOMMITTED
• Like putting WITH (NOLOCK) on every table
Slides & scripts: BrentOzar.com/sql/deadlocks/
Because with dirty reads…
1. You can see data that was never committed
2. You can see rows twice
3. You can skip rows altogether
4. Your query can fail with an error:
Could not continue scan with NOLOCK due to data movement
Slides & scripts: BrentOzar.com/sql/deadlocks/
Demoing it
If I count the number of Alexes,
and I use NOLOCK,
I get the same result every time.
As long as nothing is happening.
Slides & scripts: BrentOzar.com/sql/deadlocks/
But while it runs…
Let’s update everyone who ISN’T Alex:
Note that I am NOT inserting or deleting rows.
Just updating the non-Alexes.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Run them both at the same
time:
Slides & scripts: BrentOzar.com/sql/deadlocks/
That’s NOLOCK.
And that’s not a bug.
That’s what it’s
designed to do.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Sometimes, these are OK.
1. You can see data that was never committed
2. You can see rows twice
3. You can skip rows altogether
4. Your query can fail with an error:
Could not continue scan with NOLOCK due to data movement
But when they’re not OK, we have some fixes to
do.
Slides & scripts: BrentOzar.com/sql/deadlocks/
3 ways to fix concurrency issues
1. Have enough indexes to make your queries fast,
but not so many that they slow down DUIs,
making them hold more locks for longer times.
(I cover this in Mastering Index Tuning.)
2. Tune your transactional code.
(This module explores this topic.)
3. Use the right isolation level for your app’s needs.
(I cover this in Mastering Server Tuning.)
Slides & scripts: BrentOzar.com/sql/deadlocks/
Session agenda
Basics:
• 3 concurrency issues
• 3 ways to fix ‘em all
• 1 “fix” that makes things worse: NOLOCK
One real fix: work on tables in a consistent order
• Demo: unrealistic query
• Demo: realistic query
Using sp_BlitzLock to find the queries you need to
fix
Slides & scripts: BrentOzar.com/sql/deadlocks/
Start SSMS with two windows.
Use Lefty.sql and Righty.sql from your resources.
In Lefty, create & populate the tables.
Slides & scripts: BrentOzar.com/sql/deadlocks/
In Lefty, start a transaction.
Begin tran, update dbo.Lefty, but don’t commit.
The left window is now locking dbo.Lefty.
Slides & scripts: BrentOzar.com/sql/deadlocks/
In Righty, start another.
Begin tran, update dbo.Righty, but don’t commit.
The right window is now locking dbo.Righty.
Slides & scripts: BrentOzar.com/sql/deadlocks/
The situation so far:
Left window has:
• dbo.Lefty
exclusive lock
Right window
has:
• dbo.Righty
exclusive lock
Slides & scripts: BrentOzar.com/sql/deadlocks/
In Lefty, update dbo.Righty.
The update starts running, but is blocked, and sits
there waiting for dbo.Righty to commit or roll back.
Slides & scripts: BrentOzar.com/sql/deadlocks/
The situation so far:
Left window has:
• dbo.Lefty
exclusive lock
• Wants a lock
on dbo.Righty,
but can’t get it
(yet)
Right window
has:
• dbo.Righty
exclusive lock
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
The situation so far:
Left window has:
• dbo.Lefty
exclusive lock
• Wants a lock
on dbo.Righty,
but can’t get it
(yet)
Right window
has:
• dbo.Righty
exclusive lock
Slides & scripts: BrentOzar.com/sql/deadlocks/
But let’s do something terrible.
In the right hand window, don’t commit or roll
back: instead, try to get a lock on dbo.Lefty.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Things are going to happen fast.
I’ll describe what’s going to happen before I hit F5:
• The right window will want to run, but…
Slides & scripts: BrentOzar.com/sql/deadlocks/
The situation will become:
Left window has:
• dbo.Lefty
exclusive lock
• Wants a lock on
dbo.Righty, but
can’t get it
(ever)
Right window has:
• dbo.Righty
exclusive lock
• Wants a lock on
dbo.Lefty, but
can’t get it
(ever)
Slides & scripts: BrentOzar.com/sql/deadlocks/
Things are going to happen fast.
I’ll describe what’s going to happen before I hit F5:
• The right window will want to run, but…
• Neither side will be able to make progress
• SQL Server’s deadlock monitor wakes up every 5
seconds, and when he does, he’ll see the
problem
• He’ll pick the query that’s the easiest to roll back,
and kill it
Slides & scripts: BrentOzar.com/sql/deadlocks/
I hit F5 in the right window,
and…
Within 5 seconds, SQL Server kills one.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
The root cause: bad ordering
Left window has:
• dbo.Lefty
exclusive lock
• Wants a lock on
dbo.Righty, but
can’t get it
(ever)
Right window has:
• dbo.Righty
exclusive lock
• Wants a lock on
dbo.Lefty, but
can’t get it
(ever)
Slides & scripts: BrentOzar.com/sql/deadlocks/
The fix: better ordering
If we work on tables in a consistent order:
• Always update dbo.Lefty first,
then update dbo.Righty
Or:
• Always update dbo.Righty first,
then update dbo.Lefty
We’ll be fine either way, as long as we’re
consistent.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Trying it:
I set up both windows to work on dbo.Lefty first.
I hit execute in the left window first, then the right:
Slides & scripts: BrentOzar.com/sql/deadlocks/
This sounds bad at first.
We have a new problem: blocking.
The right window can’t make progress.
But that’s actually good:
he can’t grab a lock that would block others.
The left side is able to keep right on going.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Continuing in the left window…
Slides & scripts: BrentOzar.com/sql/deadlocks/
Continuing in the left window…
When the left finally commits, the right is free to
start making progress, and can’t be blocked by the
left.
Slides & scripts: BrentOzar.com/sql/deadlocks/
The moral of the story
Work in tables in a consistent order, like:
• Always parents, then children
• Or always children, then parents
Which one you choose is less important
than being ruthlessly consistent.
If even one query works out of order,
there will be deadlocks.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Session agenda
Basics:
• 3 concurrency issues
• 3 ways to fix ‘em all
• 1 “fix” that makes things worse: NOLOCK
One real fix: work on tables in a consistent order
• Demo: unrealistic query
• Demo: realistic query
Using sp_BlitzLock to find the queries you need to
fix
We are here.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Real-world scenario
At Stack Overflow, you can up/downvote questions.
Voting
Slides & scripts: BrentOzar.com/sql/deadlocks/
What happens when you vote
Update your Users.LastAccessDate column to show
that you’ve been accessing the site
Insert a row in the Votes table
Add one point to the question’s score
(by updating its row in Posts (Q&A))
Add one point to the question-asker’s reputation
(by updating their row in Users, set Reputation +
1)
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
How it goes wrong
What if these two happen at the exact same time:
User A upvotes a question
owned by UserB
UserB upvotes a question
owned by UserA
Slides & scripts: BrentOzar.com/sql/deadlocks/
Just for this demo
Slides & scripts: BrentOzar.com/sql/deadlocks/
Start these two at the same time
And one will always lose. (Which one? Tough to
tell.)
Slides & scripts: BrentOzar.com/sql/deadlocks/
First, we lock our own row
Last, we try to lock someone
else’s
Slides & scripts: BrentOzar.com/sql/deadlocks/
Will ordering help?
What if we move all the user updates to the top?
Just for this demo
Slides & scripts: BrentOzar.com/sql/deadlocks/
Still screwed.
It’s not enough to lock tables in the same order:
we also need to touch them as few times as
practical.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Could we update both users at once?
How might we solve this problem?
Slides & scripts: BrentOzar.com/sql/deadlocks/
Ways to fix it
“Just remove the waitfor” = “make it all faster”
• Get faster hardware
• Tune indexes on the underlying tables
• Don’t hold transactions open on the app side
Try merging both Users updates into a single query
(where it’s the Voter, OR it’s the question-owner)
Do the LastAccessDate update outside of the
transaction (does it really matter?)
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
It works though! No deadlocks.
Well, kinda: there’s a catch. Notice the runtimes.
Slides & scripts: BrentOzar.com/sql/deadlocks/
The longer it takes before others can start
work.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Another
approach
Do we really need
your Last Access
Date to be part of
the transaction?
Slides & scripts: BrentOzar.com/sql/deadlocks/
Run ‘em both at the same time…
No deadlocks, AND they both finish in 10 seconds!
Slides & scripts: BrentOzar.com/sql/deadlocks/
The more you fix, the faster it
goes
“Just remove the waitfor” = “make it all faster”
• Get faster hardware
• Tune indexes on the underlying tables
• Don’t hold transactions open on the app side
Try merging both Users updates into a single query
(where it’s the Voter, OR it’s the question-owner)
Do the LastAccessDate update outside of the
transaction (does it really matter?)
Slides & scripts: BrentOzar.com/sql/deadlocks/
Session agenda
Basics:
• 3 concurrency issues
• 3 ways to fix ‘em all
• 1 “fix” that makes things worse: NOLOCK
One real fix: work on tables in a consistent order
• Demo: unrealistic query
• Demo: realistic query
Using sp_BlitzLock to find the queries you need to
fix
Slides & scripts: BrentOzar.com/sql/deadlocks/
sp_BlitzLock helps you spot ‘em.
Thanks to SQL 2012 or newer, the default system
health Extended Events session, and Erik Darling:
Slides & scripts: BrentOzar.com/sql/deadlocks/
Top result set: list of deadlocks
Scroll to the far right, and you also get the
deadlock graph. Save it as an XDL file, then re-
open it in SSMS or in SentryOne Plan Explorer.
Slides & scripts: BrentOzar.com/sql/deadlocks/
Bottom results: analytics
This is what really helps me get to the bottom of it:
Slides & scripts: BrentOzar.com/sql/deadlocks/
Bottom results: analytics
Tables & indexes: use my D.E.A.T.H. Method on
‘em
Queries: hit tables in a consistent order, tune txns
Slides & scripts: BrentOzar.com/sql/deadlocks/
Slides & scripts: BrentOzar.com/sql/deadlocks/
3 ways to fix concurrency issues
1. Have enough indexes to make your queries fast,
but not so many that they slow down DUIs,
making them hold more locks for longer times.
(I cover this in Mastering Index Tuning.)
2. Tune your transactional code.
(This module focuses on this topic.)
3. Use the right isolation level for your app’s needs.
(I cover this in Mastering Server Tuning.)

More Related Content

What's hot

Building REST APIs using gRPC and Go
Building REST APIs using gRPC and GoBuilding REST APIs using gRPC and Go
Building REST APIs using gRPC and GoAlvaro Viebrantz
 
Productividad con oracle sql developer y data modeler
Productividad con oracle sql developer y data modelerProductividad con oracle sql developer y data modeler
Productividad con oracle sql developer y data modelerJesús Canales Guando
 
Spark Summit EU talk by Dean Wampler
Spark Summit EU talk by Dean WamplerSpark Summit EU talk by Dean Wampler
Spark Summit EU talk by Dean WamplerSpark Summit
 
Serverless Clojure and ML prototyping: an experience report
Serverless Clojure and ML prototyping: an experience reportServerless Clojure and ML prototyping: an experience report
Serverless Clojure and ML prototyping: an experience reportMetosin Oy
 
Working With a Real-World Dataset in Neo4j: Import and Modeling
Working With a Real-World Dataset in Neo4j: Import and ModelingWorking With a Real-World Dataset in Neo4j: Import and Modeling
Working With a Real-World Dataset in Neo4j: Import and ModelingNeo4j
 
The Graph Database Universe: Neo4j Overview
The Graph Database Universe: Neo4j OverviewThe Graph Database Universe: Neo4j Overview
The Graph Database Universe: Neo4j OverviewNeo4j
 
MongoDB Breakfast Milan - Mainframe Offloading Strategies
MongoDB Breakfast Milan -  Mainframe Offloading StrategiesMongoDB Breakfast Milan -  Mainframe Offloading Strategies
MongoDB Breakfast Milan - Mainframe Offloading StrategiesMongoDB
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your dataChristian Posta
 
Oracle To Sql Server migration process
Oracle To Sql Server migration processOracle To Sql Server migration process
Oracle To Sql Server migration processharirk1986
 
Modern Data Warehousing with Amazon Redshift
Modern Data Warehousing with Amazon RedshiftModern Data Warehousing with Amazon Redshift
Modern Data Warehousing with Amazon RedshiftAmazon Web Services
 
Automated Metadata Management in Data Lake – A CI/CD Driven Approach
Automated Metadata Management in Data Lake – A CI/CD Driven ApproachAutomated Metadata Management in Data Lake – A CI/CD Driven Approach
Automated Metadata Management in Data Lake – A CI/CD Driven ApproachDatabricks
 
Intro to Neo4j - Nicole White
Intro to Neo4j - Nicole WhiteIntro to Neo4j - Nicole White
Intro to Neo4j - Nicole WhiteNeo4j
 
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02연구데이터 관리와 데이터 관리 계획서 (DMP) - part02
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02Suntae Kim
 
Simplifying Big Data Integration with Syncsort DMX and DMX-h
Simplifying Big Data Integration with Syncsort DMX and DMX-hSimplifying Big Data Integration with Syncsort DMX and DMX-h
Simplifying Big Data Integration with Syncsort DMX and DMX-hPrecisely
 
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...Simplilearn
 
Amundsen: From discovering to security data
Amundsen: From discovering to security dataAmundsen: From discovering to security data
Amundsen: From discovering to security datamarkgrover
 
MongoDB Administration 101
MongoDB Administration 101MongoDB Administration 101
MongoDB Administration 101MongoDB
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Dbchriskite
 

What's hot (20)

Building REST APIs using gRPC and Go
Building REST APIs using gRPC and GoBuilding REST APIs using gRPC and Go
Building REST APIs using gRPC and Go
 
Productividad con oracle sql developer y data modeler
Productividad con oracle sql developer y data modelerProductividad con oracle sql developer y data modeler
Productividad con oracle sql developer y data modeler
 
Spark Summit EU talk by Dean Wampler
Spark Summit EU talk by Dean WamplerSpark Summit EU talk by Dean Wampler
Spark Summit EU talk by Dean Wampler
 
Serverless Clojure and ML prototyping: an experience report
Serverless Clojure and ML prototyping: an experience reportServerless Clojure and ML prototyping: an experience report
Serverless Clojure and ML prototyping: an experience report
 
Working With a Real-World Dataset in Neo4j: Import and Modeling
Working With a Real-World Dataset in Neo4j: Import and ModelingWorking With a Real-World Dataset in Neo4j: Import and Modeling
Working With a Real-World Dataset in Neo4j: Import and Modeling
 
The Graph Database Universe: Neo4j Overview
The Graph Database Universe: Neo4j OverviewThe Graph Database Universe: Neo4j Overview
The Graph Database Universe: Neo4j Overview
 
MongoDB Breakfast Milan - Mainframe Offloading Strategies
MongoDB Breakfast Milan -  Mainframe Offloading StrategiesMongoDB Breakfast Milan -  Mainframe Offloading Strategies
MongoDB Breakfast Milan - Mainframe Offloading Strategies
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your data
 
Oracle To Sql Server migration process
Oracle To Sql Server migration processOracle To Sql Server migration process
Oracle To Sql Server migration process
 
Data Storage & Preservation
Data Storage & PreservationData Storage & Preservation
Data Storage & Preservation
 
Modern Data Warehousing with Amazon Redshift
Modern Data Warehousing with Amazon RedshiftModern Data Warehousing with Amazon Redshift
Modern Data Warehousing with Amazon Redshift
 
Automated Metadata Management in Data Lake – A CI/CD Driven Approach
Automated Metadata Management in Data Lake – A CI/CD Driven ApproachAutomated Metadata Management in Data Lake – A CI/CD Driven Approach
Automated Metadata Management in Data Lake – A CI/CD Driven Approach
 
Intro to Neo4j - Nicole White
Intro to Neo4j - Nicole WhiteIntro to Neo4j - Nicole White
Intro to Neo4j - Nicole White
 
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02연구데이터 관리와 데이터 관리 계획서 (DMP) - part02
연구데이터 관리와 데이터 관리 계획서 (DMP) - part02
 
Simplifying Big Data Integration with Syncsort DMX and DMX-h
Simplifying Big Data Integration with Syncsort DMX and DMX-hSimplifying Big Data Integration with Syncsort DMX and DMX-h
Simplifying Big Data Integration with Syncsort DMX and DMX-h
 
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
 
Amundsen: From discovering to security data
Amundsen: From discovering to security dataAmundsen: From discovering to security data
Amundsen: From discovering to security data
 
WebSphere Commerce v7 Data Load
WebSphere Commerce v7 Data LoadWebSphere Commerce v7 Data Load
WebSphere Commerce v7 Data Load
 
MongoDB Administration 101
MongoDB Administration 101MongoDB Administration 101
MongoDB Administration 101
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 

Similar to Deadlocks: Lets Do One, Understand It, and Fix It

Headaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingHeadaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingBrent Ozar
 
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016IXIASOFT
 
Geek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringGeek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringIDERA Software
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214David Rodenas
 
III - Better angularjs
III - Better angularjsIII - Better angularjs
III - Better angularjsWebF
 
CNIT 126 Ch 9: OllyDbg
CNIT 126 Ch 9: OllyDbgCNIT 126 Ch 9: OllyDbg
CNIT 126 Ch 9: OllyDbgSam Bowne
 
Ruby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksRuby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksinfovore
 
When is something overflowing
When is something overflowingWhen is something overflowing
When is something overflowingPeter Hlavaty
 
CONFidence 2015: when something overflowing... - Peter Hlavaty
CONFidence 2015: when something overflowing... - Peter HlavatyCONFidence 2015: when something overflowing... - Peter Hlavaty
CONFidence 2015: when something overflowing... - Peter HlavatyPROIDEA
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8kaashiv1
 
Toad tipstricksexpertinsight
Toad tipstricksexpertinsightToad tipstricksexpertinsight
Toad tipstricksexpertinsightRaj esh
 
Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Brent Ozar
 
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...Mumbai B.Sc.IT Study
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomAlex Blom
 

Similar to Deadlocks: Lets Do One, Understand It, and Fix It (20)

Headaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingHeadaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and Deadlocking
 
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
 
Unit testing hippo
Unit testing hippoUnit testing hippo
Unit testing hippo
 
Geek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringGeek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database Mirroring
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214
 
III - Better angularjs
III - Better angularjsIII - Better angularjs
III - Better angularjs
 
CNIT 126 Ch 9: OllyDbg
CNIT 126 Ch 9: OllyDbgCNIT 126 Ch 9: OllyDbg
CNIT 126 Ch 9: OllyDbg
 
Ruby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksRuby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracks
 
When is something overflowing
When is something overflowingWhen is something overflowing
When is something overflowing
 
CONFidence 2015: when something overflowing... - Peter Hlavaty
CONFidence 2015: when something overflowing... - Peter HlavatyCONFidence 2015: when something overflowing... - Peter Hlavaty
CONFidence 2015: when something overflowing... - Peter Hlavaty
 
9: OllyDbg
9: OllyDbg9: OllyDbg
9: OllyDbg
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8
 
Ebook8
Ebook8Ebook8
Ebook8
 
Toad tipstricksexpertinsight
Toad tipstricksexpertinsightToad tipstricksexpertinsight
Toad tipstricksexpertinsight
 
Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!
 
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...
Data Warehousing (Practical Questions Paper) [CBSGS - 75:25 Pattern] {2015 Ma...
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
 
Lug
LugLug
Lug
 

More from Brent Ozar

Fundamentals of TempDB
Fundamentals of TempDBFundamentals of TempDB
Fundamentals of TempDBBrent Ozar
 
Fundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsFundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsBrent Ozar
 
Top 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerTop 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerBrent Ozar
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarBrent Ozar
 
How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineBrent Ozar
 
SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?Brent Ozar
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresBrent Ozar
 
"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server ProblemsBrent Ozar
 
Columnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalColumnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalBrent Ozar
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career InternalsBrent Ozar
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineBrent Ozar
 
Building a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBuilding a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBrent Ozar
 
How to Make SQL Server Go Faster
How to Make SQL Server Go FasterHow to Make SQL Server Go Faster
How to Make SQL Server Go FasterBrent Ozar
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career InternalsBrent Ozar
 
What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015Brent Ozar
 

More from Brent Ozar (15)

Fundamentals of TempDB
Fundamentals of TempDBFundamentals of TempDB
Fundamentals of TempDB
 
Fundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsFundamentals of Columnstore - Introductions
Fundamentals of Columnstore - Introductions
 
Top 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerTop 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL Server
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent Ozar
 
How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server Engine
 
SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
 
"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems
 
Columnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalColumnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil Agarwal
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career Internals
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the Engine
 
Building a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBuilding a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura Relativity
 
How to Make SQL Server Go Faster
How to Make SQL Server Go FasterHow to Make SQL Server Go Faster
How to Make SQL Server Go Faster
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career Internals
 
What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Deadlocks: Lets Do One, Understand It, and Fix It

  • 1. Slides & scripts: BrentOzar.com/sql/deadlocks/ Deadlocks Let’s do one, understand it, and fix it.
  • 2. Slides & scripts: BrentOzar.com/sql/deadlocks/ 99-05: dev, architect, DBA 05-08: DBA, VM, SAN admin 08-10: MCM, Quest Software Since: consulting DBA www.BrentOzar.com Help@BrentOzar.com
  • 3. Slides & scripts: BrentOzar.com/sql/deadlocks/ Session agenda Basics: • 3 concurrency issues • 3 ways to fix ‘em all • 1 “fix” that makes things worse: NOLOCK One real fix: work on tables in a consistent order • Demo: unrealistic query • Demo: realistic query Using sp_BlitzLock to find the queries you need to fix
  • 4. Slides & scripts: BrentOzar.com/sql/deadlocks/ Concurrency challenges Locking: Lefty takes out a lock. Blocking: Righty wants a lock, but Lefty already has it. SQL Server will let Righty wait for forever, and the symptom is LCK* waits. Deadlocks: Lefty has locks, then wants some held by Righty. Righty has locks, then wants some held by Lefty. SQL Server solves this one by killing somebody, and the symptom is dead bodies everywhere.
  • 5. Slides & scripts: BrentOzar.com/sql/deadlocks/ 3 ways to fix concurrency issues 1. Have enough indexes to make your queries fast, but not so many that they slow down DUIs, making them hold more locks for longer times. (I cover this in Mastering Index Tuning.) 2. Tune your transactional code. (This module focuses on this topic.) 3. Use the right isolation level for your app’s needs. (I cover this in Mastering Server Tuning.)
  • 6. Slides & scripts: BrentOzar.com/sql/deadlocks/ 1 way doesn’t fix it: dirty reads WITH (NOLOCK): • Ignores other people’s row locks • Still takes out schema stability locks (and honors other peoples’ schema locks) SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED • Like putting WITH (NOLOCK) on every table
  • 7. Slides & scripts: BrentOzar.com/sql/deadlocks/ Because with dirty reads… 1. You can see data that was never committed 2. You can see rows twice 3. You can skip rows altogether 4. Your query can fail with an error: Could not continue scan with NOLOCK due to data movement
  • 8. Slides & scripts: BrentOzar.com/sql/deadlocks/ Demoing it If I count the number of Alexes, and I use NOLOCK, I get the same result every time. As long as nothing is happening.
  • 9. Slides & scripts: BrentOzar.com/sql/deadlocks/ But while it runs… Let’s update everyone who ISN’T Alex: Note that I am NOT inserting or deleting rows. Just updating the non-Alexes.
  • 10. Slides & scripts: BrentOzar.com/sql/deadlocks/ Run them both at the same time:
  • 11. Slides & scripts: BrentOzar.com/sql/deadlocks/ That’s NOLOCK. And that’s not a bug. That’s what it’s designed to do.
  • 12. Slides & scripts: BrentOzar.com/sql/deadlocks/ Sometimes, these are OK. 1. You can see data that was never committed 2. You can see rows twice 3. You can skip rows altogether 4. Your query can fail with an error: Could not continue scan with NOLOCK due to data movement But when they’re not OK, we have some fixes to do.
  • 13. Slides & scripts: BrentOzar.com/sql/deadlocks/ 3 ways to fix concurrency issues 1. Have enough indexes to make your queries fast, but not so many that they slow down DUIs, making them hold more locks for longer times. (I cover this in Mastering Index Tuning.) 2. Tune your transactional code. (This module explores this topic.) 3. Use the right isolation level for your app’s needs. (I cover this in Mastering Server Tuning.)
  • 14. Slides & scripts: BrentOzar.com/sql/deadlocks/ Session agenda Basics: • 3 concurrency issues • 3 ways to fix ‘em all • 1 “fix” that makes things worse: NOLOCK One real fix: work on tables in a consistent order • Demo: unrealistic query • Demo: realistic query Using sp_BlitzLock to find the queries you need to fix
  • 15. Slides & scripts: BrentOzar.com/sql/deadlocks/ Start SSMS with two windows. Use Lefty.sql and Righty.sql from your resources. In Lefty, create & populate the tables.
  • 16. Slides & scripts: BrentOzar.com/sql/deadlocks/ In Lefty, start a transaction. Begin tran, update dbo.Lefty, but don’t commit. The left window is now locking dbo.Lefty.
  • 17. Slides & scripts: BrentOzar.com/sql/deadlocks/ In Righty, start another. Begin tran, update dbo.Righty, but don’t commit. The right window is now locking dbo.Righty.
  • 18. Slides & scripts: BrentOzar.com/sql/deadlocks/ The situation so far: Left window has: • dbo.Lefty exclusive lock Right window has: • dbo.Righty exclusive lock
  • 19. Slides & scripts: BrentOzar.com/sql/deadlocks/ In Lefty, update dbo.Righty. The update starts running, but is blocked, and sits there waiting for dbo.Righty to commit or roll back.
  • 20. Slides & scripts: BrentOzar.com/sql/deadlocks/ The situation so far: Left window has: • dbo.Lefty exclusive lock • Wants a lock on dbo.Righty, but can’t get it (yet) Right window has: • dbo.Righty exclusive lock
  • 21. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 22. Slides & scripts: BrentOzar.com/sql/deadlocks/ The situation so far: Left window has: • dbo.Lefty exclusive lock • Wants a lock on dbo.Righty, but can’t get it (yet) Right window has: • dbo.Righty exclusive lock
  • 23. Slides & scripts: BrentOzar.com/sql/deadlocks/ But let’s do something terrible. In the right hand window, don’t commit or roll back: instead, try to get a lock on dbo.Lefty.
  • 24. Slides & scripts: BrentOzar.com/sql/deadlocks/ Things are going to happen fast. I’ll describe what’s going to happen before I hit F5: • The right window will want to run, but…
  • 25. Slides & scripts: BrentOzar.com/sql/deadlocks/ The situation will become: Left window has: • dbo.Lefty exclusive lock • Wants a lock on dbo.Righty, but can’t get it (ever) Right window has: • dbo.Righty exclusive lock • Wants a lock on dbo.Lefty, but can’t get it (ever)
  • 26. Slides & scripts: BrentOzar.com/sql/deadlocks/ Things are going to happen fast. I’ll describe what’s going to happen before I hit F5: • The right window will want to run, but… • Neither side will be able to make progress • SQL Server’s deadlock monitor wakes up every 5 seconds, and when he does, he’ll see the problem • He’ll pick the query that’s the easiest to roll back, and kill it
  • 27. Slides & scripts: BrentOzar.com/sql/deadlocks/ I hit F5 in the right window, and… Within 5 seconds, SQL Server kills one.
  • 28. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 29. Slides & scripts: BrentOzar.com/sql/deadlocks/ The root cause: bad ordering Left window has: • dbo.Lefty exclusive lock • Wants a lock on dbo.Righty, but can’t get it (ever) Right window has: • dbo.Righty exclusive lock • Wants a lock on dbo.Lefty, but can’t get it (ever)
  • 30. Slides & scripts: BrentOzar.com/sql/deadlocks/ The fix: better ordering If we work on tables in a consistent order: • Always update dbo.Lefty first, then update dbo.Righty Or: • Always update dbo.Righty first, then update dbo.Lefty We’ll be fine either way, as long as we’re consistent.
  • 31. Slides & scripts: BrentOzar.com/sql/deadlocks/ Trying it: I set up both windows to work on dbo.Lefty first. I hit execute in the left window first, then the right:
  • 32. Slides & scripts: BrentOzar.com/sql/deadlocks/ This sounds bad at first. We have a new problem: blocking. The right window can’t make progress. But that’s actually good: he can’t grab a lock that would block others. The left side is able to keep right on going.
  • 33. Slides & scripts: BrentOzar.com/sql/deadlocks/ Continuing in the left window…
  • 34. Slides & scripts: BrentOzar.com/sql/deadlocks/ Continuing in the left window… When the left finally commits, the right is free to start making progress, and can’t be blocked by the left.
  • 35. Slides & scripts: BrentOzar.com/sql/deadlocks/ The moral of the story Work in tables in a consistent order, like: • Always parents, then children • Or always children, then parents Which one you choose is less important than being ruthlessly consistent. If even one query works out of order, there will be deadlocks.
  • 36. Slides & scripts: BrentOzar.com/sql/deadlocks/ Session agenda Basics: • 3 concurrency issues • 3 ways to fix ‘em all • 1 “fix” that makes things worse: NOLOCK One real fix: work on tables in a consistent order • Demo: unrealistic query • Demo: realistic query Using sp_BlitzLock to find the queries you need to fix We are here.
  • 37. Slides & scripts: BrentOzar.com/sql/deadlocks/ Real-world scenario At Stack Overflow, you can up/downvote questions. Voting
  • 38. Slides & scripts: BrentOzar.com/sql/deadlocks/ What happens when you vote Update your Users.LastAccessDate column to show that you’ve been accessing the site Insert a row in the Votes table Add one point to the question’s score (by updating its row in Posts (Q&A)) Add one point to the question-asker’s reputation (by updating their row in Users, set Reputation + 1)
  • 39. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 40. Slides & scripts: BrentOzar.com/sql/deadlocks/ How it goes wrong What if these two happen at the exact same time: User A upvotes a question owned by UserB UserB upvotes a question owned by UserA
  • 41. Slides & scripts: BrentOzar.com/sql/deadlocks/ Just for this demo
  • 42. Slides & scripts: BrentOzar.com/sql/deadlocks/ Start these two at the same time And one will always lose. (Which one? Tough to tell.)
  • 43. Slides & scripts: BrentOzar.com/sql/deadlocks/ First, we lock our own row Last, we try to lock someone else’s
  • 44. Slides & scripts: BrentOzar.com/sql/deadlocks/ Will ordering help? What if we move all the user updates to the top? Just for this demo
  • 45. Slides & scripts: BrentOzar.com/sql/deadlocks/ Still screwed. It’s not enough to lock tables in the same order: we also need to touch them as few times as practical.
  • 46. Slides & scripts: BrentOzar.com/sql/deadlocks/ Could we update both users at once? How might we solve this problem?
  • 47. Slides & scripts: BrentOzar.com/sql/deadlocks/ Ways to fix it “Just remove the waitfor” = “make it all faster” • Get faster hardware • Tune indexes on the underlying tables • Don’t hold transactions open on the app side Try merging both Users updates into a single query (where it’s the Voter, OR it’s the question-owner) Do the LastAccessDate update outside of the transaction (does it really matter?)
  • 48. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 49. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 50. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 51. Slides & scripts: BrentOzar.com/sql/deadlocks/ It works though! No deadlocks. Well, kinda: there’s a catch. Notice the runtimes.
  • 52. Slides & scripts: BrentOzar.com/sql/deadlocks/ The longer it takes before others can start work.
  • 53. Slides & scripts: BrentOzar.com/sql/deadlocks/ Another approach Do we really need your Last Access Date to be part of the transaction?
  • 54. Slides & scripts: BrentOzar.com/sql/deadlocks/ Run ‘em both at the same time… No deadlocks, AND they both finish in 10 seconds!
  • 55. Slides & scripts: BrentOzar.com/sql/deadlocks/ The more you fix, the faster it goes “Just remove the waitfor” = “make it all faster” • Get faster hardware • Tune indexes on the underlying tables • Don’t hold transactions open on the app side Try merging both Users updates into a single query (where it’s the Voter, OR it’s the question-owner) Do the LastAccessDate update outside of the transaction (does it really matter?)
  • 56. Slides & scripts: BrentOzar.com/sql/deadlocks/ Session agenda Basics: • 3 concurrency issues • 3 ways to fix ‘em all • 1 “fix” that makes things worse: NOLOCK One real fix: work on tables in a consistent order • Demo: unrealistic query • Demo: realistic query Using sp_BlitzLock to find the queries you need to fix
  • 57. Slides & scripts: BrentOzar.com/sql/deadlocks/ sp_BlitzLock helps you spot ‘em. Thanks to SQL 2012 or newer, the default system health Extended Events session, and Erik Darling:
  • 58. Slides & scripts: BrentOzar.com/sql/deadlocks/ Top result set: list of deadlocks Scroll to the far right, and you also get the deadlock graph. Save it as an XDL file, then re- open it in SSMS or in SentryOne Plan Explorer.
  • 59. Slides & scripts: BrentOzar.com/sql/deadlocks/ Bottom results: analytics This is what really helps me get to the bottom of it:
  • 60. Slides & scripts: BrentOzar.com/sql/deadlocks/ Bottom results: analytics Tables & indexes: use my D.E.A.T.H. Method on ‘em Queries: hit tables in a consistent order, tune txns
  • 61. Slides & scripts: BrentOzar.com/sql/deadlocks/
  • 62. Slides & scripts: BrentOzar.com/sql/deadlocks/ 3 ways to fix concurrency issues 1. Have enough indexes to make your queries fast, but not so many that they slow down DUIs, making them hold more locks for longer times. (I cover this in Mastering Index Tuning.) 2. Tune your transactional code. (This module focuses on this topic.) 3. Use the right isolation level for your app’s needs. (I cover this in Mastering Server Tuning.)