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 application architectures. However, with great power comes great responsibility — especially when managing data integrity and system performance. One of the most critical yet potentially

Nov 6, 2025 - 10:58
Nov 6, 2025 - 10:58
 1

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 application architectures. However, with great power comes great responsibility especially when managing data integrity and system performance. One of the most critical yet potentially dangerous operations in Redis is flushing keys. Flushing Redis keys means removing all data from the database, either entirely or selectively. While this can resolve memory bloat, stale sessions, or corrupted caches, it can also lead to service outages if executed improperly.

This guide provides a comprehensive, step-by-step walkthrough of how to flush Redis keys safely and effectively. Whether you're a DevOps engineer, backend developer, or system administrator, understanding the mechanics, risks, and best practices of key flushing is essential for maintaining a stable and performant Redis deployment. Well cover native commands, scripting approaches, automation tools, real-world use cases, and frequently asked questions all designed to help you master this operation without compromising system reliability.

Step-by-Step Guide

Understanding Redis Databases and Key Space

Before flushing keys, its vital to understand Rediss data organization. Redis supports up to 16 logical databases by default, indexed from 0 to 15. Each database is an isolated key space. When you execute a flush command, it affects only the currently selected database unless otherwise specified.

To check which database youre currently using, connect to Redis via the CLI and run:

redis-cli

127.0.0.1:6379> SELECT 0

OK

127.0.0.1:6379> INFO keyspace

The output will show the number of keys in each database. For example:

db0:keys=12500,expires=1200,avg_ttl=86400000

This tells you there are 12,500 keys in database 0, with 1,200 having expiration times set. Understanding your key distribution helps you decide whether a full flush is necessary or if selective deletion is preferable.

Method 1: Flushing All Keys in the Current Database

The most straightforward way to flush keys is using the FLUSHDB command. This removes all keys from the currently selected database without affecting other databases.

To use it:

  1. Open your terminal and connect to Redis:
redis-cli

  1. Verify your current database (optional):
SELECT 0

  1. Execute the flush command:
FLUSHDB

  1. Confirm success:
INFO keyspace

The output should now show db0:keys=0, confirming all keys have been removed.

Important: FLUSHDB is asynchronous in most Redis configurations. The command returns immediately, but background deletion may continue. For large datasets, this can cause temporary memory pressure. Monitor memory usage with INFO memory after execution.

Method 2: Flushing All Keys Across All Databases

If you need to clear all data across all 16 databases use the FLUSHALL command. This is more powerful and more dangerous than FLUSHDB.

To execute FLUSHALL:

  1. Connect to Redis:
redis-cli

  1. Run the command:
FLUSHALL

  1. Verify across databases:
INFO keyspace

You should see all databases (db0 through db15) reporting keys=0.

Caution: FLUSHALL affects every database, including those used by other applications. Never run this in production without confirming the target instance and ensuring no dependent services rely on existing keys. Always test in staging first.

Method 3: Flushing Keys with Asynchronous Deletion

By default, Redis deletes keys synchronously, meaning it blocks the server until all keys are removed. For databases with millions of keys, this can cause significant latency sometimes seconds or even minutes during which Redis cannot serve requests.

To avoid this, use the ASYNC flag with both FLUSHDB and FLUSHALL:

FLUSHDB ASYNC

FLUSHALL ASYNC

When using ASYNC, Redis spawns a background thread to delete keys, freeing the main thread to continue handling client requests. This is ideal for production environments with high availability requirements.

Verify the operation is running asynchronously by monitoring Redis logs or using:

INFO persistence

Look for the aof_rewrite_in_progress and rdb_bgsave_in_progress fields while not directly related, they indicate background operations are active. For precise monitoring, use:

CLIENT LIST

Look for clients with idle time increasing if the main thread is unblocked, clients will continue to respond normally.

Method 4: Selective Key Flushing Using Lua Scripts

Sometimes, you dont want to delete all keys only those matching a pattern. For example, you may want to remove all session keys prefixed with session: but leave configuration or cache keys intact.

Redis supports server-side Lua scripting, allowing complex operations without transferring data to the client. Heres a safe, reusable script to delete keys matching a pattern:

lua

local keys = redis.call('KEYS', ARGV[1]) for i=1,

keys,5000 do

redis.call('DEL', unpack(keys, i, math.min(i+4999,

keys)))

end return

keys

This script:

  • Retrieves all keys matching the pattern passed as the first argument (ARGV[1])
  • Deletes them in batches of 5,000 to avoid blocking the server for too long
  • Returns the total number of keys deleted

