Stale Read

Stale Read is a mechanism that TiDB applies to read historical versions of data stored in TiDB. Using this mechanism, you can read the corresponding historical data at a specific time or within a specified time range, and thus save the latency caused by data replication between storage nodes. When you are using Stale Read, TiDB randomly selects a replica for data reading, which means that all replicas are available for data reading.

In practice, consider carefully whether it is appropriate to enable Stale Read in TiDB based on the usage scenarios. Do not enable Stale Read if your application cannot tolerate reading non-real-time data.

TiDB provides three levels of Stale Read: statement level, transaction level, and session level.

Introduction

In the Bookshop application, you can query the latest published books and their prices through the following SQL statement:

  1. SELECT id, title, type, price FROM books ORDER BY published_at DESC LIMIT 5;

The result is as follows:

  1. +------------+------------------------------+-----------------------+--------+
  2. | id | title | type | price |
  3. +------------+------------------------------+-----------------------+--------+
  4. | 3181093216 | The Story of Droolius Caesar | Novel | 100.00 |
  5. | 1064253862 | Collin Rolfson | Education & Reference | 92.85 |
  6. | 1748583991 | The Documentary of cat | Magazine | 159.75 |
  7. | 893930596 | Myrl Hills | Education & Reference | 356.85 |
  8. | 3062833277 | Keven Wyman | Life | 477.91 |
  9. +------------+------------------------------+-----------------------+--------+
  10. 5 rows in set (0.02 sec)

In the list at this time (2022-04-20 15:20:00), the price of The Story of Droolius Caesar is 100.0.

At the same time, the seller found that the book was very popular and raised the price of the book to 150.0 through the following SQL statement:

  1. UPDATE books SET price = 150 WHERE id = 3181093216;

The result is as follows:

  1. Query OK, 1 row affected (0.00 sec)
  2. Rows matched: 1 Changed: 1 Warnings: 0

By querying the latest books list, you can see that the price of this book has increased.

  1. +------------+------------------------------+-----------------------+--------+
  2. | id | title | type | price |
  3. +------------+------------------------------+-----------------------+--------+
  4. | 3181093216 | The Story of Droolius Caesar | Novel | 150.00 |
  5. | 1064253862 | Collin Rolfson | Education & Reference | 92.85 |
  6. | 1748583991 | The Documentary of cat | Magazine | 159.75 |
  7. | 893930596 | Myrl Hills | Education & Reference | 356.85 |
  8. | 3062833277 | Keven Wyman | Life | 477.91 |
  9. +------------+------------------------------+-----------------------+--------+
  10. 5 rows in set (0.01 sec)

If it is not necessary to use the latest data, you can query with Stale Read, which might return outdated data, to avoid the latency caused by data replication during a strongly consistent read.

Assuming that in the Bookshop application, the real-time price of a book is not required on the book lists page but only required on the book details and order pages. Stale Read can be used to improve throughout of the application.

Statement level

  • SQL
  • Java

To query the price of a book before a specific time, add an AS OF TIMESTAMP <datetime> clause in the above query statement.

  1. SELECT id, title, type, price FROM books AS OF TIMESTAMP '2022-04-20 15:20:00' ORDER BY published_at DESC LIMIT 5;

The result is as follows:

  1. +------------+------------------------------+-----------------------+--------+
  2. | id | title | type | price |
  3. +------------+------------------------------+-----------------------+--------+
  4. | 3181093216 | The Story of Droolius Caesar | Novel | 100.00 |
  5. | 1064253862 | Collin Rolfson | Education & Reference | 92.85 |
  6. | 1748583991 | The Documentary of cat | Magazine | 159.75 |
  7. | 893930596 | Myrl Hills | Education & Reference | 356.85 |
  8. | 3062833277 | Keven Wyman | Life | 477.91 |
  9. +------------+------------------------------+-----------------------+--------+
  10. 5 rows in set (0.01 sec)

In addition to specifying an exact time, you can also specify the following:

  • AS OF TIMESTAMP NOW() - INTERVAL 10 SECOND queries the latest data 10 seconds ago.
  • AS OF TIMESTAMP TIDB_BOUNDED_STALENESS('2016-10-08 16:45:26', '2016-10-08 16:45:29') queries the latest data between 2016-10-08 16:45:26 and 2016-10-08 16:45:29.
  • AS OF TIMESTAMP TIDB_BOUNDED_STALENESS(NOW() -INTERVAL 20 SECOND, NOW()) queries the latest data within 20 seconds.

