SlideShare a Scribd company logo
1 of 58
Download to read offline
Transactions and
Concurrency Control
Patterns
VLAD MIHALCEA
About me
• @Hibernate Developer
• vladmihalcea.com
• @vlad_mihalcea
• vladmihalcea
Google Developers
“We believe it is better to have application
programmers deal with performance problems
due to overuse of transactions as bottlenecks arise,
rather than always coding around
the lack of transactions.”
Spanner: Google’s Globally-Distributed Database - https://static.googleusercontent.com/media/research.google.com/en//archive/spanner-osdi2012.pdf
Database transactions
• Every statement is executed in the context of a transaction
• There are two types of transactions:
• Implicit – auto-commit
• Explicit – BEGIN, COMMIT or ROLLBACK
History of ACID
In SQL-86, there were only three transaction properties:
• Consistency
• Atomicity
• Durability
The Transaction Concept: Virtues and Limitations http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
Atomicity
Atomicity
• Atomicity requires rolling back
• Rolling back requires preventing dirty writes
Dirty Write Anomaly
Consistency
• Moving the database from one valid state to another.
• Constraint checks
• column types
• column length
• column nullability
• foreign key constraints
• unique key constraints
Consistency in CAP – Linearizability
Durability
• Durability ensures that all committed transaction changes become
permanent.
Durability
SQL-92 ACID
• Atomicity
• Consistency
• Isolation
• Durability
Serializability
• Interleaving concurrent transaction statements so that the outcome
is equivalent to a serial execution
Serial execution
Conflict
Dealing with Concurrency
• Avoid it
• VoltDB (in-memory, single-threaded, guarantees Serializability)
• Control it
• RDBMS (Concurrency Control and isolation levels)
Dealing with conflicts in RDBMS
• Conflict avoidance
• 2PL (Two-Phase Locking)
• Conflict detection
• MVCC (Multi-Version Concurrency Control)
Lock types
Compatibility matrix Shared Lock Exclusive lock
Shared Lock Allow Prevent
Exclusive lock Prevent Prevent
2PL
• Simple to reason about:
• Reads acquire shared locks
• Writes acquire exclusive locks
• The 2PL protocol:
• expanding phase (acquire locks, release no lock)
• shrinking phase (release all locks, no further lock acquisition)
Cost of locking
Challenges have changed
“At present [1981], the largest airlines and
banks have about 10,000 terminals and about
100 active transactions at any instant.
These transactions live for a second or two and are
gone forever.”
The Transaction Concept: Virtues and Limitations - http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
MVCC
• Readers don’t block writers and writers don’t block readers.
• Writers block writers to prevent Dirty Writes.
MVCC – Insert row (PostgreSQL)
MVCC – Delete row (PostgreSQL)
MVCC – Update row (PostgreSQL)
MVCC
• Two types of snapshots:
• Query-level: Read Committed
• Transaction-level: Snapshot Isolation
• Watch out for long-running transactions
Phenomena
• The SQL-92 standard introduced three phenomena:
• dirty read
• non-repeatable read
• phantom read.
• In reality, there are more:
• dirty write
• read skew
• write skew
• lost update.
Dirty Read
Non-Repeatable Read
Phantom Read
Read Skew
Write Skew
Lost Update
2PL – Phantom Read
MVCC – Phantom Read
MVCC – Phantom Read?
SQL Standard Isolation Levels
Isolation
Level Dirty Read
Non-
Repeatable
Read
Phantom
Read
Read
Uncommitted Yes Yes Yes
Read
Committed No Yes Yes
Repeatable
Read No No Yes
Serializable No No No
Oracle Isolation Levels
Isolation
Level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Committed No Yes Yes Yes Yes Yes
Serializable No No No No Yes No
SQL Server Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted Yes Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No Yes No No No
Serializable No No No No No No
Read
Committed SI No Yes Yes Yes Yes Yes
Snapshot
Ioslation No No No No Yes No
PostgreSQL Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted No Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No No No Yes No
Serializable No No No No No No
MySQL Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted Yes Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No No No Yes Yes
Serializable No No No No No No
Beyond ACID
• ACID is not sufficient
• What about multi-request logical transactions?
Stateless conversation lost update
Stateful conversation lost update
Version-based optimistic locking
@Version
private int version;
UPDATE post
SET
name = ‘Name’, version = 1
WHERE
id = 1 AND version = 0
Stateful versioned conversation
Write concerns
False positives
Write-based schema mapping
Non-overlapping writes
Versionless optimistic locking
@Entity
@Table(name = "post")
@DynamicUpdate
@OptimisticLocking(type = OptimisticLockType.DIRTY)
public class Post {
@Id
private Long id;
private String title;
private long views;
private int likes;
}
Non-overlapping writes
Explicit optimistic locking modes
Lock Mode Type Description
NONE In the absence of explicit locking, the application will use implicit locking (optimistic or pessimistic)
OPTIMISTIC
Always issues a version check upon transaction commit, therefore ensuring optimistic locking
repeatable reads.
READ Same as OPTIMISTIC.
OPTIMISTIC_FORCE_INCREMENT
Always increases the entity version (even when the entity doesn’t change) and issues a version
check upon transaction commit, therefore ensuring optimistic locking repeatable reads.
WRITE Same as OPTIMISTIC_FORCE_INCREMENT.
PESSIMISTIC_READ
A shared lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_WRITE
lock.
PESSIMISTIC_WRITE
An exclusive lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ
or a PESSIMISTIC_WRITE lock.
PESSIMISTIC_FORCE_INCREMENT
A database lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or
a PESSIMISTIC_WRITE lock and the entity version is incremented upon transaction commit.
LockModeType.OPTIMISTIC_FORCE_INCREMENT
LockModeType.OPTIMISTIC_FORCE_INCREMENT
Repository repository = entityManager.find(Repository.class, 1L,
LockModeType.OPTIMISTIC_FORCE_INCREMENT);
executeSync(() -> {
doInJPA(_entityManager -> {
Repository _repository = _entityManager.find(Repository.class, 1L,
LockModeType.OPTIMISTIC_FORCE_INCREMENT);
Commit _commit = new Commit(_repository);
_commit.getChanges().add(new Change("Intro.md", "0a1,2..."));
_entityManager.persist(_commit);
});
});
Commit commit = new Commit(repository);
commit.getChanges().add(new Change("FrontMatter.md", "0a1,5..."));
commit.getChanges().add(new Change("HibernateIntro.md", "17c17..."));
entityManager.persist(commit);
LockModeType.OPTIMISTIC_FORCE_INCREMENT
Thank you
Questions and Answers

