How to Use UNLINK Command in Redis for Non-Blocking Key Deletion
Use the
UNLINK command in Redis to delete keys asynchronously without blocking the server. It accepts one or more keys and returns the number of keys that were unlinked. This is useful for deleting large keys without causing delays.Syntax
The UNLINK command syntax is simple. You provide one or more keys to delete asynchronously.
UNLINK key [key ...]: Deletes the specified keys asynchronously.- The command returns the number of keys that were unlinked.
redis
UNLINK key1 key2 key3
Example
This example shows how to use UNLINK to delete keys without blocking Redis. It deletes two keys and returns how many were removed.
redis
SET key1 "value1" SET key2 "value2" UNLINK key1 key2 EXISTS key1 EXISTS key2
Output
OK
OK
(integer) 2
(integer) 0
(integer) 0
Common Pitfalls
One common mistake is expecting UNLINK to delete keys immediately like DEL. UNLINK schedules keys for asynchronous deletion, so keys may still exist briefly. Also, UNLINK returns the number of keys it started unlinking, not whether keys existed before.
Another pitfall is using UNLINK on keys that do not exist; it simply returns zero for those keys.
redis
DEL key1 key2 # Blocks Redis until keys are deleted UNLINK key1 key2 # Deletes keys asynchronously without blocking
Quick Reference
| Command | Description | Returns |
|---|---|---|
| UNLINK key [key ...] | Asynchronously deletes specified keys | Number of keys unlinked |
| DEL key [key ...] | Synchronously deletes specified keys | Number of keys deleted |
| EXISTS key | Checks if a key exists | 1 if exists, 0 if not |
Key Takeaways
Use
UNLINK to delete keys asynchronously without blocking Redis.UNLINK accepts multiple keys and returns how many were unlinked.UNLINK does not guarantee immediate deletion; keys are removed in the background.For immediate blocking deletion, use
DEL instead.Using
UNLINK on non-existing keys returns zero without error.