SlideShare uma empresa Scribd logo
Specialties / Focus Areas / Passions:
• Performance Tuning & Troubleshooting
• Very Large Databases
• SQL Server Storage Engine
• High Availability
• Disaster Recovery
@sqlbob
bob@bobpusateri.com
heraflux.com
bobpusateri
• Concurrency Basics
• Isolation Levels
• In-Memory OLTP
• The ability for an operation to be broken up into multiple parts that can be
worked on independently
• The ability for multiple operations to access or modify a shared resource at
the same time
• More parts/users == more concurrency!
• Until a limiting factor appears…
• 5 Philosophers, bowls of spaghetti, and forks
• To eat, 2 forks are required
• Can pick up one fork at a time
• Once finished, both forks must
be returned to the table
• When not eating, a philosopher is thinking
https://en.wikipedia.org/wiki/File:An_illustration_of_the_dining_philosophers_problem.png
What if everyone picks up one fork?
https://en.wikipedia.org/wiki/File:An_illustration_of_the_dining_philosophers_problem.png
What if there’s a time limit?
What if someone never gets to eat?
$$
• Preventable Read Phenomena (ANSI-defined*)
 Dirty Reads
 Non-Repeatable Reads
 Phantom Reads
• Lost Updates
• Deadlocks
*ANSI specifies which behaviors to allow at each level, but not how to implement them
New Hampshire Dept. of Transportation
• Reading data that is not yet committed
• Changes are still “in flight” in another process
• You can read data multiple times or not at all
• “But it’s faster!”
• A.K.A. “Inconsistent Analysis”
• Multiple queries in the same transaction get differing results
• Cause: A different transaction commits changes between reads
• Only affects queries with a predicate (WHERE clause)
• Membership in the result set changes
• Multiple queries using the same predicate in the same transaction return
differing results https://flic.kr/p/4xqWnG
• “Update Conflict”
• One user’s update overwrites another user’s (simultaneous) update
• Appears as though the first update never happened
*SQL Server will not permit lost updates in any isolation level
• Two or more tasks block each other
• Each has a lock on a resource that the other task needs a lock on
• SQL Server detects and resolves these by choosing a victim
• Victim is rolled back, releasing all its locks
Process
A
Process
B
Resource 1 Resource 2
• Pessimistic Concurrency
 Conflicts are expected; locks taken to prevent them
 Readers block writers, writers block readers
 Only option available pre-2005
• Optimistic Concurrency
 Conflicts are considered possible, but unlikely
 Row versioning means less locking
• Concurrency Basics
• Isolation Levels
• In-Memory OLTP
• How isolated is my transaction from the effects of other transactions?
• Pessimistic Concurrency
 Read Committed
 Read Uncommitted
 Repeatable Read
 Serializable
• Optimistic Concurrency
 Snapshot
 Read Committed Snapshot
https://flic.kr/p/7LjDDL
• DBCC USEROPTIONS
• Can be set at the connection or query level
• Cannot be changed server-wide
• Default isolation level is READ COMMITTED
• To change at connection level:
• Change applies to all queries for the current connection
SET TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED
| READ COMMITTED | REPEATABLE READ | SNAPSHOT
| SERIALIZABLE } [;]
• To change at the query level, use table hints
• This is on a per-table basis
SELECT column
FROM table WITH (NOLOCK);
• Uses locking to prevent concurrency conflicts
• Classic locking model
 Readers don’t block readers
 Readers block writers
 Writers block readers
 Writers block writers
• PESSIMISTIC – we’re expecting problems
https://technet.microsoft.com/en-us/library/ms186396(v=sql.105).aspx
• Many different lock modes exist
• S = Shared
• X = eXclusive
Database
Table
Page
Row
Database
Table
Page
Row
[S] Shared Lock
[IS] Intent Shared Lock
[IS] Intent Shared Lock
[S] Shared Lock
Database
Table
Page
Row
[S] Shared Lock
[IX] Intent Exclusive Lock OR [IU] Intent Update Lock
[IX] Intent Exclusive Lock OR [IU] Intent Update Lock
[X] Exclusive Lock OR [U] Update Lock
• A.K.A “NOLOCK”
• May read rows multiple times
• May read rows zero times
• May return results that were NEVER true!
• Only applies to SELECT queries
 Ignored if used for data modification queries
 Could cause index corruption if you tried it (since fixed)