More Related Content

What's hot

Infinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
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
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...Malin Weiss
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormOrtus Solutions, Corp
 
A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVMAlex Birch
 
/path/to/content - the Apache Jackrabbit content repository
/path/to/content - the Apache Jackrabbit content repository/path/to/content - the Apache Jackrabbit content repository
/path/to/content - the Apache Jackrabbit content repositoryJukka Zitting
 
REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologiesjrodbx
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...J V
 
Java SE 7 New Features and Enhancements
Java SE 7 New Features and EnhancementsJava SE 7 New Features and Enhancements
Java SE 7 New Features and EnhancementsFu Cheng
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016Vlad Mihalcea
 
OSGifying the repository
OSGifying the repositoryOSGifying the repository
OSGifying the repositoryJukka Zitting
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLiteJEAN-GUILLAUME DUJARDIN
 
Stardog 1.1: An Easier, Smarter, Faster RDF Database
Stardog 1.1: An Easier, Smarter, Faster RDF DatabaseStardog 1.1: An Easier, Smarter, Faster RDF Database
Stardog 1.1: An Easier, Smarter, Faster RDF Databasekendallclark
 
Alfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursAlfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursJ V
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content RepositoriesCarsten Ziegeler
 
Design and architecture of Jackrabbit
Design and architecture of JackrabbitDesign and architecture of Jackrabbit
Design and architecture of JackrabbitJukka Zitting
 

What's hot (19)

Infinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORM
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
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...
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cborm
 
A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVM
 
/path/to/content - the Apache Jackrabbit content repository
/path/to/content - the Apache Jackrabbit content repository/path/to/content - the Apache Jackrabbit content repository
/path/to/content - the Apache Jackrabbit content repository
 
REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologies
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 
Java SE 7 New Features and Enhancements
Java SE 7 New Features and EnhancementsJava SE 7 New Features and Enhancements
Java SE 7 New Features and Enhancements
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
Jakarta EE 8 on JDK17
Jakarta EE 8 on JDK17Jakarta EE 8 on JDK17
Jakarta EE 8 on JDK17
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016
 
