TTL (key expiration) commands

Any key, of any type, can be given a time to live. Expirations live in one sparse, keyspace-wide structure — only keys that have a TTL cost anything — built as a sorted set with the roles reversed: the member is the key (its 48-bit keyspace id) and the score is a 48-bit ms-since-epoch expiry. So "what expires next" is just the minimum, and each entry is 12 bytes.

Command Summary
EXPIRE Set a TTL, in seconds from now.
PEXPIRE Set a TTL, in milliseconds from now.
EXPIREAT Set an absolute expiry, Unix seconds.
PEXPIREAT Set an absolute expiry, Unix milliseconds.
TTL Remaining time in seconds.
PTTL Remaining time in milliseconds.
EXPIRETIME Absolute expiry, Unix seconds.
PEXPIRETIME Absolute expiry, Unix milliseconds.
PERSIST Remove a key's TTL.

SET also takes EX / PX / EXAT / PXAT / KEEPTTL.

Expiration model

Persistence

TTLs are written to the snapshot in their own TTL section as absolute ms-since-epoch, so they survive save/load unchanged. A key whose expiry has already passed by the time the snapshot is loaded is dropped, not reloaded.

---

EXPIRE / PEXPIRE

EXPIRE key seconds [NX | XX | GT | LT]
PEXPIRE key milliseconds [NX | XX | GT | LT]

Set the key's TTL relative to now. Reply 1 if set, 0 if the key does not exist or the condition is not met. A non-positive amount deletes the key immediately (and still replies 1).

The optional condition (a key with no current expiry counts as +infinity):

NX is exclusive with XX / GT / LT, and GT with LT.

> SET session "abc"
OK
> EXPIRE session 60
(integer) 1
> EXPIRE session 30 GT     # 30s < 60s, so not applied
(integer) 0
> TTL session
(integer) 60

EXPIREAT / PEXPIREAT

EXPIREAT key unix-seconds [NX | XX | GT | LT]
PEXPIREAT key unix-milliseconds [NX | XX | GT | LT]

Set an absolute expiry, with the same optional condition as EXPIRE. A time already in the past deletes the key (reply 1). Reply 0 if the key does not exist or the condition is not met.

> PEXPIREAT session 1893456000000
(integer) 1

TTL / PTTL

TTL key
PTTL key

Remaining time to live: in seconds (TTL, rounded) or milliseconds (PTTL). Special replies: -2 if the key does not exist, -1 if it exists but has no expiry.

> TTL session
(integer) 60
> TTL persistent
(integer) -1
> TTL missing
(integer) -2

EXPIRETIME / PEXPIRETIME

EXPIRETIME key
PEXPIRETIME key

The absolute expiry: Unix seconds (EXPIRETIME) or milliseconds (PEXPIRETIME). -2 if the key does not exist, -1 if it has no expiry.

PERSIST

PERSIST key

Remove the key's TTL so it never expires. Reply 1 if a TTL was removed, 0 if the key is missing or already had none.

> PERSIST session
(integer) 1
> TTL session
(integer) -1

See also