How to Flush Redis Keys

How to Flush Redis Keys Redis is one of the most widely adopted in-memory data stores in modern application architectures. Known for its speed, flexibility, and support for advanced data structures like hashes, lists, sets, and sorted sets, Redis is commonly used for caching, session storage, real-time analytics, and message brokering. However, with great power comes great responsibility — and one

Oct 30, 2025 - 12:51
Oct 30, 2025 - 12:51
 0

How to Flush Redis Keys

Redis is one of the most widely adopted in-memory data stores in modern application architectures. Known for its speed, flexibility, and support for advanced data structures like hashes, lists, sets, and sorted sets, Redis is commonly used for caching, session storage, real-time analytics, and message brokering. However, with great power comes great responsibility — and one of the most critical operations any Redis administrator must understand is how to flush Redis keys.

Flushing Redis keys means removing all data from the database. This can be a necessary action during troubleshooting, environment resets, security audits, or when migrating between systems. While the command to flush keys is simple, the implications are profound. A single misstep can wipe out production data, disrupt live services, or trigger cascading failures. This guide provides a comprehensive, step-by-step breakdown of how to flush Redis keys safely, effectively, and with full awareness of the consequences.

Whether you’re a DevOps engineer, a backend developer, or a system administrator, mastering this operation ensures you maintain control over your Redis environments without compromising stability or data integrity. This tutorial covers everything from basic commands to advanced strategies, best practices, real-world examples, and common pitfalls — giving you the confidence to perform this operation correctly, every time.

Step-by-Step Guide

Understanding Redis Databases and Keyspaces

Before flushing keys, it’s essential to understand how Redis organizes data. Redis supports multiple logical databases — by default, 16, numbered from 0 to 15. Each database is an independent keyspace, meaning keys in database 0 are separate from keys in database 1, and so on. When you connect to Redis, you’re typically connected to database 0 unless otherwise specified.

To check which database you’re 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> DBSIZE

(integer) 42

The DBSIZE command returns the number of keys in the currently selected database. This gives you a baseline before performing any destructive operation.

Flushing All Keys in the Current Database

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

To execute this:

  1. Open your terminal or SSH session.
  2. Connect to Redis using the CLI: redis-cli
  3. Ensure you’re in the correct database: SELECT 0 (or your target database number)
  4. Run: FLUSHDB
  5. Confirm success: DBSIZE should return (integer) 0

Example session:

redis-cli

127.0.0.1:6379> SELECT 1

OK

127.0.0.1:6379> DBSIZE

(integer) 89

127.0.0.1:6379> FLUSHDB

OK

127.0.0.1:6379> DBSIZE

(integer) 0

This is ideal for resetting a staging environment or clearing a specific cache namespace without impacting other services.

Flushing All Keys Across All Databases

If you need to wipe everything — all databases, all keys, all data — use the FLUSHALL command. This is a global operation and affects every logical database in the Redis instance.

Warning: This command cannot be undone. There is no recycle bin, no undo, no confirmation prompt. Once executed, data is permanently removed from memory.

To execute:

  1. Connect to Redis: redis-cli
  2. Run: FLUSHALL
  3. Verify: INFO keyspace will show zero keys across all databases

Example:

redis-cli

127.0.0.1:6379> INFO keyspace

Keyspace

db0:keys=42,expires=0,avg_ttl=0

db1:keys=89,expires=0,avg_ttl=0

127.0.0.1:6379> FLUSHALL

OK

127.0.0.1:6379> INFO keyspace

Keyspace

db0:keys=0,expires=0,avg_ttl=0

db1:keys=0,expires=0,avg_ttl=0

Use FLUSHALL only when you’re certain no live service depends on Redis data. This is typically done during full system resets, container rebuilds, or when re-provisioning a test environment.

Flushing Keys via Redis API or Programming Languages

While the CLI is useful for manual operations, automated systems often require programmatic control. Most Redis client libraries expose methods to flush keys.

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(); // Current DB

// OR

await redis.flushall(); // All DBs

Java (Jedis)

Jedis jedis = new Jedis("localhost");

jedis.flushDB(); // Current DB

// OR

jedis.flushAll(); // All DBs

Go (go-redis)

package main

import (

"context"

"github.com/go-redis/redis/v8"

)

ctx := context.Background()

client := redis.NewClient(&redis.Options{

Addr: "localhost:6379",

})

err := client.FlushDB(ctx).Err() // Current DB

// OR

err = client.FlushAll(ctx).Err() // All DBs

When using these APIs in production automation scripts, always wrap flush operations in conditional checks and logging. Never trigger a flush based on unverified user input or automated triggers without explicit approval workflows.

Using Redis CLI with Authentication

If your Redis instance requires authentication (which it should in production), you must provide a password before executing flush commands.

Use the -a flag to pass the password:

