SlideShare a Scribd company logo
INNODB LOCKING
EXPLAINED
WITH STICK FIGURES
Bill Karwin
Bill Karwin
• Senior Database Architect at School Messenger
(West Corporation)
• Author of SQL Antipatterns: Avoiding the Pitfalls of
Database Programming
• 20+ years experience with SQL databases, software
development, MySQL consulting and training
why locking?
• When multiple clients
access the same data,
they have to avoid
clobbering each others’
work.
• Databases must restrict
access to one client at a
time for a given table or
row.
https://commons.wikimedia.org/wiki/File:New_York_City_Gridlock.jpg  
why locking?
• The DBMS creates locks
against tables and rows, and
gives them to clients, first-
come, first-serve.
• When a client requests a
exclusive lock, but a different
client currently holds it, the
requestor waits until the
holder releases its lock.
• Most locks last until the end of
the transaction.
https://commons.wikimedia.org/wiki/Traffic_lights#/media/File:LED_traffic_light.jpg
the analogy
a museum
• Many people can visit the museum (a database
table) to view art (rows of data).
reads and writes
reads
• Many visitors can view paintings at the same time—
no locking required.
https://commons.wikimedia.org/wiki/File:L%27%C3%A9glise_d%27Auvers-­‐‑sur-­‐‑Oise.jpg
writes
• A curator can change the paintings—while casual
visitors are viewing them.
https://commons.wikimedia.org/wiki/File:Vincent_Willem_van_Gogh_128.jpg
writes
• A curator can change the paintings—while casual
visitors are viewing them.
repeatable reads
• The viewers still see the prior painting in spite of the
change, because they used their tablets to capture
the image.*
*  Please  do  not  take  photographs  of  the  art  in  a  real  museum.
read committed
• If the viewers are okay allowing their view to
change, they can simply say so.
READ  
COMMITTED
read committed
• If the viewers are okay allowing their view to
change, they can simply say so.
READ  
COMMITTED
I  don’t  mind
exclusive locks
exclusive locks
• The curator can change the painting if they are the
exclusive person working on it.
exclusive locks
• Casual viewers don’t block the curator.
X-­‐‑lock!
exclusive locks
• A second curator who tries to change the same
painting must wait for the first curator to finish.
X-­‐‑lock!…
https://commons.wikimedia.org/wiki/Vincent_van_Gogh#/media/File:Vincent_Willem_van_Gogh_107.jpg
what is an exclusive lock?
• A lock that does not share.
• It must be the only lock on the resource.
• Request for an exclusive lock waits for the release of
any other shared or exclusive lock on that resource.
shared locks
shared locks
• The curator cannot make changes while the art
critic is viewing a painting.
S-­‐‑lock!
.  .  .
shared locks
• Art critics can share—they do not block each other.
S-­‐‑lock!
.  .  .
S-­‐‑lock!
shared locks
• Once the art critics leave, the curator can proceed
to change the art.
X-­‐‑lock!
shared locks
• A new art critic will not begin his viewing while the
curator is still working on changing the painting.
X-­‐‑lock!…
what is a shared lock?
• A lock that allows other shared locks on the same
table or rows.
• Shared locks blocks exclusive locks.
• Exclusive locks block shared locks.
table intention locks
table locks
• A construction worker needs to remodel the
museum, but not while visitors are inside.
table locks
• Each person is given a special badge as they enter
the museum, showing their
intention to view or change
the paintings.
IS!IX!
table locks
• A construction worker requests exclusive access to
the museum, but can not get it.
.  .  .IS!
IX!
table locks
• When all the visitors have left, the worker can finally
get his exclusive access to do his work.
LOCK  
TABLE!
table locks
• While the construction is going on, visitors cannot
get their badges, and therefore
cannot enter the museum.
…
https://commons.wikimedia.org/wiki/Category:Under_construction_icons#/media/File:Enobras.PNG
LOCK  
TABLE!
…
what is an intention lock?
• Before SELECT…LOCK IN SHARE MODE or other
shared lock, request an intention shared lock (“IS”)
on the table.
• Before SELECT…FOR UPDATE, INSERT, UPDATE,
DELETE, request an intention exclusive lock (“IX”).
• IS and IX locks allow access by multiple clients.
They won’t necessarily conflict until they try to get
real locks on the same rows.
• But a table lock (ALTER TABLE, DROP TABLE, LOCK
TABLES) blocks both IS and IX, and vice-versa.
gap locks
gap locks
• The art critic needs to view the whole collection
without changes and no new inserts.
gap
.  .  .
S-­‐‑lock!
what is a gap lock?
• A lock on a painting locks the “space” before the
painting.
• The gap lock prevents inserts of new paintings
before the locked painting (within the space).
• This happens automatically, to prevent “phantom
reads”—i.e. the view of data changes during a
transaction.
what is a gap lock?
• Exception: if the art critic is okay with seeing the
latest additions among the paintings, he can
choose to use the READ COMMITTED transaction
isolation level.
• Another exception: no gap lock is needed for a
UNIQUE or PRIMARY KEY index.
gap locks
• Optionally be more permissive about inserts.
gap
S-­‐‑lock!
READ  
COMMITTED
gap locks
• Optionally be more permissive about inserts.
X-­‐‑lock!
S-­‐‑lock!
READ  
COMMITTED
I  don’t  mind
traveling exhibit
• Some art exhibits move to another museum.
installation plans
• The curators must keep records of how to install the
art, so the show is the same at each museum.
Label  all  
paintings  on  
this  wall  with  
“Van  Gogh”
installation plans
• The curators must keep records of how to install the
art, so the show is the same at each museum.
Van  Gogh Van  Gogh
installation plans
• Another painting is added.
Van  Gogh Van  Gogh
Install  this  in  
the  gap  and  
label  it  
“Lautrec”
https://commons.wikimedia.org/wiki/Moulin_Rouge#/media/File:Lautrec_at_the_moulin_rouge_two_women_waltzing_1892.jpg
installation plans
• Another painting is installed in the gap.
Van  Gogh Van  GoghLautrec
installation plans
• The latter curator commits his installation plans first.
Van  Gogh Van  GoghLautrec
COMMIT
installation plans
• Then the first curator commits his installation plans.
Van  Gogh Van  GoghLautrec
COMMIT
traveling exhibit
• The exhibit is installed in the second museum.
order matters
• The installation instructions are carried out in the
wrong order!
Install  this  in  
the  gap  and  
label  it  
“Lautrec”
order matters
• The installation instructions are carried out in the
wrong order!
Lautrec
Label  all  
paintings  on  
this  wall  with  
“Van  Gogh”
order matters
• The installation instructions are carried out in the
wrong order!
Van  GoghVan  Gogh Van  Gogh
what happened?
• Installation instructions are recorded in the order
they were committed, not the order they were
originally done.
• Therefore the installation at the next museum may
repeat the steps in an incorrect order.
how to solve this?
• Labeling “Van Gogh” should have first locked all
the spaces on that wall.
Van  Gogh Van  Gogh
gap
how to solve this?
• The addition would be forced to wait for the locks
to be released.
Van  Gogh Van  Gogh
gap
…
insert intention locks
insert intention locks
• One curator wants to update paintings where
year > 1886
X-­‐‑lock!
gap
insert intention locks
• The second curator wants to insert an 1887 painting,
but it would fall within the existing gap lock.
X-­‐‑lock! …
gap
insert intention locks
---TRANSACTION 32070411, ACTIVE 6 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 360, 1 row lock(s),
undo log entries 1
MySQL thread id 26, OS thread handle 0x7f2ba845f700,
query id 1423 192.168.50.1 root update
insert into Museum (year) values (1887)
------- TRX HAS BEEN WAITING 6 SEC FOR THIS LOCK TO BE
GRANTED:
RECORD LOCKS space id 3337 page no 4 n bits 72 index
`year` of table `test`.`Museum` trx id 32070411 lock_mode X
insert intention waiting
insert intention locks
• But if the first curator doesn’t care about new
paintings entering his view…
X-­‐‑lock!
gap
READ  
COMMITTED
insert intention locks
• Then the second curator gets an insert intention
lock, and is then free to insert.
insert-­‐‑
lock!
gap
X-­‐‑lock!
READ  
COMMITTED
I  don’t  mind
insert intention locks
• Then the second curator gets an insert intention
lock, and is then free to insert.
X-­‐‑lock!X-­‐‑lock!
READ  
COMMITTED
I  don’t  mind
what is an insert intention lock?
• A special kind of gap lock, requested before a
client tries to insert a row.
• Insert locks are shared, not exclusive—multiple
clients can acquire insert locks on the same gap.
• But insert locks conflict with other exclusive locks.
why is insert intention lock shared?
• Multiple clients prepare to insert into the same gap.
• They may be inserting different rows within the same
gap, so they don’t conflict with each other.
• But the insert intention lock blocks other clients from
requesting exclusive locks on the same gap.
auto-inc locks
auto-inc locks
• Two curators are installing paintings. They both need
to post a unique number for self-guided tours.
? ?
auto-inc locks
• There must be one number
generator per table.
• One curator at a time can
request the next value.
http://www.istockphoto.com/photo/ticket-­‐‑dispenser-­‐‑isolated-­‐‑9396862
auto-inc locks
• The first curator gets a number.
auto-­‐‑inc! 1 …
auto-inc locks
• As soon as the first curator gets his number, the
second curator can proceed.
1 2 auto-­‐‑inc!
auto-inc locks
• They may both keep locks on the paintings, but
they’re done allocating numbers.
X-­‐‑lock! 1 2 X-­‐‑lock!
what is an auto-inc lock?
• A table lock, used when a client requests the next
unique id for a given table.
• Ensures that each id is given to one client.
• Brief—it is released as soon as the id is generated,
instead of lasting to the end of the transaction like
other locks.
• Because the lock is so brief, neither client can
“undo”— i.e. they cannot return their id to the stack
for someone else to use.
deadlocks
deadlocks
• Two curators are updating the art, but they start
from different ends of the collection.
X-­‐‑lock!X-­‐‑lock!
deadlocks
• A curator requests a lock on the second painting,
which is already locked. He waits.
X-­‐‑lock!X-­‐‑lock!
…
deadlocks
• The other curator requests a lock on the first
painting, which is already locked. He also waits.
X-­‐‑lock!X-­‐‑lock!
…
…
deadlocks
• Neither will give up the lock they have, so they are
doomed to wait until one or both of them dies.
X-­‐‑lock!
X-­‐‑lock!
… …
what is a deadlock?
• When two or more concurrent clients wait for each
other to release their locks, but since they are both
waiting, they will never give up the lock they have.
• In other words, a “catch-22” of lock-waits.
• Many people use the term “deadlock” incorrectly—
when they are describing a simple one-way lock
wait.
resolving deadlocks
• MySQL detects cycles in lock waits, and kills one of
the transactions immediately.
X-­‐‑lock!X-­‐‑lock!
…
…
resolving deadlocks
• MySQL detects cycles in lock waits, and
automatically kills one of the transactions.
X-­‐‑lock!
X-­‐‑lock!
avoiding deadlocks
• All clients request locks in the same order.
X-­‐‑lock!
…
X-­‐‑lock!
avoiding deadlocks
• Each client locks everything they need in one
atomic request.
X-­‐‑lock!
…
conclusion
read committed
all the things?
• Yes … and no.
• READ COMMITTED avoids gap locks, therefore
reduces lock waits and allows greater throughput.
• But using READ COMMITTED allows more cases
where you could get deadlocks.
thank you
• I hope your trip to the museum was educational!
license and copyright
Copyright 2015-2016 Bill Karwin
http://www.slideshare.net/billkarwin
Released under a Creative Commons 3.0 License:
http://creativecommons.org/licenses/by-nc-nd/3.0/
You are free to share—to copy, distribute, and
transmit this work, under the following conditions:
Attribution.
You  must  attribute  this  
work  to  Bill  Karwin.
Noncommercial.
You  may  not  use  this  
work  for  commercial  
purposes.
No  Derivative  Works.
You may  not  alter,  
transform,  or  build  upon  
this  work.
Ad