To execute it:

redis-cli --eval delete_keys.lua , "session:*"

Replace "session:*" with your desired pattern (e.g., "cache:*", "temp:*").

Why not use KEYS directly? The KEYS command scans the entire key space and can block Redis for extended periods. The Lua script mitigates this by batching deletions, making it production-safe.

Method 5: Flushing Keys via Redis Client Libraries

If youre managing Redis through application code, you can flush keys programmatically using client libraries.

Python (redis-py)

import redis

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

Flush current database

or

r.flushall()

Flush all databases

Node.js (ioredis)

const Redis = require('ioredis');

const redis = new Redis();

await redis.flushdb(); // Flush current DB

// or

await redis.flushall(); // Flush all DBs

Java (Jedis)

Jedis jedis = new Jedis("localhost");

jedis.flushDB(); // Flush current DB

// or

jedis.flushAll(); // Flush all DBs

Always wrap these calls in try-catch blocks and log the operation for audit purposes. In production, consider implementing rate limiting or requiring a confirmation token before execution.

Method 6: Flushing Keys via Redis CLI with Authentication

If your Redis instance requires authentication, you must provide a password before executing flush commands.

Use the -a flag:

redis-cli -a yourpassword FLUSHALL

Alternatively, connect first, then authenticate:

redis-cli

127.0.0.1:6379> AUTH yourpassword

OK

127.0.0.1:6379> FLUSHALL

For enhanced security, avoid passing passwords on the command line. Instead, use environment variables or Redis configuration files with requirepass set, and authenticate via interactive CLI.

Method 7: Flushing Keys in Redis Cluster Mode

Redis Cluster distributes data across multiple nodes. Flushing keys in a cluster requires special handling because FLUSHALL and FLUSHDB operate per node.

To flush all keys in a Redis Cluster:

  1. Connect to any node:
redis-cli -c -h cluster-node-1 -p 7000

  1. Run FLUSHALL:
FLUSHALL

  1. Verify across nodes:
CLUSTER NODES

Each node will return its own key count. To confirm all are flushed, run:

CLUSTER SLOTS

Then connect to each nodes IP:port and run INFO keyspace.

Pro Tip: Use a script to automate cluster-wide flushing. Tools like redis-trib.rb (deprecated) or redis-cli --cluster can help manage multi-node operations:

redis-cli --cluster flushall 127.0.0.1:7000

This command sends FLUSHALL to every node in the cluster. Always test in a non-production cluster first.

Best Practices

1. Always Backup Before Flushing

Redis supports two persistence mechanisms: RDB (snapshotting) and AOF (append-only file). Before flushing keys, ensure a recent backup exists.

To manually trigger an RDB snapshot:

redis-cli SAVE

Or, to avoid blocking:

redis-cli BGSAVE

Check the status:

INFO persistence

Look for rdb_bgsave_in_progress:0 and rdb_last_bgsave_status:ok.

For critical systems, automate backups using cron jobs or orchestration tools like Ansible or Kubernetes Jobs. Store backups off-server in encrypted object storage (e.g., AWS S3, Google Cloud Storage).

2. Use Read-Only Mode for Verification

Before executing a flush, verify what youre about to delete. Use SCAN instead of KEYS to iterate safely:

SCAN 0 MATCH session:* COUNT 1000

This returns a cursor and a batch of matching keys without blocking. Repeat with the returned cursor until it returns 0.

Combine this with a script to log keys for audit:

redis-cli --scan --pattern "session:*" > keys_to_delete.txt

Review the file before proceeding.

3. Schedule Flushing During Low-Traffic Windows

Even with ASYNC, large-scale deletions can impact memory fragmentation and garbage collection. Schedule flushes during maintenance windows or off-peak hours.

Use cron to automate safe flushes:

0 3 * * * redis-cli -a $REDIS_PASSWORD FLUSHDB ASYNC >> /var/log/redis-flush.log 2>&1

This runs daily at 3 AM. Include timestamps and output logs for accountability.

4. Implement Access Controls and Role-Based Permissions

Redis 6+ supports ACL (Access Control Lists). Create a restricted user for flushing:

ACL SETUSER flusher on >mypass ~cache:* +FLUSHDB +FLUSHALL

This user can only flush databases and only access keys matching cache:*. Never grant FLUSHALL to users with broad access.

Test permissions:

redis-cli -u flusher

127.0.0.1:6379> FLUSHALL