redis-cli -a yourpassword FLUSHDB

redis-cli -a yourpassword FLUSHALL

Alternatively, connect first and authenticate:

redis-cli

127.0.0.1:6379> AUTH yourpassword

OK

127.0.0.1:6379> FLUSHALL

OK

Never hardcode passwords in scripts. Use environment variables or secret management tools like HashiCorp Vault, AWS Secrets Manager, or Kubernetes Secrets.

Flushing Keys on Remote or Cloud Redis Instances

Many organizations use managed Redis services like Amazon ElastiCache, Google Memorystore, or Azure Cache for Redis. The process remains the same, but access is typically via a public or private endpoint.

For example, with ElastiCache:

redis-cli -h your-redis-cluster.xxxxxx.ng.0001.use1.cache.amazonaws.com -p 6379 -a yourpassword FLUSHALL

Ensure your security group or VPC peering allows outbound connections from your client machine. Some cloud providers require additional IAM permissions or VPC endpoints for Redis access.

Verifying the Flush Operation

After executing a flush, always verify the result. Don’t assume success. Use these commands to confirm:

  • DBSIZE — returns the number of keys in the current database
  • INFO keyspace — shows key count and expiration stats for all databases
  • KEYS * — lists all keys (use cautiously in production; can block Redis)
  • SCAN 0 — safer alternative to KEYS for large datasets

Example verification:

127.0.0.1:6379> FLUSHALL

OK

127.0.0.1:6379> INFO keyspace

Keyspace

db0:keys=0,expires=0,avg_ttl=0

db1:keys=0,expires=0,avg_ttl=0

127.0.0.1:6379> SCAN 0

1) "0"

2) (empty list or set)

If keys still exist, the flush failed. Investigate connection issues, authentication errors, or whether you’re connected to the wrong instance.

Best Practices

Always Backup Before Flushing

Redis provides built-in persistence through RDB snapshots and AOF (Append-Only File) logs. However, these are not substitutes for a proper backup strategy.

Before performing any flush operation, trigger a manual snapshot:

redis-cli SAVE

This forces an immediate RDB dump to disk. For larger datasets, use BGSAVE to avoid blocking the server:

redis-cli BGSAVE

Verify the dump was created:

ls -la /var/lib/redis/dump.rdb

Additionally, ensure your Redis instance is configured with dir and dbfilename in redis.conf, and that the backup directory has sufficient disk space and proper permissions.

Use Environment Isolation

Never flush keys in production unless absolutely necessary. Always test flush operations in staging or development environments first. Use separate Redis instances per environment with clear naming conventions (e.g., redis-prod, redis-staging, redis-dev).

Consider using Redis databases 0–3 for different environments:

  • Database 0: Production
  • Database 1: Staging
  • Database 2: QA
  • Database 3: Development

Label your connections explicitly in code and documentation to prevent accidental cross-environment operations.

Implement Approval Workflows

Automated scripts that flush Redis should never run without human oversight. Use infrastructure-as-code tools like Terraform or Ansible with manual approval gates. In CI/CD pipelines, require a manual trigger or approval step before executing a flush command.

For example, in GitHub Actions:

name: Reset Redis Staging

on:

workflow_dispatch:

inputs:

confirm_flush:

description: 'Type "YES" to confirm flush'

required: true

jobs:

flush-redis:

runs-on: ubuntu-latest

if: ${{ github.event.inputs.confirm_flush == 'YES' }}

steps:

- name: Flush Redis

run: redis-cli -h ${{ secrets.REDIS_HOST }} -p ${{ secrets.REDIS_PORT }} -a ${{ secrets.REDIS_PASSWORD }} FLUSHDB

This prevents accidental execution and creates an audit trail.

Monitor Redis During and After Flush

Flushing large datasets can temporarily increase memory fragmentation and CPU usage. Monitor Redis performance metrics before, during, and after the operation:

  • Memory usage (INFO memory)
  • Connected clients (INFO clients)
  • Command stats (INFO commandstats)
  • Replication status (if using Redis replication)

Use tools like RedisInsight, Prometheus + Grafana, or Datadog to visualize Redis metrics in real time.

Disable Persistence Temporarily (If Needed)

In some cases, you may want to flush keys without triggering an RDB snapshot or AOF rewrite. For example, if you’re clearing a cache and want to avoid disk I/O overhead.

Temporarily disable persistence:

redis-cli CONFIG SET save ""

redis-cli CONFIG SET appendonly no

Then flush:

FLUSHALL

Re-enable persistence afterward:

redis-cli CONFIG SET save "900 1 300 10 60 10000"

redis-cli CONFIG SET appendonly yes

Use this technique cautiously — disabling persistence leaves your data vulnerable to loss on restart.

Use Redis Modules for Granular Control

