Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

DEL, UNLINK, FlushDB

Learn to delete keys individually with DEL, perform non-blocking removal with UNLINK, and wipe all keys with FLUSHDB in Redis. Includes hands-on exercises, performance comparisons, and troubleshooting edge cases.

Focus: use del, unlink, and flushdb

Sponsored

Imagine your Redis instance is a high-speed warehouse where every key is a pallet of data. As your application grows, you need to remove pallets that are no longer needed—either one at a time or in bulk. Using DEL, UNLINK, and FLUSHDB gives you the control to delete keys individually, perform non-blocking removal, or wipe an entire database. Without these commands, memory leaks and stale data can degrade performance, making your caching layer unreliable. This lesson teaches you how to use each command effectively, so you can maintain a clean and responsive Redis server.

The problem this lesson solves

When Redis holds data that is no longer valid—like expired sessions, outdated cache entries, or temporary results—you need a way to remove it. Accumulating stale keys consumes memory, increases key lookup times, and can trigger eviction policies prematurely. Using the wrong deletion method can block the server (especially with large sets), while ignoring cleanup leads to memory bloat. This lesson solves the practical need to del, unlink, and flushdb with confidence, balancing performance and safety.

Core concept / mental model

Think of Redis as a bookshelf:

  • DEL is like taking a book off the shelf and throwing it away immediately — synchronous and blocking. If the book is heavy (e.g., a large list or set), you have to wait until it's fully removed before you can do anything else.
  • UNLINK is like marking a book for disposal and having a janitor collect it later — asynchronous and non-blocking. The command returns quickly, and the actual memory reclamation happens in the background.
  • FLUSHDB is like emptying the entire bookshelf in one go — synchronous by default, but can also be asynchronous. It removes all keys in the current database.

Key definition: Time complexity matters — DEL is O(N) where N is the number of keys; UNLINK also O(N) but the N is just unlinking overhead; FLUSHDB is O(N) for all keys in the database.

How it works step by step

Step 1: Deleting a single key with DEL

DEL mykey
  • DEL removes the key synchronously.
  • Returns the number of keys removed (1 or 0 if key doesn't exist).
  • If the value is a large data structure (e.g., a list with millions of items), the server blocks until deletion completes.
  • Best for small values or when you need immediate confirmation.

Step 2: Non-blocking deletion with UNLINK

UNLINK mykey
  • UNLINK is asynchronous — it unlinks the key from the keyspace immediately.
  • Returns 1 if the key existed, 0 otherwise.
  • The actual memory reclamation happens in a background thread, so the server stays responsive.
  • Preferred for large values (e.g., big sorted sets, hashes, or strings).

Step 3: Flushing an entire database with FLUSHDB

FLUSHDB
  • Removes all keys in the currently selected database.
  • Synchronous by default — blocks until all keys are deleted.
  • For asynchronous execution, use FLUSHDB ASYNC. This returns immediately and reclaims memory in the background.
  • Use with extreme care in production — there is no undo.

Hands-on walkthrough

Let's simulate a real scenario. Start by adding some test data:

redis-cli
SET session:alice "active"
SET session:bob "expired"
LPUSH messages:queue "msg1" "msg2" "msg3"
SADD tags:active "python" "redis" "tutorial"
HSET user:1 name "Alice" score 100

Now, list all keys:

KEYS *

Expected output:

1) "session:alice"
2) "session:bob"
3) "messages:queue"
4) "tags:active"
5) "user:1"

Example 1: Delete a single key with DEL

DEL session:bob

Output:

(integer) 1

Now verify:

EXISTS session:bob

Output:

(integer) 0

Example 2: Delete multiple keys at once

DEL session:alice messages:queue

Output:

(integer) 2

Example 3: Use UNLINK for a large set

First, create a large list:

LPUSH biglist $(seq 1 1000000)

Now unlink it:

UNLINK biglist

Output:

(integer) 1

Notice the command returns instantly even though the list had a million items.

Example 4: Flush the entire database

FLUSHDB

Output:

OK

Verify all keys are gone:

DBSIZE

Output:

(integer) 0

Pro tip: In Python, you can use redis-py to execute these commands. Example:

import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('temp', 'value')
print(r.del('temp'))          # Returns 1
print(r.unlink('temp2'))      # Returns 0 if key doesn't exist
r.flushdb()                   # Wipes all keys in current db
print(r.dbsize())             # 0