More Related Content

What's hot (20)

InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internal
mysqlops
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
Tanel Poder
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
Constantine Slisenka
 
The InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQLThe InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQL
Morgan Tocker
 
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder
 
Receive side scaling (RSS) with eBPF in QEMU and virtio-net
Receive side scaling (RSS) with eBPF in QEMU and virtio-netReceive side scaling (RSS) with eBPF in QEMU and virtio-net
Receive side scaling (RSS) with eBPF in QEMU and virtio-net
Yan Vugenfirer
 
Kafka at Peak Performance
Kafka at Peak PerformanceKafka at Peak Performance
Kafka at Peak Performance
Todd Palino
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
Norvald Ryeng
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
Aurimas Mikalauskas
 
How Netflix Tunes EC2 Instances for Performance
How Netflix Tunes EC2 Instances for PerformanceHow Netflix Tunes EC2 Instances for Performance
How Netflix Tunes EC2 Instances for Performance
Brendan Gregg
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Dvir Volk
 
Liquibase
LiquibaseLiquibase
Liquibase
Sergii Fesenko
 
Using Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query PerformanceUsing Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query Performance
oysteing
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
John Beresniewicz
 
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdfMySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
Alkin Tezuysal
 
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxData
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
InfluxData
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
MongoDB
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning Concept
Chien Chung Shen
 
