Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk10 min

How to Manage Redis Databases and Keys Safely

Learn how to select Redis databases, inspect keys without blocking production, manage TTLs, delete data safely, restrict dangerous commands with ACLs, and choose an eviction policy that protects the data that matters.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Manage Redis safely by treating a database selection, key scan, expiration, deletion, access control, and memory policy as separate decisions. Select the intended logical database with SELECT, count it with DBSIZE, inspect it incrementally with SCAN rather than blocking the server with KEYS, apply and verify TTLs, and reserve FLUSHDB or FLUSHALL for deliberately approved resets. ACLs must deny whole-database commands when a user should be restricted to a key pattern, and your eviction policy must match whether losing data is acceptable.

What a Redis database is—and what a key operation affects

A Redis server can expose multiple logical databases. Each database is a separate key namespace identified by an integer index, but the databases share the same Redis process and memory limit. A client connection has one selected database at a time; commands such as GET, SET, SCAN, DBSIZE, and FLUSHDB operate against that selected database.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Redis keys are unique within their database. The same key name can exist in database 0 and database 2 without being the same object. Logical databases are useful for lightweight separation on a single server, but they are not equivalent to independent Redis instances: they share resources, configuration, persistence, and failure boundaries.

Select the intended database before you inspect or change it

Use SELECT to change the connection’s database

Run SELECT on the connection that will perform the work. The command changes only that connection’s selected database, so a second connection can remain on another index.

#1 Best Overall
SELECT 2
DBSIZE

DBSIZE returns the number of keys in the currently selected database. It does not count keys in other logical databases. Include the selected index in operational notes and scripts; a forgotten SELECT is a common cause of inspecting or deleting the wrong namespace.

Verify connection context in automation

Connection pools can reuse a client after another request selected a different database. Set the database explicitly when a client is created or at the beginning of a job, then run a harmless check such as DBSIZE. Do not assume that a pooled connection is still on database 0 or on the database used by the previous request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

List keys without blocking Redis

Use cursor-based SCAN for routine inspection

SCAN returns a cursor and a batch of keys instead of attempting to return the entire keyspace in one response. Start at cursor 0, optionally filter by a pattern, and continue with each returned cursor until it becomes 0.

SCAN 0 MATCH user:* COUNT 100

MATCH filters names; it does not make the operation a point lookup. COUNT is a work hint, not a guaranteed result size. A scan can return an empty batch while its cursor is not yet 0, so clients must continue until completion. During concurrent writes, an iteration can see a key more than once or miss a key that is added and removed while the scan is in progress; design cleanup jobs to be idempotent.

Why KEYS is risky

KEYS pattern tries to find every matching key before returning. Redis documentation warns that KEYS blocks the server until all keys are returned. On a large or busy production database, that pause can delay unrelated reads, writes, and expiration processing. Use it only on a controlled, very small dataset or during an emergency diagnostic where the blocking impact has been explicitly accepted.

Need Preferred operation Operational effect
Explore a potentially large keyspace SCAN Incremental cursor iteration; suitable for batches and resumable jobs
Check a tiny, controlled dataset KEYS pattern Single blocking operation; use only when the impact is understood
Count the selected database DBSIZE Reports that database’s key count, not the whole server’s total

Make scans useful and safe

  • Use a naming convention such as user:, session:, or queue: so that MATCH can target a bounded class of keys.
  • Process each batch promptly rather than collecting the entire key list in application memory.
  • Throttle destructive follow-up work and record the selected database, pattern, cursor progress, and operator.
  • Before changing values, inspect their type with TYPE; a key may hold a string, list, hash, set, sorted set, stream, JSON value, or another supported structure.

Set, inspect, and remove key expiration

Set a TTL when writing a key

For a session that should last one hour, set the value and expiration together:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
SET session:123 abc EX 3600

EX expresses the lifetime in seconds. Redis also accepts millisecond lifetimes with PX, and the command family includes EXPIRE and PEXPIRE for applying a lifetime to an existing key.

EXPIRE session:123 600
PEXPIRE session:123 600000

Expiration resolution is one millisecond. Redis stores expiration information as an absolute timestamp for persistence and replication, so clock configuration and clock changes on servers involved in those operations matter.

Check how long a key has left

TTL session:123
PTTL session:123

TTL reports remaining time in seconds; PTTL reports milliseconds. A negative result distinguishes important states: -1 means the key exists without an expiration, while -2 means the key does not exist. Check the result immediately before a renewal or cleanup decision because another client may change or delete the key.

