Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 42 ยท Core Data Types

Keys, Expiry and TTL

Learn Redis key expiry: EXPIRE, TTL, PERSIST, lazy and active expiry, SCAN versus KEYS, TYPE, RENAME, DEL versus UNLINK and key naming conventions.

Every Redis value hangs off a key, and most real applications want some of those keys to disappear on their own: a login session after 30 minutes, a cached page after five, a rate-limit counter after a minute. Redis calls this expiry, and it is one of the main reasons Redis works so well as a cache. You attach a time to live (TTL) to a key, and the server deletes the key when the time is up.

This lesson covers setting and reading expiry, how Redis actually removes expired keys, and the everyday commands for exploring and managing keys: TYPE, SCAN, RENAME, DEL and UNLINK. Real syntax appears in read-only blocks. Runnable examples use the JavaScript MiniRedis emulator from What Is Redis? with a fake clock (a variable we move forward), so expiry is deterministic. It models command behavior, not real performance.

Setting an expiry

Keys have no expiry by default. You attach one with the EXPIRE family, or while writing a string with SET key value EX 60.

Command Argument
EXPIRE key seconds Time to live in seconds
PEXPIRE key milliseconds Time to live in milliseconds
EXPIREAT key unix-seconds Absolute deadline as a Unix timestamp
PEXPIREAT key unix-ms Absolute deadline in milliseconds

Each returns 1 if the expiry was set and 0 if it was not (for example because the key does not exist). Since Redis 7.0 you can add a condition: NX (only if the key has no expiry), XX (only if it has one), GT (only if the new deadline is later than the current one) and LT (only if it is earlier). A key without an expiry counts as "infinite", so GT never applies to it and LT always does.

If you pass a time in the past, or a negative number of seconds, the key is deleted immediately.

To read the remaining time use TTL (seconds) or PTTL (milliseconds). Both use special negative values:

  • -2 means the key does not exist (or has already expired).
  • -1 means the key exists but has no expiry.

PERSIST key removes the expiry and returns 1, or 0 if there was nothing to remove.

Reading a TTL

Positive number Time left until the key is removed.
-1 The key exists with no expiry.
-2 No such key.

Check for -2 and -1 before treating the result as time.

1 / 3

Try it: TTL, conditions and PERSIST

JS EXPIRE, TTL and PERSIST with a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After wait(20) the TTL dropped from 60 to 40. GT extended the deadline to 100 seconds, then refused to shorten it, while LT allowed shortening to 30. The PEXPIREAT deadline is an absolute time on the emulator's clock, which started at the Unix time 1700000000000, so 200 seconds after the start.

How Redis removes expired keys

Redis uses two cooperating mechanisms, so it never has to scan everything at once.

  • Lazy expiry: whenever a command touches a key, Redis first checks its deadline. If the time has passed, the key is deleted and the command behaves as if it never existed.
  • Active expiry: about ten times a second, Redis samples a small batch of keys that have an expiry, deletes the expired ones and repeats if a large share of the sample was expired (it also limits how much time it spends). This reclaims memory for keys nobody asks about.

Two consequences matter in practice. First, an expired key is never visible to your commands, even if the server has not freed the memory yet. Second, DBSIZE and memory numbers can briefly include keys that are logically gone. On a replica, the primary sends explicit DEL commands for expired keys, but reads on the replica still hide keys whose time has passed.

The emulator below has a lazy check on every access and a method activeCycle() that stands in for the periodic sweep (real Redis samples randomly, the emulator takes the first 20 for repeatable output).

Exploring keys safely: SCAN vs KEYS

KEYS pattern returns every matching key in one reply. It is simple, and it is dangerous on a large database: it must look at all keys while no other command runs, which can freeze a busy server for seconds. Use it only on small development data.

SCAN walks the keyspace in small steps instead. You start with cursor 0; each call returns a new cursor and a batch of keys, and you stop when the cursor comes back as 0.

TEXT
127.0.0.1:6379> SCAN 0 MATCH user:* COUNT 100
1) "17"
2) 1) "user:3"
   2) "user:9"
127.0.0.1:6379> SCAN 17 MATCH user:* COUNT 100
1) "0"
2) 1) "user:12"

Rules for SCAN that surprise newcomers:

  • COUNT is a hint for work per call, not a guaranteed batch size.
  • MATCH filters after the batch is read, so a batch can be empty while the cursor is not 0 yet.
  • Every key that existed for the whole iteration is returned, but a key can appear more than once, and keys added or removed during the walk may or may not show up. Make your processing idempotent.
  • SCAN itself is cheap per call, so other clients keep being served between calls.

Similar commands exist for collections: SSCAN, HSCAN and ZSCAN, covered in later lessons. The emulator's cursor is just a position in a list, which is simpler than real Redis's internal order but shows the same calling pattern and the same empty-batch effect.

  • TYPE key returns string, list, set, zset, hash, stream and so on, or none for a missing key. Use it to debug, not to branch in production code.
  • RENAME key newkey moves a value to a new name, overwriting the destination, and returns an error if the source does not exist. The expiry travels with the value. RENAMENX renames only if the destination is free.
  • DEL key [key ...] removes keys and returns how many existed. For a huge list or hash, freeing the memory takes time and blocks the server while it happens.
  • UNLINK key [key ...] is the same from your point of view, but it removes the key from the keyspace at once and frees the memory on a background thread. Prefer it for large values. The emulator returns the same numbers as DEL because it cannot show the memory work.

