SlideShare a Scribd company logo
1
Confidential
Deadlocks in SQL: Turning Fear into
Understanding
Nov 20, 2024
2
Confidential
About me…
• Lead Java Engineer at GlobalLogic
• Overall experience: 11 years
• Has hands-on experience with SQL/NoSQL
DBs
• AWS certified
• Java certified
• Trusted interviewer
3
Confidential
Agenda
• Deadlock definition
• Reasons why deadlocks occur
• Type of SQL locks
• Configuration
• Monitoring
• How to read deadlock dump information
• Deadlock prevention techniques
• Practical examples (demo)
• Q/A
4
Confidential
What is a deadlock?
Deadlock occurs when two or more
tasks permanently block each other
by each task having a lock on a
resource that the other tasks are
trying to lock
5
Confidential
Deadlocks in real life
Driving test question My typical day in Kyiv
* gridlock 1 * gridlock 2
6
Confidential
How does deadlock detection works?
There is a process that automatically detects
when a deadlock occurs, and automatically rolls
back one of the transactions involved
(the victim).
deadlock victim
7
Confidential
How does the engine pick the victim?
InnoDB automatically detects transaction deadlocks and rolls back a transaction or
transactions to break the deadlock. InnoDB tries to pick small transactions to roll
back.
The size of a transaction is based on factors like:
• The number of rows modified by the transaction.
• The amount of undo log space used by the transaction.
8
Confidential
Why developers don’t like deadlocks?
Because…
9
Confidential
Are deadlocks dangerous?
“Deadlocks are a classic problem in transactional
databases, but they are not dangerous unless they
are so frequent that you cannot run certain
transactions at all. Normally, you must write your
applications so that they are always prepared to re-
issue a transaction if it gets rolled back because of a
deadlock.” MySQL Reference Manual
So, always be prepared to re-issue a transaction if it
fails due to deadlock. Deadlocks are not dangerous.
Just try again.
10
Confidential
When a deadlock may occur?
“A deadlock can occur when transactions lock rows in multiple tables, but in the
opposite order.
A deadlock can also occur when such statements lock ranges of index records
and gaps, with each transaction acquiring some locks but not others due to a
timing issue.”
MySQL Reference Manual
11
Confidential
What are locks?
Locks in InnoDB provide fine-grained
concurrency control while maintaining
transactional consistency and isolation
across multiple simultaneous transactions.
12
Confidential
Types of locks (InnoDB)
• Record Lock (Row lock): Locks a single row.
• Table Locks: Shared or exclusive locks at the table level.
• Gap Lock: Locks the gap between index records to prevent
inserts.
• Next-Key Lock: A combination of a record lock and a gap lock.
• Auto-Increment Lock: Manages auto-increment values for
inserts.
• Intention Locks (IS/IX): Signals intention to acquire shared
or exclusive row-level locks.
• Insert Intention Lock: Used when inserting rows into a gap.
13
Confidential
How to minimize and handle deadlocks?
1. Do not use DBs
2. Do proper configuration
3. Do proper monitoring
4. Keep you transactions as small as possible
5. Controll the order of your operations
6. Do retries
7. Use less lockings
14
Confidential
Configuration
15
Confidential
Configuration (innodb_print_all_deadlocks)
Fortunately, from mysql 5.5.30 there is a
setting
called innodb_print_all_deadlocks that
helps printing out all deadlocks into mysql
error log. Enabling this does not cause any
downtime.
Note, a simple SHOW ENGINE INNODB
STATUS it shows only the latest deadlock,
which is not very helpful to feel the whole
picture of deadlocks across a period of time.
16
Confidential
Configuration (innodb_deadlock_detect)
This option is used to disable deadlock
detection. On high concurrency systems,
deadlock detection can cause a slowdown
when numerous threads wait for the same
lock. At times, it may be more efficient to
disable deadlock detection and rely on the
innodb_lock_wait_timeout setting for
transaction rollback when a deadlock occurs.
17
Confidential
Monitorin
g
18
Confidential
Monitoring with AWS Cloud Watch
19
Confidential
Troubleshooting
20
Confidential
Useful queries (see latest deadlock)
SHOW ENGINE INNODB STATUS
------------------------
LATEST DETECTED DEADLOCK
------------------------
2024-09-11 07:00:10 22964724647680
*** (1) TRANSACTION:
TRANSACTION 4695804883, ACTIVE 0 sec inserting
Displays operational information about a storage engine, including information about the
latest deadlock.
21
Confidential
How to read deadlock dumps?
What it gives What’s really important
22
Confidential
Useful queries (get all active locks)
select,
ENGINE_TRANSACTION_ID,
THREAD_ID,
LOCK_TYPE,
LOCK_MODE,
LOCK_STATUS,
LOCK_DATA
from performance_schema.data_locks;
23
Confidential
Tips: Adding comments to your SQLs will safe your time
Marking each SQL query with the unique readable comment will help you to find the needed
query fast.
In case you are using JPA:
Use @Meta annotation Enable comments
24
Confidential
Tips: How to reproduce a deadlock?
Switch to manual transaction
mode
START TRANSACTION (BEGIN);
…
COMMIT;
ROLLBACK;
IDE build-in
feature
Use SQL syntax
25
Confidential
Fixing
26
Confidential
Tips: use @Retryable
pom.xml
27
Confidential
@Retryable testing
28
Confidential
Demo
29
Confidential
Demo
1. Having one table and having 2 opened
session
2. Demonstrate locking (instead of blocking)
3. Demonstrate blocking
4. Show locks
5. Show deadlock dump
6. Show how to fix it (just preserve the order)
Demo 1 – SQL command line
1. Create an small web app
2. Reproduce deadlock
3. Fix deadlock
4. Cover with the test
Demo 2 – Java app
https://github.com/sergeystets/deadlock
30
Confidential
QA
31
Confidential
1. https://kendralittle.com/course/troubleshooting-blocking-and-deadlocks-for-beginners/the-p
roblem-with-deadlocks-2-minutes/
2. https://dev.mysql.com/doc/refman/8.4/en/innodb-locking.html
3. https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlock-detection.html
4. https://medium.com/@vmoulds01/springboot-retry-random-backoff-136f41a3211a
5. https://dev.to/eyo000000/a-straightforward-guide-for-mysql-locks-56i1
6. https://aws.amazon.com/blogs/database/monitor-errors-in-amazon-aurora-mysql-and-amaz
on-rds-for-mysql-using-amazon-cloudwatch-and-send-notifications-using-amazon-sns/
Links
32
Confidential
Jokes I found while preparing this presentation…
33
Confidential
Thank
You
Ad

