Expire at Timestamp

Difficulty: Beginner

Question

How do you make a Redis key expire at a specific point in time (for example, midnight tonight) rather than after a relative number of seconds?

Answer

Use EXPIREAT key <unix-seconds> (or PEXPIREAT key <unix-milliseconds>) to give a key an absolute deadline. If you are writing the value at the same time, SET key value EXAT <unix-seconds> (Redis 6.2+) sets the value and the deadline in one atomic command. Redis deletes the key once the server clock passes that timestamp.

The commands that deal with absolute expiry

CommandUnitWhat it does
EXPIREAT key tssecondsSet absolute expiry on an existing key
PEXPIREAT key tsmillisecondsSame with millisecond precision
SET key val EXAT ts / PXAT tss / msWrite value and absolute expiry together (6.2+)
GETEX key EXAT tssecondsRead a value and set its absolute expiry (6.2+)
EXPIRETIME key / PEXPIRETIME keys / msReturn the absolute expiry timestamp (7.0+)
TTL key / PTTL keys / msReturn remaining time to live

EXPIREAT returns 1 if the timeout was set and 0 if the key does not exist (or the condition below was not met). If the timestamp is already in the past, the key is deleted immediately and the command still returns 1.

Conditional flags added in Redis 7.0

EXPIRE, EXPIREAT and their millisecond variants accept one option:

  • NX: set expiry only if the key has none
  • XX: set expiry only if the key already has one
  • GT: set only if the new expiry is later than the current one
  • LT: set only if the new expiry is earlier than the current one

GT is handy when several code paths extend a deadline and you never want one of them to shorten it by accident.

Why absolute time is useful

  • Daily quotas. A UPI-style limit of N transactions per day resets at midnight IST, not 24 hours after the first transaction. Compute the next midnight and use EXPIREAT.
  • Sale windows. A flash-sale price cache on an e-commerce site should die exactly when the sale ends at 23:59:59.
  • Replication. Since Redis 7.0, relative expiries such as EXPIRE and SETEX are written to replicas and the AOF as absolute PEXPIREAT, so a replayed AOF does not extend keys' lives.

Gotchas

  • Seconds vs milliseconds. Date.now() in JavaScript returns milliseconds. Passing it to EXPIREAT sets an expiry thousands of years in the future. Divide by 1000 or use PEXPIREAT.
  • Time zones. UNIX time is always UTC. Compute "midnight in India" by converting from Asia/Kolkata, not from the server's local zone.
  • Server clock. Expiry is evaluated against the Redis server clock. A badly skewed clock or a restored RDB on a machine with a different clock changes when keys die.
  • Overwriting removes TTL. A plain SET on the key later clears the expiry unless you pass KEEPTTL (6.0+) or a new expiry.
Resetting a daily quota at midnight IST. The app computes an absolute deadline once and lets Redis delete the counter on time.
  1. First request of the day: INCR quota:user:42 returns 1.
  2. Compute next midnight in IST: Convert to UNIX seconds in UTC.
  3. EXPIREAT quota:user:42 <ts> NX: NX avoids resetting the deadline on later calls.
  4. Later requests only INCR: The deadline stays fixed.
  5. Clock passes midnight: Redis removes the key and the count starts again.

Code examples

Absolute expiry from redis-cli

# Expire at 2026-12-31 18:30:00 UTC (midnight IST on 1 Jan 2027)
SET sale:price:sku123 49900
EXPIREAT sale:price:sku123 1798741800

# Set value and deadline in one command (Redis 6.2+)
SET sale:banner "Year end sale" EXAT 1798741800

# Inspect (EXPIRETIME needs Redis 7.0+)
EXPIRETIME sale:banner
TTL sale:banner

EXPIREAT works on an existing key, SET ... EXAT does both steps atomically. TTL output depends on when you run it.

Daily counter that resets at midnight IST (Node.js, ioredis)

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

// Next midnight in Asia/Kolkata (UTC+5:30) as UNIX seconds
function nextIstMidnightSeconds() {
  const IST_OFFSET_MS = 5.5 * 60 * 60 * 1000;
  const nowIst = new Date(Date.now() + IST_OFFSET_MS);
  nowIst.setUTCHours(24, 0, 0, 0); // midnight of the next IST day
  return Math.floor((nowIst.getTime() - IST_OFFSET_MS) / 1000);
}

export async function countPayment(userId) {
  const key = `quota:payments:${userId}`;
  const [[, count]] = await redis
    .multi()
    .incr(key)
    .expireat(key, nextIstMidnightSeconds(), 'NX') // NX flag needs Redis 7.0+
    .exec();
  return count;
}

MULTI keeps the increment and expiry together. Note the division by 1000: EXPIREAT takes seconds, while Date.now() gives milliseconds.

Key points

  • EXPIREAT takes UNIX seconds, PEXPIREAT takes milliseconds
  • A timestamp in the past deletes the key immediately
  • SET ... EXAT/PXAT and GETEX ... EXAT exist since Redis 6.2
  • EXPIRETIME and the NX/XX/GT/LT flags arrived in Redis 7.0
  • UNIX time is UTC; convert local deadlines such as midnight IST carefully

Common follow-up questions

  • What is the difference between TTL returning -1 and -2?
  • How does Redis actually delete expired keys (lazy vs active expiry)?
  • What happens to a key's TTL when you overwrite it with SET?
  • How are expiries handled on replicas?

Interview tips

  • Mention the seconds vs milliseconds trap; it is the most common real bug
  • Bring up SET ... EXAT for atomic write plus deadline instead of two commands
  • Give a concrete use case like a daily quota or a sale ending at a fixed time

Concepts covered

EXPIREAT, PEXPIREAT, UNIX timestamp, EXPIRETIME, SET EXAT

More Redis & Caching questions