Of course! Let's break down how to use flushdb in Python with Redis, covering everything from basic usage to important safety considerations.

What is FLUSHDB?
FLUSHDB is a Redis command that deletes all the keys in the currently selected database.
- Important: This is a destructive operation. There is no "undo" button.
- It only affects the database number you are connected to (e.g.,
db 0by default). It does not affect other databases on the same server (likedb 1,db 2, etc.). For that, you would useFLUSHALL.
Prerequisites
First, you need to have the redis Python library installed and a Redis server running.
Install the library:
pip install redis
Start your Redis server: If you don't have a Redis server running, the easiest way is with Docker:

docker run -d -p 6379:6379 redis
This command starts a Redis container in the background, mapping its default port (6379) to your machine.
Basic Usage: flushdb()
The redis-py library provides a convenient flushdb() method that directly maps to the Redis command.
Here is a simple, step-by-step example.
import redis
# 1. Connect to Redis
# By default, it connects to localhost on port 6379 using database 0.
r = redis.Redis(host='localhost', port=6379, db=0)
# 2. Add some data to the database to demonstrate
print("Adding some keys to the database...")
r.set('user:1:name', 'Alice')
r.set('user:1:email', 'alice@example.com')
r.set('session:abc123', 'some_session_data')
r.hset('product:100', name='Laptop', price=1200) # Hash example
print(f"Number of keys in DB 0: {len(r.keys('*'))}") # Should be 4
# 3. Execute FLUSHDB
print("\n--- Executing FLUSHDB ---")
# This will delete ALL keys in the currently selected database (db 0)
r.flushdb()
print("FLUSHDB command executed.")
# 4. Verify that the database is now empty
print(f"Number of keys in DB 0 after flush: {len(r.keys('*'))}") # Should be 0
# 5. Check that other databases are unaffected
# Let's add a key to a different database (e.g., db 1)
r.select(1) # Switch to database 1
r.set('persistent_data', 'this should not be deleted')
print(f"Number of keys in DB 1: {len(r.keys('*'))}") # Should be 1
# Switch back to db 0 to confirm it's still empty
r.select(0)
print(f"Number of keys in DB 0 after switching back: {len(r.keys('*'))}") # Should be 0
print("\nScript finished.")
Output of the script:
Adding some keys to the database...
Number of keys in DB 0: 4
--- Executing FLUSHDB ---
FLUSHDB command executed.
Number of keys in DB 0 after flush: 0
Number of keys in DB 1: 1
Number of keys in DB 0 after switching back: 0
Script finished.
Safety First: The async Version
For long-running or large databases, the synchronous flushdb() can block your application for a few seconds. To prevent this, you should use the asynchronous version (asyncio).
The asynchronous version is non-blocking, meaning your application can continue to do other work while the database is being cleared.
import asyncio
import redis.asyncio as redis
async def main():
# 1. Connect to Redis asynchronously
r = redis.Redis(host='localhost', port=6379, db=0)
# 2. Add some data
print("Adding some keys...")
await r.set('key1', 'value1')
await r.set('key2', 'value2')
print(f"Keys before flush: {await r.keys('*')}")
# 3. Execute FLUSHDB asynchronously
print("\n--- Executing async FLUSHDB (non-blocking) ---")
# This is an awaitable operation, so it won't block the event loop
await r.flushdb()
print("Async FLUSHDB command has been sent.")
# 4. Verify the database is empty
print(f"Keys after flush: {await r.keys('*')}")
# Close the connection
await r.aclose()
# Run the async function
asyncio.run(main())
Output of the async script:
Adding some keys...
Keys before flush: [b'key2', b'key1']
--- Executing async FLUSHDB (non-blocking) ---
Async FLUSHDB command has been sent.
Keys after flush: []
Advanced: flushdb(async_=True)
The synchronous redis-py client also has a built-in mechanism to avoid blocking by using threads under the hood. You can enable this by passing async_=True to the flushdb() method.
import redis
import time
# This will use a background thread to execute the command
r = redis.Redis(host='localhost', port=6379, db=0)
# Add a lot of data to simulate a long-running flush
# for i in range(100000):
# r.set(f'big_key_{i}', 'x' * 1000)
print("Executing FLUSHDB with async_=True...")
# This call will return immediately, while the flush happens in the background.
r.flushdb(async_==True)
print("Flush command initiated. The main thread is not blocked.")
# Do other work here...
print("Main thread can continue doing other work immediately.")
time.sleep(2) # Simulate other work
# Check the result
print(f"Number of keys: {len(r.keys('*'))}")
Important Considerations & Best Practices
- Irreversible Operation:
FLUSHDBis permanent. Double- and triple-check your code before running it in a production environment. - Use
FLUSHALLwith Extreme Caution: If you need to clear all databases on your Redis instance, user.flushall(). This is even more destructive and should almost never be used in production. - Performance Impact: On a database with millions of large keys,
FLUSHDBcan take a significant amount of time and consume a lot of CPU and I/O resources. Use the asynchronous methods (asyncioorasync_=True) in applications to avoid blocking. - Don't Run in Production Code (Usually): A common pattern is to use
flushdbin test scripts or as part of a deployment process to reset a stateful service, but it's rarely something you want to call from your main application logic. - Alternatives for "Soft" Resets: If you need to clear specific parts of your cache, consider using more targeted commands like
del r[key1, key2, key3]or pattern-based deletion with a loop (e.g., forkeysmatchinguser:*). This is safer and more efficient than deleting everything.
