How to Flush Redis Keys

How to Flush Redis Keys Redis is an in-memory data structure store widely used for caching, session management, real-time analytics, and message brokering. Its speed and flexibility make it indispensable in modern web architectures. However, with great power comes great responsibility — especially when managing data lifecycle. One of the most critical operations in Redis administration is flushing

Nov 10, 2025 - 12:27
Nov 10, 2025 - 12:27
 0

How to Flush Redis Keys

Redis is an in-memory data structure store widely used for caching, session management, real-time analytics, and message brokering. Its speed and flexibility make it indispensable in modern web architectures. However, with great power comes great responsibility especially when managing data lifecycle. One of the most critical operations in Redis administration is flushing keys: removing all or selected data from memory. Whether you're debugging a misbehaving application, resetting a test environment, or reclaiming memory after a data leak, knowing how to flush Redis keys safely and effectively is essential.

This comprehensive guide walks you through every aspect of flushing Redis keys from basic commands to advanced strategies, best practices, real-world examples, and troubleshooting. By the end, youll not only know how to delete data in Redis, but also understand when, why, and how to do it without disrupting production systems.

Step-by-Step Guide

Understanding the FLUSHALL and FLUSHDB Commands

Redis provides two primary commands for flushing keys: FLUSHALL and FLUSHDB. Both are powerful and irreversible, so understanding their scope is the first step.

  • FLUSHALL removes all keys from all databases in the Redis instance. Redis supports multiple databases (default is 16, indexed from 0 to 15), and FLUSHALL clears every single one.
  • FLUSHDB removes all keys from the currently selected database only. This is useful when you're working in a multi-database setup and want to isolate cleanup to a single namespace.

By default, Redis connects to database 0. To check which database you're currently using, run the SELECT command:

SELECT 1

To verify your current database index, use:

INFO keyspace

This returns statistics for each database, including the number of keys. If you see db0:keys=1000,expires=0, youre working with 1,000 keys in database 0.

Flushing All Keys with FLUSHALL

To completely wipe the entire Redis instance:

  1. Connect to your Redis server using the Redis CLI:
redis-cli

  1. Run the FLUSHALL command:
FLUSHALL

  1. Confirm success with a response:
OK

  1. Verify all keys are gone by checking the keyspace:
INFO keyspace

You should now see db0:keys=0,expires=0 for all databases.

Flushing a Single Database with FLUSHDB

If you're using multiple databases (e.g., database 0 for caching, database 1 for session storage), you may want to clear only one:

  1. Connect to Redis CLI:
redis-cli

  1. Select the target database (e.g., database 1):
SELECT 1

  1. Flush only that database:
FLUSHDB

  1. Confirm the operation:
OK

  1. Switch back to database 0 and verify other databases are untouched:
SELECT 0

INFO keyspace

Youll see that database 0 still retains its keys, while database 1 is now empty.

Using Asynchronous Flushing

By default, both FLUSHALL and FLUSHDB are synchronous operations. This means Redis blocks all other clients until the operation completes. On large datasets (millions of keys), this can cause significant latency potentially triggering timeouts or service degradation.

To avoid blocking, use the ASYNC flag:

FLUSHALL ASYNC

or

FLUSHDB ASYNC

When you use ASYNC, Redis initiates the deletion in the background using a separate thread. The command returns immediately with OK, and the actual cleanup runs asynchronously. This is ideal for production environments where minimizing downtime is critical.

Flushing Keys via Redis Client Libraries

Most programming languages have Redis client libraries that expose these commands. Here are examples in popular languages:

Python (using redis-py)

import redis

Connect to Redis

r = redis.Redis(host='localhost', port=6379, db=0)

Flush entire instance

r.flushall()

Flush only current database

r.flushdb()

Asynchronous flush

r.flushall(async=True)

r.flushdb(async=True)

Node.js (using ioredis)

const Redis = require('ioredis');

const redis = new Redis();

// Flush all

await redis.flushall();

// Flush current db

await redis.flushdb();

// Async flush

await redis.flushall('ASYNC');

await redis.flushdb('ASYNC');

Java (using Jedis)

import redis.clients.jedis.Jedis;

Jedis jedis = new Jedis("localhost");

// Flush all

jedis.flushAll();

// Flush current db

jedis.flushDB();

// Asynchronous (Jedis 3.0+)

