In Redis 4.0, there is a new command UNLINK to delete the keys in Redis memory.
This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. This is where the command name comes from: the command just unlinks the keys from the keyspace. The actual removal will happen later asynchronously.
So one can always (100% times) use UNLINK instead of DEL as UNLINK is nonblocking, unlike DEL, right?
Before discussing which one is better, let's take a look at the difference between these commands. Both
DEL
andUNLINK
free the key part in blocking mode. And the difference is the way they free the value part.DEL
always frees the value part in blocking mode. However, if the value is too large, e.g. too many allocations for a largeLIST
orHASH
, it blocks Redis for a long time. In order to solve the problem, Redis implements theUNLINK
command, i.e. an 'non-blocking' delete.In fact,
UNLINK
is NOT always non-blocking/async. If the value is small, e.g. the size ofLIST
orHASH
is less than64
, the value will be freed immediately. In this way,UNLINK
is almost the same asDEL
, except that it costs a few more function calls thanDEL
. However, if the value is large, Redis puts the value into a list, and the value will be freed by another thread i.e. the non-blocking free. In this way, the main thread has to do some synchronization with the background thread, and that's also a cost.In a conclusion, if the value is small,
DEL
is at least, as good asUNLINK
. If value is very large, e.g.LIST
with thousands or millions of items,UNLINK
is much better thanDEL
. You can always safely replaceDEL
withUNLINK
. However, if you find the thread synchronization becomes a problem (multi-threading is always a headache), you can rollback toDEL
.YES. please have a read on Lazy Redis is better Redis from antirez. But the reason is not that the unlink is nonblocking command. The reason is unlink is smarter than del.
Also, I think the more fast way is we do the decision for redis: using DEL for small key, using UNLINK for a huge key such as big list or set. We can decrease the needless calculation of redis.