Skip to content
SET with EX — Atomic Set+Expire
step 1/3

Reading — step 1 of 3

Atomic Set+Expire

~1 min readKey Expiry

SET with EX/PX — Atomic Set+Expire

Setting a key and its expiry should be atomic. SET key value EX 10 does both in one command.

Extended SET Syntax

SET key value [EX seconds] [PX milliseconds] [NX|XX]
  • EX seconds — expire in N seconds
  • PX milliseconds — expire in N milliseconds
  • Can combine with NX/XX: SET key value EX 10 NX

PTTL

PTTL key returns remaining TTL in milliseconds (vs TTL which returns seconds).

Why Atomic?

Without atomic set+expire, there's a race condition:

  1. SET key value → succeeds
  2. Server crashes before EXPIRE key 60
  3. Key lives forever — a memory leak

SET key value EX 60 can't have this problem.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…