More Related Content

Similar to Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets) (20)

Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash Safety
Jean-François Gagné
 
ch16
ch16ch16
ch16
KITE www.kitecolleges.com
 
Database concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal OlierDatabase concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal Olier
sqlserver.co.il
 
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
 
Troubleshooting Deadlocks in SQL Server 2000
Troubleshooting Deadlocks in SQL Server 2000Troubleshooting Deadlocks in SQL Server 2000
Troubleshooting Deadlocks in SQL Server 2000
elliando dias
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
Aaron Hnatiw
 
MySQL Parallel Replication: inventory, use-cases and limitations
MySQL Parallel Replication: inventory, use-cases and limitationsMySQL Parallel Replication: inventory, use-cases and limitations
MySQL Parallel Replication: inventory, use-cases and limitations
Jean-François Gagné
 
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UKStorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS
 
MySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspectiveMySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspective
Ulf Wendel
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Running Galera Cluster on Microsoft Azure
Running Galera Cluster on Microsoft AzureRunning Galera Cluster on Microsoft Azure
Running Galera Cluster on Microsoft Azure
Codership Oy - Creators of Galera Cluster
 
MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014)
Frazer Clement
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
ashish61_scs
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
ashish61_scs
 
Locks
LocksLocks
Locks
Vu Tran
 
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
 
2-ZeroLab_blockchain_dev_essentials-1608.pptx
2-ZeroLab_blockchain_dev_essentials-1608.pptx2-ZeroLab_blockchain_dev_essentials-1608.pptx
2-ZeroLab_blockchain_dev_essentials-1608.pptx
ClaudioTebaldi2
 
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Bob Pusateri
 
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
 
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Severalnines
 
Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash Safety
Jean-François Gagné
 
Database concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal OlierDatabase concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal Olier
sqlserver.co.il
 
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
 
Troubleshooting Deadlocks in SQL Server 2000
Troubleshooting Deadlocks in SQL Server 2000Troubleshooting Deadlocks in SQL Server 2000
Troubleshooting Deadlocks in SQL Server 2000
elliando dias
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
Aaron Hnatiw
 
