Redis keys and TTL
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
let now=0;const cache=new Map();function set(key,value,ttlMs){cache.set(key,{value,expires:now+ttlMs});}function get(key){const e=cache.get(key);if(!e)return null;if(now>=e.expires){cache.delete(key);return null;}return e.value;}set('catalog:b1','Rivers',1000);now=999;console.log(get('catalog:b1'));now=1000;console.log(get('catalog:b1'));Run node main.mjs in a disposable directory with the files shown. Expected standard output:
RiversnullHow it works
Redis strings can store serialized JSON; hashes store field/value pairs, sets model unique members and sorted sets order members by score. In the node-redis candidate use set with EX seconds to write a value and expiry together. A missing GET returns null. Do not equate TTL with guaranteed freshness: a database update may make data stale before expiry, and eviction may remove it earlier. The local model uses a controllable clock in milliseconds and expires exactly at the deadline; it is not Redis server timing evidence.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial node-redis v5-style candidate; connected fixture client is injected.export async function cacheBook(client){ await client.set('bm:v6:catalog:b1',JSON.stringify({title:'Rivers'}),{EX:30}); const raw=await client.get('bm:v6:catalog:b1'); return raw===null?null:JSON.parse(raw);}Returns the cached synthetic book if still available; key may expire or be evicted. NOT RUN.
Common mistake
Do not cache important records indefinitely without a policy. Do not confuse milliseconds (PX) and seconds (EX), or use cache absence as evidence the original record does not exist.
Practice
Read the key one millisecond before expiration and exactly at expiration. Explain the boundary.
Documentation: primary source. Candidate lookup: node-redis-keys-and-ttl-lookup. Prerequisite: node-atomic-updates-and-transactions (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Redis keys and TTL — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What unit does EX specify?
What should a missing cache key imply?
What does the clock model verify?