Remove an expiration without deleting the value

PERSIST session:123

PERSIST removes the expiration and leaves the value in place. Use it deliberately: converting a temporary session, cache entry, or lock into a non-expiring key can consume memory indefinitely. If the business rule is to extend the lifetime, use a new explicit EXPIRE or PEXPIRE instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Expiration is not a transaction guarantee

A TTL can reach zero between inspection and a subsequent command. For workflows that require atomicity, combine related operations in a transaction or Lua function appropriate to the application, and make the operation safe when the key has already disappeared. Treat an expiring key as optional state unless the application has a durable source of truth elsewhere.

Delete one key, a group, or an entire database

Delete named keys deliberately

Use DEL for explicit keys when synchronous deletion is acceptable. UNLINK can detach keys and reclaim memory asynchronously, which is useful for large values when you want to reduce the time spent in the command’s critical path. Neither command is a substitute for verifying the selected database and the exact key list.

Reset only the selected database with FLUSHDB

FLUSHDB ASYNC

FLUSHDB removes every key from the currently selected logical database. The command reference classifies its work as O(N) in the number of keys in that database. The ASYNC option schedules the memory freeing work so the command can return sooner; it does not make the data recoverable or undo an accidental selection.

Reset every logical database with FLUSHALL

FLUSHALL ASYNC

FLUSHALL removes all keys from all logical databases on the server. It is a dangerous operation, has O(N) complexity in the total number of keys, and can clear the RDB persistence file. Treat it as a separately approved disaster-level action, not as a convenient way to clean one application’s namespace.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Operation Scope Use case Risk boundary
DEL Named keys Targeted removal when synchronous work is acceptable Wrong key names or types can remove live data
UNLINK Named keys Targeted removal with asynchronous memory reclamation Deletion is still immediate and irreversible from Redis’s perspective
FLUSHDB Current logical database Approved database reset O(N) work; selected database must be verified
FLUSHALL Every logical database Approved server-wide reset Dangerous, O(N), and may clear the RDB persistence file

Use a change-control checklist before flushing

  • Confirm the hostname, environment, server role, and selected database on the same connection that will run the command.
  • Capture a key count with DBSIZE and identify whether any other application uses the instance.
  • Check replication, persistence, backups, and the recovery procedure; a flush is not a backup.
  • Prefer a targeted scan and deletion when only a namespace or key family must be removed.
  • Record who approved the action and whether asynchronous freeing has completed before declaring memory reclaimed.

Protect operators and tenants with Redis ACLs

Redis ACLs limit which commands a connection can execute and which key patterns it can access. A pattern such as ~tenant1:* is useful for tenant-scoped data, but key patterns do not constrain commands that operate on an entire database.

In particular, FLUSHALL, FLUSHDB, and SWAPDB can bypass a user’s key-pattern boundary. A user who can run one of those commands may affect keys outside the pattern, even when ordinary reads and writes are restricted.

ACL SETUSER tenant1 on >strong-password ~tenant1:* +@all -flushall -flushdb -swapdb

This example enables the user, grants the broad command category, limits ordinary key access to tenant1:*, and explicitly removes the three whole-database commands. In production, use a separately generated secret and grant only the command categories and individual commands the service needs; +@all is intentionally broad and should be narrowed for least privilege.

Test ACLs as the real user

Do not validate a policy only as an administrator. Authenticate as the restricted user and test an allowed key, a different tenant’s key, FLUSHDB, FLUSHALL, and SWAPDB. Confirm that denied commands fail before deploying the account to an application or automation system. Recheck ACLs after upgrades or policy changes because command permissions and operational tooling can evolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an eviction policy that matches the value of your data

When Redis reaches its configured memory limit, the eviction policy determines whether writes can remove existing keys. This is separate from TTL expiration: a key can be evicted because of memory pressure even when it has no expiration, depending on the policy.

Policy family Keys eligible for eviction When it fits
allkeys-lru Any key; least recently used first Every key is disposable and recency predicts usefulness
allkeys-lfu Any key; least frequently used first Every key is disposable and access frequency is meaningful
allkeys-random Any key, selected randomly Any key may go and access patterns offer little guidance
volatile-lru Only keys with an expiration; least recently used first Non-expiring keys must be protected and expiring keys are cache-like
volatile-lfu Only expiring keys; least frequently used first Expiring data is disposable and frequency is meaningful
volatile-random Only expiring keys, selected randomly Only TTL-bearing data may be removed and no ranking is needed
volatile-ttl Only expiring keys, favoring the shortest remaining TTL Keys closest to natural expiration are the best eviction candidates
no eviction None Writes must fail rather than delete data; capacity must be sized accordingly