Redis modules like RedisJSON, RedisGraph, or RediSearch store data in specialized formats. Flushing with FLUSHALL removes them too, but you may need to restart the module or reinitialize schemas afterward.

Always consult module documentation before flushing. Some modules maintain internal state or indexes that require manual cleanup or regeneration.

Document and Communicate

Every flush operation should be documented. Record:

  • Who performed the operation
  • When it occurred
  • Why it was needed
  • What data was affected
  • How it was verified

Store this in a shared runbook or incident management system. This ensures accountability and helps future teams understand the state of the system.

Tools and Resources

Redis CLI

The Redis Command-Line Interface is the most direct and reliable tool for flushing keys. It’s lightweight, fast, and available on all platforms. Always ensure you’re using a recent version of Redis CLI to avoid compatibility issues.

RedisInsight

RedisInsight is a free, GUI-based tool from Redis Labs that allows you to visually explore, monitor, and manage Redis instances. You can browse keys, view memory usage, and execute commands — including FLUSHDB and FLUSHALL — through a point-and-click interface.

Benefits:

  • Visual key browsing before deletion
  • Real-time metrics and alerts
  • Multi-instance management
  • Command history and audit logs

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

Prometheus + Grafana

For production environments, integrate Redis with Prometheus using the redis_exporter. This allows you to monitor key metrics like:

  • redis_connected_clients
  • redis_used_memory
  • redis_total_commands_processed
  • redis_keyspace_hits

Set up Grafana dashboards to visualize Redis health before and after flush operations. This helps detect anomalies, such as unexpected spikes in memory or latency.

Ansible and Terraform

Infrastructure automation tools can safely orchestrate Redis flush operations as part of deployment workflows. For example, an Ansible playbook can:

  1. Check Redis health
  2. Trigger a backup
  3. Wait for confirmation
  4. Execute FLUSHDB
  5. Verify completion

Example Ansible task:

- name: Flush Redis staging database

command: redis-cli -h {{ redis_host }} -p {{ redis_port }} -a {{ redis_password }} FLUSHDB

args:

chdir: /opt/redis

register: flush_result

when: environment == "staging"

notify: Log Redis Flush

- name: Log Redis flush

lineinfile:

path: /var/log/redis-flush.log

line: "{{ ansible_date_time.iso8601 }} - User {{ ansible_user_id }} flushed Redis DB on {{ redis_host }}"

create: yes

Redis Monitoring Scripts

Create simple bash or Python scripts to automate pre-flush checks:

!/bin/bash

pre-flush-check.sh

REDIS_HOST="localhost"

REDIS_PORT="6379"

REDIS_PASSWORD="yourpassword"

echo "Checking Redis health..."

KEY_COUNT=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a $REDIS_PASSWORD DBSIZE 2>/dev/null)

if [ $? -ne 0 ]; then

echo "ERROR: Could not connect to Redis"

exit 1

fi

echo "Current key count: $KEY_COUNT"

if [ "$KEY_COUNT" -eq 0 ]; then

echo "No keys to flush. Exiting."

exit 0

fi

echo "Proceeding with flush..."

redis-cli -h $REDIS_HOST -p $REDIS_PORT -a $REDIS_PASSWORD FLUSHDB

echo "Flush completed."

Redis Documentation and Community

Always refer to the official Redis documentation for the most accurate and up-to-date command behavior:

Community forums like Stack Overflow, Reddit’s r/redis, and the Redis GitHub discussions are excellent resources for troubleshooting edge cases.

Real Examples

Example 1: Resetting a Caching Layer After a Deployment

Scenario: A new version of a web application is deployed, and the old cache keys are incompatible with the updated schema. The team needs to clear the cache to prevent stale data from being served.

Steps:

  1. Notify all teams of scheduled maintenance window.
  2. Verify the Redis instance is dedicated to caching (not session storage).
  3. Run redis-cli -h cache-prod.example.com DBSIZE — returns 12,450 keys.
  4. Trigger redis-cli -h cache-prod.example.com BGSAVE to create a backup.
  5. Wait for backup to complete (confirmed via INFO persistence).
  6. Execute redis-cli -h cache-prod.example.com FLUSHDB.
  7. Verify with DBSIZE — returns 0.
  8. Monitor application logs for cache misses — expected behavior.
  9. Update documentation: “Cache flushed on 2024-06-15 after v2.3 deployment.”

Result: Application resumes normal operation with fresh cache entries. No downtime occurred.

Example 2: Cleaning a Staging Environment Before QA Testing

Scenario: QA engineers need a clean Redis state to test a new feature that relies on session data.

Steps:

  1. Confirm no active users are connected to staging Redis.
  2. Use RedisInsight to browse keys — notice keys like “session:*”, “temp:*”, and “auth:*”.
  3. Take a screenshot of the key structure for reference.
  4. Execute FLUSHALL via RedisInsight GUI with confirmation dialog.
  5. Run a test script that creates 100 new session keys.
  6. Verify keys are created and accessible via application UI.
  7. Log the operation in the team’s internal wiki.