Compare options / when to choose what

Command Blocking? Memory reclamation Use case
DEL Synchronous Immediate Small values or when you need confirmation before next operation
UNLINK Non-blocking Background Large values (lists, sets, sorted sets, hashes)
FLUSHDB Synchronous (default) Immediate or async Reset a database entirely (e.g., development, testing)
FLUSHALL Synchronous (default) Immediate or async Reset all databases on the server
  • DEL is fine for single small keys (strings, short lists).
  • UNLINK is the safer choice for production code when you delete unknown-sized keys.
  • FLUSHDB should be used with ASYNC in production to avoid blocking the server.

Troubleshooting & edge cases

Key doesn't exist

DEL nonexistent

Output: (integer) 0 — no error.

Deleting many keys at once with DEL

If you delete thousands of keys in one DEL command, the server blocks until all are removed. Prefer UNLINK or use a pipeline with DEL spread over time.

Using FLUSHDB on a database with millions of keys

Default synchronous flush can block Redis for seconds or minutes. Always use FLUSHDB ASYNC in production:

FLUSHDB ASYNC

Accidentally flushing the wrong database

Warning: FLUSHDB has no confirmation prompt. Always double-check which database you are connected to with SELECT and CLIENT ID.

Memory not reclaimed immediately after UNLINK

UNLINK only removes the key from the keyspace instantly. The memory is freed by a background thread, so INFO MEMORY may show delayed reduction.

What you learned & what's next

You now understand the core difference between DEL (synchronous, blocking) and UNLINK (asynchronous, non-blocking) for individual key deletion, and FLUSHDB for clearing an entire database. You practiced deleting single keys, multiple keys, large data structures, and flushing databases both synchronously and asynchronously. You also learned when to choose each command based on performance and safety.

Next step: Move on to the next lesson in this track to explore more advanced Redis operations, such as key expiration with EXPIRE, TTL, and PERSIST. Understanding deletion patterns will help you design more efficient caching and data management strategies.

Practice recap

Try this: Add a large list of 500,000 items, then delete it using both DEL and UNLINK while timing each operation. Notice how DEL blocks while UNLINK returns instantly. Then flush the database with FLUSHDB ASYNC and verify with DBSIZE. This hands-on exercise will solidify the performance differences.

Common mistakes

  • Using DEL on extremely large data structures (millions of elements) can block Redis for seconds, causing timeouts. Always use UNLINK for large values.
  • Calling FLUSHDB without the ASYNC option in production can block the server until all keys are removed — use FLUSHDB ASYNC to avoid downtime.
  • Assuming UNLINK immediately frees memory — memory reclamation happens in the background, so INFO MEMORY may not show an instant drop.
  • Deleting a non-existent key and checking the return value — both DEL and UNLINK return 0 without an error, so handle that in application logic.

Variations

  1. You can use FLUSHALL instead of FLUSHDB to clear all databases on the Redis server — use with extreme caution.
  2. For deleting keys matching a pattern (e.g., session:*), consider using SCAN with DEL or UNLINK to avoid blocking — never use KEYS in production.
  3. In Redis 6.2+, you can use UNLINK with multiple keys just like DEL — e.g., UNLINK key1 key2 key3.

Real-world use cases

  • Removing expired user sessions from a Redis cache — use UNLINK to avoid blocking the server when clearing thousands of session keys simultaneously.
  • Flushing a development or testing database before running a fresh set of integration tests — use FLUSHDB ASYNC to reset quickly without affecting other processes.
  • Deleting a large sorted set that stores leaderboard data after a competition ends — use UNLINK to reclaim memory without pausing score reads.

Key takeaways

  • DEL removes keys synchronously and blocks the server until deletion completes; prefer UNLINK for large values.
  • UNLINK is asynchronous — it unlinks the key immediately and frees memory in the background, keeping Redis responsive.
  • FLUSHDB deletes all keys in the current database; always use FLUSHDB ASYNC in production to avoid blocking.
  • Both DEL and UNLINK return the number of keys removed (0 if key doesn't exist).
  • For deleting multiple keys matching a pattern, use SCAN + UNLINK rather than KEYS + DEL to avoid blocking.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.