Dirty Nonrepeatable Phantom
Yes Yes Yes
(public domain) https://commons.wikimedia.org/wiki/File:8_ball_break_time_lapse.jpg
• “No locks are taken”
 WRONG!
 No shared locks are taken when reading data
 Other locks are still taken as normal
• “It makes this query faster”
 WRONG(ish)!
 Only true if query had a lot of blocking on SELECT statements
• Not a terrible setting, it exists for a reason
• BUT make sure you understand the risks and consequences
• The Default Default Isolation level
• Guarantee: Data that is read is guaranteed to be committed.
 No Dirty Reads
 No other guarantees
Dirty Nonrepeatable Phantom
No Yes Yes
• Ensure only committed data is read by locking
• (Locks only last as long as the read, released immediately after)
Rows already read.
Unlocked.
Row currently being
read. Locked.
Rows not yet read.
Unlocked.
SCAN
https://commons.wikimedia.org/wiki/File:Horizon202.jpg
https://commons.wikimedia.org/wiki/File:Horizon202sketch.png
• Unlocked rows can move at any time
Rows already read.
Unlocked.
Row currently being
read. Locked.
Rows not yet read.
Unlocked.
SCAN
• Unlocked rows can move at any time
Rows already read.
Unlocked.
Row currently being
read. Locked.
Rows not yet read.
Unlocked.
SCAN
• Builds on READ COMMITTED
• If a query is repeated within the same transaction, records read the first
time will not change
• Once a row is read, locks are held for length of the transaction
 Even rows that don’t qualify as results
• These locks will not stop additional rows from being added or included in
subsequent queries
Dirty Nonrepeatable Phantom
No No Yes
• Once read, rows are locked for duration of transaction
Rows already read.
Locked.
Row currently being
read. Locked.
Rows not yet read.
Unlocked.
SCAN
• On a second scan, new rows may enter
Rows already read.
Locked.
Row currently being
read. Locked.
Rows not yet read.
Unlocked.
SCAN
• Builds on REPEATABLE READ
• If a query is repeated within the same transaction, results will be the same
• No data seen previously will change; no new results will appear
• We now need to lock data that doesn’t exist!
Dirty Nonrepeatable Phantom
No No No
• Key-range locks
• Prevent phantom reads by defining a range that other transactions cannot
insert rows within
• If you select a row/range that doesn’t exist, that gets locked too
• Range Locks cover the entire range AND the first row outside it
Rows already read.
Locked.
Row currently being
read. Locked.
Rows not yet read.
Locked.
RANGE BEING SELECTED
First key outside
range. Locked.
• Uses row versioning to prevent concurrency conflicts
• Fewer locks are needed, so blocking is reduced
 Readers no longer block writers
 Writers no longer block readers
 Writers still block writers
• Uses a version store to do this
• Version Store lives in tempdb
• Remember, it’s OPTIMISTIC!
• Whenever a row is updated, previous version is stored in the version store
• New version of row has a pointer to the previous version
• Versions are stored for as long as operations exist that might need them
 All versions of rows modified by a transaction must be kept for as long as that
transaction is open
Current Version
(ID=6, Val=4) [T=n]
Previous Version
(ID=6, Val=7) [T=n-1]
Previous Version
(ID=6, Val=9) [T=n-5]
T=9
T=9
T=5 T=1
T=1
T=1T=5
T=4
T=9
T=9
T=5 T=1
T=1
T=1T=5
T=4
Current State
T=9
T=9
T=5 T=1
T=1
T=1T=5
T=4
State at T=7
T=9
T=9
T=5 T=1
T=1
T=1T=5
T=4
State at T=4
• Same guarantees as READ COMMITTED, just an optimistic implementation
• Statement-level snapshot isolation
 Queries will see the most recent committed values as of the beginning of that
statement (not the transaction)
Dirty Nonrepeatable Phantom
No Yes Yes
T=5 T=1
T=1
T=1T=5
T=4
T=5 T=1
T=1
T=1T=5
T=4
State at T=7
Statement
sees this:
T=9
T=9
T=5 T=1
T=1
T=1T=5
T=4
State at T=7
Statement
sees this:
Update Occurs!
Updater is not blocked.
Statement continues to read same version.
• When enabled, RCSI becomes the default isolation level for this database.
• Command will block if DB has other connections
 NO_WAIT will prevent blocking and just fail instead
 ROLLBACK_IMMEDIATE will rollback other transactions