(error) NOPERM this user has no permissions to run the 'flushall' command or its subcommand

5. Monitor After Flushing

After flushing, monitor:

  • Memory usage: INFO memory ensure memory is reclaimed
  • Latency: redis-cli --latency watch for spikes
  • Client connections: CLIENT LIST ensure no connection leaks
  • Replication lag: If using replicas, check INFO replication for delays

Set up alerts using Prometheus + Grafana or Datadog to trigger notifications if memory usage spikes unexpectedly after a flush.

6. Avoid Flushing in Replicated Environments Without Coordination

If youre using Redis with replication (master-slave), flushing on the master will propagate to all replicas. This is usually desired but if a replica is used for reporting or read scaling, unintended data loss can occur.

Best practice: Pause read traffic to replicas during flushes, or use a separate Redis instance for reporting. Alternatively, use Redis Sentinel or Redis Cluster to manage failover and redundancy without relying on replication for data isolation.

7. Document and Audit All Flush Operations

Treat every flush as a production event. Log:

  • Who initiated it
  • Which command was used
  • What keys were targeted
  • Timestamp
  • System impact (e.g., 500ms latency spike observed)

Use centralized logging (e.g., ELK Stack, Loki) to correlate flush events with application behavior. This aids in troubleshooting and compliance.

Tools and Resources

Redis CLI

The standard Redis command-line interface is your primary tool for manual operations. Its lightweight, fast, and included with every Redis installation. Use it for testing, debugging, and small-scale flushes.

RedisInsight

RedisInsight is a free, GUI-based tool from Redis Labs. It provides a visual interface to browse keys, monitor memory, and execute commands including flush operations with confirmation prompts to reduce human error.

Features:

  • Key browser with pattern search
  • Real-time metrics dashboard
  • Command history and audit trail
  • Multi-instance management

Download: https://redis.com/redis-enterprise/redis-insight/

Redis Commander

An open-source web-based Redis management tool written in Node.js. Ideal for teams without GUI access to servers.

Install via Docker:

docker run -p 8081:8081 -e REDIS_HOST=your-redis-host rediscommander/redis-commander:latest

Access at http://localhost:8081 to browse and delete keys visually.

Redis Desktop Manager (RDM)

A cross-platform desktop application for managing Redis instances. Supports SSL, authentication, and key filtering. Useful for developers who prefer desktop tools over CLI.

Website: https://redisdesktop.com/

Automation Tools

  • Ansible: Use the redis_db module to automate flushes across environments.
  • Terraform: Integrate with cloud Redis services (e.g., AWS ElastiCache) to trigger flushes via lifecycle hooks.
  • GitHub Actions / GitLab CI: Trigger flushes as part of deployment pipelines (e.g., clear cache after code deploy).

Monitoring & Alerting

  • Prometheus + Redis Exporter: Expose Redis metrics (keys, memory, connections) for scraping.
  • Grafana: Build dashboards showing key count trends before and after flushes.
  • Datadog / New Relic: Set up synthetic monitors to detect unexpected key loss.

Documentation & Learning

Real Examples

Example 1: Clearing Stale User Sessions After a Deployment

A web application uses Redis to store user sessions with keys like session:abc123. After a major code update, all existing sessions are incompatible. The team needs to flush all session keys without affecting product catalog data stored in product:*.

Steps Taken:

  1. Executed redis-cli --scan --pattern "session:*" > sessions.txt to list keys.
  2. Verified no critical data was included (e.g., no config: or cache: keys).
  3. Used a Lua script to delete in batches:
redis-cli --eval delete_keys.lua , "session:*"

  1. Monitored memory usage: dropped from 1.2GB to 200MB.
  2. Logged the operation in the teams incident tracker with timestamp and executor ID.

Outcome: Users were prompted to log in again. No service disruption occurred. Application logs showed a 15% reduction in session-related errors post-deploy.

Example 2: Emergency Cache Flush Due to Data Corruption

A caching layer in a financial analytics platform began returning corrupted data. Logs indicated a bug in the cache writer logic that had been writing malformed JSON into keys prefixed with cache:report:.

Response:

  1. Immediately isolated the affected Redis instance (non-production replica).
  2. Executed FLUSHDB ASYNC on the replica to prevent propagation.
  3. Deployed a fix to the cache writer service.
  4. After 10 minutes, flushed the primary instance using FLUSHDB ASYNC during low-traffic hours.
  5. Triggered a full cache warm-up via background jobs.