Kafka Streams State Stores Being Persistent
Kafka Streams State Stores Being PersistentKafka Streams State Stores Being Persistent
Kafka Streams State Stores Being Persistent
confluent
 
InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internal
mysqlops
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
Tanel Poder
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
Constantine Slisenka
 
The InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQLThe InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQL
Morgan Tocker
 
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Tanel Poder
 
Receive side scaling (RSS) with eBPF in QEMU and virtio-net
Receive side scaling (RSS) with eBPF in QEMU and virtio-netReceive side scaling (RSS) with eBPF in QEMU and virtio-net
Receive side scaling (RSS) with eBPF in QEMU and virtio-net
Yan Vugenfirer
 
Kafka at Peak Performance
Kafka at Peak PerformanceKafka at Peak Performance
Kafka at Peak Performance
Todd Palino
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
Norvald Ryeng
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
Aurimas Mikalauskas
 
How Netflix Tunes EC2 Instances for Performance
How Netflix Tunes EC2 Instances for PerformanceHow Netflix Tunes EC2 Instances for Performance
How Netflix Tunes EC2 Instances for Performance
Brendan Gregg
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Dvir Volk
 
Using Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query PerformanceUsing Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query Performance
oysteing
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
John Beresniewicz
 
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdfMySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
MySQL Ecosystem in 2023 - FOSSASIA'23 - Alkin.pptx.pdf
Alkin Tezuysal
 
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxDB IOx Tech Talks: Replication, Durability and Subscriptions in InfluxD...
InfluxData
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
InfluxData
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
MongoDB
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning Concept
Chien Chung Shen
 