Dirty Nonrepeatable Phantom
No Yes Yes
ALTER DATABASE <DB_NAME>
SET READ_COMMITTED_SNAPSHOT ON
[WITH (NO_WAIT | ROLLBACK IMMEDIATE)];
• Same guarantees as SERIALIZABLE, just an optimistic implementation
• Transaction-level snapshot isolation
 Queries will see the most recent committed values as of the beginning of that
transaction (the first data read in it)
Dirty Nonrepeatable Phantom
No No No
• First statement merely allows snapshot isolation
Dirty Nonrepeatable Phantom
No No No
ALTER DATABASE <DB_NAME>
SET ALLOW_SNAPSHOT_ISOLATION ON;
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
• Process 1 reads data in a transaction, does not commit
• Process 2 reads/updates same data,
• Process 1’s snapshot does not see Process 2’s update
• Process 1 tries to update, gets blocked
• As soon as Process 2 commits, Process 1 errors out
• This will raise error 3960 on process 1
https://flic.kr/p/4WHW81
• Everything I’ve covered here behaves the same in Azure SQL Database
• Exception: RCSI is enabled by default
• Concurrency Basics
• Isolation Levels
• In-Memory OLTP
• This could be its own presentation by itself
• Optimistic multi-version concurrency control
 No locks required at any time
 (Not even for data modification)
 No waiting because of blocking!
 No latches or spinlocks either
• Waits can still occur….
 (Waiting for log writes to disk following a transaction)
• No existing row is ever modified
 UPDATE creates a new version of a row
 There may be multiple versions in play at once
• Transactions needing to read are presented with the correct version
10 <inf> 1 Red
Begin
Time
End
Time Data Columns
10 <inf> 3 Green
Now at time 20, let’s:
Delete (1, Red)
Update (3, Green) to (3, Blue)
Insert (6, Pink)
10 20 1 Red
10 20 3 Green
20 <inf> 3 Blue
20 <inf> 6 Pink
Begin
Time
End
Time Data Columns
• Craig Freedman’s posts on SQL Server Isolation Levels
https://blogs.msdn.microsoft.com/craigfr/tag/isolation-levels/
• SQL Server Concurrency: Locking, Blocking, and Row Versioning
(Kalen Delaney, Simple Talk Publishing)
• Myths and Misconceptions about Transaction Isolation Levels
http://www.sqlpassion.at/archive/2014/01/21/myths-and-misconceptions-about-transaction-isolation-levels/
71
@sqlbob
bob@bobpusateri.com
bobpusateri.com
bobpusateri

Mais conteúdo relacionado

Mais procurados

Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)
Ben Evans
 
Growing an ecosystem on the JVM
Growing an ecosystem on the JVMGrowing an ecosystem on the JVM
Growing an ecosystem on the JVM
Iulian Dragos
 
Advance java session 15
Advance java session 15Advance java session 15
Advance java session 15
Smita B Kumar
 
Revision
RevisionRevision
Revision
David Sherlock
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
Smita B Kumar
 
Conditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean ReillyConditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean Reilly
JAXLondon2014
 
EhTrace -- RoP Hooks
EhTrace -- RoP HooksEhTrace -- RoP Hooks
EhTrace -- RoP Hooks
Shane Macaulay
 
10 Things you should know about Ruby
10 Things you should know about Ruby10 Things you should know about Ruby
10 Things you should know about Ruby
sikachu
 
Interactions complicate debugging
Interactions complicate debuggingInteractions complicate debugging
Interactions complicate debugging
Syed Zaid Irshad
 
Silt: Lessons Learned
Silt: Lessons LearnedSilt: Lessons Learned
Silt: Lessons Learned
ESUG
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
Haim Yadid
 
Aspect j introduction for non-programmers
Aspect j introduction for non-programmersAspect j introduction for non-programmers
Aspect j introduction for non-programmers
Tamas Rev
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
Boris Hristov
 
Java SE 7 New Features and Enhancements
Java SE 7 New Features and EnhancementsJava SE 7 New Features and Enhancements
Java SE 7 New Features and Enhancements
Fu Cheng
 
Introduction to Dependency Injection
Introduction to Dependency InjectionIntroduction to Dependency Injection
Introduction to Dependency Injection
SolTech, Inc.
 
MEFilicious Applications
MEFilicious ApplicationsMEFilicious Applications
MEFilicious Applications
buildmaster
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
Bill Buchan
 
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus HaganderPG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
pgdayrussia
 
