SlideShare a Scribd company logo
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

PDF
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
PPT
Java Persistence API (JPA) - A Brief Overview
ODP
ORM, JPA, & Hibernate Overview
PDF
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASSDC User Gr...
PPT
Orm and hibernate
KEY
Hibernate performance tuning
PPTX
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Hibernate ORM: Tips, Tricks, and Performance Techniques
Java Persistence API (JPA) - A Brief Overview
ORM, JPA, & Hibernate Overview
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASSDC User Gr...
Orm and hibernate
Hibernate performance tuning
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]

What's hot (19)

PDF
Infinum Android Talks #09 - DBFlow ORM
PPTX
Apache Cayenne: a Java ORM Alternative
PDF
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
PPTX
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
PDF
ITB2017 - Slaying the ORM dragons with cborm
PPTX
A tour of Java and the JVM
PPTX
/path/to/content - the Apache Jackrabbit content repository
PPTX
REST Methodologies
PDF
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 
PPT
Java SE 7 New Features and Enhancements
PDF
Scala Frameworks for Web Application 2016
PDF
Jakarta EE 8 on JDK17
PDF
High-Performance Hibernate Devoxx France 2016
PPTX
OSGifying the repository
PDF
PHP, the GraphQL ecosystem and GraphQLite
PDF
Stardog 1.1: An Easier, Smarter, Faster RDF Database
PDF
Alfresco Content Modelling and Policy Behaviours
 
PDF
JCR - Java Content Repositories
PPT
Design and architecture of Jackrabbit
Infinum Android Talks #09 - DBFlow ORM
Apache Cayenne: a Java ORM Alternative
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
ITB2017 - Slaying the ORM dragons with cborm
A tour of Java and the JVM
/path/to/content - the Apache Jackrabbit content repository
REST Methodologies
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 
Java SE 7 New Features and Enhancements
Scala Frameworks for Web Application 2016
Jakarta EE 8 on JDK17
High-Performance Hibernate Devoxx France 2016
OSGifying the repository
PHP, the GraphQL ecosystem and GraphQLite
Stardog 1.1: An Easier, Smarter, Faster RDF Database
Alfresco Content Modelling and Policy Behaviours
 
JCR - Java Content Repositories
Design and architecture of Jackrabbit
Ad

Viewers also liked (20)

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

Similar to Transactions and Concurrency Control Patterns (20)

PDF
Transactions and Concurrency Control Patterns
PPTX
MVCC for Ruby developers
PDF
Database transaction isolation and locking in Java
PPTX
Multi version Concurrency Control and its applications in Advanced database s...
PPT
Svetlin Nakov - Database Transactions
PPTX
Spring@transaction,isolation
PDF
Transactions and Concurrency Control Patterns - 2019
PPT
05 Transactions
PPTX
DBMS UNIT IV.pptx
PPTX
Transaction
PPTX
Transactions in database systems and functions
PDF
Dbms module iii
PPTX
DBMS: Week 13 - Transactions and Concurrency Control
PPTX
Transation in data base management system.pptx
PDF
Transaction Properties(ACID Properties)
ODP
Lecture 5. MS SQL. Transactions
KEY
NoSQL Databases: Why, what and when
PDF
SQL Transactions - What they are good for and how they work
PPT
Hibernate Session 3
PDF
MySQL Overview
Transactions and Concurrency Control Patterns
MVCC for Ruby developers
Database transaction isolation and locking in Java
Multi version Concurrency Control and its applications in Advanced database s...
Svetlin Nakov - Database Transactions
Spring@transaction,isolation
Transactions and Concurrency Control Patterns - 2019
05 Transactions
DBMS UNIT IV.pptx
Transaction
Transactions in database systems and functions
Dbms module iii
DBMS: Week 13 - Transactions and Concurrency Control
Transation in data base management system.pptx
Transaction Properties(ACID Properties)
Lecture 5. MS SQL. Transactions
NoSQL Databases: Why, what and when
SQL Transactions - What they are good for and how they work
Hibernate Session 3
MySQL Overview

Recently uploaded (20)

DOCX
Unit-3 cyber security network security of internet system
PPTX
innovation process that make everything different.pptx
PPTX
Funds Management Learning Material for Beg
PPTX
artificial intelligence overview of it and more
PPTX
SAP Ariba Sourcing PPT for learning material
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PDF
Paper PDF World Game (s) Great Redesign.pdf
PPTX
Introduction to Information and Communication Technology
PPT
Ethics in Information System - Management Information System
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
DOC
Rose毕业证学历认证,利物浦约翰摩尔斯大学毕业证国外本科毕业证
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
PDF
Sims 4 Historia para lo sims 4 para jugar
PPTX
Internet___Basics___Styled_ presentation
Unit-3 cyber security network security of internet system
innovation process that make everything different.pptx
Funds Management Learning Material for Beg
artificial intelligence overview of it and more
SAP Ariba Sourcing PPT for learning material
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
Job_Card_System_Styled_lorem_ipsum_.pptx
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Slides PDF The World Game (s) Eco Economic Epochs.pdf
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
Paper PDF World Game (s) Great Redesign.pdf
Introduction to Information and Communication Technology
Ethics in Information System - Management Information System
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
Rose毕业证学历认证,利物浦约翰摩尔斯大学毕业证国外本科毕业证
SASE Traffic Flow - ZTNA Connector-1.pdf
Power Point - Lesson 3_2.pptx grad school presentation
Sims 4 Historia para lo sims 4 para jugar
Internet___Basics___Styled_ presentation

Transactions and Concurrency Control Patterns

  • 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);