OSGifying the repository
OSGifying the repositoryOSGifying the repository
OSGifying the repository
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLite
 
Stardog 1.1: An Easier, Smarter, Faster RDF Database
Stardog 1.1: An Easier, Smarter, Faster RDF DatabaseStardog 1.1: An Easier, Smarter, Faster RDF Database
Stardog 1.1: An Easier, Smarter, Faster RDF Database
 
Alfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursAlfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy Behaviours
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content Repositories
 
Design and architecture of Jackrabbit
Design and architecture of JackrabbitDesign and architecture of Jackrabbit
Design and architecture of Jackrabbit
 

Viewers also liked

High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016Vlad Mihalcea
 
High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016Vlad Mihalcea
 
Navigating the Incubator at the Apache Software Foundation
Navigating the Incubator at the Apache Software FoundationNavigating the Incubator at the Apache Software Foundation
Navigating the Incubator at the Apache Software FoundationBrett Porter
 
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!CodeFest
 
Вебинар начало
Вебинар началоВебинар начало
Вебинар началоcatarus
 
Осознанность рефакторинга: Модель принятия инженерных решений
Осознанность рефакторинга: Модель принятия инженерных решенийОсознанность рефакторинга: Модель принятия инженерных решений
Осознанность рефакторинга: Модель принятия инженерных решенийEvgeniy Krivosheev
 
[Altibase] 6 what is the mvcc
[Altibase] 6 what is the mvcc[Altibase] 6 what is the mvcc
[Altibase] 6 what is the mvccaltistory
 
Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesEr. Gaurav Kumar
 
Введение в веб каркас Struts2
Введение в веб каркас Struts2Введение в веб каркас Struts2
Введение в веб каркас Struts2Evgeniy Krivosheev
 
Developing With JAAS
Developing With JAASDeveloping With JAAS
Developing With JAASrahmed_sct
 
Mv unmasked.w.code.march.2013
Mv unmasked.w.code.march.2013Mv unmasked.w.code.march.2013
Mv unmasked.w.code.march.2013EDB
 
Locking unit 1 topic 3
Locking unit 1 topic 3Locking unit 1 topic 3
Locking unit 1 topic 3avniS
 
Building Rich Domain Models
Building Rich Domain ModelsBuilding Rich Domain Models
Building Rich Domain ModelsChris Richardson
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
Transaction and concurrency control
Transaction and concurrency controlTransaction and concurrency control
Transaction and concurrency controlAnil Shrestha
 
Pagination Done the Right Way
Pagination Done the Right WayPagination Done the Right Way
Pagination Done the Right WayMarkus Winand
 
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlPostgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlReactive.IO
 

Viewers also liked (20)

High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016
 
High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016
 
Navigating the Incubator at the Apache Software Foundation
Navigating the Incubator at the Apache Software FoundationNavigating the Incubator at the Apache Software Foundation
Navigating the Incubator at the Apache Software Foundation
 
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
 
Вебинар начало
Вебинар началоВебинар начало
Вебинар начало
 
Tdd Workshop Disscussions
Tdd Workshop DisscussionsTdd Workshop Disscussions
Tdd Workshop Disscussions
 
Осознанность рефакторинга: Модель принятия инженерных решений
Осознанность рефакторинга: Модель принятия инженерных решенийОсознанность рефакторинга: Модель принятия инженерных решений
Осознанность рефакторинга: Модель принятия инженерных решений
 
Google GIN
Google GINGoogle GIN
Google GIN
 
[Altibase] 6 what is the mvcc
[Altibase] 6 what is the mvcc[Altibase] 6 what is the mvcc
[Altibase] 6 what is the mvcc
 
Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examples
 
Введение в веб каркас Struts2
Введение в веб каркас Struts2Введение в веб каркас Struts2
Введение в веб каркас Struts2
 
Developing With JAAS
Developing With JAASDeveloping With JAAS
Developing With JAAS
 
Mv unmasked.w.code.march.2013
Mv unmasked.w.code.march.2013Mv unmasked.w.code.march.2013
Mv unmasked.w.code.march.2013
 
Locking unit 1 topic 3
Locking unit 1 topic 3Locking unit 1 topic 3
Locking unit 1 topic 3
 