Cetpa dotnet taining
Cetpa dotnet tainingCetpa dotnet taining
Cetpa dotnet taining
sharmamohan13989
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearch
Anton Udovychenko
 

Mais procurados (20)

Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)Perl On The JVM (London.pm Talk 2009-04)
Perl On The JVM (London.pm Talk 2009-04)
 
Growing an ecosystem on the JVM
Growing an ecosystem on the JVMGrowing an ecosystem on the JVM
Growing an ecosystem on the JVM
 
Advance java session 15
Advance java session 15Advance java session 15
Advance java session 15
 
Revision
RevisionRevision
Revision
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
 
Conditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean ReillyConditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean Reilly
 
EhTrace -- RoP Hooks
EhTrace -- RoP HooksEhTrace -- RoP Hooks
EhTrace -- RoP Hooks
 
10 Things you should know about Ruby
10 Things you should know about Ruby10 Things you should know about Ruby
10 Things you should know about Ruby
 
Interactions complicate debugging
Interactions complicate debuggingInteractions complicate debugging
Interactions complicate debugging
 
Silt: Lessons Learned
Silt: Lessons LearnedSilt: Lessons Learned
Silt: Lessons Learned
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
Aspect j introduction for non-programmers
Aspect j introduction for non-programmersAspect j introduction for non-programmers
Aspect j introduction for non-programmers
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
Java SE 7 New Features and Enhancements
Java SE 7 New Features and EnhancementsJava SE 7 New Features and Enhancements
Java SE 7 New Features and Enhancements
 
Introduction to Dependency Injection
Introduction to Dependency InjectionIntroduction to Dependency Injection
Introduction to Dependency Injection
 
MEFilicious Applications
MEFilicious ApplicationsMEFilicious Applications
MEFilicious Applications
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus HaganderPG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
PG Day'14 Russia, Secure PostgreSQL Deployment, Magnus Hagander
 
Cetpa dotnet taining
Cetpa dotnet tainingCetpa dotnet taining
Cetpa dotnet taining
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearch
 

Semelhante a Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASSDC User Group)

Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)
Antonios Chatzipavlis
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!
Boris Hristov
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
Boris Hristov
 
The nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levelsThe nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levels
Boris Hristov
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!
Boris Hristov
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
Boris Hristov
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
Jeremy Likness
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
Boris Hristov
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Ofer Zelig
 
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and LockingGeek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
IDERA Software
 
Store Beyond Glorp
Store Beyond GlorpStore Beyond Glorp
Store Beyond Glorp
ESUG
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
Boris Hristov
 
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
Bob Pusateri
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
Boris Hristov
 
A20 dfs2
A20 dfs2A20 dfs2
A20 dfs2
Pradeep Kumar
 
High scale flavour
High scale flavourHigh scale flavour
High scale flavour
Tomas Doran
 
Akka Actors
Akka ActorsAkka Actors
Akka Actors
Dylan Forciea
 
Automate Server Mastery by Stack Advisors - Automation Nation 2018
Automate Server Mastery by Stack Advisors - Automation Nation 2018Automate Server Mastery by Stack Advisors - Automation Nation 2018
Automate Server Mastery by Stack Advisors - Automation Nation 2018
Scott Wilson
 
Sql server update-lock
Sql server update-lockSql server update-lock
Sql server update-lock
Shah Faisal
 

Semelhante a Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASSDC User Group) (20)

Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
The nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levelsThe nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levels
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and LockingGeek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
 
Store Beyond Glorp
Store Beyond GlorpStore Beyond Glorp
Store Beyond Glorp
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
Select Stars: A DBA's Guide to Azure Cosmos DB (SQL Saturday Oslo 2018)
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
A20 dfs2
A20 dfs2A20 dfs2
A20 dfs2
 
High scale flavour
High scale flavourHigh scale flavour
High scale flavour
 
Akka Actors
Akka ActorsAkka Actors
Akka Actors
 
Automate Server Mastery by Stack Advisors - Automation Nation 2018
Automate Server Mastery by Stack Advisors - Automation Nation 2018Automate Server Mastery by Stack Advisors - Automation Nation 2018
Automate Server Mastery by Stack Advisors - Automation Nation 2018
 
Sql server update-lock
Sql server update-lockSql server update-lock
Sql server update-lock
 

Último

一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
bmucuha
 
Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
jitskeb
 
