[CockroachDB Internals #4] CockroachDB leverages multi-version concurrency control to process concurrent requests and guarantee consistency. Let’s quickly understand what it is ⚡
The core idea behind MVCC is to never overwrite the existing value. So, how does the update work?
⚡ No In-place Update
When an update is shot at CockroachDB, it never replaces or overwrites the existing data. Instead, it creates a new version of the data and assigns it a version number.
This eradicates dense lock contentions and improves concurrency. This also allows multiple transactions can seamlessly operate in parallel.
⚡ Version numbers
The key component of MVCC is the version number and CockroachDB uses a Hybrid Logical Timestamp (HLC) as the version number.
Because the HLC values are roughly timestamps and monotonically increasing, it is used in differentiating multiple versions of data, powering the transaction isolation, and enabling Time Travel.
We will talk about HLC in-depth in the future.
⚡ Time Travel
Because of MVCC, CockroachDB supports time travel queries, which essentially means, we can get a consistent data view of the database for a previous timestamp. Here’s a simple query demonstrating time travel
SELECT * FROM orders AS OF SYSTEM TIME '-14d';
⚡ Reads and Writes
When a read transaction starts, it specifies the timestamp (HLC) at which it wants to read the data. This timestamp is used to determine which versions of the data are visible to the transaction.
CockroachDB ensures that the transaction only sees versions of the data that were committed before the specified timestamp, providing snapshot isolation guarantees.
When a write transaction modifies a key, it assigns a new version number to the key’s value, making the new version visible to subsequent read transactions that start after the write transaction commits.
⚡ Recently, I started diving deep into CockroachDB internals and will share my learning in public. So, if you find it amusing, follow along.