Transaction Restraints

This document briefly introduces the transaction restraints in TiDB.

Isolation levels

The isolation levels supported by TiDB are RC (Read Committed) and SI (Snapshot Isolation), where SI is basically equivalent to the RR (Repeatable Read) isolation level.

isolation level

Snapshot Isolation can avoid phantom reads

The SI isolation level of TiDB can avoid Phantom Reads, but the RR in ANSI/ISO SQL standard cannot.

The following two examples show what phantom reads is.

  • Example 1: Transaction A first gets n rows according to the query, and then Transaction B changes m rows other than these n rows or adds m rows that match the query of Transaction A. When Transaction A runs the query again, it finds that there are n+m rows that match the condition. It is like a phantom, so it is called a phantom read.

  • Example 2: Admin A changes the grades of all students in the database from specific scores to ABCDE grades, but Admin B inserts a record with a specific score at this time. When Admin A finishes changing and finds that there is still a record (the one inserted by Admin B) that has not been changed yet. That is a phantom read.

SI cannot avoid write skew

TiDB’s SI isolation level cannot avoid write skew exceptions. You can use the SELECT FOR UPDATE syntax to avoid write skew exceptions.

A write skew exception occurs when two concurrent transactions read different but related records, and then each transaction updates the data it reads and eventually commits the transaction. If there is a constraint between these related records that cannot be modified concurrently by multiple transactions, then the end result will violate the constraint.

For example, suppose you are writing a doctor shift management program for a hospital. Hospitals typically require several doctors to be on call at the same time, but the minimum requirement is that at least one doctor is on call. Doctors can drop their shifts (for example, if they are feeling sick) as long as at least one doctor is on call during that shift.

Now there is a situation where doctors Alice and Bob are on call. Both are feeling sick, so they decide to take sick leave. They happen to click the button at the same time. Let’s simulate this process with the following program:

  • Java
  • Golang
  1. package com.pingcap.txn.write.skew;
  2. import com.zaxxer.hikari.HikariDataSource;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.concurrent.CountDownLatch;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.Semaphore;
  11. public class EffectWriteSkew {
  12. public static void main(String[] args) throws SQLException, InterruptedException {
  13. HikariDataSource ds = new HikariDataSource();
  14. ds.setJdbcUrl("jdbc:mysql://localhost:4000/test?useServerPrepStmts=true&cachePrepStmts=true");
  15. ds.setUsername("root");
  16. // prepare data
  17. Connection connection = ds.getConnection();
  18. createDoctorTable(connection);
  19. createDoctor(connection, 1, "Alice", true, 123);
  20. createDoctor(connection, 2, "Bob", true, 123);
  21. createDoctor(connection, 3, "Carol", false, 123);
  22. Semaphore txn1Pass = new Semaphore(0);
  23. CountDownLatch countDownLatch = new CountDownLatch(2);
  24. ExecutorService threadPool = Executors.newFixedThreadPool(2);
  25. threadPool.execute(() -> {
  26. askForLeave(ds, txn1Pass, 1, 1);
  27. countDownLatch.countDown();
  28. });
  29. threadPool.execute(() -> {
  30. askForLeave(ds, txn1Pass, 2, 2);
  31. countDownLatch.countDown();
  32. });
  33. countDownLatch.await();
  34. }
  35. public static void createDoctorTable(Connection connection) throws SQLException {
  36. connection.createStatement().executeUpdate("CREATE TABLE `doctors` (" +
  37. " `id` int(11) NOT NULL," +
  38. " `name` varchar(255) DEFAULT NULL," +
  39. " `on_call` tinyint(1) DEFAULT NULL," +
  40. " `shift_id` int(11) DEFAULT NULL," +
  41. " PRIMARY KEY (`id`)," +
  42. " KEY `idx_shift_id` (`shift_id`)" +
  43. " ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin");
  44. }
  45. public static void createDoctor(Connection connection, Integer id, String name, Boolean onCall, Integer shiftID) throws SQLException {
  46. PreparedStatement insert = connection.prepareStatement(
  47. "INSERT INTO `doctors` (`id`, `name`, `on_call`, `shift_id`) VALUES (?, ?, ?, ?)");
  48. insert.setInt(1, id);
  49. insert.setString(2, name);
  50. insert.setBoolean(3, onCall);
  51. insert.setInt(4, shiftID);
  52. insert.executeUpdate();
  53. }
  54. public static void askForLeave(HikariDataSource ds, Semaphore txn1Pass, Integer txnID, Integer doctorID) {
  55. try(Connection connection = ds.getConnection()) {
  56. try {
  57. connection.setAutoCommit(false);
  58. String comment = txnID == 2 ? " " : "" + "/* txn #{txn_id} */ ";
  59. connection.createStatement().executeUpdate(comment + "BEGIN");
  60. // Txn 1 should be waiting for txn 2 done
  61. if (txnID == 1) {
  62. txn1Pass.acquire();
  63. }
  64. PreparedStatement currentOnCallQuery = connection.prepareStatement(comment +
  65. "SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = ? AND `shift_id` = ?");
  66. currentOnCallQuery.setBoolean(1, true);
  67. currentOnCallQuery.setInt(2, 123);
  68. ResultSet res = currentOnCallQuery.executeQuery();
  69. if (!res.next()) {
  70. throw new RuntimeException("error query");
  71. } else {
  72. int count = res.getInt("count");
  73. if (count >= 2) {
  74. // If current on-call doctor has 2 or more, this doctor can leave
  75. PreparedStatement insert = connection.prepareStatement( comment +
  76. "UPDATE `doctors` SET `on_call` = ? WHERE `id` = ? AND `shift_id` = ?");
  77. insert.setBoolean(1, false);
  78. insert.setInt(2, doctorID);
  79. insert.setInt(3, 123);
  80. insert.executeUpdate();
  81. connection.commit();
  82. } else {
  83. throw new RuntimeException("At least one doctor is on call");
  84. }
  85. }
  86. // Txn 2 done, let txn 1 run again
  87. if (txnID == 2) {
  88. txn1Pass.release();
  89. }
  90. } catch (Exception e) {
  91. // If got any error, you should roll back, data is priceless
  92. connection.rollback();
  93. e.printStackTrace();
  94. }
  95. } catch (SQLException e) {
  96. e.printStackTrace();
  97. }
  98. }
  99. }