Result: QA environment is reset, test suite passes, and the team gains confidence in the new feature.

Example 3: Emergency Data Cleanup After a Security Breach

Scenario: A vulnerability in a third-party library caused unauthorized access to Redis. Suspicious keys were found, including “malware:payload” and “backdoor:cmd”.

Steps:

  1. Isolate the Redis instance from public networks.
  2. Connect via internal network or jump host.
  3. Run KEYS * to list all keys — identify malicious patterns.
  4. Run FLUSHALL to remove all data.
  5. Immediately change Redis password and regenerate TLS certificates.
  6. Enable Redis ACLs and firewall rules to restrict access.
  7. Restore data from a clean backup taken before the breach.
  8. Conduct a post-mortem and update security policies.

Result: Malicious data is eradicated, system is hardened, and future risk is mitigated.

Example 4: Automated CI/CD Pipeline Reset

Scenario: A CI/CD pipeline runs integration tests against a Redis-backed microservice. Each test run must start with a clean Redis state.

Implementation:

name: Integration Tests

on: [push]

jobs:

test:

runs-on: ubuntu-latest

steps:

- uses: actions/checkout@v4

- name: Start Redis

uses: supercharge/redis-github-action@1.5.0

- name: Flush Redis

run: redis-cli FLUSHALL

- name: Run Tests

run: |

npm install

npm test

- name: Archive Test Results

uses: actions/upload-artifact@v3

with:

name: test-results

path: test-results/

Result: Each test run is isolated and repeatable. No test contamination occurs between runs.

FAQs

What is the difference between FLUSHDB and FLUSHALL?

FLUSHDB removes all keys from the currently selected Redis database. FLUSHALL removes all keys from all databases in the Redis instance. Use FLUSHDB for targeted resets and FLUSHALL for complete data wipes.

Can I undo a FLUSHALL command?

No. Redis does not have an undo feature. Once keys are flushed, they are permanently removed from memory. Recovery is only possible if you have a prior backup (RDB or AOF file).

Does FLUSHDB affect Redis persistence?

No. FLUSHDB only clears the in-memory dataset. Persistence files (RDB/AOF) remain unchanged. However, if persistence is enabled, the next snapshot or rewrite will reflect the empty state.

Can I flush only specific keys?

Yes, but not with FLUSHDB or FLUSHALL. To remove specific keys, use the DEL command with key patterns. For example: DEL user:123 session:abc. For bulk deletion by pattern, use a script with SCAN and DEL, or use the UNLINK command for non-blocking deletion.

Will flushing Redis affect connected clients?

Yes. All clients lose access to the data they were using. Applications relying on Redis for session storage, caching, or queuing will experience errors or timeouts until data is repopulated. Always plan for this impact.

Is it safe to flush Redis in production?

Only if you have a validated backup, a clear business justification, and coordinated downtime. In most cases, avoid flushing production Redis. Use separate instances for production and non-production environments.

How long does FLUSHALL take?

It’s typically instantaneous — even with millions of keys — because Redis removes keys from memory in O(n) time without writing to disk. However, if persistence is enabled, a background rewrite may trigger afterward, which can cause temporary performance impact.

Can I flush Redis remotely without CLI access?

Yes, if you have API access via HTTP (e.g., through RedisInsight or a custom API wrapper). However, direct CLI or client library access is preferred for reliability and security.

Why does FLUSHALL sometimes appear to hang?

It rarely does. If it appears to hang, check for network latency, authentication failures, or connection timeouts. Use redis-cli --latency to test connection health.

How do I prevent accidental flushes?

Use strong authentication, restrict CLI access, implement approval workflows, use environment separation, and enable Redis ACLs (Access Control Lists) to limit who can execute dangerous commands.

Conclusion

Flushing Redis keys is a powerful and potentially dangerous operation. While the commands — FLUSHDB and FLUSHALL — are simple to execute, their consequences can be severe if performed without caution. This guide has provided you with a comprehensive, step-by-step roadmap to safely and effectively flush Redis keys across multiple environments, use cases, and platforms.

From understanding the difference between databases to implementing automated workflows and monitoring tools, you now have the knowledge to handle this operation with confidence. Remember: always verify your target, backup your data, document your actions, and test in non-production environments first.

Redis is designed for speed and simplicity, but that simplicity demands responsibility. By following the best practices outlined here, you ensure that your Redis instances remain reliable, secure, and performant — even after the most drastic data-clearing operations.

As Redis continues to power mission-critical applications at scale, mastering foundational operations like flushing keys isn’t just a technical skill — it’s a professional obligation. Use this guide as your reference, revisit it before every operation, and never underestimate the weight of a single command.