jedis.flushAll(FlushMode.ASYNC);

jedis.flushDB(FlushMode.ASYNC);

Flushing Keys Using Redis Inspectors and GUI Tools

If you prefer a visual interface, several GUI tools allow you to flush keys with a single click:

  • RedisInsight (official Redis GUI): Navigate to the "Database" tab, select your database, click "Actions" ? "Flush Database".
  • Medis: Right-click on a database ? "Flush DB".
  • Redis Desktop Manager: Right-click database ? "Flush DB" or "Flush All".

These tools are excellent for development and debugging but should be used with caution in production. Always verify the selected database before executing a flush.

Flushing Keys via API or Scripting

For automation, you can wrap flush commands in shell scripts or CI/CD pipelines. Heres a simple Bash script to flush Redis safely:

!/bin/bash

flush-redis.sh

RED='\033[0;31m' NC='\033[0m'

No Color

echo -e "${RED}Warning: This will flush ALL Redis data.${NC}"

read -p "Are you sure? (yes/no): " -n 1 -r

echo

if [[ $REPLY =~ ^[Yy]$ ]]; then

redis-cli FLUSHALL ASYNC

echo "Flush initiated asynchronously."

else

echo "Operation cancelled."

fi

Make it executable:

chmod +x flush-redis.sh

./flush-redis.sh

This approach adds a safety layer to prevent accidental execution.

Flushing Keys in Docker and Kubernetes Environments

If Redis is containerized:

Docker

docker exec -it redis-container redis-cli FLUSHALL ASYNC

Replace redis-container with your container name or ID.

Kubernetes

If you're running Redis in a Pod:

kubectl exec -it redis-pod -- redis-cli FLUSHDB

For asynchronous flush in Kubernetes:

kubectl exec -it redis-pod -- redis-cli FLUSHDB ASYNC

Always ensure your Pod has the redis-cli binary installed. If not, you may need to use a sidecar container or a debug image.

Best Practices

Never Flush in Production Without Verification

One of the most common causes of outages is accidental execution of FLUSHALL on a production Redis instance. Always follow these rules:

  • Use FLUSHDB instead of FLUSHALL unless youre certain all databases need clearing.
  • Always confirm your current database using SELECT and INFO keyspace before flushing.
  • Use ASYNC mode in production to avoid blocking client connections.
  • Never run flush commands directly from your terminal in production always use scripts with confirmation prompts.

Use Database Isolation for Multi-Tenancy

If your application uses Redis for multiple services (e.g., caching, sessions, queues), assign each to a separate database:

  • DB 0: Application cache
  • DB 1: User sessions
  • DB 2: Rate limiting counters

This allows you to flush one component (e.g., cache) without affecting others. Its far safer than using a single database with key prefixes.

Prefer Key Prefixes Over Multiple Databases

While multiple databases offer isolation, theyre not recommended for production use in Redis Cluster mode (which doesnt support multiple databases). Instead, use key naming conventions:

cache:user:123

session:user:456

rate_limit:ip:192.168.1.1

With prefixes, you can selectively delete keys using the SCAN command and DEL in batches, avoiding full flushes entirely.

Use SCAN for Selective Deletion

Instead of flushing entire databases, consider deleting keys matching a pattern:

SCAN 0 MATCH cache:* COUNT 1000

This returns up to 1,000 keys matching the pattern. You can then delete them in batches:

DEL cache:user:123 cache:user:456 ...

For automation, use a script:

redis-cli --scan --pattern "cache:*" | xargs -L 1000 redis-cli DEL

This avoids blocking the server and gives you fine-grained control over what gets deleted.

Monitor Memory and Keys Before and After

Always check memory usage and key count before and after flushing:

INFO memory

INFO keyspace

Redis reports:

  • used_memory: Total memory allocated
  • used_memory_human: Human-readable memory usage
  • total_keys: Total number of keys

After a flush, memory should drop significantly. If it doesnt, check for background processes (like AOF rewriting or replication) that may be holding onto memory.

Enable AOF and RDB Backups Before Flushing

Redis persistence options AOF (Append-Only File) and RDB (Snapshotting) can help you recover data if a flush is accidental.

Before flushing:

  • Ensure AOF is enabled in redis.conf: appendonly yes
  • Trigger a manual RDB snapshot: SAVE or BGSAVE
  • Verify backup files exist in your Redis data directory: dump.rdb and appendonly.aof