Try it: lazy and active expiry, SCAN and RENAME

JS Lazy vs active expiry, SCAN and RENAME

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the two DBSIZE lines after the clock moved: still 5, because nothing touched the expired keys yet. After EXISTS temp:1 triggered lazy deletion the number drops by one, and the sweep removes the rest. The SCAN loop walks 26 keys in three calls with COUNT 10. Each batch reads up to ten keys and only then applies the MATCH filter, so the batches hold 9, 3 and 0 matching keys, and the last one is an empty batch that still has to be fetched to learn the walk is over.

Copying, moving and sampling keys

A few more key commands finish the set. They work on any value type, because they handle the key rather than what is inside.

Command What it does
RENAMENX key newkey Renames only if newkey does not exist. Returns 1 on success, 0 if the target is taken. Plain RENAME overwrites silently.
COPY source destination [DB n] [REPLACE] Duplicates a key, including its type and its TTL. Fails with 0 if the destination exists, unless you add REPLACE. Added in Redis 6.2.
MOVE key db Moves a key to another numbered database on the same server. Returns 0 if the key is missing or already exists there. Databases are not available in Redis Cluster, so avoid it in new code.
RANDOMKEY Returns one random key from the current database (nil if empty). Handy for sampling, never for picking "a fair random user".
DUMP key Returns an opaque, versioned, checksummed serialization of the value. The TTL is not included.
RESTORE key ttl serialized [REPLACE] Recreates a key from a DUMP payload. A ttl of 0 means no expiry; the TTL is in milliseconds. Fails with BUSYKEY if the key exists unless you add REPLACE.
Text
SET draft:1 "hello"
COPY draft:1 backup:1
RENAMENX draft:1 published:1
DUMP backup:1
RESTORE restored:1 60000 "\x00\x05hello\x0b\x00..."

DUMP and RESTORE are the building blocks of tools that migrate a key between servers (MIGRATE uses them internally). The payload is tied to the Redis version that wrote it, so do not store it long term as a backup format; use snapshots for that.

The model below shows the behaviour that trips people up: RENAMENX and COPY refusing to overwrite, COPY keeping the TTL while DUMP drops it, and RESTORE demanding REPLACE for an existing key.

JS RENAMENX, COPY, DUMP and RESTORE

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both COPY and RENAMENX give an answer of 0 rather than an error when the target exists, so check the reply. RENAME and RENAMENX are atomic, which makes them a good way to publish a prepared key: build report:tmp, then RENAME report:tmp report:current, and readers never see a half-built value.

Key naming conventions

A key is just a binary-safe string up to 512 MB, so the rules are yours to set. Good habits:

  • Use a namespace and colons: app:object:id:field, for example shop:cart:9f3a or cache:product:1001. Tools group keys by colon.
  • Be consistent. A fixed order (object:id:field) makes keys guessable and patterns like cache:product:* useful.
  • Keep keys short enough to be cheap in memory, but readable. user:42:profile beats both u42p and a 200-character URL.
  • Put a version in cache keys when the cached shape can change: cache:v2:product:1001. You can then deploy a new format without flushing.
  • Never build keys from raw, unbounded user input such as a search box, because an attacker can fill memory with unique keys. Hash it or validate it first.
  • Always give cache-like keys a TTL. A key that should be temporary but has none will stay until you notice it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does TTL return for a key that exists but has no expiry?

    -1 means the key exists with no expiry. -2 means the key does not exist (or already expired).
  2. 2. Why is KEYS * risky on a large production database?

    KEYS must visit every key while no other command can run. SCAN does the same walk in small, cheap steps.
  3. 3. A SCAN call returns cursor 8 and an empty list of keys. What should you do?

    COUNT is only a hint and MATCH filters after reading, so empty batches are normal. The iteration ends only when the cursor is 0.
  4. 4. What happens to a key's TTL when you run RENAME on it?

    RENAME moves the value together with its expiry, and any previous key at the destination is overwritten.
  5. 5. Why prefer UNLINK to DEL for a list with millions of items?

    Both remove the key, but DEL frees a large value on the main thread, which stalls every other client.

Summary

  • Keys have no expiry unless you add one with EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT or SET ... EX; Redis 7 adds NX, XX, GT and LT conditions.
  • TTL and PTTL return remaining time, -1 for no expiry and -2 for a missing key; PERSIST removes an expiry, and a plain SET clears one.
  • Expired keys are removed lazily on access and actively by a periodic sample, so they are never visible but may briefly count in DBSIZE.
  • Use SCAN (with a repeat-safe loop) instead of KEYS on real data; COUNT is a hint and MATCH can yield empty batches.
  • RENAME keeps the TTL; UNLINK frees large values in the background while DEL blocks.
  • Name keys with colon-separated namespaces, version cache keys and give temporary keys a TTL.

Next, store ordered collections with Lists.