Setting Expiry

Difficulty: Beginner

Question

How do you set a key to expire in 60 seconds in Redis, and how do you check or change its remaining time?

Answer

Use EXPIRE key 60 on an existing key, or set the value and the expiry together with SET key value EX 60. After 60 seconds Redis deletes the key automatically. You can check the remaining time with TTL key (seconds) or PTTL key (milliseconds).

All the ways to set an expiry

CommandWhat it does
SET key value EX 60Set value and 60-second TTL atomically
SET key value PX 60000Same, in milliseconds
EXPIRE key 60Add a TTL to an existing key
PEXPIRE key 60000Same, in milliseconds
EXPIREAT key 1760300000Expire at a Unix timestamp in seconds
PEXPIREAT key ...Expire at a Unix timestamp in milliseconds
GETEX key EX 60Read the value and reset its TTL (6.2+)
PERSIST keyRemove the TTL, key lives forever

Prefer SET ... EX when creating a cache entry. Running SET then EXPIRE as two commands leaves a gap where a crash could leave a key with no TTL at all.

Reading TTL values

  • TTL key returns the seconds remaining.
  • It returns -1 if the key exists but has no expiry.
  • It returns -2 if the key does not exist.
  • EXPIRETIME key (7.0+) returns the absolute Unix timestamp at which the key will expire.

Behaviours that catch people out

  • Overwriting clears the TTL: a plain SET key newvalue removes the existing expiry. Use SET key newvalue KEEPTTL (6.0+) to keep it.
  • Modifying does not clear it: INCR, HSET, LPUSH, APPEND and similar commands keep the existing TTL.
  • EXPIRE with a zero or negative value deletes the key immediately.
  • Since Redis 7.0, EXPIRE accepts NX (only if no TTL), XX (only if a TTL exists), GT and LT (only if the new TTL is greater or less). EXPIRE session:9 1800 GT extends a session without ever shortening it.
  • TTLs apply to whole keys. Since Redis 7.4 you can expire individual hash fields with HEXPIRE, HTTL and HPERSIST.
  • RENAME keeps the TTL with the renamed key.

How Redis actually deletes expired keys

Redis does not run a timer per key. It uses two mechanisms:

  1. Lazy expiry: when a client accesses a key, Redis checks if it is expired and deletes it on the spot, returning nil.
  2. Active expiry: a background cycle runs several times a second (driven by hz, default 10), samples keys that have a TTL, and deletes expired ones. If many in the sample were expired, it repeats.

So an expired key might sit in memory briefly, but no client will ever read it. Watch expired_keys in INFO stats to see how many keys expire.

Real uses

  • OTP codes valid for 5 minutes: SET otp:9876543210 482913 EX 300.
  • Session tokens extended on each request with EXPIRE ... GT.
  • Rate limit windows: INCR a counter and set EXPIRE only when it was just created.
  • Cache entries with jitter, like 3600 plus a random 0 to 300 seconds, to avoid many keys expiring at the same moment.

Code examples

Setting and checking expiry

redis-cli SET otp:9876543210 482913 EX 60   # value + 60s TTL atomically
redis-cli TTL otp:9876543210

redis-cli SET page:home '<html>'
redis-cli EXPIRE page:home 60                 # add TTL to existing key
redis-cli PTTL page:home

redis-cli SET page:home '<html v2>'           # plain SET clears TTL!
redis-cli TTL page:home

redis-cli SET page:home '<html v3>' EX 60
redis-cli SET page:home '<html v4>' KEEPTTL    # keep remaining TTL
redis-cli TTL page:home

redis-cli TTL does:not:exist

TTL returns -1 for a key with no expiry and -2 for a missing key. KEEPTTL preserves the expiry when you overwrite a value.

Fixed-window rate limiter in Node.js

import Redis from 'ioredis';
const redis = new Redis();

// Allow 100 requests per user per 60-second window
async function allow(userId) {
  const key = `rl:${userId}:${Math.floor(Date.now() / 60000)}`;
  const [[, count]] = await redis
    .multi()
    .incr(key)
    .expire(key, 60, 'NX') // set TTL only on first hit (Redis 7+)
    .exec();
  return count <= 100;
}

INCR keeps any existing TTL, and EXPIRE with NX only sets it when none exists, so the window is not extended on every request.

Key points

  • SET key value EX 60 sets value and TTL atomically; prefer it over SET then EXPIRE.
  • TTL returns -1 for no expiry and -2 for a missing key.
  • A plain SET removes the TTL; INCR and other modifications keep it; KEEPTTL preserves it.
  • Redis 7.0 added NX, XX, GT and LT options to EXPIRE; 7.4 added per-field hash expiry.
  • Expired keys are removed lazily on access and by a background sampling cycle.

Common follow-up questions

  • What happens to a key's TTL when you overwrite it with SET?
  • How does Redis delete expired keys if nobody reads them?
  • How are expirations handled on replicas?
  • Why add random jitter to cache TTLs?

Interview tips

  • Give SET with EX as the main answer and explain why it is better than two commands.
  • Mention the SET-clears-TTL gotcha; it is a common production bug.
  • Briefly describing lazy plus active expiry turns a beginner question into a strong answer.

Concepts covered

EXPIRE, SET EX, TTL and PTTL, PERSIST, Lazy and Active Expiry

More Redis & Caching questions