Kafka Streams State Stores Being Persistent
Kafka Streams State Stores Being PersistentKafka Streams State Stores Being Persistent
Kafka Streams State Stores Being Persistent
confluent
 

Viewers also liked (20)

Citus Architecture: Extending Postgres to Build a Distributed Database
Citus Architecture: Extending Postgres to Build a Distributed DatabaseCitus Architecture: Extending Postgres to Build a Distributed Database
Citus Architecture: Extending Postgres to Build a Distributed Database
Ozgun Erdogan
 
领域驱动设计与模型驱动开发
领域驱动设计与模型驱动开发领域驱动设计与模型驱动开发
领域驱动设计与模型驱动开发
Weijun Zhong
 
Development with Qt for Windows CE
Development with Qt for Windows CEDevelopment with Qt for Windows CE
Development with Qt for Windows CE
account inactive
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
rfyiamcool
 
Enterprise Architecture Implementation And The Open Group Architecture Framew...
Enterprise Architecture Implementation And The Open Group Architecture Framew...Enterprise Architecture Implementation And The Open Group Architecture Framew...
Enterprise Architecture Implementation And The Open Group Architecture Framew...
Alan McSweeney
 
Micro service
Micro serviceMicro service
Micro service
rfyiamcool
 
Mysql展示功能与源码对应
Mysql展示功能与源码对应Mysql展示功能与源码对应
Mysql展示功能与源码对应
zhaolinjnu
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
Karwin Software Solutions LLC
 
MySQL High Availability Deep Dive
MySQL High Availability Deep DiveMySQL High Availability Deep Dive
MySQL High Availability Deep Dive
hastexo
 
Why MySQL Replication Fails, and How to Get it Back
Why MySQL Replication Fails, and How to Get it BackWhy MySQL Replication Fails, and How to Get it Back
Why MySQL Replication Fails, and How to Get it Back
Sveta Smirnova
 
MySQL Group Replication - HandsOn Tutorial
MySQL Group Replication - HandsOn TutorialMySQL Group Replication - HandsOn Tutorial
MySQL Group Replication - HandsOn Tutorial
Kenny Gryp
 
MySQL Replication Performance Tuning for Fun and Profit!
MySQL Replication Performance Tuning for Fun and Profit!MySQL Replication Performance Tuning for Fun and Profit!
MySQL Replication Performance Tuning for Fun and Profit!
Vitor Oliveira
 
Why MySQL High Availability Matters
Why MySQL High Availability MattersWhy MySQL High Availability Matters
Why MySQL High Availability Matters
Matt Lord
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability
Mydbops
 
Эффективная отладка репликации MySQL
Эффективная отладка репликации MySQLЭффективная отладка репликации MySQL
Эффективная отладка репликации MySQL
Sveta Smirnova
 