To adapt TiDB transactions, write a util according to the following code:

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "sync"
  6. "github.com/pingcap-inc/tidb-example-golang/util"
  7. _ "github.com/go-sql-driver/mysql"
  8. )
  9. func main() {
  10. openDB("mysql", "root:@tcp(127.0.0.1:4000)/test", func(db *sql.DB) {
  11. writeSkew(db)
  12. })
  13. }
  14. func openDB(driverName, dataSourceName string, runnable func(db *sql.DB)) {
  15. db, err := sql.Open(driverName, dataSourceName)
  16. if err != nil {
  17. panic(err)
  18. }
  19. defer db.Close()
  20. runnable(db)
  21. }
  22. func writeSkew(db *sql.DB) {
  23. err := prepareData(db)
  24. if err != nil {
  25. panic(err)
  26. }
  27. waitingChan, waitGroup := make(chan bool), sync.WaitGroup{}
  28. waitGroup.Add(1)
  29. go func() {
  30. defer waitGroup.Done()
  31. err = askForLeave(db, waitingChan, 1, 1)
  32. if err != nil {
  33. panic(err)
  34. }
  35. }()
  36. waitGroup.Add(1)
  37. go func() {
  38. defer waitGroup.Done()
  39. err = askForLeave(db, waitingChan, 2, 2)
  40. if err != nil {
  41. panic(err)
  42. }
  43. }()
  44. waitGroup.Wait()
  45. }
  46. func askForLeave(db *sql.DB, waitingChan chan bool, goroutineID, doctorID int) error {
  47. txnComment := fmt.Sprintf("/* txn %d */ ", goroutineID)
  48. if goroutineID != 1 {
  49. txnComment = "\t" + txnComment
  50. }
  51. txn, err := util.TiDBSqlBegin(db, true)
  52. if err != nil {
  53. return err
  54. }
  55. fmt.Println(txnComment + "start txn")
  56. // Txn 1 should be waiting until txn 2 is done.
  57. if goroutineID == 1 {
  58. <-waitingChan
  59. }
  60. txnFunc := func() error {
  61. queryCurrentOnCall := "SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = ? AND `shift_id` = ?"
  62. rows, err := txn.Query(queryCurrentOnCall, true, 123)
  63. if err != nil {
  64. return err
  65. }
  66. defer rows.Close()
  67. fmt.Println(txnComment + queryCurrentOnCall + " successful")
  68. count := 0
  69. if rows.Next() {
  70. err = rows.Scan(&count)
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. rows.Close()
  76. if count < 2 {
  77. return fmt.Errorf("at least one doctor is on call")
  78. }
  79. shift := "UPDATE `doctors` SET `on_call` = ? WHERE `id` = ? AND `shift_id` = ?"
  80. _, err = txn.Exec(shift, false, doctorID, 123)
  81. if err == nil {
  82. fmt.Println(txnComment + shift + " successful")
  83. }
  84. return err
  85. }
  86. err = txnFunc()
  87. if err == nil {
  88. txn.Commit()
  89. fmt.Println("[runTxn] commit success")
  90. } else {
  91. txn.Rollback()
  92. fmt.Printf("[runTxn] got an error, rollback: %+v\n", err)
  93. }
  94. // Txn 2 is done. Let txn 1 run again.
  95. if goroutineID == 2 {
  96. waitingChan <- true
  97. }
  98. return nil
  99. }
  100. func prepareData(db *sql.DB) error {
  101. err := createDoctorTable(db)
  102. if err != nil {
  103. return err
  104. }
  105. err = createDoctor(db, 1, "Alice", true, 123)
  106. if err != nil {
  107. return err
  108. }
  109. err = createDoctor(db, 2, "Bob", true, 123)
  110. if err != nil {
  111. return err
  112. }
  113. err = createDoctor(db, 3, "Carol", false, 123)
  114. if err != nil {
  115. return err
  116. }
  117. return nil
  118. }
  119. func createDoctorTable(db *sql.DB) error {
  120. _, err := db.Exec("CREATE TABLE IF NOT EXISTS `doctors` (" +
  121. " `id` int(11) NOT NULL," +
  122. " `name` varchar(255) DEFAULT NULL," +
  123. " `on_call` tinyint(1) DEFAULT NULL," +
  124. " `shift_id` int(11) DEFAULT NULL," +
  125. " PRIMARY KEY (`id`)," +
  126. " KEY `idx_shift_id` (`shift_id`)" +
  127. " ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin")
  128. return err
  129. }
  130. func createDoctor(db *sql.DB, id int, name string, onCall bool, shiftID int) error {
  131. _, err := db.Exec("INSERT INTO `doctors` (`id`, `name`, `on_call`, `shift_id`) VALUES (?, ?, ?, ?)",
  132. id, name, onCall, shiftID)
  133. return err
  134. }

SQL log:

  1. /* txn 1 */ BEGIN
  2. /* txn 2 */ BEGIN
  3. /* txn 2 */ SELECT COUNT(*) as `count` FROM `doctors` WHERE `on_call` = 1 AND `shift_id` = 123
  4. /* txn 2 */ UPDATE `doctors` SET `on_call` = 0 WHERE `id` = 2 AND `shift_id` = 123
  5. /* txn 2 */ COMMIT
  6. /* txn 1 */ SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = 1 and `shift_id` = 123
  7. /* txn 1 */ UPDATE `doctors` SET `on_call` = 0 WHERE `id` = 1 AND `shift_id` = 123
  8. /* txn 1 */ COMMIT

Running result:

  1. mysql> SELECT * FROM doctors;
  2. +----+-------+---------+----------+
  3. | id | name | on_call | shift_id |
  4. +----+-------+---------+----------+
  5. | 1 | Alice | 0 | 123 |
  6. | 2 | Bob | 0 | 123 |
  7. | 3 | Carol | 0 | 123 |
  8. +----+-------+---------+----------+

In both transactions, the application first checks if two or more doctors are on call; if so, it assumes that one doctor can safely take leave. Since the database uses the snapshot isolation, both checks return 2, so both transactions move on to the next stage. Alice updates her record to be off duty, and so does Bob. Both transactions are successfully committed. Now there are no doctors on duty which violates the requirement that at least one doctor should be on call. The following diagram (quoted from Designing Data-Intensive Applications) illustrates what actually happens.

Write Skew

Now let’s change the sample program to use SELECT FOR UPDATE to avoid the write skew problem:

  • Java
  • Golang
  1. package com.pingcap.txn.write.skew;
  2. import com.zaxxer.hikari.HikariDataSource;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.concurrent.CountDownLatch;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.Semaphore;
  11. public class EffectWriteSkew {
  12. public static void main(String[] args) throws SQLException, InterruptedException {
  13. HikariDataSource ds = new HikariDataSource();
  14. ds.setJdbcUrl("jdbc:mysql://localhost:4000/test?useServerPrepStmts=true&cachePrepStmts=true");
  15. ds.setUsername("root");
  16. // prepare data
  17. Connection connection = ds.getConnection();
  18. createDoctorTable(connection);
  19. createDoctor(connection, 1, "Alice", true, 123);
  20. createDoctor(connection, 2, "Bob", true, 123);
  21. createDoctor(connection, 3, "Carol", false, 123);
  22. Semaphore txn1Pass = new Semaphore(0);
  23. CountDownLatch countDownLatch = new CountDownLatch(2);
  24. ExecutorService threadPool = Executors.newFixedThreadPool(2);
  25. threadPool.execute(() -> {
  26. askForLeave(ds, txn1Pass, 1, 1);
  27. countDownLatch.countDown();
  28. });
  29. threadPool.execute(() -> {
  30. askForLeave(ds, txn1Pass, 2, 2);
  31. countDownLatch.countDown();
  32. });
  33. countDownLatch.await();
  34. }
  35. public static void createDoctorTable(Connection connection) throws SQLException {
  36. connection.createStatement().executeUpdate("CREATE TABLE `doctors` (" +
  37. " `id` int(11) NOT NULL," +
  38. " `name` varchar(255) DEFAULT NULL," +
  39. " `on_call` tinyint(1) DEFAULT NULL," +
  40. " `shift_id` int(11) DEFAULT NULL," +
  41. " PRIMARY KEY (`id`)," +
  42. " KEY `idx_shift_id` (`shift_id`)" +
  43. " ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin");
  44. }
  45. public static void createDoctor(Connection connection, Integer id, String name, Boolean onCall, Integer shiftID) throws SQLException {
  46. PreparedStatement insert = connection.prepareStatement(
  47. "INSERT INTO `doctors` (`id`, `name`, `on_call`, `shift_id`) VALUES (?, ?, ?, ?)");
  48. insert.setInt(1, id);
  49. insert.setString(2, name);
  50. insert.setBoolean(3, onCall);
  51. insert.setInt(4, shiftID);
  52. insert.executeUpdate();
  53. }
  54. public static void askForLeave(HikariDataSource ds, Semaphore txn1Pass, Integer txnID, Integer doctorID) {
  55. try(Connection connection = ds.getConnection()) {
  56. try {
  57. connection.setAutoCommit(false);
  58. String comment = txnID == 2 ? " " : "" + "/* txn #{txn_id} */ ";
  59. connection.createStatement().executeUpdate(comment + "BEGIN");
  60. // Txn 1 should be waiting for txn 2 done
  61. if (txnID == 1) {
  62. txn1Pass.acquire();
  63. }
  64. PreparedStatement currentOnCallQuery = connection.prepareStatement(comment +
  65. "SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = ? AND `shift_id` = ? FOR UPDATE");
  66. currentOnCallQuery.setBoolean(1, true);
  67. currentOnCallQuery.setInt(2, 123);
  68. ResultSet res = currentOnCallQuery.executeQuery();
  69. if (!res.next()) {
  70. throw new RuntimeException("error query");
  71. } else {
  72. int count = res.getInt("count");
  73. if (count >= 2) {
  74. // If current on-call doctor has 2 or more, this doctor can leave
  75. PreparedStatement insert = connection.prepareStatement( comment +
  76. "UPDATE `doctors` SET `on_call` = ? WHERE `id` = ? AND `shift_id` = ?");
  77. insert.setBoolean(1, false);
  78. insert.setInt(2, doctorID);
  79. insert.setInt(3, 123);
  80. insert.executeUpdate();
  81. connection.commit();
  82. } else {
  83. throw new RuntimeException("At least one doctor is on call");
  84. }
  85. }
  86. // Txn 2 done, let txn 1 run again
  87. if (txnID == 2) {
  88. txn1Pass.release();
  89. }
  90. } catch (Exception e) {
  91. // If got any error, you should roll back, data is priceless
  92. connection.rollback();
  93. e.printStackTrace();
  94. }
  95. } catch (SQLException e) {
  96. e.printStackTrace();
  97. }
  98. }
  99. }
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "sync"
  6. "github.com/pingcap-inc/tidb-example-golang/util"
  7. _ "github.com/go-sql-driver/mysql"
  8. )
  9. func main() {
  10. openDB("mysql", "root:@tcp(127.0.0.1:4000)/test", func(db *sql.DB) {
  11. writeSkew(db)
  12. })
  13. }
  14. func openDB(driverName, dataSourceName string, runnable func(db *sql.DB)) {
  15. db, err := sql.Open(driverName, dataSourceName)
  16. if err != nil {
  17. panic(err)
  18. }
  19. defer db.Close()
  20. runnable(db)
  21. }
  22. func writeSkew(db *sql.DB) {
  23. err := prepareData(db)
  24. if err != nil {
  25. panic(err)
  26. }
  27. waitingChan, waitGroup := make(chan bool), sync.WaitGroup{}
  28. waitGroup.Add(1)
  29. go func() {
  30. defer waitGroup.Done()
  31. err = askForLeave(db, waitingChan, 1, 1)
  32. if err != nil {
  33. panic(err)
  34. }
  35. }()
  36. waitGroup.Add(1)
  37. go func() {
  38. defer waitGroup.Done()
  39. err = askForLeave(db, waitingChan, 2, 2)
  40. if err != nil {
  41. panic(err)
  42. }
  43. }()
  44. waitGroup.Wait()
  45. }
  46. func askForLeave(db *sql.DB, waitingChan chan bool, goroutineID, doctorID int) error {
  47. txnComment := fmt.Sprintf("/* txn %d */ ", goroutineID)
  48. if goroutineID != 1 {
  49. txnComment = "\t" + txnComment
  50. }
  51. txn, err := util.TiDBSqlBegin(db, true)
  52. if err != nil {
  53. return err
  54. }
  55. fmt.Println(txnComment + "start txn")
  56. // Txn 1 should be waiting until txn 2 is done.
  57. if goroutineID == 1 {
  58. <-waitingChan
  59. }
  60. txnFunc := func() error {
  61. queryCurrentOnCall := "SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = ? AND `shift_id` = ?"
  62. rows, err := txn.Query(queryCurrentOnCall, true, 123)
  63. if err != nil {
  64. return err
  65. }
  66. defer rows.Close()
  67. fmt.Println(txnComment + queryCurrentOnCall + " successful")
  68. count := 0
  69. if rows.Next() {
  70. err = rows.Scan(&count)
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. rows.Close()
  76. if count < 2 {
  77. return fmt.Errorf("at least one doctor is on call")
  78. }
  79. shift := "UPDATE `doctors` SET `on_call` = ? WHERE `id` = ? AND `shift_id` = ?"
  80. _, err = txn.Exec(shift, false, doctorID, 123)
  81. if err == nil {
  82. fmt.Println(txnComment + shift + " successful")
  83. }
  84. return err
  85. }
  86. err = txnFunc()
  87. if err == nil {
  88. txn.Commit()
  89. fmt.Println("[runTxn] commit success")
  90. } else {
  91. txn.Rollback()
  92. fmt.Printf("[runTxn] got an error, rollback: %+v\n", err)
  93. }
  94. // Txn 2 is done. Let txn 1 run again.
  95. if goroutineID == 2 {
  96. waitingChan <- true
  97. }
  98. return nil
  99. }
  100. func prepareData(db *sql.DB) error {
  101. err := createDoctorTable(db)
  102. if err != nil {
  103. return err
  104. }
  105. err = createDoctor(db, 1, "Alice", true, 123)
  106. if err != nil {
  107. return err
  108. }
  109. err = createDoctor(db, 2, "Bob", true, 123)
  110. if err != nil {
  111. return err
  112. }
  113. err = createDoctor(db, 3, "Carol", false, 123)
  114. if err != nil {
  115. return err
  116. }
  117. return nil
  118. }
  119. func createDoctorTable(db *sql.DB) error {
  120. _, err := db.Exec("CREATE TABLE IF NOT EXISTS `doctors` (" +
  121. " `id` int(11) NOT NULL," +
  122. " `name` varchar(255) DEFAULT NULL," +
  123. " `on_call` tinyint(1) DEFAULT NULL," +
  124. " `shift_id` int(11) DEFAULT NULL," +
  125. " PRIMARY KEY (`id`)," +
  126. " KEY `idx_shift_id` (`shift_id`)" +
  127. " ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin")
  128. return err
  129. }
  130. func createDoctor(db *sql.DB, id int, name string, onCall bool, shiftID int) error {
  131. _, err := db.Exec("INSERT INTO `doctors` (`id`, `name`, `on_call`, `shift_id`) VALUES (?, ?, ?, ?)",
  132. id, name, onCall, shiftID)
  133. return err
  134. }

SQL log:

  1. /* txn 1 */ BEGIN
  2. /* txn 2 */ BEGIN
  3. /* txn 2 */ SELECT COUNT(*) AS `count` FROM `doctors` WHERE on_call = 1 AND `shift_id` = 123 FOR UPDATE
  4. /* txn 2 */ UPDATE `doctors` SET on_call = 0 WHERE `id` = 2 AND `shift_id` = 123
  5. /* txn 2 */ COMMIT
  6. /* txn 1 */ SELECT COUNT(*) AS `count` FROM `doctors` WHERE `on_call` = 1 FOR UPDATE
  7. At least one doctor is on call
  8. /* txn 1 */ ROLLBACK

Running result:

  1. mysql> SELECT * FROM doctors;
  2. +----+-------+---------+----------+
  3. | id | name | on_call | shift_id |
  4. +----+-------+---------+----------+
  5. | 1 | Alice | 1 | 123 |
  6. | 2 | Bob | 0 | 123 |
  7. | 3 | Carol | 0 | 123 |
  8. +----+-------+---------+----------+

Support for savepoint and nested transactions

The PROPAGATION_NESTED propagation behavior supported by Spring triggers a nested transaction, which is a child transaction that is started independently of the current transaction. A savepoint is recorded when the nested transaction starts. If the nested transaction fails, the transaction will roll back to the savepoint state. The nested transaction is part of the outer transaction and will be committed together with the outer transaction.

The following example demonstrates the savepoint mechanism:

  1. mysql> BEGIN;
  2. mysql> INSERT INTO T2 VALUES(100);
  3. mysql> SAVEPOINT svp1;
  4. mysql> INSERT INTO T2 VALUES(200);
  5. mysql> ROLLBACK TO SAVEPOINT svp1;
  6. mysql> RELEASE SAVEPOINT svp1;
  7. mysql> COMMIT;
  8. mysql> SELECT * FROM T2;
  9. +------+
  10. | ID |
  11. +------+
  12. | 100 |
  13. +------+

Transaction Restraints - 图3

Note

Since v6.2.0, TiDB supports the savepoint feature. If your TiDB cluster is earlier than v6.2.0, your TiDB cluster does not support the PROPAGATION_NESTED behavior. If your applications are based on the Java Spring framework that use the PROPAGATION_NESTED propagation behavior, you need to adapt it on the application side to remove the logic for nested transactions.

Large transaction restrictions

The basic principle is to limit the size of the transaction. At the KV level, TiDB has a restriction on the size of a single transaction. At the SQL level, one row of data is mapped to one KV entry, and each additional index will add one KV entry. The restriction is as follows at the SQL level:

  • The maximum single row record size is 120 MB. You can configure it by performance.txn-entry-size-limit for TiDB v5.0 and later versions. The value is 6 MB for earlier versions.
  • The maximum single transaction size supported is 10 GB. You can configure it by performance.txn-total-size-limit for TiDB v4.0 and later versions. The value is 100 MB for earlier versions.

Note that for both the size restrictions and row restrictions, you should also consider the overhead of encoding and additional keys for the transaction during the transaction execution. To achieve optimal performance, it is recommended to write one transaction every 100 ~ 500 rows.

Auto-committed SELECT FOR UPDATE statements do NOT wait for locks

Currently locks are not added to auto-committed SELECT FOR UPDATE statements. The effect is shown in the following figure:

The situation in TiDB

This is a known incompatibility issue with MySQL. You can solve this issue by using the explicit BEGIN;COMMIT; statements.