# TSO Assignment: Time Window

![`smart`](TSOTimeWindow_aa_001_20220509.png)

------------------------------------------------------------------------------
The first thing that needs to be solved with the single-point timestamp generation is the single point of failure problem.

The PD cluster uses Raft consensus algorithm to ensure that a new Leader is elected immediately after the primary node goes down, and the timing service will be recovered in a short period of time.

Then, the current TSO of the previous Leader must be stored, and the storage must also be highly reliable, so the TiDB uses the etcd. The rate at which TSOs are generated is related to the I/O capability of the disk, and there will be bottlenecks. TiDB uses a pre-allocation time window to resolve performance issues.

As shown in the figure, the current PD Leader's TSO is 700 (this is an imaginary value for ease of explanation), and PD has requested an time window from etcd. The span of the time window can be specified by parameters. The default time window configuration of the system is 3 seconds. 

The example uses the default configuration, so the starting point of this window is TSO 700, and the ending point of the time window is at TSO 703. After etcd is successfully written, PD will get an time window from 700 to 703. Within this time window, PD can use the system's physical time as a high position, concatenate the logical time it has accumulated in memory, and assign timestamps to its clients. 

This design means that the high point of all PD allotted timestamps, or physical time, is always less than the maximum value stored by the etcd. Then, if PD Leader goes down, the new Leader can read the maximum value stored in the etcd and apply for a new time window based on that, so the new Leader can ensure that allocating a TSO that is always larger than the previous Leader. Also, in order to reduce communication overhead, each client can request multiple TSO at once, and the number of TSO is passed as a parameter from the client to PD. 

However, that once TSO are cached on the client, the clock between multiple clients is no longer strictly monotonously incremental.