What you wanted to know about MySQL, but could not find using inernal instrum...
What you wanted to know about MySQL, but could not find using inernal instrum...What you wanted to know about MySQL, but could not find using inernal instrum...
What you wanted to know about MySQL, but could not find using inernal instrum...
Sveta Smirnova
 
MySQL High Availability Solutions
MySQL High Availability SolutionsMySQL High Availability Solutions
MySQL High Availability Solutions
Lenz Grimmer
 
Hbase源码初探
Hbase源码初探Hbase源码初探
Hbase源码初探
zhaolinjnu
 
Мониторинг и отладка MySQL: максимум информации при минимальных потерях
Мониторинг и отладка MySQL: максимум информации при минимальных потеряхМониторинг и отладка MySQL: максимум информации при минимальных потерях
Мониторинг и отладка MySQL: максимум информации при минимальных потерях
Sveta Smirnova
 
Advanced mysql replication techniques
Advanced mysql replication techniquesAdvanced mysql replication techniques
Advanced mysql replication techniques
Giuseppe Maxia
 
Citus Architecture: Extending Postgres to Build a Distributed Database
Citus Architecture: Extending Postgres to Build a Distributed DatabaseCitus Architecture: Extending Postgres to Build a Distributed Database
Citus Architecture: Extending Postgres to Build a Distributed Database
Ozgun Erdogan
 
领域驱动设计与模型驱动开发
领域驱动设计与模型驱动开发领域驱动设计与模型驱动开发
领域驱动设计与模型驱动开发
Weijun Zhong
 
Development with Qt for Windows CE
Development with Qt for Windows CEDevelopment with Qt for Windows CE
Development with Qt for Windows CE
account inactive
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
rfyiamcool
 
Enterprise Architecture Implementation And The Open Group Architecture Framew...
Enterprise Architecture Implementation And The Open Group Architecture Framew...Enterprise Architecture Implementation And The Open Group Architecture Framew...
Enterprise Architecture Implementation And The Open Group Architecture Framew...
Alan McSweeney
 
Mysql展示功能与源码对应
Mysql展示功能与源码对应Mysql展示功能与源码对应
Mysql展示功能与源码对应
zhaolinjnu
 
MySQL High Availability Deep Dive
MySQL High Availability Deep DiveMySQL High Availability Deep Dive
MySQL High Availability Deep Dive
hastexo
 
Why MySQL Replication Fails, and How to Get it Back
Why MySQL Replication Fails, and How to Get it BackWhy MySQL Replication Fails, and How to Get it Back
Why MySQL Replication Fails, and How to Get it Back
Sveta Smirnova
 
MySQL Group Replication - HandsOn Tutorial
MySQL Group Replication - HandsOn TutorialMySQL Group Replication - HandsOn Tutorial
MySQL Group Replication - HandsOn Tutorial
Kenny Gryp
 
MySQL Replication Performance Tuning for Fun and Profit!
MySQL Replication Performance Tuning for Fun and Profit!MySQL Replication Performance Tuning for Fun and Profit!
MySQL Replication Performance Tuning for Fun and Profit!
Vitor Oliveira
 
Why MySQL High Availability Matters
Why MySQL High Availability MattersWhy MySQL High Availability Matters
Why MySQL High Availability Matters
Matt Lord
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability
Mydbops
 
Эффективная отладка репликации MySQL
Эффективная отладка репликации MySQLЭффективная отладка репликации MySQL
Эффективная отладка репликации MySQL
Sveta Smirnova
 
What you wanted to know about MySQL, but could not find using inernal instrum...
What you wanted to know about MySQL, but could not find using inernal instrum...What you wanted to know about MySQL, but could not find using inernal instrum...
What you wanted to know about MySQL, but could not find using inernal instrum...
Sveta Smirnova
 
MySQL High Availability Solutions
MySQL High Availability SolutionsMySQL High Availability Solutions
MySQL High Availability Solutions
Lenz Grimmer
 
Hbase源码初探
Hbase源码初探Hbase源码初探
Hbase源码初探
zhaolinjnu
 
Мониторинг и отладка MySQL: максимум информации при минимальных потерях
Мониторинг и отладка MySQL: максимум информации при минимальных потеряхМониторинг и отладка MySQL: максимум информации при минимальных потерях
Мониторинг и отладка MySQL: максимум информации при минимальных потерях
Sveta Smirnova
 
Advanced mysql replication techniques
Advanced mysql replication techniquesAdvanced mysql replication techniques
Advanced mysql replication techniques
Giuseppe Maxia
 
Ad