Palo Alto Cortex XDR presentation .......
Palo Alto Cortex XDR presentation .......Palo Alto Cortex XDR presentation .......
Palo Alto Cortex XDR presentation .......
Sachin Paul
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
v7oacc3l
 
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
sameer shah
 
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
z6osjkqvd
 
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
a9qfiubqu
 
Population Growth in Bataan: The effects of population growth around rural pl...
Population Growth in Bataan: The effects of population growth around rural pl...Population Growth in Bataan: The effects of population growth around rural pl...
Population Growth in Bataan: The effects of population growth around rural pl...
Bill641377
 
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
y3i0qsdzb
 
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
Walaa Eldin Moustafa
 
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
xclpvhuk
 
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
bmucuha
 
Predictably Improve Your B2B Tech Company's Performance by Leveraging Data
Predictably Improve Your B2B Tech Company's Performance by Leveraging DataPredictably Improve Your B2B Tech Company's Performance by Leveraging Data
Predictably Improve Your B2B Tech Company's Performance by Leveraging Data
Kiwi Creative
 
End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024
Lars Albertsson
 
Intelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicineIntelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicine
AndrzejJarynowski
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
aqzctr7x
 
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
nuttdpt
 
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
apvysm8
 
Build applications with generative AI on Google Cloud
Build applications with generative AI on Google CloudBuild applications with generative AI on Google Cloud
Build applications with generative AI on Google Cloud
Márton Kodok
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
ihavuls
 

Último (20)

一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
 
Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
 
Palo Alto Cortex XDR presentation .......
Palo Alto Cortex XDR presentation .......Palo Alto Cortex XDR presentation .......
Palo Alto Cortex XDR presentation .......
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
 
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
 
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
一比一原版英属哥伦比亚大学毕业证(UBC毕业证书)学历如何办理
 
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
 
Population Growth in Bataan: The effects of population growth around rural pl...
Population Growth in Bataan: The effects of population growth around rural pl...Population Growth in Bataan: The effects of population growth around rural pl...
Population Growth in Bataan: The effects of population growth around rural pl...
 
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
 
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
 
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
一比一原版(Unimelb毕业证书)墨尔本大学毕业证如何办理
 
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
一比一原版(CU毕业证)卡尔顿大学毕业证如何办理
 
Predictably Improve Your B2B Tech Company's Performance by Leveraging Data
Predictably Improve Your B2B Tech Company's Performance by Leveraging DataPredictably Improve Your B2B Tech Company's Performance by Leveraging Data
Predictably Improve Your B2B Tech Company's Performance by Leveraging Data
 
End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024
 
Intelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicineIntelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicine
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
 
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
 
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
办(uts毕业证书)悉尼科技大学毕业证学历证书原版一模一样
 