Building Rich Domain Models
Building Rich Domain ModelsBuilding Rich Domain Models
Building Rich Domain Models
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
Hibernate
HibernateHibernate
Hibernate
 
Transaction and concurrency control
Transaction and concurrency controlTransaction and concurrency control
Transaction and concurrency control
 
Pagination Done the Right Way
Pagination Done the Right WayPagination Done the Right Way
Pagination Done the Right Way
 
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlPostgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
 

Similar to Transactions and Concurrency Control Patterns Overview

Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Peter Lawrey
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Fwdays
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon Web Services
 
Cloud Foundry Summit 2015: 12 Factor Apps For Operations
Cloud Foundry Summit 2015: 12 Factor Apps For OperationsCloud Foundry Summit 2015: 12 Factor Apps For Operations
Cloud Foundry Summit 2015: 12 Factor Apps For OperationsVMware Tanzu
 
The working architecture of NodeJs applications
The working architecture of NodeJs applicationsThe working architecture of NodeJs applications
The working architecture of NodeJs applicationsViktor Turskyi
 
XPDays Ukraine: Legacy
XPDays Ukraine: LegacyXPDays Ukraine: Legacy
XPDays Ukraine: LegacyVictor_Cr
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency modelsAbid Khan
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID CodeAdil Mughal
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsŁukasz Sowa
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Aaron Hnatiw
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling SoftwareAbdelmonaim Remani
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminarGal Marder
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remanijaxconf
 
AWS Lambda from the Trenches
AWS Lambda from the TrenchesAWS Lambda from the Trenches
AWS Lambda from the TrenchesYan Cui
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systemsBill Buchan
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016Peter Lawrey
 

Similar to Transactions and Concurrency Control Patterns Overview (20)

Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016Microservices for performance - GOTO Chicago 2016
Microservices for performance - GOTO Chicago 2016
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
Cloud Foundry Summit 2015: 12 Factor Apps For Operations
Cloud Foundry Summit 2015: 12 Factor Apps For OperationsCloud Foundry Summit 2015: 12 Factor Apps For Operations
Cloud Foundry Summit 2015: 12 Factor Apps For Operations
 
The working architecture of NodeJs applications
The working architecture of NodeJs applicationsThe working architecture of NodeJs applications
The working architecture of NodeJs applications
 
XPDays Ukraine: Legacy
XPDays Ukraine: LegacyXPDays Ukraine: Legacy
XPDays Ukraine: Legacy
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency models
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
 
NoSQL and ACID
NoSQL and ACIDNoSQL and ACID
NoSQL and ACID
 
Apache Drill (ver. 0.2)
Apache Drill (ver. 0.2)Apache Drill (ver. 0.2)
Apache Drill (ver. 0.2)
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problems
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling Software
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminar
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
 
AWS Lambda from the Trenches
AWS Lambda from the TrenchesAWS Lambda from the Trenches
AWS Lambda from the Trenches
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systems
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016
 

Recently uploaded

定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 

Recently uploaded (20)

定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 