More from Karwin Software Solutions LLC (17)

How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
Karwin Software Solutions LLC
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
Karwin Software Solutions LLC
 
Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
Karwin Software Solutions LLC
 
SQL Outer Joins for Fun and Profit
SQL Outer Joins for Fun and ProfitSQL Outer Joins for Fun and Profit
SQL Outer Joins for Fun and Profit
Karwin Software Solutions LLC
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
Karwin Software Solutions LLC
 
Survey of Percona Toolkit
Survey of Percona ToolkitSurvey of Percona Toolkit
Survey of Percona Toolkit
Karwin Software Solutions LLC
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
Karwin Software Solutions LLC
 
Schemadoc
SchemadocSchemadoc
Schemadoc
Karwin Software Solutions LLC
 
Percona toolkit
Percona toolkitPercona toolkit
Percona toolkit
Karwin Software Solutions LLC
 
MySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB StatusMySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB Status
Karwin Software Solutions LLC
 
Requirements the Last Bottleneck
Requirements the Last BottleneckRequirements the Last Bottleneck
Requirements the Last Bottleneck
Karwin Software Solutions LLC
 
Mentor Your Indexes
Mentor Your IndexesMentor Your Indexes
Mentor Your Indexes
Karwin Software Solutions LLC
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
Karwin Software Solutions LLC
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
Karwin Software Solutions LLC
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
Karwin Software Solutions LLC
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
Karwin Software Solutions LLC
 
Ad

Recently uploaded (20)

Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 