Build applications with generative AI on Google Cloud
Build applications with generative AI on Google CloudBuild applications with generative AI on Google Cloud
Build applications with generative AI on Google Cloud
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
 

Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASSDC User Group)

  • 1.
  • 2. Specialties / Focus Areas / Passions: • Performance Tuning & Troubleshooting • Very Large Databases • SQL Server Storage Engine • High Availability • Disaster Recovery @sqlbob bob@bobpusateri.com heraflux.com bobpusateri
  • 3. • Concurrency Basics • Isolation Levels • In-Memory OLTP
  • 4. • The ability for an operation to be broken up into multiple parts that can be worked on independently • The ability for multiple operations to access or modify a shared resource at the same time • More parts/users == more concurrency! • Until a limiting factor appears…
  • 5. • 5 Philosophers, bowls of spaghetti, and forks • To eat, 2 forks are required • Can pick up one fork at a time • Once finished, both forks must be returned to the table • When not eating, a philosopher is thinking https://en.wikipedia.org/wiki/File:An_illustration_of_the_dining_philosophers_problem.png
  • 6. What if everyone picks up one fork? https://en.wikipedia.org/wiki/File:An_illustration_of_the_dining_philosophers_problem.png What if there’s a time limit? What if someone never gets to eat?
  • 7. $$
  • 8. • Preventable Read Phenomena (ANSI-defined*)  Dirty Reads  Non-Repeatable Reads  Phantom Reads • Lost Updates • Deadlocks *ANSI specifies which behaviors to allow at each level, but not how to implement them New Hampshire Dept. of Transportation
  • 9. • Reading data that is not yet committed • Changes are still “in flight” in another process • You can read data multiple times or not at all • “But it’s faster!”
  • 10. • A.K.A. “Inconsistent Analysis” • Multiple queries in the same transaction get differing results • Cause: A different transaction commits changes between reads
  • 11. • Only affects queries with a predicate (WHERE clause) • Membership in the result set changes • Multiple queries using the same predicate in the same transaction return differing results https://flic.kr/p/4xqWnG
  • 12. • “Update Conflict” • One user’s update overwrites another user’s (simultaneous) update • Appears as though the first update never happened *SQL Server will not permit lost updates in any isolation level
  • 13. • Two or more tasks block each other • Each has a lock on a resource that the other task needs a lock on • SQL Server detects and resolves these by choosing a victim • Victim is rolled back, releasing all its locks Process A Process B Resource 1 Resource 2
  • 14. • Pessimistic Concurrency  Conflicts are expected; locks taken to prevent them  Readers block writers, writers block readers  Only option available pre-2005 • Optimistic Concurrency  Conflicts are considered possible, but unlikely  Row versioning means less locking
  • 15. • Concurrency Basics • Isolation Levels • In-Memory OLTP
  • 16. • How isolated is my transaction from the effects of other transactions? • Pessimistic Concurrency  Read Committed  Read Uncommitted  Repeatable Read  Serializable • Optimistic Concurrency  Snapshot  Read Committed Snapshot https://flic.kr/p/7LjDDL
  • 18. • Can be set at the connection or query level • Cannot be changed server-wide • Default isolation level is READ COMMITTED • To change at connection level: • Change applies to all queries for the current connection SET TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SNAPSHOT | SERIALIZABLE } [;]
  • 19. • To change at the query level, use table hints • This is on a per-table basis SELECT column FROM table WITH (NOLOCK);
  • 20. • Uses locking to prevent concurrency conflicts • Classic locking model  Readers don’t block readers  Readers block writers  Writers block readers  Writers block writers • PESSIMISTIC – we’re expecting problems
  • 23. Database Table Page Row [S] Shared Lock [IS] Intent Shared Lock [IS] Intent Shared Lock [S] Shared Lock
  • 24. Database Table Page Row [S] Shared Lock [IX] Intent Exclusive Lock OR [IU] Intent Update Lock [IX] Intent Exclusive Lock OR [IU] Intent Update Lock [X] Exclusive Lock OR [U] Update Lock
  • 25. • A.K.A “NOLOCK” • May read rows multiple times • May read rows zero times • May return results that were NEVER true! • Only applies to SELECT queries  Ignored if used for data modification queries  Could cause index corruption if you tried it (since fixed) Dirty Nonrepeatable Phantom Yes Yes Yes
  • 27. • “No locks are taken”  WRONG!  No shared locks are taken when reading data  Other locks are still taken as normal • “It makes this query faster”  WRONG(ish)!  Only true if query had a lot of blocking on SELECT statements
  • 28.
  • 29. • Not a terrible setting, it exists for a reason • BUT make sure you understand the risks and consequences
  • 30. • The Default Default Isolation level • Guarantee: Data that is read is guaranteed to be committed.  No Dirty Reads  No other guarantees Dirty Nonrepeatable Phantom No Yes Yes
  • 31. • Ensure only committed data is read by locking • (Locks only last as long as the read, released immediately after) Rows already read. Unlocked. Row currently being read. Locked. Rows not yet read. Unlocked. SCAN
  • 33.
  • 34. • Unlocked rows can move at any time Rows already read. Unlocked. Row currently being read. Locked. Rows not yet read. Unlocked. SCAN
  • 35. • Unlocked rows can move at any time Rows already read. Unlocked. Row currently being read. Locked. Rows not yet read. Unlocked. SCAN
  • 36.
  • 37. • Builds on READ COMMITTED • If a query is repeated within the same transaction, records read the first time will not change • Once a row is read, locks are held for length of the transaction  Even rows that don’t qualify as results • These locks will not stop additional rows from being added or included in subsequent queries Dirty Nonrepeatable Phantom No No Yes
  • 38.
  • 39. • Once read, rows are locked for duration of transaction Rows already read. Locked. Row currently being read. Locked. Rows not yet read. Unlocked. SCAN
  • 40. • On a second scan, new rows may enter Rows already read. Locked. Row currently being read. Locked. Rows not yet read. Unlocked. SCAN
  • 41.
  • 42. • Builds on REPEATABLE READ • If a query is repeated within the same transaction, results will be the same • No data seen previously will change; no new results will appear • We now need to lock data that doesn’t exist! Dirty Nonrepeatable Phantom No No No
  • 43. • Key-range locks • Prevent phantom reads by defining a range that other transactions cannot insert rows within • If you select a row/range that doesn’t exist, that gets locked too
  • 44. • Range Locks cover the entire range AND the first row outside it Rows already read. Locked. Row currently being read. Locked. Rows not yet read. Locked. RANGE BEING SELECTED First key outside range. Locked.
  • 45.
  • 46. • Uses row versioning to prevent concurrency conflicts • Fewer locks are needed, so blocking is reduced  Readers no longer block writers  Writers no longer block readers  Writers still block writers • Uses a version store to do this • Version Store lives in tempdb • Remember, it’s OPTIMISTIC!
  • 47. • Whenever a row is updated, previous version is stored in the version store • New version of row has a pointer to the previous version • Versions are stored for as long as operations exist that might need them  All versions of rows modified by a transaction must be kept for as long as that transaction is open
  • 48. Current Version (ID=6, Val=4) [T=n] Previous Version (ID=6, Val=7) [T=n-1] Previous Version (ID=6, Val=9) [T=n-5]
  • 53. • Same guarantees as READ COMMITTED, just an optimistic implementation • Statement-level snapshot isolation  Queries will see the most recent committed values as of the beginning of that statement (not the transaction) Dirty Nonrepeatable Phantom No Yes Yes
  • 55. T=5 T=1 T=1 T=1T=5 T=4 State at T=7 Statement sees this:
  • 56. T=9 T=9 T=5 T=1 T=1 T=1T=5 T=4 State at T=7 Statement sees this: Update Occurs! Updater is not blocked. Statement continues to read same version.
  • 57. • When enabled, RCSI becomes the default isolation level for this database. • Command will block if DB has other connections  NO_WAIT will prevent blocking and just fail instead  ROLLBACK_IMMEDIATE will rollback other transactions Dirty Nonrepeatable Phantom No Yes Yes ALTER DATABASE <DB_NAME> SET READ_COMMITTED_SNAPSHOT ON [WITH (NO_WAIT | ROLLBACK IMMEDIATE)];
  • 58.
  • 59. • Same guarantees as SERIALIZABLE, just an optimistic implementation • Transaction-level snapshot isolation  Queries will see the most recent committed values as of the beginning of that transaction (the first data read in it) Dirty Nonrepeatable Phantom No No No
  • 60. • First statement merely allows snapshot isolation Dirty Nonrepeatable Phantom No No No ALTER DATABASE <DB_NAME> SET ALLOW_SNAPSHOT_ISOLATION ON; SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
  • 61. • Process 1 reads data in a transaction, does not commit • Process 2 reads/updates same data, • Process 1’s snapshot does not see Process 2’s update • Process 1 tries to update, gets blocked • As soon as Process 2 commits, Process 1 errors out • This will raise error 3960 on process 1 https://flic.kr/p/4WHW81
  • 62.
  • 63. • Everything I’ve covered here behaves the same in Azure SQL Database • Exception: RCSI is enabled by default
  • 64. • Concurrency Basics • Isolation Levels • In-Memory OLTP
  • 65. • This could be its own presentation by itself • Optimistic multi-version concurrency control  No locks required at any time  (Not even for data modification)  No waiting because of blocking!  No latches or spinlocks either • Waits can still occur….  (Waiting for log writes to disk following a transaction)
  • 66. • No existing row is ever modified  UPDATE creates a new version of a row  There may be multiple versions in play at once • Transactions needing to read are presented with the correct version
  • 67. 10 <inf> 1 Red Begin Time End Time Data Columns 10 <inf> 3 Green Now at time 20, let’s: Delete (1, Red) Update (3, Green) to (3, Blue) Insert (6, Pink) 10 20 1 Red 10 20 3 Green 20 <inf> 3 Blue 20 <inf> 6 Pink Begin Time End Time Data Columns
  • 68. • Craig Freedman’s posts on SQL Server Isolation Levels https://blogs.msdn.microsoft.com/craigfr/tag/isolation-levels/ • SQL Server Concurrency: Locking, Blocking, and Row Versioning (Kalen Delaney, Simple Talk Publishing) • Myths and Misconceptions about Transaction Isolation Levels http://www.sqlpassion.at/archive/2014/01/21/myths-and-misconceptions-about-transaction-isolation-levels/