MySQL Parallel Replication: inventory, use-cases and limitations
MySQL Parallel Replication: inventory, use-cases and limitationsMySQL Parallel Replication: inventory, use-cases and limitations
MySQL Parallel Replication: inventory, use-cases and limitations
Jean-François Gagné
 
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UKStorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS, Storage for Containers Shouldn't Be Annoying at Container Camp UK
StorageOS
 
MySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspectiveMySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspective
Ulf Wendel
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014)
Frazer Clement
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
ashish61_scs
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
ashish61_scs
 
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
 
2-ZeroLab_blockchain_dev_essentials-1608.pptx
2-ZeroLab_blockchain_dev_essentials-1608.pptx2-ZeroLab_blockchain_dev_essentials-1608.pptx
2-ZeroLab_blockchain_dev_essentials-1608.pptx
ClaudioTebaldi2
 
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Bob Pusateri
 
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
 
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Webinar slides: 9 DevOps Tips for Going in Production with Galera Cluster for...
Severalnines
 

More from GlobalLogic Ukraine (20)

GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Ukraine
 
Ad

Recently uploaded (20)

DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
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
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
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
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
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
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
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
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
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
 
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.
 
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
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
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
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
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
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
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
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
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
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
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
 
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.
 
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
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Ad

Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)

