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.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
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.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRedis 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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteList 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.
Rank #2
| 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:, orqueue:so thatMATCHcan 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:
Recommended Free Tools
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.
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.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →| 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
DBSIZEand 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.
Rank #4
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.
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.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.
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
- Identify the target. Record the Redis endpoint, environment, selected database index, and authenticated username. Select the index explicitly with
SELECT. - 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. - Inspect incrementally. Use
SCANwith a narrowMATCHpattern and a practicalCOUNT. Inspect representative values and types before writing a deletion script. - Check lifetime rules. Use
TTLorPTTLon representative keys. Add an expiration withEXPIRE/PEXPIRE, preserve one withPERSIST, or correct the application write path if TTLs are missing. - Choose the smallest deletion scope. Delete named keys with
DELorUNLINK. UseFLUSHDBonly for the selected database andFLUSHALLonly for an approved server-wide reset. - Confirm authorization. Ensure the operator or service account cannot bypass its intended boundary through whole-database commands. Test the ACL as that account.
- 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.
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.
Quick Recap
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.