Even with backups, remember: Redis is an in-memory store. Backups are not real-time. If you flush and then the server crashes before a backup, you lose data.

Use Role-Based Access Control (ACL) to Restrict Flush Permissions

Redis 6+ supports ACLs. Create a restricted user for applications:

ACL SETUSER appuser on >password ~cache:* +get +set +del -flushall -flushdb

This user can read, write, and delete keys under the cache: prefix but cannot flush entire databases. Only admin users should have +flushall or +flushdb permissions.

Log and Audit All Flush Operations

Enable Redis logging and monitor for flush events:

loglevel notice

Look for entries like:

12345:M 10 Apr 12:30:00.123 

Client sent FLUSHALL command

Integrate Redis logs with centralized logging tools like ELK Stack, Datadog, or Loki to trigger alerts on flush events.

Test Flushing in Staging First

Always simulate a flush in a staging environment that mirrors production. Use the same data volume, key structure, and traffic patterns. Monitor performance impact, memory release, and downstream service behavior.

Tools and Resources

Official Redis Documentation

The authoritative source for all Redis commands is the official documentation: https://redis.io/commands/. Always refer here for version-specific behavior and flags.

RedisInsight

RedisInsight is the official GUI from Redis Labs. It provides real-time monitoring, key browsing, and one-click flush options. Download it at https://redis.com/redis-enterprise/redis-insight/.

Redis CLI with Pretty Output

Use the --raw flag for cleaner output:

redis-cli --raw INFO keyspace

Or use --bigkeys to find large keys before flushing:

redis-cli --bigkeys

Redis Benchmark Tool

After flushing, use redis-benchmark to test performance recovery:

redis-benchmark -t set,get -n 10000 -c 50

This helps verify that the Redis instance is operating normally post-flush.

Monitoring Tools

  • Prometheus + Redis Exporter: Export Redis metrics for graphing and alerting.
  • Datadog: Built-in Redis integration with dashboards for memory, keys, and latency.
  • New Relic: Monitor Redis performance and detect anomalies after flush operations.

Open Source Scripts

GitHub hosts many community scripts for safe Redis management:

Redis Cluster Considerations

In Redis Cluster mode, FLUSHALL and FLUSHDB operate per node. You must run the command on each shard:

redis-cli -c -h cluster-node-1 FLUSHDB ASYNC

redis-cli -c -h cluster-node-2 FLUSHDB ASYNC

...

Alternatively, use a script to loop through all nodes:

for node in $(cat redis-nodes.txt); do

echo "Flushing $node"

redis-cli -c -h $node FLUSHDB ASYNC

done

Always use ASYNC in clusters to avoid network timeouts and node failures.

Real Examples

Example 1: Clearing a Stale Cache After Deployment

A web application uses Redis to cache product data. After a new release, the cache format changed, and old keys are now invalid. Instead of restarting the service, the DevOps team flushes only the cache database.

Steps:

  1. Identify the cache database: DB 0
  2. Check key count: INFO keyspace ? db0:keys=54231
  3. Run: redis-cli FLUSHDB ASYNC
  4. Monitor memory usage: drops from 850MB to 12MB
  5. Verify application behavior: new requests repopulate cache with updated format

Result: Zero downtime, immediate cache reset, no service restart required.

Example 2: Debugging a Memory Leak in a Session Store

A microservice stores user sessions in Redis. Over time, memory usage grows despite sessions expiring. The team suspects orphaned keys.

Steps:

  1. Use redis-cli --bigkeys to find large keys discovers 10,000+ expired keys with TTL=0
  2. Run: SCAN 0 MATCH session:* COUNT 5000
  3. Filter out keys with TTL > 0 using a Python script
  4. Batch delete expired keys: DEL session:123 session:456 ...
  5. After deletion, memory drops by 60%

Result: Root cause identified application failed to set TTL on some session keys. Fixed in code. No full flush needed.

Example 3: Resetting a Test Environment Before CI/CD

A CI pipeline runs integration tests that depend on Redis state. Before each test run, the pipeline resets Redis to a clean state.

CI YAML snippet (GitHub Actions):

- name: Reset Redis

run: |

redis-cli FLUSHALL ASYNC

sleep 2

redis-cli INFO keyspace | grep "keys=0"

The sleep 2 ensures the async flush completes before tests begin. The final check confirms the database is empty.