Editor's Notes

  • #1: Дякую Ірино. Вітаю колеги, дякую усім, що приєднались. Тема у нас сьогодні цікава, хоч і складна. Буду розповідати про дедлоки в SQL. I як обіціяє сам title презитнації я намагатимусь позбавити страхів стосовно дедлоків, та надам достатньо інформації для розуміння.
  • #2: Класичний слайд про мене…Хто я такий? шо я тут роблю? I чого це мене потрібно взагалі слухати? На даному етапі я лід в компанії GlobalLogic. Я iз тих лідів, що не тільки люблять тасочки роздать а й трохи покодити. Вважаю себе більше технічною людиной, аніж людиною-менеджером. Але якщо треба щось порішать з точки зору менеджменту, то мені здається, що це в мене також виходить. Загалом якщо взяти, то у IT сфері з 2013, починав як trainee. Тому я звичайно знаю такі страшні слова як web.xml, jsp, servlet-и, скреплети. Увійшов в IT, коли це ще не було mainstream-м. Маю наразі AWS сертифікацію. Сертифікацію по джаві. Також є трастид інтервьюером. Провожду інтервью для зовнішніх та внутрішніх кандидатів.
  • #3: Agenda... Про що ми сьогодні поговоримо? 1. Що таке делок 2. причини дедлоків 3. локи 4. конфігурація 5. монітронг 6. що таке sql dump, як його читати 7. deadlock prevention technics 8. приклади делоків у вигляді демо 9. секція q/a, де можна і треба задавати мені питтаня.
  • #4: Дедлок виникає тоді, коли два якихось різних потоки (thread-a) перехресно хочуть заволодіти двома різніими обьєктами (чи ресурсами). При тому, перший thread володіє першим обєктом і бажає отримати другой обєкт, а другий thread володіє другим обєктом і бажає володіти першим. І ніхто не хоче поступатися.
  • #5: Чи трапляються дедлоки в реальному житті? Відповідь – так, звичайно. Перший малюнок (ліворуч), ви могли потенційно бачити, якщо готувались до екзамену по (правилам дорожнього руху) ПДР. Ну це якщо ви здавали цей екзамен. Бо в цілому бути водієм і вчити ПДР, то різні речі  Для тих, кто не памятає, то на нерегульованому перехресті у нас діє правило перешкода праворуч. Але в данній ситцації у кожного є така парешкода, тому ми знаходимось у deadlock ситацїї. Яке ж тоді вирішення? Хтось має бути першим, а хтось останнім. Ну а стосовно другої картини, то тут рішення ніякого немає, бо це Київ. Київ це пробки. Просто чекаєш в пробках  Що це за ранок без пробок у Києві? В реальному житті таку ситуацію с трафіком не називають deadlock, a викорстовують спецальний термін: англійскьою він звучить gridlock (або “затор” українською). Grid lock (image with the cars) - https://en.wikipedia.org/wiki/Gridlock
  • #6: Повернімося до баз даних. В базах даних є процес який автоматично виявляє дедлоки і вирішує їх (resolve-ть). Яким чином? Процес обирає одну із транзакцій і відкатує її (rollback), таку транзакцію називають deadlock victim (або жертва). https://dev.mysql.com/doc/refman/8.4/en/glossary.html#glos_deadlock_detection
  • #7: Яким чином MySQL InnoDB engine обираю собі жертву? Тобто яка саме тразанкція продовже виконання, а яка буде затермінована? InnoDB обирає найменшу транзакцію. Розмір визначається кількістю рядків, які ми всталяємо, апдейтимо чи видаляємо, а також розміром undo log-a, який викростовує транзакція. https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlock-detection.html
  • #8: Чому розробники побоюються deadlock-ів. ....Тому що :) Якісь причини точно є, наприклад 1. Вони не розуміють чи deadlock це поломка, чи expected behaviour. Чи це погано? Здається, що погано, але наскільки? 2. Не розуміють, як моніторити 3. Як траблшутити/репродюстити 4. Як фіксити https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks-handling.html
  • #9: Що нам каже документація? Дедлоки це страшно чи ні? Каже, що дедлоки це класина проблема системю які мають справу з транзакціями. Вони не є небезпечними, до тих пір поки це не впливає на вашу апку. В цілому, ви повинні завжди бути гото https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks-handling.html
  • #10: Коли може виниктути дедлок? Він може виниктути як уже було сказано в момент, коли різні траназакції блокують рядки в таблиці або в таблицях але у протилежному порядку. (я покажу вам це на прикладі під час демо). Також дедлок може виниктиту коли транзакції блокуть діапазаони знову ж таки в протилежному порядку. Тут я виділив пару ключових слів, серед яких є lock (блокування). https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks.html
  • #11: Ну і перед тим як йти далі, було б непогано згадати, що таке взагалі locks (локи), для чого вони потрібні. Локи потрібні для того, щоб гарантувати consistency (цілісність) та isolation (ізоляцію), що є частинию принципів ACID (atomacy, consistency, isolation, durability), яким слідує RDBMS. Хоча ACID необмежена RDBMS і може застосовуватись до любої системи, що працює з транзакціями. Links: https://dev.mysql.com/doc/refman/8.4/en/innodb-locking.html Gap locks deadlock - https://www.youtube.com/watch?v=vYQXpvy1Nm4&ab_channel=RoelVandePaar
  • #12: Record Lock (Блокування рядка): Це блокування застосовується до конкретного рядка у таблиці. Використовується для запобігання одночасного доступу до одного й того ж рядка під час транзакцій. Table Locks (Блокування таблиці): Застосовується на рівні всієї таблиці. Може бути спільним (shared) або ексклюзивним (exclusive): Спільне: дозволяє одночасне читання таблиці. Ексклюзивне: блокує всі операції, окрім тієї, що встановила блокування. Gap Lock Блокує проміжки між записами у індексі, щоб запобігти вставкам у ці проміжки. Використовується для забезпечення узгодженості (consistency) у транзакціях, які потребують повторюваного читання (REPEATABLE READ). Наприклад, якщо транзакція читає певний діапазон даних, Gap Lock гарантує, що нові записи в цей діапазон не будуть вставлені до завершення транзакції. Next-Key Lock: Це комбінація Record Lock та Gap Lock. Блокує рядок і проміжок перед ним, щоб запобігти вставкам, які могли б порушити порядок у індексі. Використовується для запобігання фантомним читанням (phantom reads). Auto-Increment Lock Управляє значенням автоінкременту під час вставки нових рядків. Забезпечує унікальність і правильний порядок згенерованих значень. Це глобальне блокування, яке діє на всю таблицю. Intention Locks (Інтенційні блокування IS/IX): Це сигнали про намір отримати спільне або ексклюзивне блокування на рівні рядків. IS (Intention Shared): транзакція планує отримати спільне блокування на окремих рядках. IX (Intention Exclusive): транзакція планує отримати ексклюзивне блокування на окремих рядках. Ці блокування працюють на рівні таблиці та сигналізують про можливі дії, дозволяючи уникнути конфліктів при блокуваннях рядків. Insert Intention Lock (Блокування наміру вставки): Використовується під час вставки нового рядка у таблицю. Блокує проміжок, але не для читання чи оновлення, а щоб запобігти конфлікту між кількома транзакціями, які вставляють у той самий проміжок. Interesting fact: It is not recommended to mix locking statements (UPDATE, INSERT, DELETE, or SELECT ... FOR ...) with non-locking SELECT statements in a single REPEATABLE READ transaction, because typically in such cases you want SERIALIZABLE. This is because a non-locking SELECT statement presents the state of the database from a read view which consists of transactions committed before the read view was created, and before the current transaction's own writes, while the locking statements use the most recent state of the database to use locking. In general, these two different table states are inconsistent with each other and difficult to parse. Links: https://dev.to/eyo000000/a-straightforward-guide-for-mysql-locks-56i1
  • #13: https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks-handling.html То як хендлити дедлоки? Перший пункт не викорстовувати базу даних. Напевно, він нам не підходить. Якщо без жартів. То перший пункт, я би сказав, це зрозумiти, чи є проблема взагалі. Для цього нам потрібно правильно сконфiгурувати базу даних, щоб мати можливість отримувати детальну iнформацiю про deadlocks. Також нам потрібно налаштувати монiторiнг та alerting. Стосовно того, як зменишити появу дедлоків, то тут рекомендують, звертати уваги на порядок ваших операцій, бути готовим до того, що траназкцію потрібно повторити, в деяках випадках використовувати менше блокувань.
  • #16: https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlock-detection.html https://medium.com/geekculture/how-to-deal-with-deadlocks-in-mysql-58f4d830788b https://aws.amazon.com/blogs/database/monitor-errors-in-amazon-aurora-mysql-and-amazon-rds-for-mysql-using-amazon-cloudwatch-and-send-notifications-using-amazon-sns/ This option is used to disable deadlock detection. On high concurrency systems, deadlock detection can cause a slowdown when numerous threads wait for the same lock. At times, it may be more efficient to disable deadlock detection and rely on the innodb_lock_wait_timeout setting for transaction rollback when a deadlock occurs. (https://dev.mysql.com/doc/refman/8.4/en/innodb-parameters.html#sysvar_innodb_deadlock_detect)
  • #18: https://aws.amazon.com/blogs/database/monitor-errors-in-amazon-aurora-mysql-and-amazon-rds-for-mysql-using-amazon-cloudwatch-and-send-notifications-using-amazon-sns/
  • #20: https://dev.mysql.com/doc/refman/8.4/en/show-engine.html
  • #21: https://severalnines.com/blog/understanding-deadlocks-mysql-postgresql/ https://medium.com/geekculture/how-to-deal-with-deadlocks-in-mysql-58f4d830788b Коли я вперше побачив перед собою такий дамп, я не зовсім чітко розумів, що переді мною, бо він містить досить багато extra інформації, яка скоріше всього не є цінною для вас у плані траблшутінгу. А також цей дамп містить дуже багато незрозумілих слів 
  • #22: https://www.youtube.com/watch?v=-RmrOWNta6Q&ab_channel=BetweenJobs
  • #23: Tips and tricks that are used on our project https://docs.spring.io/spring-data/jpa/docs/3.1.6/reference/html/ Query: <update id="update" parameterType="com.myapp.entity.UpdateUserEntity"> /* myapp.user.update */ UPDATE user SET phone = #{phone} # ... WHERE id = #{id} </update> SQL Dump: *** (1) TRANSACTION: TRANSACTION 450913541522, ACTIVE 0 sec starting index read mysql tables in use 1, locked 1 LOCK WAIT 7 lock structs), heap size 1136, 3 row lock(s), undo log entries 2 MySQL thread id 93608210, OS thread handle 47321957033728, query id 10802490531 10.0.64.165 db updating /* myapp.user.update */ UPDATE user SET phone = #{phone} WHERE id = 42
  • #26: https://www.baeldung.com/spring-retry https://medium.com/@vmoulds01/springboot-retry-random-backoff-136f41a3211a Please remember to include spring-aop for the retry annotation to work.
  • #29: https://www.youtube.com/watch?v=3EwDn9hqgkg&ab_channel=SQLBits DO SLEEP(5); - useful command to emulate hardware slowness Remember a deadlock may occur even if we have the same order of operations but we touch the same table TWICE.
  • #33: Дякую усім за увагу, сподіваюсь, що було корисно, будуть питання, або пропозиції, пишіть на пошту.