Step 1 of 3 · Reading · ~3 min
Atomic Set+Expire
Key Expiry
SET with EX — Atomic Set+Expire
You now have SET, conditional flags (NX/XX), and a standalone EXPIRE. This lesson combines them: Redis lets you set a value and its expiry in a single atomic command, SET key value EX <seconds> or SET key value PX <milliseconds>. Understanding why this matters — not just how to parse the flag — is the point of this lesson.
The race condition this avoids
If a client had to do SET key value followed by a separate EXPIRE key 10, there's a window between the two commands where the key exists with no expiry at all. Any process reading that key in that window (or a crash between the two calls) leaves a permanent key where a temporary one was intended — a classic source of unbounded cache growth in real systems. Folding the expiry into the SET call itself closes that window: the key never exists without its TTL.
Implementation
Extend your flag-parsing loop from the NX/XX lesson to also recognize EX and PX, which — unlike NX/XX — consume an extra argument (the duration):
The easy-to-miss rule: SET clears existing TTL
A subtle but important behavior: SET key newvalue without EX/PX on a key that already had a TTL removes that TTL entirely — the key becomes permanent. This makes sense once you think about it as "SET replaces the entire key, value and metadata both" — but it's the kind of rule you only remember by testing it explicitly, so make sure your implementation calls expires.pop(key, None) on every plain SET, not just leaving stale expiry entries behind.
PTTL
PTTL mirrors TTL but reports milliseconds instead of seconds, using the same -2/-1/non-negative contract:
Edge cases
EXandPXtogether in the same call is a syntax error in real Redis — decide how strictly you want to enforce mutual exclusion.- Combining
NXwithEX:SET key val EX 10 NXshould still respect the NX check before ever touchingexpires, exactly as if you'd short-circuited on the conditional flags first — order of operations matters here. - Non-integer duration values (
SET key val EX abc) should produce a clear error rather than an uncaught exception.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…