Note that the specified timestamp or interval cannot be too early or later than the current time. Additionally, NOW() defaults to second precision. To achieve higher precision, you can add a parameter, such as using NOW(3) for millisecond precision. For more information, see MySQL documentation.

Expired data will be recycled by Garbage Collection in TiDB, and the data will be retained for a short period before being cleared. The period is called GC Life Time (default 10 minutes). When a GC starts, the current time minus the time period will be used as the GC Safe Point. If you try to read the data before GC Safe Point, TiDB will report the following error:

  1. ERROR 9006 (HY000): GC life time is shorter than transaction duration...

If the given timestamp is a future time, TiDB will report the following error:

  1. ERROR 9006 (HY000): cannot set read timestamp to a future time.
  1. public class BookDAO {
  2. // Omit some code...
  3. public List<Book> getTop5LatestBooks() throws SQLException {
  4. List<Book> books = new ArrayList<>();
  5. try (Connection conn = ds.getConnection()) {
  6. Statement stmt = conn.createStatement();
  7. ResultSet rs = stmt.executeQuery("""
  8. SELECT id, title, type, price FROM books ORDER BY published_at DESC LIMIT 5;
  9. """);
  10. while (rs.next()) {
  11. Book book = new Book();
  12. book.setId(rs.getLong("id"));
  13. book.setTitle(rs.getString("title"));
  14. book.setType(rs.getString("type"));
  15. book.setPrice(rs.getDouble("price"));
  16. books.add(book);
  17. }
  18. }
  19. return books;
  20. }
  21. public void updateBookPriceByID(Long id, Double price) throws SQLException {
  22. try (Connection conn = ds.getConnection()) {
  23. PreparedStatement stmt = conn.prepareStatement("""
  24. UPDATE books SET price = ? WHERE id = ?;
  25. """);
  26. stmt.setDouble(1, price);
  27. stmt.setLong(2, id);
  28. int affects = stmt.executeUpdate();
  29. if (affects == 0) {
  30. throw new SQLException("Failed to update the book with id: " + id);
  31. }
  32. }
  33. }
  34. public List<Book> getTop5LatestBooksWithStaleRead(Integer seconds) throws SQLException {
  35. List<Book> books = new ArrayList<>();
  36. try (Connection conn = ds.getConnection()) {
  37. PreparedStatement stmt = conn.prepareStatement("""
  38. SELECT id, title, type, price FROM books AS OF TIMESTAMP NOW() - INTERVAL ? SECOND ORDER BY published_at DESC LIMIT 5;
  39. """);
  40. stmt.setInt(1, seconds);
  41. ResultSet rs = stmt.executeQuery();
  42. while (rs.next()) {
  43. Book book = new Book();
  44. book.setId(rs.getLong("id"));
  45. book.setTitle(rs.getString("title"));
  46. book.setType(rs.getString("type"));
  47. book.setPrice(rs.getDouble("price"));
  48. books.add(book);
  49. }
  50. } catch (SQLException e) {
  51. if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 1105) {
  52. System.out.println("WARN: cannot set read timestamp to a future time.");
  53. } else if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 9006) {
  54. System.out.println("WARN: GC life time is shorter than transaction duration.");
  55. } else {
  56. throw e;
  57. }
  58. }
  59. return books;
  60. }
  61. }
  1. List<Book> top5LatestBooks = bookDAO.getTop5LatestBooks();
  2. if (top5LatestBooks.size() > 0) {
  3. System.out.println("The latest book price (before update): " + top5LatestBooks.get(0).getPrice());
  4. Book book = top5LatestBooks.get(0);
  5. bookDAO.updateBookPriceByID(book.getId(), book.price + 10);
  6. top5LatestBooks = bookDAO.getTop5LatestBooks();
  7. System.out.println("The latest book price (after update): " + top5LatestBooks.get(0).getPrice());
  8. // Use the stale read.
  9. top5LatestBooks = bookDAO.getTop5LatestBooksWithStaleRead(5);
  10. System.out.println("The latest book price (maybe stale): " + top5LatestBooks.get(0).getPrice());
  11. // Try to stale read the data at the future time.
  12. bookDAO.getTop5LatestBooksWithStaleRead(-5);
  13. // Try to stale read the data before 20 minutes.
  14. bookDAO.getTop5LatestBooksWithStaleRead(20 * 60);
  15. }

The following result shows that the price returned by Stale Read is 100.00, which is the value before the update.

  1. The latest book price (before update): 100.00
  2. The latest book price (after update): 150.00
  3. The latest book price (maybe stale): 100.00
  4. WARN: cannot set read timestamp to a future time.
  5. WARN: GC life time is shorter than transaction duration.