Transactions and Concurrency Control Patterns Overview

  • 2. About me • @Hibernate Developer • vladmihalcea.com • @vlad_mihalcea • vladmihalcea
  • 3. Google Developers “We believe it is better to have application programmers deal with performance problems due to overuse of transactions as bottlenecks arise, rather than always coding around the lack of transactions.” Spanner: Google’s Globally-Distributed Database - https://static.googleusercontent.com/media/research.google.com/en//archive/spanner-osdi2012.pdf
  • 4. Database transactions • Every statement is executed in the context of a transaction • There are two types of transactions: • Implicit – auto-commit • Explicit – BEGIN, COMMIT or ROLLBACK
  • 5. History of ACID In SQL-86, there were only three transaction properties: • Consistency • Atomicity • Durability The Transaction Concept: Virtues and Limitations http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
  • 7. Atomicity • Atomicity requires rolling back • Rolling back requires preventing dirty writes
  • 9. Consistency • Moving the database from one valid state to another. • Constraint checks • column types • column length • column nullability • foreign key constraints • unique key constraints
  • 10. Consistency in CAP – Linearizability
  • 11. Durability • Durability ensures that all committed transaction changes become permanent.
  • 13. SQL-92 ACID • Atomicity • Consistency • Isolation • Durability
  • 14. Serializability • Interleaving concurrent transaction statements so that the outcome is equivalent to a serial execution
  • 17. Dealing with Concurrency • Avoid it • VoltDB (in-memory, single-threaded, guarantees Serializability) • Control it • RDBMS (Concurrency Control and isolation levels)
  • 18. Dealing with conflicts in RDBMS • Conflict avoidance • 2PL (Two-Phase Locking) • Conflict detection • MVCC (Multi-Version Concurrency Control)
  • 19. Lock types Compatibility matrix Shared Lock Exclusive lock Shared Lock Allow Prevent Exclusive lock Prevent Prevent
  • 20. 2PL • Simple to reason about: • Reads acquire shared locks • Writes acquire exclusive locks • The 2PL protocol: • expanding phase (acquire locks, release no lock) • shrinking phase (release all locks, no further lock acquisition)
  • 22. Challenges have changed “At present [1981], the largest airlines and banks have about 10,000 terminals and about 100 active transactions at any instant. These transactions live for a second or two and are gone forever.” The Transaction Concept: Virtues and Limitations - http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
  • 23. MVCC • Readers don’t block writers and writers don’t block readers. • Writers block writers to prevent Dirty Writes.
  • 24. MVCC – Insert row (PostgreSQL)
  • 25. MVCC – Delete row (PostgreSQL)
  • 26. MVCC – Update row (PostgreSQL)
  • 27. MVCC • Two types of snapshots: • Query-level: Read Committed • Transaction-level: Snapshot Isolation • Watch out for long-running transactions
  • 28. Phenomena • The SQL-92 standard introduced three phenomena: • dirty read • non-repeatable read • phantom read. • In reality, there are more: • dirty write • read skew • write skew • lost update.
  • 38. SQL Standard Isolation Levels Isolation Level Dirty Read Non- Repeatable Read Phantom Read Read Uncommitted Yes Yes Yes Read Committed No Yes Yes Repeatable Read No No Yes Serializable No No No
  • 39. Oracle Isolation Levels Isolation Level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Committed No Yes Yes Yes Yes Yes Serializable No No No No Yes No
  • 40. SQL Server Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted Yes Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No Yes No No No Serializable No No No No No No Read Committed SI No Yes Yes Yes Yes Yes Snapshot Ioslation No No No No Yes No
  • 41. PostgreSQL Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted No Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No No No Yes No Serializable No No No No No No
  • 42. MySQL Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted Yes Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No No No Yes Yes Serializable No No No No No No
  • 43. Beyond ACID • ACID is not sufficient • What about multi-request logical transactions?
  • 46. Version-based optimistic locking @Version private int version; UPDATE post SET name = ‘Name’, version = 1 WHERE id = 1 AND version = 0
  • 52. Versionless optimistic locking @Entity @Table(name = "post") @DynamicUpdate @OptimisticLocking(type = OptimisticLockType.DIRTY) public class Post { @Id private Long id; private String title; private long views; private int likes; }
  • 54. Explicit optimistic locking modes Lock Mode Type Description NONE In the absence of explicit locking, the application will use implicit locking (optimistic or pessimistic) OPTIMISTIC Always issues a version check upon transaction commit, therefore ensuring optimistic locking repeatable reads. READ Same as OPTIMISTIC. OPTIMISTIC_FORCE_INCREMENT Always increases the entity version (even when the entity doesn’t change) and issues a version check upon transaction commit, therefore ensuring optimistic locking repeatable reads. WRITE Same as OPTIMISTIC_FORCE_INCREMENT. PESSIMISTIC_READ A shared lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_WRITE lock. PESSIMISTIC_WRITE An exclusive lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or a PESSIMISTIC_WRITE lock. PESSIMISTIC_FORCE_INCREMENT A database lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or a PESSIMISTIC_WRITE lock and the entity version is incremented upon transaction commit.
  • 56. LockModeType.OPTIMISTIC_FORCE_INCREMENT Repository repository = entityManager.find(Repository.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); executeSync(() -> { doInJPA(_entityManager -> { Repository _repository = _entityManager.find(Repository.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); Commit _commit = new Commit(_repository); _commit.getChanges().add(new Change("Intro.md", "0a1,2...")); _entityManager.persist(_commit); }); }); Commit commit = new Commit(repository); commit.getChanges().add(new Change("FrontMatter.md", "0a1,5...")); commit.getChanges().add(new Change("HibernateIntro.md", "17c17...")); entityManager.persist(commit);