COP 503: Coprocessor Intro
In RAFTSTORE 502, Raftstore returned a snapshot that gives a reader a consistent view of one Region's data. TiKV can use the snapshot to read a single key or scan a key range.
This chapter follows the range-scan path used for SQL queries. TiDB can push part of a query plan to TiKV, where the coprocessor, or cop, scans the relevant keys and performs the requested computation.
Push Computation to Storage
A table may span many Regions distributed across different TiKV stores. Consider this query:
SELECT COUNT(*) FROM orders WHERE status = 'paid';
Without pushdown, TiDB would fetch the scanned rows from those Regions, then filter and count them itself.
TiKV scans rows -> scanned rows -> TiDB filters and counts
The answer is one number, but all the scanned rows cross the network.
With pushdown, TiDB sends the filter and count operation with the scan request. Each TiKV task scans its portion of the table, keeps the paid rows, and returns a partial count. TiDB then adds the counts together.
TiKV scans, filters, and counts -> partial counts -> TiDB combines
The input data remains close to storage, and only the much smaller partial results cross the network.
Cop supports more than this particular combination. Filters select rows, aggregations such as COUNT and SUM reduce many rows to a value, and TopN keeps the first N rows under an ordering. TiDB can combine such operators and push the resulting work to TiKV.
Cop Tasks
TiKV stores table rows and index entries as ordered keys. A table or index scan therefore becomes a scan over a continuous interval of keys.
That interval may span multiple Regions. TiDB splits it at Region boundaries and sends a cop task to each relevant Region. These tasks can run in parallel across TiKV stores.
TiDB cop request
|
v
Raftstore obtains a snapshot
|
v
scan the Region's key interval
|
v
run the pushed-down operators
|
v
return a partial result
Each task processes only its Region's portion of the data. For the COUNT example, each task returns a partial count, and TiDB adds them together.
The Read Pool
TiKV runs cop tasks on read-pool workers. A task occupies a worker while it scans data and executes operators.
Its cost depends on the data scanned and the computation performed, not only on the result size. Broad scans or expensive operators can therefore keep workers busy even when they return little data. When all workers are busy, later tasks wait and latency rises.
COP 606 will examine TiKV key mapping and common coprocessor access patterns in more depth.