InnoDB Locking Explained with Stick Figures

  • 2. Bill Karwin • Senior Database Architect at School Messenger (West Corporation) • Author of SQL Antipatterns: Avoiding the Pitfalls of Database Programming • 20+ years experience with SQL databases, software development, MySQL consulting and training
  • 3. why locking? • When multiple clients access the same data, they have to avoid clobbering each others’ work. • Databases must restrict access to one client at a time for a given table or row. https://commons.wikimedia.org/wiki/File:New_York_City_Gridlock.jpg  
  • 4. why locking? • The DBMS creates locks against tables and rows, and gives them to clients, first- come, first-serve. • When a client requests a exclusive lock, but a different client currently holds it, the requestor waits until the holder releases its lock. • Most locks last until the end of the transaction. https://commons.wikimedia.org/wiki/Traffic_lights#/media/File:LED_traffic_light.jpg
  • 6. a museum • Many people can visit the museum (a database table) to view art (rows of data).
  • 8. reads • Many visitors can view paintings at the same time— no locking required. https://commons.wikimedia.org/wiki/File:L%27%C3%A9glise_d%27Auvers-­‐‑sur-­‐‑Oise.jpg
  • 9. writes • A curator can change the paintings—while casual visitors are viewing them. https://commons.wikimedia.org/wiki/File:Vincent_Willem_van_Gogh_128.jpg
  • 10. writes • A curator can change the paintings—while casual visitors are viewing them.
  • 11. repeatable reads • The viewers still see the prior painting in spite of the change, because they used their tablets to capture the image.* *  Please  do  not  take  photographs  of  the  art  in  a  real  museum.
  • 12. read committed • If the viewers are okay allowing their view to change, they can simply say so. READ   COMMITTED
  • 13. read committed • If the viewers are okay allowing their view to change, they can simply say so. READ   COMMITTED I  don’t  mind
  • 15. exclusive locks • The curator can change the painting if they are the exclusive person working on it.
  • 16. exclusive locks • Casual viewers don’t block the curator. X-­‐‑lock!
  • 17. exclusive locks • A second curator who tries to change the same painting must wait for the first curator to finish. X-­‐‑lock!… https://commons.wikimedia.org/wiki/Vincent_van_Gogh#/media/File:Vincent_Willem_van_Gogh_107.jpg
  • 18. what is an exclusive lock? • A lock that does not share. • It must be the only lock on the resource. • Request for an exclusive lock waits for the release of any other shared or exclusive lock on that resource.
  • 20. shared locks • The curator cannot make changes while the art critic is viewing a painting. S-­‐‑lock! .  .  .
  • 21. shared locks • Art critics can share—they do not block each other. S-­‐‑lock! .  .  . S-­‐‑lock!
  • 22. shared locks • Once the art critics leave, the curator can proceed to change the art. X-­‐‑lock!
  • 23. shared locks • A new art critic will not begin his viewing while the curator is still working on changing the painting. X-­‐‑lock!…
  • 24. what is a shared lock? • A lock that allows other shared locks on the same table or rows. • Shared locks blocks exclusive locks. • Exclusive locks block shared locks.
  • 26. table locks • A construction worker needs to remodel the museum, but not while visitors are inside.
  • 27. table locks • Each person is given a special badge as they enter the museum, showing their intention to view or change the paintings. IS!IX!
  • 28. table locks • A construction worker requests exclusive access to the museum, but can not get it. .  .  .IS! IX!
  • 29. table locks • When all the visitors have left, the worker can finally get his exclusive access to do his work. LOCK   TABLE!
  • 30. table locks • While the construction is going on, visitors cannot get their badges, and therefore cannot enter the museum. … https://commons.wikimedia.org/wiki/Category:Under_construction_icons#/media/File:Enobras.PNG LOCK   TABLE! …
  • 31. what is an intention lock? • Before SELECT…LOCK IN SHARE MODE or other shared lock, request an intention shared lock (“IS”) on the table. • Before SELECT…FOR UPDATE, INSERT, UPDATE, DELETE, request an intention exclusive lock (“IX”). • IS and IX locks allow access by multiple clients. They won’t necessarily conflict until they try to get real locks on the same rows. • But a table lock (ALTER TABLE, DROP TABLE, LOCK TABLES) blocks both IS and IX, and vice-versa.
  • 33. gap locks • The art critic needs to view the whole collection without changes and no new inserts. gap .  .  . S-­‐‑lock!
  • 34. what is a gap lock? • A lock on a painting locks the “space” before the painting. • The gap lock prevents inserts of new paintings before the locked painting (within the space). • This happens automatically, to prevent “phantom reads”—i.e. the view of data changes during a transaction.
  • 35. what is a gap lock? • Exception: if the art critic is okay with seeing the latest additions among the paintings, he can choose to use the READ COMMITTED transaction isolation level. • Another exception: no gap lock is needed for a UNIQUE or PRIMARY KEY index.
  • 36. gap locks • Optionally be more permissive about inserts. gap S-­‐‑lock! READ   COMMITTED
  • 37. gap locks • Optionally be more permissive about inserts. X-­‐‑lock! S-­‐‑lock! READ   COMMITTED I  don’t  mind
  • 38. traveling exhibit • Some art exhibits move to another museum.
  • 39. installation plans • The curators must keep records of how to install the art, so the show is the same at each museum. Label  all   paintings  on   this  wall  with   “Van  Gogh”
  • 40. installation plans • The curators must keep records of how to install the art, so the show is the same at each museum. Van  Gogh Van  Gogh
  • 41. installation plans • Another painting is added. Van  Gogh Van  Gogh Install  this  in   the  gap  and   label  it   “Lautrec” https://commons.wikimedia.org/wiki/Moulin_Rouge#/media/File:Lautrec_at_the_moulin_rouge_two_women_waltzing_1892.jpg
  • 42. installation plans • Another painting is installed in the gap. Van  Gogh Van  GoghLautrec
  • 43. installation plans • The latter curator commits his installation plans first. Van  Gogh Van  GoghLautrec COMMIT
  • 44. installation plans • Then the first curator commits his installation plans. Van  Gogh Van  GoghLautrec COMMIT
  • 45. traveling exhibit • The exhibit is installed in the second museum.
  • 46. order matters • The installation instructions are carried out in the wrong order! Install  this  in   the  gap  and   label  it   “Lautrec”
  • 47. order matters • The installation instructions are carried out in the wrong order! Lautrec Label  all   paintings  on   this  wall  with   “Van  Gogh”
  • 48. order matters • The installation instructions are carried out in the wrong order! Van  GoghVan  Gogh Van  Gogh
  • 49. what happened? • Installation instructions are recorded in the order they were committed, not the order they were originally done. • Therefore the installation at the next museum may repeat the steps in an incorrect order.
  • 50. how to solve this? • Labeling “Van Gogh” should have first locked all the spaces on that wall. Van  Gogh Van  Gogh gap
  • 51. how to solve this? • The addition would be forced to wait for the locks to be released. Van  Gogh Van  Gogh gap …
  • 53. insert intention locks • One curator wants to update paintings where year > 1886 X-­‐‑lock! gap
  • 54. insert intention locks • The second curator wants to insert an 1887 painting, but it would fall within the existing gap lock. X-­‐‑lock! … gap
  • 55. insert intention locks ---TRANSACTION 32070411, ACTIVE 6 sec inserting mysql tables in use 1, locked 1 LOCK WAIT 2 lock struct(s), heap size 360, 1 row lock(s), undo log entries 1 MySQL thread id 26, OS thread handle 0x7f2ba845f700, query id 1423 192.168.50.1 root update insert into Museum (year) values (1887) ------- TRX HAS BEEN WAITING 6 SEC FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 3337 page no 4 n bits 72 index `year` of table `test`.`Museum` trx id 32070411 lock_mode X insert intention waiting
  • 56. insert intention locks • But if the first curator doesn’t care about new paintings entering his view… X-­‐‑lock! gap READ   COMMITTED
  • 57. insert intention locks • Then the second curator gets an insert intention lock, and is then free to insert. insert-­‐‑ lock! gap X-­‐‑lock! READ   COMMITTED I  don’t  mind
  • 58. insert intention locks • Then the second curator gets an insert intention lock, and is then free to insert. X-­‐‑lock!X-­‐‑lock! READ   COMMITTED I  don’t  mind
  • 59. what is an insert intention lock? • A special kind of gap lock, requested before a client tries to insert a row. • Insert locks are shared, not exclusive—multiple clients can acquire insert locks on the same gap. • But insert locks conflict with other exclusive locks.
  • 60. why is insert intention lock shared? • Multiple clients prepare to insert into the same gap. • They may be inserting different rows within the same gap, so they don’t conflict with each other. • But the insert intention lock blocks other clients from requesting exclusive locks on the same gap.
  • 62. auto-inc locks • Two curators are installing paintings. They both need to post a unique number for self-guided tours. ? ?
  • 63. auto-inc locks • There must be one number generator per table. • One curator at a time can request the next value. http://www.istockphoto.com/photo/ticket-­‐‑dispenser-­‐‑isolated-­‐‑9396862
  • 64. auto-inc locks • The first curator gets a number. auto-­‐‑inc! 1 …
  • 65. auto-inc locks • As soon as the first curator gets his number, the second curator can proceed. 1 2 auto-­‐‑inc!
  • 66. auto-inc locks • They may both keep locks on the paintings, but they’re done allocating numbers. X-­‐‑lock! 1 2 X-­‐‑lock!
  • 67. what is an auto-inc lock? • A table lock, used when a client requests the next unique id for a given table. • Ensures that each id is given to one client. • Brief—it is released as soon as the id is generated, instead of lasting to the end of the transaction like other locks. • Because the lock is so brief, neither client can “undo”— i.e. they cannot return their id to the stack for someone else to use.
  • 69. deadlocks • Two curators are updating the art, but they start from different ends of the collection. X-­‐‑lock!X-­‐‑lock!
  • 70. deadlocks • A curator requests a lock on the second painting, which is already locked. He waits. X-­‐‑lock!X-­‐‑lock! …
  • 71. deadlocks • The other curator requests a lock on the first painting, which is already locked. He also waits. X-­‐‑lock!X-­‐‑lock! … …
  • 72. deadlocks • Neither will give up the lock they have, so they are doomed to wait until one or both of them dies. X-­‐‑lock! X-­‐‑lock! … …
  • 73. what is a deadlock? • When two or more concurrent clients wait for each other to release their locks, but since they are both waiting, they will never give up the lock they have. • In other words, a “catch-22” of lock-waits. • Many people use the term “deadlock” incorrectly— when they are describing a simple one-way lock wait.
  • 74. resolving deadlocks • MySQL detects cycles in lock waits, and kills one of the transactions immediately. X-­‐‑lock!X-­‐‑lock! … …
  • 75. resolving deadlocks • MySQL detects cycles in lock waits, and automatically kills one of the transactions. X-­‐‑lock! X-­‐‑lock!
  • 76. avoiding deadlocks • All clients request locks in the same order. X-­‐‑lock! … X-­‐‑lock!
  • 77. avoiding deadlocks • Each client locks everything they need in one atomic request. X-­‐‑lock! …
  • 79. read committed all the things? • Yes … and no. • READ COMMITTED avoids gap locks, therefore reduces lock waits and allows greater throughput. • But using READ COMMITTED allows more cases where you could get deadlocks.
  • 80. thank you • I hope your trip to the museum was educational!
  • 81. license and copyright Copyright 2015-2016 Bill Karwin http://www.slideshare.net/billkarwin Released under a Creative Commons 3.0 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ You are free to share—to copy, distribute, and transmit this work, under the following conditions: Attribution. You  must  attribute  this   work  to  Bill  Karwin. Noncommercial. You  may  not  use  this   work  for  commercial   purposes. No  Derivative  Works. You may  not  alter,   transform,  or  build  upon   this  work.