Example 4: Handling a Security Incident

A Redis instance is compromised unauthorized keys are added, including malicious scripts and backdoor data.

Response:

  1. Immediately isolate the Redis instance from public access.
  2. Take a snapshot: BGSAVE
  3. Run: FLUSHALL ASYNC
  4. Change authentication password and enable ACLs.
  5. Review firewall rules and network policies.
  6. Restore only trusted data from backup.

Result: System secured, data purged, compliance maintained.

FAQs

Is FLUSHALL reversible?

No. Once keys are flushed, they are permanently deleted from memory. If persistence (AOF or RDB) was enabled and a recent backup exists, you may restore from that file but only if Redis hasnt overwritten it with new data.

Does FLUSHALL affect Redis persistence files?

No. FLUSHALL clears only in-memory data. AOF and RDB files remain unchanged. However, the next persistence snapshot will reflect the empty state. If you need to restore old data, you must manually restore from a backup file.

How long does FLUSHALL take?

It depends on the number of keys and server hardware. For 10,000 keys: under 100ms. For 10 million keys: 15 seconds synchronously. Use ASYNC to avoid blocking.

Can I flush keys by pattern without FLUSHALL?

Yes. Use SCAN with DEL to delete keys matching a pattern. Example: redis-cli --scan --pattern "temp:*" | xargs redis-cli DEL. This is safer and more precise than a full flush.

Why is my memory not freed after FLUSHALL?

Redis doesnt always return memory to the OS immediately. It retains allocated memory for future use. Use INFO memory to check used_memory. If its still high, check for fragmentation or background processes like AOF rewriting. You can force memory release with CONFIG SET maxmemory-policy allkeys-lru followed by a restart, but this is rarely necessary.

Whats the difference between FLUSHDB and DEL *?

DEL * is not a valid Redis command you cannot use wildcards with DEL. FLUSHDB deletes all keys in the current database in one atomic operation. DEL requires explicit key names or batched SCAN+DEL operations.

Can I flush Redis remotely via HTTP?

Redis does not natively support HTTP. However, you can expose a REST API using a proxy like redis-rdb-tools or a custom microservice. Be extremely cautious exposing Redis to HTTP increases attack surface. Always use authentication and rate limiting.

How do I prevent accidental flushes in production?

  • Use ACLs to restrict flush permissions to admin users only.
  • Require two-factor confirmation for flush commands in scripts.
  • Disable FLUSHALL/FLUSHDB in production Redis configs using rename-command (e.g., rename FLUSHALL to a non-obvious name).
  • Use network segmentation only allow Redis access from trusted internal IPs.

Does flushing affect Redis replication?

Yes. If Redis is configured as a replica (slave), FLUSHALL or FLUSHDB triggers a full resynchronization with the master. The replica will delete its data and download a new RDB snapshot. Use ASYNC to minimize disruption, but expect temporary replication lag.

Can I flush only expired keys?

Redis automatically removes expired keys in the background. You can force cleanup by running CONFIG SET active-expire-effort 10 (higher value = more aggressive cleanup). There is no direct command to flush only expired keys but using SCAN to find keys with TTL=0 and deleting them manually is possible.

Conclusion

Flushing Redis keys is a powerful, high-impact operation that should never be treated lightly. Whether youre resetting a test environment, recovering from a data corruption, or optimizing memory usage, knowing how to execute FLUSHALL and FLUSHDB safely and when to avoid them entirely is a hallmark of a skilled Redis operator.

This guide has equipped you with the knowledge to:

  • Understand the difference between FLUSHALL and FLUSHDB
  • Use ASYNC mode to prevent service disruption
  • Implement key prefixes and database isolation for safer operations
  • Replace full flushes with targeted SCAN+DEL patterns
  • Secure Redis using ACLs and access controls
  • Monitor and verify the impact of flush operations
  • Apply best practices in Docker, Kubernetes, and cluster environments

Remember: Redis is fast, but it doesnt ask for confirmation. Treat every flush command like a nuclear button only press it when youre absolutely certain of the consequences. Combine technical precision with operational discipline, and youll avoid costly mistakes while maximizing Rediss potential.

As your applications scale and Redis becomes more central to your infrastructure, mastering key management including selective deletion and controlled flushing will be one of the most valuable skills in your DevOps and engineering toolkit.