I am currently using Redis and want to replace the existing Redis with TiKV. However, I am using Redis’s atomic incrby as a distributed lock to ensure that only one thread operates on critical resources at the same time. I would like to ask if this atomic incrby can also be achieved using TiKV to get the same effect as using Redis? Thank you.
Well, the atomicity of Redis and the transactional support provided by TiKV are different in their specific manifestations.
Redis relies on a single-threaded queue model to ensure that only one resource can be scheduled and executed at the same time.
TiKV needs to rely on some mechanisms to meet this requirement. It can inherently support atomicity because the upper layer of atomicity is transactional.
Mainly, TiKV consists of multiple nodes, and data can be distributed across different nodes.
Redis relies on the slot algorithm to find the point and node for reading (in cluster mode).
Therefore, if you want to use TiKV to implement Redis’s distributed lock, you will need to implement some additional functionalities yourself.
Can you specifically say what functions? I guess: since TiKV is multiple nodes, you need to implement a single-threaded queue mode similar to native Redis in the application. Considering that I am now using Tidis as middleware, can these functions be implemented in Tidis, right?
The official PingCAP Tidis has not been open-sourced yet, but it is expected to be open next week. Please stay tuned.
Tidis currently implements the incrby command, and it can ensure atomicity in terms of semantics. However, in cases of high concurrency modifying the same key, transaction conflicts may occur, and it will automatically retry. This extreme scenario needs to be verified in specific contexts.
Yes, retry logic is worth considering. Additionally, incorporating the single-threaded concept of Redis into Tidis to create a specific custom version is also a feasible approach, right?
I think it’s entirely possible to use TiDB to implement distributed locks.
Implement distributed locks based on the database.
The “select for update” method can achieve this.
It can be divided into optimistic lock and pessimistic lock modes, depending on the tolerance of your application, you can implement it yourself.
Pessimistic lock: Use “select … where … for update” exclusive lock
Optimistic lock: Implement optimistic lock by adding an incrementing version number field
My main consideration right now is to replace my current Redis with TiKV. Replacing Redis with TiDB might be considered in the future. However, you mentioned using TiDB for distributed locking, and I can refer to that idea when the time comes.
Using the features of the database, it can be achieved. There are definitely databases using this method now. Create a table and encapsulate an API, and it should work.