Outcome: Data integrity restored within 25 minutes. No customer-facing errors occurred. The incident led to the implementation of cache validation hooks and automated health checks.

Example 3: Automated Daily Cache Cleanup in a Microservices Architecture

A microservices platform uses Redis for temporary data storage. Each service writes keys with a TTL of 1 hour, but some services fail to set TTLs correctly, causing memory growth.

Solution:

  • Created a Kubernetes CronJob that runs daily at 2 AM:
apiVersion: batch/v1

kind: CronJob

metadata:

name: redis-cache-cleanup

spec:

schedule: "0 2 * * *"

jobTemplate:

spec:

template:

spec:

containers:

- name: redis-cli

image: redis:7-alpine

command: ["redis-cli", "-h", "redis-service", "-a", "$REDIS_PASSWORD", "FLUSHDB", "ASYNC"]

env:

- name: REDIS_PASSWORD

valueFrom:

secretKeyRef:

name: redis-secrets

key: password

restartPolicy: OnFailure

  • Added a Prometheus alert: Redis key count > 500K for 10 minutes
  • Integrated with Slack to notify the platform team on flush events

Outcome: Memory usage stabilized at 400MB. No manual intervention required for 6 months.

FAQs

What is the difference between FLUSHDB and FLUSHALL?

FLUSHDB deletes all keys in the currently selected database (default is 0). FLUSHALL deletes keys from all 16 databases. Use FLUSHDB when you want to clear only one logical data set; use FLUSHALL only when you intend to wipe the entire Redis instance.

Can I undo a flush operation?

No. Once keys are flushed, they are permanently deleted. Redis does not maintain a recycle bin or undo log. Always back up data before flushing.

Does FLUSHALL affect persistence files (RDB/AOF)?

Yes. After a flush, Redis will update the persistence files to reflect the empty state. If you restore from an old RDB file, youll restore the old data so ensure your backups are current and versioned.

Why is my Redis server slow after flushing keys?

Flushing large datasets can cause memory fragmentation. Even after deletion, the memory allocator may not return memory to the OS immediately. Use MEMORY PURGE (Redis 4.0+) to force cleanup, or restart Redis if fragmentation is severe.

Can I flush keys without stopping the Redis server?

Yes. Both FLUSHDB and FLUSHALL are non-blocking when used with the ASYNC flag. The server continues serving requests while background threads handle deletion. However, high-frequency flushes can still impact performance.

How do I know if a key has an expiration time before flushing?

Use the TTL command:

TTL session:abc123

It returns:

  • -2 key does not exist
  • -1 key exists but has no TTL
  • n seconds until expiration

To list all non-expiring keys:

redis-cli --scan --pattern "*" | while read key; do if [ $(redis-cli ttl "$key") -eq -1 ]; then echo "$key"; fi; done

Is it safe to flush Redis in a production environment?

It can be, but only if:

  • Youve verified the target instance
  • Youve backed up critical data
  • Youre using ASYNC mode
  • Youve scheduled it during low traffic
  • Youve tested the procedure in staging
  • Youve notified relevant stakeholders

What happens if I flush keys while a replica is syncing?

Flushing the master will replicate the empty state to all replicas. This is normal behavior. However, if a replica is offline during the flush, it will resync from scratch upon reconnect, which can cause high network and CPU load. Plan accordingly.

How can I prevent accidental flushes?

Use Redis ACLs to restrict access. Disable the FLUSH commands for most users. Require multi-person approval via automation (e.g., a Slack bot that requires two confirmations before executing a flush). Log all attempts even failed ones to detect malicious or mistaken activity.

Conclusion

Flushing Redis keys is a powerful operation that can resolve data issues, reclaim memory, and reset systems but it carries significant risk if misused. This guide has walked you through the mechanics of FLUSHDB and FLUSHALL, demonstrated safe alternatives like Lua scripting and ASYNC deletion, and provided real-world examples of how teams successfully manage this task in production environments.

The key to mastering Redis key flushing lies in preparation, verification, and automation. Never flush blindly. Always scan, log, backup, and monitor. Use tools like RedisInsight and ACLs to reduce human error. Integrate flush operations into your CI/CD and incident response workflows to make them repeatable and auditable.

As Redis continues to evolve with features like Redis Streams, RedisJSON, and Redisearch the need for precise data management grows. Flushing keys is not a last-resort hack; its a core operational skill. By following the best practices outlined here, youll ensure your Redis deployments remain resilient, performant, and trustworthy even under the most demanding conditions.