ARTICLE 7 — Implementing GET, SET, and TTL
These are the three commands every Redis user knows.
But knowing how to use them and knowing how they work are very different things.
SET — more than just storing a value
Basic usage:
SET name "Aryan"
But SET has optional arguments that most people never use:
SET name "Aryan" EX 3600 # Expire in 3600 seconds (1 hour)
SET name "Aryan" PX 3600000 # Expire in milliseconds
SET name "Aryan" NX # Only SET if key doesn't exist
SET name "Aryan" XX # Only SET if key already exists
SET name "Aryan" GET # SET and return the old value
These aren't just conveniences. NX is how you implement distributed locks in Redis. XX prevents accidental overwrites. GET enables atomic swap operations.
GET — simple on the surface
GET name → "Aryan"
GET missing_key → nil
Under the hood, GET:
The hash table lookup is O(1). That's why GET is fast regardless of how many keys you have.
TTL — understanding time in Redis
TTL name → 3542 (seconds remaining)
TTL name → -1 (key exists, no expiry)
TTL name → -2 (key doesn't exist)
The three possible returns from TTL tell you everything about a key's state.
PTTL gives you the same in milliseconds — useful when you need precision.
The design pattern TTL enables:
Stop thinking "how do I store this" and start thinking "how long should this live."
Session data → TTL of 24 hours OTP codes → TTL of 5 minutes Rate limit counters → TTL of 60 seconds Cache entries → TTL based on how stale data is acceptable
Redis handles the cleanup. You handle the logic.
The common beginner mistake:
Setting keys without TTLs for "temporary" data.
Then wondering six months later why Redis is using 8GB of RAM.
Every key you store without a TTL is a key you have to manually delete. Redis doesn't know your data is temporary unless you tell it.
When in doubt — set a TTL.
📌 Read Also: