Skip to content
JZLeetCode
Go back

System Design - How TiDB Executes AS OF TIMESTAMP Reads

Table of contents

Open Table of contents

The question a historical read asks

Suppose an order was updated several times. A normal query asks for the newest committed value. A historical query asks TiDB to answer as if it were reading the database at a chosen point in the past:

SELECT * FROM orders
AS OF TIMESTAMP '2026-11-30 12:00:00'
WHERE order_id = 42;

TiDB calls this a stale read because it intentionally reads an earlier database state. Its source code has to keep two things aligned: the timestamp used to read row versions and the schema that existed at that timestamp. Then the storage layer must make sure a replica is ready to serve that timestamp.

This walkthrough follows five pieces of the path: TiDB’s staleReadProcessor, StalenessTxnContextProvider, and executorBuilder, then TiKV’s Raft Peer and MVCC SnapshotReader.

Follow one query through the code

Client -> staleReadProcessor: parse and validate timestamp T
staleReadProcessor -> StalenessTxnContextProvider: T + historical InfoSchema
StalenessTxnContextProvider -> executorBuilder: snapshot at T
executorBuilder -> TiKV Peer: stale-read request at T
TiKV Peer -> SnapshotReader: serve only if safe_ts >= T
SnapshotReader -> TiDB: MVCC version visible at T
TiDB -> Client: result

1. The SQL timestamp becomes a read timestamp

During preprocessing, staleReadProcessor.OnSelectTable sees the AS OF clause. It evaluates the timestamp expression and calls ValidateSnapshotReadTS. The processor also checks that tables in the same statement use one consistent timestamp. It loads the historical InfoSchema, TiDB’s catalog of databases, tables, and columns, so planning uses the schema that matched the requested time.

The planner then marks the statement as stale and creates a StalenessTxnContextProvider with that timestamp and InfoSchema. The code is in TiDB’s stale-read processor, the preprocessor handoff, and the snapshot timestamp validation.

The schema snapshot matters as much as the row timestamp. If a column was added after time T, TiDB should plan the old read using the table definition from T, not assume the newer column existed.

2. The transaction provider holds the timestamp steady

StalenessTxnContextProvider carries the chosen timestamp and historical InfoSchema. For a stale-read transaction, activateStaleTxn prepares the transaction with a constant timestamp and marks it read-only. A statement-level AS OF TIMESTAMP read outside an explicit transaction can instead use a direct snapshot at T.

When the executor needs a snapshot, GetSnapshotWithStmtReadTS returns the active transaction’s snapshot or creates one at the same timestamp. It also applies the session’s replica-read choice and marks the request as a stale read. See the provider implementation, its transaction setup, and its snapshot method.

The executor builder does not invent another timestamp. For a regular read, executorBuilder.getSnapshot asks the transaction manager for the statement’s read snapshot and initializes its request options. That keeps the timestamp chosen by the stale-read path attached to the read request. See TiDB’s executor snapshot builder and stale-read snapshot options.

How TiKV keeps a follower read safe

A follower may have applied fewer committed Raft entries than the leader. It cannot serve a read at time T just because it received the request; it must first know that its local data is safe through T.

TiDB marks the storage request as a stale read. In TiKV’s Raft Peer request handling, a stale-read request can be handled locally. Before reading, the peer compares the request timestamp with its safe_ts. If safe_ts < read_ts, TiKV rejects that attempt with DataIsNotReady; it can also ask the resolved-timestamp mechanism to advance when the gap is large. The peer does not return data from a replica that has not reached the requested time.

This check is per region. A query that reads several regions can therefore use the same timestamp while each region replica independently proves it is ready.

The versions that the query can see

After the peer accepts the request, TiKV’s MVCC reader uses the timestamp as the transaction’s read time. SnapshotReader stores a start_ts and passes it to MvccReader when it reads a key. The storage engine can contain several committed versions of that key, but versions newer than T are invisible to the query.

key: order:42

commit_ts = 10 -> status = "created"
commit_ts = 20 -> status = "paid"
commit_ts = 30 -> status = "shipped"

read_ts = 25 -> returns status = "paid"

The relevant code is TiKV’s SnapshotReader and its get method. MVCC gives the query a consistent historical view; it does not rewind the database or change the stored rows.

Settings that affect historical reads

A few settings control different parts of the path:

SettingWhat it affects
tidb_gc_life_timeThe retention window for old MVCC versions. A timestamp older than the effective GC safe point cannot be read because the needed versions may already be removed.
tidb_replica_readWhether TiDB may send reads to follower replicas. A follower still has to pass TiKV’s safe timestamp check.
TiKV [resolved-ts] advance-ts-intervalHow often TiKV advances Resolved TS. A shorter interval can reduce waits when a stale read asks for a timestamp that replicas have not made safe yet, at the cost of more CPU and inter-node traffic.

GC retention and safe timestamps solve different problems. GC determines whether old versions still exist. Safe TS determines whether a particular replica has applied enough work to serve the requested time. Increasing the retention window does not make an unready follower safe.

Limits to remember

AS OF TIMESTAMP is a read-only query feature. TiDB rejects it inside an already active transaction, and stale-read transaction providers do not support locking reads such as SELECT ... FOR UPDATE. If a timestamp is too old for the GC safe point, the query fails instead of returning a partial history.

If the read is unexpectedly slow, check both the retention window and the replica’s resolved or safe timestamp. A long wait can mean the replica has not yet advanced far enough; it does not mean TiDB is silently reading a newer version.

References

  1. TiDB documentation, Stale Read
  2. TiDB documentation, Troubleshoot stale reads and safe-ts in TiKV
  3. TiDB documentation, System variables
  4. PingCAP blog, Time Synchronization in Distributed Systems: TiDB’s Timestamp Oracle
  5. TiDB source, stale-read processing, provider, and executor builder
  6. TiKV source, Raft peer safe timestamp check and MVCC snapshot reader
Share this post on:

Previous Post
System Design - How AWS Lambda Reuses Execution Environments
Next Post
LeetCode 136 Single Number