Database / TiDB Interview questions
Last updated
1. What is TiDB?
TiDB is an open-source distributed SQL database from PingCAP. It speaks the MySQL protocol, scales out horizontally and keeps data strongly consistent through Raft replication, so you get a familiar MySQL interface without hand-managing shards.
Compute and storage are separate. Stateless TiDB servers parse and plan SQL, while TiKV (row store) and TiFlash (column store) hold the data. The PD cluster keeps metadata and hands out timestamps.
Because one system serves both transactional and analytical queries, it is also described as an HTAP database. Common uses are OLTP workloads that outgrew a single MySQL, real-time analytics on live data, and merging many MySQL shards into one cluster.
Take quiz
An embedded single-file database for mobile apps
An in-memory key-value cache with no SQL layer
A distributed SQL database that speaks the MySQL protocol and scales out
A document store with its own JSON query language
Stores Raft logs on local disks
Allocates cluster-wide timestamps
Schedules Region replicas across stores
Parses and plans SQL while the data lives in TiKV and TiFlash
2. What are the core components of TiDB?
A TiDB cluster has four core components, each with a separate job.
| Component | Role |
| TiDB server | Stateless SQL layer: speaks MySQL protocol, parses, optimizes and executes SQL |
| TiKV | Distributed transactional row store built on Raft and RocksDB |
| TiFlash | Columnar replica of TiKV data for analytical queries |
| PD (Placement Driver) | Cluster brain: metadata, timestamp oracle and replica scheduling |
TiFlash is optional. Around the core sit tools such as TiUP, TiCDC, TiDB Lightning, BR and TiDB Dashboard.
flowchart LR A["MySQL client"] --> B["TiDB server"] B --> C[TiKV] B --> D[TiFlash] B --> E[PD] C --- E
Take quiz
TiKV
TiFlash
TiDB server
PD
TiFlash
TiKV
PD
TiDB server
3. What is TiKV?
TiKV is the distributed, transactional key-value store that holds the row data of a TiDB cluster. It is written in Rust and is also a CNCF graduated project.
Each TiKV node runs RocksDB instances to persist data on disk. Keys are split into Regions, and every Region is replicated (three copies by default) using the Raft protocol, which gives high availability and strong consistency.
TiKV also implements MVCC for snapshot reads and the Percolator-style transaction protocol. A coprocessor lets it run filters and aggregations next to the data, so less data travels to the TiDB server.
Take quiz
Through the Raft consensus protocol
By periodic rsync of data files
By MySQL binlog shipping
By a two-node primary-secondary heartbeat only
To allocate transaction timestamps
To push down filters and aggregations close to the data
To parse incoming SQL text
To authenticate MySQL users
4. What is the role of PD in TiDB?
PD (Placement Driver) is the metadata and scheduling brain of the cluster. It does three main things.
- Stores cluster metadata: which Region lives on which TiKV store and who the Region leader is.
- Allocates timestamps: it is the TSO (timestamp oracle) that gives every transaction a globally increasing start and commit timestamp.
- Schedules data: it balances Region leaders and replicas, and repairs replicas when a store goes down.
PD embeds etcd and runs as a Raft group, so production clusters use at least three PD nodes. Only the PD leader serves TSO requests.
Take quiz
The Region splitter
The timestamp oracle (TSO)
The SQL optimizer
The coprocessor
Each PD stores one third of the table rows
TiDB servers must connect to exactly three PDs
PD runs as a Raft group and needs a majority to stay available
PD needs three nodes to serve MySQL traffic
5. What is TiFlash?
TiFlash is the columnar storage engine of TiDB, built for analytical queries. It keeps a column-oriented copy of tables that you choose to replicate from TiKV.
The copy is fed through Raft as a learner replica. It receives logs asynchronously and does not vote, so TiFlash never slows down OLTP writes. Reads still return consistent data because TiFlash confirms with the Region leader that it has caught up before answering.
The optimizer decides per query whether TiKV or TiFlash is cheaper, and large scans, aggregations and joins can run in distributed MPP mode across TiFlash nodes.
Take quiz
As the Region leader
As a voting follower
As a non-voting learner replica
As a PD member
Single-row primary key lookups
Storing Raft logs for PD
Managing user passwords
Large scans, aggregations and joins
6. What does HTAP mean in TiDB?
HTAP stands for Hybrid Transactional and Analytical Processing. In TiDB it means the same cluster can serve OLTP queries and real-time analytics, without an ETL pipeline into a separate warehouse.
It works through two storage engines holding the same data: TiKV (rows) for transactions and TiFlash (columns) for analytics. Raft learner replication keeps TiFlash fresh, and the optimizer picks the engine per query, or even per table inside one query.
| TiKV | TiFlash | |
| Layout | Row-oriented | Column-oriented |
| Best for | Point lookups, small transactions | Scans, aggregates, large joins |
| Replication | Raft voter | Raft learner |
Workload isolation comes from running each engine on separate nodes, so heavy reports do not steal CPU from OLTP.
Take quiz
A nightly Dumpling export
Manual INSERT ... SELECT jobs
A Kafka topic written by the application
TiFlash replicates from TiKV through Raft learner logs
They can run on separate TiFlash nodes
They are always limited to one row
They run only at night
TiKV rejects all SELECT statements
7. Is TiDB compatible with MySQL?
Largely yes. TiDB is compatible with the MySQL protocol and with most MySQL 5.7 and 8.0 syntax, so existing drivers, ORMs and tools such as Navicat, MySQL Workbench or the mysql CLI work unchanged. Connect on port 4000 instead of 3306.
Compatibility is not total. Stored procedures, triggers, events and some storage-engine specific features are not supported, and behaviour differs in places, for example auto-increment ordering and the default isolation implementation.
Check the running version with:
SELECT tidb_version();
Always test your application against TiDB before migrating, since the supported feature list changes between releases.
Take quiz
4000
3306
2379
20160
SELECT statements are not allowed
Stored procedures and triggers are not supported
Clients must use a custom binary protocol
Tables cannot have primary keys
8. What is a Region in TiDB?
A Region is the basic unit of data distribution and replication in TiKV. It is a contiguous range of the sorted key space, for example all keys from t10_r1 to t10_r5000.
By default a Region is about 96 MiB and is split once it grows beyond roughly 144 MiB. Each Region is replicated three times and the copies form a Raft group with one leader that serves reads and writes.
PD moves Regions and their leaders between TiKV stores to balance load. Because data moves in small Region-sized pieces, scaling out needs no manual resharding.
Take quiz
It is deleted
It is split into smaller Regions
It is converted to TiFlash format
The whole cluster stops writes
A MySQL replication chain
A consistent hash ring
A Raft group with a single leader
A two-phase lock table
9. What are the key features of TiDB?
The features interviewers expect you to name:
- Horizontal scalability: add TiDB or TiKV nodes online, no resharding.
- MySQL compatibility: same protocol and mostly the same SQL.
- Strong consistency and HA: Raft replicas with automatic failover and no data loss when a minority of replicas fail.
- Distributed ACID transactions across rows, tables and nodes.
- HTAP through TiKV and TiFlash.
- Cloud-native design: separated compute and storage, Kubernetes operator, managed TiDB Cloud.
- Open source under Apache 2.0.
Take quiz
Table-level read locks
A single global primary node
Region-based automatic splitting and balancing
Binary log filtering
GPL v2 with a commercial add-on only
Proprietary, closed source
Creative Commons
Apache 2.0
10. What is TiUP used for?
TiUP is the package manager and cluster management tool for TiDB. It installs components, deploys clusters and runs day-two operations from one CLI.
Two modes are used most often. tiup playground starts a throwaway local cluster for learning, and tiup cluster manages real multi-host deployments from a YAML topology file.
tiup playground tiup cluster deploy prod-tidb v8.5.0 topology.yaml --user tidb tiup cluster start prod-tidb tiup cluster display prod-tidb tiup cluster scale-out prod-tidb scale.yaml tiup cluster upgrade prod-tidb v8.5.1
It also handles rolling upgrades, scale-in, configuration changes and launching tools such as BR and Dumpling.
Take quiz
tiup cluster deploy --prod
tiup br backup
tiup cdc start-local
tiup playground
A YAML topology file
A MySQL dump
A Docker Compose file only
A PD configuration table
11. What are the default ports used by TiDB components?
Knowing the default ports helps with firewall rules and troubleshooting.
| Component | Port | Purpose |
| TiDB server | 4000 | MySQL protocol clients |
| TiDB server | 10080 | HTTP status and metrics |
| PD | 2379 | Client communication, TiDB Dashboard |
| PD | 2380 | Peer communication between PD nodes |
| TiKV | 20160 | Client and peer service |
| TiKV | 20180 | Status and metrics |
| Prometheus / Grafana | 9090 / 3000 | Monitoring |
All ports are configurable in the TiUP topology file. Open 4000 to application servers only, keep 2379, 2380 and 20160 restricted to cluster hosts, and expose 10080, 9090 and 3000 just to your monitoring and admin network.
Take quiz
4000
2380
10080
9090
4000
2380
20180
3000
12. What is TiDB Dashboard?
TiDB Dashboard is the built-in web UI for monitoring and diagnosing a cluster. It ships inside PD, so you open it at http://<pd-host>:2379/dashboard with a TiDB SQL user.
Key pages include:
- Key Visualizer: heatmap of read and write traffic by key range, used to spot hotspots.
- SQL Statements and Slow Queries: top statements by latency and the slow query log.
- Top SQL: CPU consumption per SQL over time.
- Continuous Profiling, cluster diagnostics, and log search.
Take quiz
Slow Queries
Key Visualizer
Log Search
SQL Statements
Inside TiFlash only
As a separate Java server
Inside the PD component
On the TiKV status port
13. What is TiDB Cloud?
TiDB Cloud is PingCAP's fully managed Database-as-a-Service for TiDB, available on AWS and Google Cloud, with Azure support on some tiers. PingCAP runs provisioning, upgrades, backups and monitoring for you.
It has two main flavours. The serverless tier (now branded Starter or Essential, plan names have changed over time) autoscales and bills by usage, which suits small apps and development. Dedicated gives you an isolated cluster with chosen node sizes, VPC peering and TiFlash for production.
It is the quickest way to try TiDB without managing infrastructure. Check the console for the current plan names.
Take quiz
You, entirely through TiUP
Only your cloud provider's support team
PingCAP as a managed service
Nobody, it is fully manual
Playground
Dumpling
Sandbox mode
Dedicated
14. What is TiCDC used for?
TiCDC (Change Data Capture) streams row-level changes from a TiDB cluster to other systems. It pulls changes from TiKV, orders them, and pushes them to a downstream sink through a changefeed.
Supported sinks include MySQL-compatible databases, Kafka, Pulsar, and cloud storage such as S3. Typical uses are disaster recovery with a standby cluster, feeding event streams to downstream services, and syncing to a data warehouse.
tiup cdc cli changefeed create --server=http://127.0.0.1:8300 --sink-uri="mysql://root:pwd@10.0.0.5:3306/" --changefeed-id="dr-sync"
Take quiz
A Dumpling snapshot
A PD scheduler
A Lightning backend
A changefeed with a sink URI
Streaming changes to Kafka or a standby cluster
Rewriting SQL execution plans
Compressing Region data
Generating Raft snapshots
15. What is TiDB Lightning?
TiDB Lightning is a high-speed data import tool for loading large datasets, such as Dumpling exports or Parquet files, into TiDB.
It has two modes:
- Physical import mode: encodes data into sorted key-value pairs and ingests SST files straight into TiKV. It is the fastest option, but the target tables should be empty and are not available for writes during the import.
- Logical import mode: executes INSERT statements. It is slower, but the cluster stays online and tables can be non-empty.
From v7.2 the SQL statement IMPORT INTO offers a simpler way to do similar imports without a separate tool.
Take quiz
Physical import mode
Logical import mode
Replica mode
Streaming mode
It only works on PD
Target tables should be empty and not written to during import
It cannot import CSV files
It needs a Kafka cluster
16. What is Dumpling in TiDB?
Dumpling is a logical export tool that writes data from TiDB or MySQL into SQL or CSV files. It is the TiDB counterpart of mysqldump and mydumper, but multi-threaded and able to split big tables into chunks.
It takes a consistent snapshot using TiDB's snapshot reads, so the export does not need to lock tables. Output can go to local disk or S3-compatible storage.
tiup dumpling -h 127.0.0.1 -P 4000 -u root -t 8 -F 256MiB -o /data/dump
Dumpling pairs naturally with Lightning for import and with DM for MySQL migrations.
Take quiz
RocksDB SST only
SQL and CSV
Raft log segments
Parquet only
mysqlbinlog
pg_basebackup
mysqldump / mydumper
redis-cli
17. What is TiDB Data Migration (DM)?
TiDB Data Migration (DM) migrates and continuously replicates data from MySQL-compatible databases (MySQL, MariaDB, Aurora) into TiDB.
A DM task usually runs three phases: full export of existing data, import into TiDB, and incremental replication by reading the upstream binlog. This lets you cut over with little downtime.
Its standout feature is shard merging: tables from many upstream MySQL instances or schemas can be merged into one TiDB table, with DDL coordination across shards. It is operated with dmctl, backed by dm-master and dm-worker nodes.
Take quiz
The TiKV Raft log
PD etcd snapshots
The upstream MySQL binlog
The TiFlash delta tree
Automatically converting MySQL to MongoDB
Disabling all DDL on upstream
Encrypting binlogs with TSO
Merging many shard tables into one TiDB table
18. What MySQL features are not supported in TiDB?
TiDB covers most everyday MySQL SQL, but some features are missing or limited:
- Stored procedures, triggers and events
- User-defined functions
- FULLTEXT and SPATIAL indexes
- XA transactions and some storage-engine specific syntax such as
CREATE TABLE ... ENGINE=behaviour (the clause is accepted but ignored) - Foreign keys, which arrived as experimental in v6.6 and have been maturing since
The list shrinks with every release, so confirm against the compatibility page for your exact version before a migration.
Take quiz
Views
Secondary indexes
Window functions
Stored procedures
It is accepted but ignored
It selects InnoDB storage on disk
It switches the table to MyISAM
It forces a TiFlash replica
19. How do you connect to a TiDB cluster?
Use any MySQL client or driver and point it at a TiDB server on port 4000.
mysql -h 10.0.0.11 -P 4000 -u root -p
For Java the JDBC URL looks like jdbc:mysql://10.0.0.11:4000/shop. Python, Go, Node.js and ORMs such as Hibernate or SQLAlchemy work the same way.
Because TiDB servers are stateless, production setups put a load balancer such as HAProxy, LVS or TiProxy in front of several of them. Clients connect to the balancer's address, and a failed TiDB node simply drops out of rotation. Enable TLS for anything leaving a private network.
Take quiz
TiDB servers are stateless
Each server owns a private shard
Clients must use sticky shards
Servers share a single disk
jdbc:tidb://host:2379/db
jdbc:mysql://host:4000/db
jdbc:mysql://host:20160/db
jdbc:postgresql://host:4000/db
20. What isolation levels does TiDB support?
TiDB supports Read Committed and Repeatable Read. The default is Repeatable Read, but TiDB implements it as Snapshot Isolation (SI): each transaction reads a snapshot taken at its start timestamp.
| Behaviour | TiDB Repeatable Read | MySQL InnoDB Repeatable Read |
| Read view | Snapshot at transaction start | Snapshot at first read |
| Phantom reads | Not seen in snapshot reads | Prevented with gap locks |
| Write skew | Possible | Possible |
Read Committed is available only with pessimistic transactions. SERIALIZABLE is not supported, so use SELECT ... FOR UPDATE when you need to guard against write skew.
Take quiz
Strict serializability
Snapshot Isolation
Read Uncommitted
Gap-lock based isolation
Switch to MyISAM tables
Lower the Region size
Use SELECT ... FOR UPDATE on the rows you depend on
Disable the TSO
21. How does TiDB store table rows in TiKV?
TiDB maps relational data to ordered key-value pairs, so TiKV only needs to store keys and values.
| Data | Key | Value |
| Row | t{tableID}_r{rowID} |
All column values of the row |
| Non-unique index | t{tableID}_i{indexID}_{indexedValues}_{rowID} |
Empty / small marker |
| Unique index | t{tableID}_i{indexID}_{indexedValues} |
The rowID |
The rowID is the integer primary key when the table uses a clustered integer key, otherwise TiDB generates a hidden _tidb_rowid.
Keys are sorted, so rows of one table sit side by side and range scans stay sequential. The whole key space is then cut into Regions and spread across stores.
Take quiz
row_{tableName}_{pk}
r{rowID}_t{tableID}_idx
t{tableID}_r{rowID}
{database}.{table}.{column}
The Region ID
The PD timestamp only
The server connection ID
A hidden _tidb_rowid
22. How does TiDB scale horizontally?
TiDB scales each layer on its own.
Compute: add more stateless TiDB servers and put them behind the load balancer. Nothing needs to be rebalanced.
Storage: add TiKV nodes. PD notices the new stores and moves Regions and Region leaders onto them in the background until the load is even. Growing Regions split automatically, so data distribution follows size without a resharding project.
Analytics: add TiFlash nodes to grow columnar capacity separately from OLTP.
The result is that capacity and throughput grow roughly linearly as long as the workload avoids a single hot key range.
Take quiz
Restarts all TiDB servers
Drops the oldest Region
Rebuilds the SQL schema
Moves Regions and leaders onto it in the background
The stateless TiDB server layer
TiKV
TiFlash
PD etcd
23. How does Raft replication work in TiKV?
Each Region is its own Raft group with one leader and usually two followers. All reads and writes for the Region go to the leader.
- The leader appends the write as a log entry.
- It sends the entry to followers.
- Once a majority (2 of 3) has persisted it, the entry is committed.
- The leader applies it to RocksDB and answers the client.
If the leader dies, followers stop receiving heartbeats and hold an election, so another replica takes over. A group of three survives one failed replica, a group of five survives two.
sequenceDiagram participant C as Client participant L as Leader participant F1 as Follower 1 participant F2 as Follower 2 C->>L: write L->>F1: append log L->>F2: append log F1-->>L: ack L-->>C: committed after majority
Take quiz
After a majority of replicas have persisted it
As soon as the leader receives it
After all replicas including TiFlash ack
After PD approves it
Zero
One
Two
Three
24. What is the difference between TiDB and MySQL?
They share a protocol but are built very differently.
| Aspect | TiDB | MySQL |
| Architecture | Distributed, compute and storage separated | Single node, optional replicas |
| Scaling writes | Add nodes, automatic rebalancing | Vertical scaling or manual sharding |
| Storage | TiKV (row) plus TiFlash (column) | InnoDB (row) |
| HA | Raft, automatic failover | Async or semi-sync replication, failover tooling |
| Transactions | Distributed ACID, snapshot isolation | Single-node ACID, lock-based RR |
| Analytics | HTAP via TiFlash | Separate warehouse usually needed |
| Missing features | No stored procedures or triggers | Full feature set |
Pick MySQL for small to mid data on one box. Pick TiDB when data or write throughput outgrows one machine.
Take quiz
Both scale writes only by adding read replicas
TiDB scales writes by adding nodes, MySQL usually scales vertically
MySQL scales writes automatically through Raft
TiDB cannot scale writes
Manual binlog replay
Cron-based promotion script
Raft-based automatic leader election
DNS round robin only
25. What is the difference between optimistic and pessimistic transactions in TiDB?
The difference is when conflicts are detected.
| Pessimistic (default) | Optimistic | |
| Locking | Locks rows when DML runs | Locks only at commit (prewrite) |
| Conflict seen | Immediately, statement waits or deadlocks | At COMMIT, as a write conflict |
| Behaviour on conflict | Waits for the lock | COMMIT fails, application retries |
| Best for | High contention, MySQL-like behaviour | Low contention, many short transactions |
Pessimistic mode has been the default since v3.0.8 and matches MySQL expectations. You can choose per transaction:
BEGIN PESSIMISTIC; BEGIN OPTIMISTIC;
An optimistic failure surfaces as error 9007 (write conflict), so the application must be ready to retry.
Take quiz
Pessimistic
Read Committed only
Optimistic
Both detect only after GC
Optimistic
Serializable
No default, must be set per session
Pessimistic
26. How does TiDB implement distributed transactions?
TiDB uses a Percolator-style two-phase commit (2PC) on top of TiKV, with MVCC and timestamps from PD.
- Get
start_tsfrom PD. Reads use it as the snapshot. - Prewrite: pick one written key as the primary, then lock every key in the transaction, pointing the locks at the primary.
- Get
commit_tsfrom PD. - Commit: commit the primary key. This is the real commit point.
- Commit the secondary keys asynchronously.
If the client dies midway, another reader that meets a leftover lock checks the primary key's state and either rolls the lock forward or back. No central transaction coordinator is needed.
sequenceDiagram participant T as TiDB participant P as PD participant K as TiKV T->>P: get start_ts T->>K: prewrite primary + secondaries T->>P: get commit_ts T->>K: commit primary K-->>T: success T-)K: commit secondaries async
Take quiz
Writing the first secondary key
Getting start_ts
The prewrite of the last key
Committing the primary key
Locks point to the primary key, whose state decides the outcome
A global transaction log in PD
A background MySQL binlog
A heartbeat from the client
27. What is TSO in TiDB?
TSO is the Timestamp Oracle, a service inside the PD leader that issues globally unique, strictly increasing timestamps.
A timestamp is a 64-bit value: the high part is a physical time in milliseconds and the low 18 bits are a logical counter, so one millisecond can serve up to 262,144 timestamps.
Every transaction asks TSO for a start_ts (its snapshot) and a commit_ts. These ordered numbers are how MVCC decides which version of a row a transaction can see. TiDB batches requests to PD, but if PD is far away in network terms, the round trip adds latency to every transaction.
Take quiz
To define the snapshot it reads from
To pick the Region leader
To name the Raft group
To size the RocksDB cache
Any TiKV node
The PD leader
The TiFlash node
The TiDB server that owns the session
28. What is the difference between AUTO_INCREMENT and AUTO_RANDOM?
Both generate primary key values, but they behave differently under distributed load.
| AUTO_INCREMENT | AUTO_RANDOM | |
| Value pattern | Increasing, cached in batches per TiDB server | Random high bits + incrementing low bits |
| Ordering | Unique, not strictly monotonic across servers | Not ordered |
| Hotspot risk | High, inserts hit the latest Region | Low, inserts scatter |
| Column type | Any integer key | BIGINT clustered primary key only |
CREATE TABLE orders ( id BIGINT PRIMARY KEY AUTO_RANDOM(5), amount DECIMAL(10,2) );
If you need MySQL-like monotonic IDs, use AUTO_ID_CACHE 1 (v6.4+), at the cost of throughput.
Take quiz
It disables Raft
It scatters new rows across many Regions
It stores all rows in TiFlash
It locks the table
Any VARCHAR column
A DATETIME column
A BIGINT clustered primary key
A non-indexed INT
29. What is a clustered index in TiDB?
With a clustered index the primary key is the row key itself, so the row is stored directly under the primary key value. A primary key lookup needs one read from TiKV.
With a non-clustered primary key, TiDB stores the row under a hidden _tidb_rowid and keeps the primary key as a separate unique index. A lookup then needs an index read followed by a table read (two steps).
CREATE TABLE t ( id BIGINT PRIMARY KEY CLUSTERED, v INT );
Clustered is faster for point lookups and range scans on the key. The trade-off is that monotonic keys write to one place. Use AUTO_RANDOM, or a non-clustered key with SHARD_ROW_ID_BITS, to spread inserts. The default depends on version and tidb_enable_clustered_index.
Take quiz
Three
Always two
One
None, it uses cache only
Lookups become impossible
Rows must be stored twice
TiFlash replicas fail
Inserts concentrate on the last Region
30. Explain the execution flow of a SQL statement in TiDB?
A statement travels through the stateless TiDB server, then fans out to storage.
- The client sends SQL over the MySQL protocol and the TiDB server parses it into an AST.
- The optimizer builds a logical plan and applies rule-based rewrites such as predicate pushdown.
- The cost-based optimizer, using statistics, picks a physical plan and decides whether to read TiKV or TiFlash.
- The executor asks PD for a timestamp if needed, finds Regions through its Region cache, and sends coprocessor requests to TiKV or TiFlash.
- Storage nodes filter and aggregate locally. TiDB merges the partial results and returns the final result set.
flowchart LR A[Client] --> B[Parse] B --> C["Logical plan"] C --> D["Cost-based physical plan"] D --> E[Executor] E --> F["TiKV / TiFlash coprocessor"] F --> E E --> A
Take quiz
Parsing
Returning the result set
Raft log append
The cost-based physical plan optimization
To filter and aggregate data at the storage node
To parse SQL on TiKV
To elect a Raft leader
To reconnect clients
31. How do you read TiDB EXPLAIN output?
Run EXPLAIN for the plan or EXPLAIN ANALYZE to execute it and see real numbers.
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 42;
Key columns:
- id: operator names. Read the tree bottom-up, children feed their parent.
- estRows / actRows: estimated versus actual rows. A big gap points to stale statistics.
- task:
rootruns on TiDB,cop[tikv]andcop[tiflash]are pushed down. - access object and operator info: the table, index and ranges used.
Red flags are TableFullScan on a big table, no pushdown for selective filters, and a large IndexLookUp double read.
Take quiz
Stale or missing statistics
A failed Raft election
Too many PD nodes
A closed MySQL port
It runs on the client
The operator is pushed down to TiKV
It reads from PD
It is waiting on a lock
32. How does TiDB collect optimizer statistics?
TiDB keeps per-table statistics: row counts, column histograms, Count-Min Sketch and TopN values, and distinct counts. The optimizer reads them to estimate row counts and choose indexes and join orders.
You collect them manually with:
ANALYZE TABLE orders;
Auto analyze runs in the background when the ratio of modified rows crosses tidb_auto_analyze_ratio (0.5 by default), inside the configured time window. Check health with SHOW STATS_HEALTHY and SHOW STATS_META.
Run a manual ANALYZE after bulk loads or large deletes, since auto analyze may lag behind.
Take quiz
OPTIMIZE TABLE
ANALYZE TABLE
FLUSH STATS
REBUILD INDEX
Every restart of PD
Each SELECT statement
Modified row ratio passing the configured threshold
A TiFlash replica becoming available
33. When should you use TiFlash replicas?
Add a TiFlash replica when queries scan or aggregate lots of rows and a row store is the wrong shape for them.
- Dashboards and reports over live data
- Large GROUP BY, window functions and multi-table joins
- Wide tables where queries touch only a few columns
- Mixed workloads where analytics must not slow down OLTP
Skip it for pure point lookups and small transactional tables, because TiKV already serves those well and the replica only adds storage cost.
The optimizer chooses between engines by cost, and you can force one with a hint:
SELECT /*+ READ_FROM_STORAGE(TIFLASH[o]) */ SUM(amount) FROM orders o;
Take quiz
Single-row lookup by primary key
Updating one counter
Large aggregations over many rows
Inserting one small row
USE_TIFLASH(t)
FORCE ENGINE tiflash
SET_COLUMNAR(t)
READ_FROM_STORAGE(TIFLASH[t])
34. How do you create a TiFlash replica for a table?
You need at least one TiFlash node in the cluster, then run:
ALTER TABLE orders SET TIFLASH REPLICA 1;
The number is the replica count, and it cannot exceed the number of TiFlash nodes. Check progress with:
SELECT TABLE_NAME, REPLICA_COUNT, AVAILABLE, PROGRESS FROM information_schema.tiflash_replica WHERE TABLE_SCHEMA = 'shop';
Reads use TiFlash once AVAILABLE is 1. To remove it, set the count to 0. You can also apply it to a whole database with ALTER DATABASE shop SET TIFLASH REPLICA 1.
Take quiz
mysql.tiflash_status
performance_schema.replica
SHOW SLAVE STATUS
information_schema.tiflash_replica
The number of TiFlash nodes
The number of PD nodes
The TiDB server count
The table's primary key type
35. What is the difference between Stale Read and Follower Read?
Both let you read from replicas other than the leader, but for different goals.
| Stale Read | Follower Read | |
| Data returned | Historical data at a chosen timestamp | Latest committed data |
| Goal | Lower latency, read from the nearest replica | Offload the leader, spread read load |
| How | AS OF TIMESTAMP, tidb_read_staleness |
SET tidb_replica_read = 'follower' |
| Consistency | Slightly old but consistent snapshot | Strongly consistent (confirmed with leader) |
SELECT * FROM orders AS OF TIMESTAMP NOW() - INTERVAL 5 SECOND;
Stale Read suits multi-region deployments where a few seconds of lag is fine. Follower Read is a better fit when a hot Region leader is saturated but answers must stay fresh.
Take quiz
Stale Read
Follower Read
Leader lease read
Async commit
tidb_read_staleness
tidb_replica_read
tidb_follower_mode
tidb_snapshot_tso
36. Explain how TiDB performs online DDL?
TiDB changes schema without blocking reads or writes, using the state-machine approach from Google's F1 paper.
A schema object moves through intermediate states, for example for a new index:
- none: index does not exist.
- delete only: deletes maintain it, nothing reads or inserts.
- write only: inserts and deletes maintain it, reads still ignore it.
- write reorganization: existing rows are backfilled.
- public: queries can use it.
Only two adjacent schema versions can be active across servers at once, so mixed versions never corrupt data. One TiDB server is the DDL owner and runs queued jobs. Follow progress with ADMIN SHOW DDL JOBS. Since v6.3, tidb_ddl_enable_fast_reorg speeds up ADD INDEX backfill.
Take quiz
The index is dropped
Existing rows are backfilled into the new index
Clients are disconnected
Raft leaders transfer
SHOW DDL STATUS
SHOW PROCESSLIST ONLY
ADMIN SHOW DDL JOBS
ADMIN CHECK TABLE
37. What are Placement Rules in SQL?
Placement Rules in SQL let you control where replicas and leaders of your data are stored, using plain SQL instead of editing PD configuration.
It builds on store labels (region, zone, host, disk type). You create a policy and attach it to a table, partition or database:
CREATE PLACEMENT POLICY eu_only PRIMARY_REGION="eu-west-1" REGIONS="eu-west-1,eu-central-1" FOLLOWERS=2; ALTER TABLE customers PLACEMENT POLICY = eu_only;
Typical uses are keeping data inside a legal region, putting hot partitions on fast SSD stores and old ones on cheaper disks, and isolating a critical table onto dedicated nodes. The feature became GA in v6.0.
Take quiz
How SQL text is parsed
Which MySQL port is used
Where replicas and leaders of data are stored
Password complexity
SET TABLE POLICY name
GRANT PLACEMENT ON table
ALTER REGION ... USE name
ALTER TABLE ... PLACEMENT POLICY = name
38. How do you back up and restore TiDB?
The main tool is BR (Backup and Restore), which works at the storage layer and is far faster than logical dumps for large clusters.
- Snapshot backup: a full backup at one timestamp.
- Log backup: continuous capture of changes, which enables point-in-time recovery (PITR) from v6.2.
tiup br backup full --pd 10.0.0.1:2379 --storage "s3://bucket/full-2026-11-11" tiup br log start --task-name=pitr --pd 10.0.0.1:2379 --storage "s3://bucket/log" tiup br restore point --pd 10.0.0.1:2379 --full-backup-storage "s3://bucket/full-2026-11-11" --storage "s3://bucket/log" --restored-ts "2026-11-11 10:30:00+0000"
Storage targets include S3, GCS, Azure Blob and NFS. For small data sets, Dumpling logical exports also work.
Take quiz
Dumpling with --where
TiCDC changefeed pause
tiup cluster restart
Log backup with PITR
BR
Dumpling
DM
TiProxy
39. What is the difference between Dumpling, Lightning and BR?
They solve different parts of data movement.
| Tool | Level | Direction | Best for |
| Dumpling | Logical (SQL/CSV) | Export from TiDB or MySQL | Small to mid exports, feeding Lightning |
| Lightning | Physical or logical | Import into TiDB | Fast initial loads of large datasets |
| BR | Physical (SST files) | Backup and restore TiDB clusters | Full backups, PITR, cluster cloning |
A common migration chain is Dumpling to Lightning for the initial load, then DM or TiCDC for incremental sync. BR is for TiDB-to-TiDB protection, not for loading MySQL dumps.
Take quiz
BR
Dumpling
DM
TiUP playground
BR
Dumpling
TiCDC
PD Control
40. Why choose TiDB over sharded MySQL?
Sharded MySQL scales, but the complexity moves into your application and operations. TiDB moves it into the database.
| Concern | Sharded MySQL | TiDB |
| Cross-shard transactions | Hard, needs XA or sagas | Native distributed ACID |
| Resharding | Planned migration project | Automatic Region split and balancing |
| Cross-shard queries and joins | Application or middleware work | Plain SQL |
| Schema changes | Run on every shard | One online DDL |
| Failover | Per shard tooling | Raft automatic failover |
The trade-offs: TiDB commits take extra network round trips, so single-row latency is higher than local MySQL, and it needs at least three storage nodes. If your data fits one MySQL comfortably, the simpler option wins.
Take quiz
Running SELECT 1
Transactions spanning rows on different shards
Creating a user
Connecting with a client
No SQL support
Cannot use indexes
Higher single-row commit latency and more nodes
Loses data when a node fails
41. What causes hotspots in TiDB and how do you fix them?
A hotspot is when most reads or writes hit one Region, so one TiKV node saturates while others idle.
Common causes:
- Monotonic keys, such as AUTO_INCREMENT primary keys or timestamp-prefixed indexes
- A small, very popular table living in a single Region
- Sequential bulk inserts
Fixes:
- Use
AUTO_RANDOMfor the primary key. - For non-clustered tables use
SHARD_ROW_ID_BITSwithPRE_SPLIT_REGIONS. - Add a hash or bucket prefix to monotonic index keys.
- Use Follower Read for hot read Regions, and let load-based split divide busy Regions.
CREATE TABLE logs ( id BIGINT AUTO_RANDOM PRIMARY KEY, msg TEXT ); -- or CREATE TABLE t2 (a INT, b INT) SHARD_ROW_ID_BITS=4 PRE_SPLIT_REGIONS=3;
Detect hotspots with the Key Visualizer heatmap in TiDB Dashboard.
Take quiz
AUTO_ID_CACHE 1
tidb_replica_read
SHARD_ROW_ID_BITS with PRE_SPLIT_REGIONS
ENGINE=InnoDB
Top SQL
ADMIN SHOW DDL
Dumpling
Key Visualizer
42. How do you troubleshoot slow queries in TiDB?
Work from finding the query to understanding its plan.
- Find it: open Slow Queries in TiDB Dashboard or query
information_schema.slow_query. The threshold istidb_slow_log_threshold(300 ms default).statements_summaryand Top SQL show the heaviest statements overall. - Inspect the plan: run
EXPLAIN ANALYZEand compare estRows to actRows. - Check statistics: run
ANALYZE TABLEif they are stale. - Look at time breakdown: parse, compile, coprocessor wait, lock wait, or TiKV scan time in the slow log fields.
- Fix: add a covering index, rewrite the query, use an optimizer hint or a SQL binding to pin a good plan.
SELECT query_time, query FROM information_schema.slow_query ORDER BY query_time DESC LIMIT 5;
If a plan keeps regressing after upgrades, Plan Replayer captures the environment for offline analysis.
Take quiz
10 ms
5 seconds
1 minute
300 ms
SQL binding
Placement policy
Raft learner
TTL table option
43. How does garbage collection work in TiDB?
MVCC keeps old versions of rows so transactions can read consistent snapshots. GC removes versions that no transaction can need anymore.
The elected GC leader (one TiDB server) calculates a safe point equal to current time minus tidb_gc_life_time (10 minutes by default). Then it:
- Resolves leftover locks older than the safe point.
- Deletes dropped table and index ranges.
- Lets TiKV drop old versions during compaction.
A transaction or snapshot read older than the safe point fails with a "GC life time is shorter than transaction duration" error. Services such as BR and TiCDC register their own service safe points, which hold GC back and can cause growth in storage if left running. Raise tidb_gc_life_time only when you really need long snapshot reads.
Take quiz
10 minutes
24 hours
1 second
7 days
It is promoted to serializable
It can fail with a GC life time error
It switches to TiFlash
It is silently committed twice
44. What happens when a TiKV node fails?
The cluster keeps serving as long as each affected Region still has a majority of replicas.
- Raft leaders on the failed node stop sending heartbeats. Followers of those Regions hold an election and a new leader takes over, usually within seconds.
- TiDB servers get a region error, refresh their Region cache from PD and retry on the new leader.
- PD marks the store Disconnected. It waits
max-store-down-time(30 minutes by default) in case the node returns. - After that the store is Down and PD recreates the missing replicas on other stores by copying from surviving replicas.
If a Region loses its majority (for example two of three replicas), it becomes unavailable until replicas return, or an operator performs unsafe recovery, which can risk data loss.
Take quiz
Deletes the affected tables
Rebuilds the lost replicas on other stores
Switches TiDB to read-only
Restarts all TiKV nodes
When any single replica fails
When a TiDB server restarts
When it loses a majority of its replicas
When a TiFlash node restarts
45. What happens when the PD leader fails?
PD runs on embedded etcd as a Raft group, so the remaining PD members elect a new leader, typically within a few seconds.
The new leader reloads cluster metadata and, importantly, restarts the TSO from a safe value. PD persists a TSO upper bound to etcd ahead of time, so the new leader can start above every timestamp the old one could have issued. Timestamps therefore never go backwards.
During the election, requests that need a timestamp wait, so new transactions pause briefly. TiDB and TiKV cache Region routing, so work that does not need PD can continue for a short time. Once the new leader is up, everything resumes.
If PD loses its majority (two of three nodes), the cluster cannot allocate timestamps or schedule, and transactions stop until a majority returns.
Take quiz
TiKV reissues all timestamps
Clients generate their own TSO
The timestamp upper bound is persisted in etcd ahead of use
The timestamps are random
Only DDL on TiFlash
Only backups
Nothing, PD is optional
Timestamp allocation and scheduling
46. How can you speed up bulk data loading into TiDB?
Pick the method by size, then tune writes so they spread across the cluster.
- Very large initial loads: TiDB Lightning in physical import mode or the
IMPORT INTOstatement. They write sorted SST files directly to TiKV. - Ongoing inserts: batch multi-row
INSERTstatements (a few hundred rows each), run on many connections in parallel, and keep transactions well below the size limit. - Avoid hotspots: use
AUTO_RANDOMorSHARD_ROW_ID_BITSwith pre-split Regions so inserts hit many Regions at once. - Big deletes or updates: use non-transactional DML (
BATCH ON id LIMIT 5000 DELETE ...) to split work into small chunks.
After loading, run ANALYZE TABLE so the optimizer sees real row counts.
Take quiz
Single-row INSERT in a loop
Dumpling --rows
TiCDC changefeed
Lightning physical import mode
It cuts per-statement and commit overhead
It disables MVCC
It bypasses Raft
It makes the table clustered
47. How do async commit and 1PC reduce latency?
Standard 2PC costs two sequential rounds: prewrite, then commit. That extra round adds noticeable latency, especially across zones.
Async commit lets the client report success once prewrite has succeeded. The primary lock stores the list of secondary keys, so any reader can still determine the outcome even if the commit step has not finished. The final commit phase runs in the background.
1PC applies to transactions that touch keys in only one Region. TiKV can write the data and commit it in a single Raft write, skipping the second phase altogether.
Variables: tidb_enable_async_commit and tidb_enable_1pc. The trade-off is that they give causal consistency, not external consistency (linearizability), between transactions. Applications that need strict ordering across independent clients should check this before enabling them.
Take quiz
After the prewrite phase succeeds
Before prewrite starts
After all secondaries are committed
After the next GC run
Only for SELECT statements
When all keys of the transaction are in one Region
Only when TiFlash is disabled
Only for DDL
48. Explain the internal working of TiFlash MPP mode?
MPP (massively parallel processing) lets several TiFlash nodes run one query together, exchanging data between them instead of sending everything to the TiDB server.
- The TiDB optimizer picks MPP when it is cheaper and splits the plan into fragments at exchange points.
- The TiDB node acts as coordinator and dispatches fragments as tasks to TiFlash nodes.
- Each TiFlash node scans its local column data and runs its fragment in a vectorized pipeline.
- Exchange operators move rows between nodes: broadcast a small table to everyone, shuffle by hash key for big joins and aggregations, or pass results to the final stage.
- The last fragment sends results back to TiDB.
flowchart LR A["TiDB coordinator"] --> B["TiFlash node 1"] A --> C["TiFlash node 2"] B <-->|shuffle / broadcast| C B --> D["Final fragment"] C --> D D --> A
Plans show mpp[tiflash] and ExchangeSender / ExchangeReceiver operators. Control it with tidb_allow_mpp and tidb_enforce_mpp.
Take quiz
IndexLookUp
ExchangeSender and ExchangeReceiver
TableFullScan
SelectLock
PD leader
A random TiKV node
The TiDB node that received it
The Dashboard
49. How do you troubleshoot write conflicts and deadlocks in TiDB?
Start by identifying which transaction mode and error you see.
- Error 9007 (write conflict): seen in optimistic mode at commit. Retry the transaction in the application, shorten it, or switch hot paths to pessimistic mode.
- Error 1205 (lock wait timeout): a pessimistic transaction waited too long. Find the blocker in
information_schema.data_lock_waitsand look attidb_trxfor long runners. - Error 1213 (deadlock): TiDB detects cycles and aborts one victim. Review
information_schema.deadlocksto see which statements collided.
Prevention:
- Touch rows in a consistent order in every code path.
- Keep transactions short and avoid user think-time inside them.
- Use
SELECT ... FOR UPDATE NOWAITwhen you prefer failing fast over waiting. - Always add retry logic with backoff for 9007 and 1213.
Take quiz
mysql.deadlock_log
performance_schema.locks
information_schema.deadlocks
information_schema.tidb_slow
Using longer transactions
Disabling retries
Increasing the Region size
Accessing rows in the same order everywhere
50. How do you scale out a TiDB cluster?
With TiUP, scaling out is online and needs no downtime.
- Write a small topology file listing only the new nodes (for example one more
tikv_servershost). - Run the scale-out command.
- Verify the new nodes are
Up. - For TiDB servers, add them to the load balancer.
tiup cluster scale-out prod-tidb scale-out.yaml tiup cluster display prod-tidb
After a new TiKV starts, PD gradually moves Regions and leaders to it, which you can watch in Grafana. To scale in, run tiup cluster scale-in prod-tidb -N 10.0.0.9:20160. A TiKV node goes Offline while Regions migrate away, then Tombstone, and you remove it with tiup cluster prune. Do not shrink below three TiKV nodes with three replicas.
On Kubernetes, change the replica count of the component in the TidbCluster resource and TiDB Operator does the rest.