Transaction level

With the START TRANSACTION READ ONLY AS OF TIMESTAMP statement, you can start a read-only transaction based on historical time, which reads historical data from a specified historical timestamp.

  • SQL
  • Java

For example:

  1. START TRANSACTION READ ONLY AS OF TIMESTAMP NOW() - INTERVAL 5 SECOND;

By querying the latest price of the book, you can see that the price of The Story of Droolius Caesar is still 100.0, which is the value before the update.

  1. SELECT id, title, type, price FROM books ORDER BY published_at DESC LIMIT 5;

The result is as follows:

  1. +------------+------------------------------+-----------------------+--------+
  2. | id | title | type | price |
  3. +------------+------------------------------+-----------------------+--------+
  4. | 3181093216 | The Story of Droolius Caesar | Novel | 100.00 |
  5. | 1064253862 | Collin Rolfson | Education & Reference | 92.85 |
  6. | 1748583991 | The Documentary of cat | Magazine | 159.75 |
  7. | 893930596 | Myrl Hills | Education & Reference | 356.85 |
  8. | 3062833277 | Keven Wyman | Life | 477.91 |
  9. +------------+------------------------------+-----------------------+--------+
  10. 5 rows in set (0.01 sec)

After the transaction with the COMMIT; statement is committed, you can read the latest data.

  1. +------------+------------------------------+-----------------------+--------+
  2. | id | title | type | price |
  3. +------------+------------------------------+-----------------------+--------+
  4. | 3181093216 | The Story of Droolius Caesar | Novel | 150.00 |
  5. | 1064253862 | Collin Rolfson | Education & Reference | 92.85 |
  6. | 1748583991 | The Documentary of cat | Magazine | 159.75 |
  7. | 893930596 | Myrl Hills | Education & Reference | 356.85 |
  8. | 3062833277 | Keven Wyman | Life | 477.91 |
  9. +------------+------------------------------+-----------------------+--------+
  10. 5 rows in set (0.01 sec)

You can define a helper class for transactions, which encapsulates the command to enable Stale Read at the transaction level as a helper method.

  1. public static class StaleReadHelper {
  2. public static void startTxnWithStaleRead(Connection conn, Integer seconds) throws SQLException {
  3. conn.setAutoCommit(false);
  4. PreparedStatement stmt = conn.prepareStatement(
  5. "START TRANSACTION READ ONLY AS OF TIMESTAMP NOW() - INTERVAL ? SECOND;"
  6. );
  7. stmt.setInt(1, seconds);
  8. stmt.execute();
  9. }
  10. }

Then define a method to enable the Stale Read feature through a transaction in the BookDAO class. Use the method to query instead of adding AS OF TIMESTAMP to the query statement.

  1. public class BookDAO {
  2. // Omit some code...
  3. public List<Book> getTop5LatestBooksWithTxnStaleRead(Integer seconds) throws SQLException {
  4. List<Book> books = new ArrayList<>();
  5. try (Connection conn = ds.getConnection()) {
  6. // Start a read only transaction.
  7. TxnHelper.startTxnWithStaleRead(conn, seconds);
  8. Statement stmt = conn.createStatement();
  9. ResultSet rs = stmt.executeQuery("""
  10. SELECT id, title, type, price FROM books ORDER BY published_at DESC LIMIT 5;
  11. """);
  12. while (rs.next()) {
  13. Book book = new Book();
  14. book.setId(rs.getLong("id"));
  15. book.setTitle(rs.getString("title"));
  16. book.setType(rs.getString("type"));
  17. book.setPrice(rs.getDouble("price"));
  18. books.add(book);
  19. }
  20. // Commit transaction.
  21. conn.commit();
  22. } catch (SQLException e) {
  23. if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 1105) {
  24. System.out.println("WARN: cannot set read timestamp to a future time.");
  25. } else if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 9006) {
  26. System.out.println("WARN: GC life time is shorter than transaction duration.");
  27. } else {
  28. throw e;
  29. }
  30. }
  31. return books;
  32. }
  33. }
  1. List<Book> top5LatestBooks = bookDAO.getTop5LatestBooks();
  2. if (top5LatestBooks.size() > 0) {
  3. System.out.println("The latest book price (before update): " + top5LatestBooks.get(0).getPrice());
  4. Book book = top5LatestBooks.get(0);
  5. bookDAO.updateBookPriceByID(book.getId(), book.price + 10);
  6. top5LatestBooks = bookDAO.getTop5LatestBooks();
  7. System.out.println("The latest book price (after update): " + top5LatestBooks.get(0).getPrice());
  8. // Use the stale read.
  9. top5LatestBooks = bookDAO.getTop5LatestBooksWithTxnStaleRead(5);
  10. System.out.println("The latest book price (maybe stale): " + top5LatestBooks.get(0).getPrice());
  11. // After the stale read transaction is committed.
  12. top5LatestBooks = bookDAO.getTop5LatestBooks();
  13. System.out.println("The latest book price (after the transaction commit): " + top5LatestBooks.get(0).getPrice());
  14. }

The result is as follows:

  1. The latest book price (before update): 100.00
  2. The latest book price (after update): 150.00
  3. The latest book price (maybe stale): 100.00
  4. The latest book price (after the transaction commit): 150

With the SET TRANSACTION READ ONLY AS OF TIMESTAMP statement, you can set the opened transaction or the next transaction to be a read-only transaction based on a specified historical time. The transaction will read historical data based on the provided historical time.

  • SQL
  • Java

For example, you can use the following AS OF TIMESTAMP statement to switch the ongoing transactions to the read-only mode and read historical data 5 seconds ago.

  1. SET TRANSACTION READ ONLY AS OF TIMESTAMP NOW() - INTERVAL 5 SECOND;

You can define a helper class for transactions, which encapsulates the command to enable Stale Read at the transaction level as a helper method.

  1. public static class TxnHelper {
  2. public static void setTxnWithStaleRead(Connection conn, Integer seconds) throws SQLException {
  3. PreparedStatement stmt = conn.prepareStatement(
  4. "SET TRANSACTION READ ONLY AS OF TIMESTAMP NOW() - INTERVAL ? SECOND;"
  5. );
  6. stmt.setInt(1, seconds);
  7. stmt.execute();
  8. }
  9. }

Then define a method to enable the Stale Read feature through a transaction in the BookDAO class. Use the method to query instead of adding AS OF TIMESTAMP to the query statement.

  1. public class BookDAO {
  2. // Omit some code...
  3. public List<Book> getTop5LatestBooksWithTxnStaleRead2(Integer seconds) throws SQLException {
  4. List<Book> books = new ArrayList<>();
  5. try (Connection conn = ds.getConnection()) {
  6. StaleReadHelper.setTxnWithStaleRead(conn, seconds);
  7. // Start a read only transaction.
  8. conn.setAutoCommit(false);
  9. Statement stmt = conn.createStatement();
  10. ResultSet rs = stmt.executeQuery("""
  11. SELECT id, title, type, price FROM books ORDER BY published_at DESC LIMIT 5;
  12. """);
  13. while (rs.next()) {
  14. Book book = new Book();
  15. book.setId(rs.getLong("id"));
  16. book.setTitle(rs.getString("title"));
  17. book.setType(rs.getString("type"));
  18. book.setPrice(rs.getDouble("price"));
  19. books.add(book);
  20. }
  21. // Commit transaction.
  22. conn.commit();
  23. } catch (SQLException e) {
  24. if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 1105) {
  25. System.out.println("WARN: cannot set read timestamp to a future time.");
  26. } else if ("HY000".equals(e.getSQLState()) && e.getErrorCode() == 9006) {
  27. System.out.println("WARN: GC life time is shorter than transaction duration.");
  28. } else {
  29. throw e;
  30. }
  31. }
  32. return books;
  33. }
  34. }

Session level

To support reading historical data, TiDB has introduced a new system variable tidb_read_staleness since v5.4. you can use it to set the range of historical data that the current session is allowed to read. Its data type is int and its scope is SESSION.

  • SQL
  • Java

Enable Stale Read in a session:

  1. SET @@tidb_read_staleness="-5";

For example, if the value is set to -5 and TiKV or TiFlash has the corresponding historical data, TiDB selects a timestamp as new as possible within a 5-second time range.

Disable Stale Read in the session:

  1. set @@tidb_read_staleness="";
  1. public static class StaleReadHelper{
  2. public static void enableStaleReadOnSession(Connection conn, Integer seconds) throws SQLException {
  3. PreparedStatement stmt = conn.prepareStatement(
  4. "SET @@tidb_read_staleness= ?;"
  5. );
  6. stmt.setString(1, String.format("-%d", seconds));
  7. stmt.execute();
  8. }
  9. public static void disableStaleReadOnSession(Connection conn) throws SQLException {
  10. PreparedStatement stmt = conn.prepareStatement(
  11. "SET @@tidb_read_staleness=\"\";"
  12. );
  13. stmt.execute();
  14. }
  15. }

Read more