Apply the policy to the data model, not just the workload

Choose an allkeys-* policy when any key can be regenerated or lost. Choose a volatile-* policy only when every key that may be removed has an expiration and non-expiring keys must survive. If losing any existing key is unacceptable, use no eviction and plan for write failures, capacity headroom, alerts, and a durable system of record.

Best Value

A volatile policy does not guarantee that Redis can evict enough memory: if eligible keys are absent or too few, writes can still fail. Conversely, an all-keys policy can remove persistent-looking data that an application assumed would remain. Test the policy with realistic key sizes, TTLs, and traffic before relying on it during an incident.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use Redis Insight for exploration, with the same safeguards

Redis Insight is Redis’s official graphical interface. It can browse, filter, visualize, and perform CRUD operations on strings, lists, hashes, sets, sorted sets, streams, JSON, and other supported structures. A GUI is helpful when you need to inspect a value’s type and contents or make a controlled edit without memorizing command syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

GUI convenience does not reduce production risk. Confirm the connection and selected database, prefer filtered or incremental browsing, restrict access to trained operators, and put destructive edits and database flushes through the same approval and audit process as CLI commands. Use a read-only account for investigation whenever possible.

A safe maintenance workflow

  1. Identify the target. Record the Redis endpoint, environment, selected database index, and authenticated username. Select the index explicitly with SELECT.
  2. Measure before changing. Run DBSIZE, check memory and persistence health, and establish whether the keys are cache data, session state, queues, or authoritative application data.
  3. Inspect incrementally. Use SCAN with a narrow MATCH pattern and a practical COUNT. Inspect representative values and types before writing a deletion script.
  4. Check lifetime rules. Use TTL or PTTL on representative keys. Add an expiration with EXPIRE/PEXPIRE, preserve one with PERSIST, or correct the application write path if TTLs are missing.
  5. Choose the smallest deletion scope. Delete named keys with DEL or UNLINK. Use FLUSHDB only for the selected database and FLUSHALL only for an approved server-wide reset.
  6. Confirm authorization. Ensure the operator or service account cannot bypass its intended boundary through whole-database commands. Test the ACL as that account.
  7. Watch recovery. After changes, monitor key counts, memory, latency, replication, persistence, application errors, and eviction counters. Verify that asynchronous deletion has finished before judging the memory result.

Troubleshooting common Redis management mistakes

The key appears to be missing

Check the database index first, then verify the exact spelling and key type. A key may have expired, been evicted, been deleted by another client, or exist in another logical database. Compare TTL output with application timestamps and inspect eviction behavior before recreating it blindly.

A scan seems incomplete

Continue requesting SCAN with the returned cursor until it is 0. Do not treat an empty batch as completion. If the keyspace is changing rapidly, expect duplicate observations and design the consumer to tolerate them.

Writes fail at the memory limit

Determine whether the configured policy is no eviction, whether a volatile policy has too few TTL-bearing candidates, or whether an all-keys policy is evicting data that should be durable. Reduce memory use, increase capacity, correct TTL assignment, or move authoritative data to durable storage rather than simply raising the limit without a policy decision.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An operator can flush more than intended

Key-pattern ACLs alone are insufficient. Explicitly deny FLUSHALL, FLUSHDB, and SWAPDB for tenant-scoped users, then test those denials using the actual account and connection path used by automation.

Command reference

Command Purpose Important qualification
SELECT n Choose logical database n for the connection Connection-local; make it explicit in pooled clients
DBSIZE Count keys in the selected database Does not count other databases
SCAN cursor MATCH pattern COUNT n Iterate through keys incrementally Repeat until cursor 0; batches are not guaranteed to contain exactly n keys
EXPIRE key seconds / PEXPIRE key milliseconds Assign a lifetime Expiration resolution is one millisecond
TTL key / PTTL key Inspect remaining lifetime -1 means no expiration; -2 means absent
PERSIST key Remove expiration Value remains and can become unbounded
DEL key / UNLINK key Remove named keys UNLINK frees memory asynchronously
FLUSHDB [ASYNC] Remove the selected database O(N) in that database; irreversible from Redis’s perspective
FLUSHALL [ASYNC] Remove every logical database Dangerous, O(N) overall, and may clear the RDB persistence file

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.