Before you start, ensure that you have set up a TiKV cluster and installed the Python package according to .
TiKV Java client’s Transaction API has not been released yet, so the Python client is used in this example.
Transaction isolation is one of the foundations of database transaction processing. Isolation is one of the four key properties of a transaction (commonly referred as ACID).
TiKV implements consistency, which means that:
- all reads made in a transaction will see a consistent snapshot of the database (in practice, TiKV Client reads the last committed values that exist since TiKV Client has started);
The following example shows how to test TiKV’s snapshot isolation.
Run the test script
python3 test_snapshot_isolation.py
[]
[]
From the above example, you can find that snapshot1
cannot read the data before and after txn2
is commited. This indicates that snapshot1
can see a consistent snapshot of the database.
TiKV supports distributed transactions using either pessimistic or optimistic transaction models.
TiKV uses the optimistic transaction model by default. With optimistic transactions, conflicting changes are detected as part of a transaction commit. This helps improve the performance when concurrent transactions infrequently modify the same rows, because the process of acquiring row locks can be skipped.
The following example shows how to test TiKV with optimistic transaction model.
Run the test script
python3 test_optimistic.py
Exception: KeyError WriteConflict
From the above example, you can find that with optimistic transactions, conflicting changes are detected when the transaction commits.
In the optimistic transaction model, transactions might fail to be committed because of write–write conflict in heavy contention scenarios. In the case that concurrent transactions frequently modify the same rows (a conflict), pessimistic transactions might perform better than optimistic transactions.
The following example shows how to test TiKV with pessimistic transaction model.
Save the following script to file test_pessimistic.py
.
python3 test_pessimistic.py
Exception: KeyError
From the above example, you can find that with pessimistic transactions, conflicting changes are detected at the moment of data writing.