100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Redis

Key Expiration and TTL

Learn how Redis lets keys expire automatically using TTLs, and how expiration is implemented internally through lazy and active mechanisms.

Key ManagementBeginner9 min readJul 10, 2026
Analogies

What Is a TTL?

A Time To Live (TTL) is a countdown, in seconds or milliseconds, that Redis attaches to a key. Once the TTL reaches zero, Redis treats the key as if it never existed, even though the data structure and memory may not be reclaimed the exact instant the countdown hits zero. TTLs are the primary mechanism for building caches, session stores, rate limiters, and temporary locks in Redis, because they let you say 'store this, but forget it automatically' without writing any cleanup code yourself.

🏏

Cricket analogy: A TTL is like the 90-second injury assessment window a physio gets on the field for Rishabh Pant after a blow to the helmet — once the clock runs out, the umpire's decision to continue or retire the batter happens automatically, no manual reminder needed.

Setting and Inspecting TTLs

You can attach a TTL when writing a key using SET key value EX seconds (or PX for milliseconds), or apply one afterward with EXPIRE key seconds, PEXPIRE key milliseconds, EXPIREAT key unix-timestamp, or PEXPIREAT for millisecond-precision absolute timestamps. To check remaining lifetime, use TTL key (seconds) or PTTL key (milliseconds); both return -1 if the key exists but has no expiration set, and -2 if the key does not exist at all. Removing an expiration entirely, so the key becomes permanent again, is done with PERSIST key.

🏏

Cricket analogy: Setting EXPIREAT is like the ICC scheduling a rain-delay cutoff time for a T20 match at exactly 11:00 PM local time — it's an absolute deadline, not a countdown from now, just as EXPIREAT takes a Unix timestamp rather than a relative duration.

bash
# Set a key with a 60-second TTL at write time
SET session:user:42 "active" EX 60

# Check remaining time to live
TTL session:user:42
(integer) 60

# Apply an expiration to an existing key
SET cache:homepage "<html>..." 
EXPIRE cache:homepage 300

# Set an absolute expiration timestamp (Unix epoch seconds)
EXPIREAT promo:code:SUMMER25 1752192000

# Remove the expiration, making the key permanent again
PERSIST cache:homepage

# PTTL for millisecond precision
PTTL session:user:42
(integer) 58213

How Redis Actually Expires Keys

Redis does not run a dedicated timer thread per key; instead it uses two complementary strategies. Lazy (passive) expiration checks a key's TTL the moment it's accessed by any command — if it's expired, Redis deletes it on the spot and reports a miss, as if it had never existed. Active expiration runs a background cycle roughly 10 times per second, in which Redis randomly samples a small batch of keys with TTLs set, deletes any that have expired, and repeats the sampling if more than 25% of the sample was expired, so that infrequently accessed expired keys don't sit around forever consuming memory.

🏏

Cricket analogy: Lazy expiration is like a scorer only checking whether a batter has already been given out when the next ball is about to be bowled, rather than watching continuously; active expiration is like the third umpire periodically reviewing random deliveries even without an appeal.

Because active expiration samples keys randomly rather than scanning everything, a key with a TTL can briefly continue consuming memory after its logical expiration time, especially under high key-space cardinality. If you need guaranteed prompt cleanup for memory-sensitive workloads, consider combining TTLs with Redis keyspace notifications or monitoring INFO memory rather than assuming instantaneous reclamation.

Replication and Persistence Behavior

In a primary-replica setup, replicas do not independently expire keys; instead the primary detects expiration (lazily or actively) and propagates an explicit DEL (or UNLINK) command to replicas, so all nodes agree on when a key disappeared. This avoids clock-drift inconsistencies between servers. On RDB snapshot reload or AOF replay, Redis checks each key's stored expiration timestamp against the current time and skips loading any key whose TTL has already passed, so expired data doesn't come back to life after a restart.

🏏

Cricket analogy: This is like the on-field umpire, not the third umpire, making the final call on a run-out and radioing it to the scorers' box, so every scoreboard around the ground updates in sync rather than each one guessing independently.

OBJECT FREQ, DEBUG JMAP, and RDB timestamp fields aside, the practical takeaway is simple: TTLs are primary-driven and propagate as explicit deletions, and RDB/AOF reload always re-validates expiration against wall-clock time before restoring a key. Never assume a restarted Redis instance will resurrect data past its TTL.

  • TTLs can be set at write time (SET ... EX/PX) or after the fact (EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT).
  • TTL and PTTL report remaining lifetime in seconds/milliseconds; -1 means no TTL, -2 means the key doesn't exist.
  • PERSIST removes a key's expiration, making it permanent again.
  • Redis combines lazy expiration (checked on access) with active expiration (a background sampling cycle ~10 times/second).
  • Active expiration re-samples if more than 25% of the sampled batch was expired, to keep memory pressure low.
  • Primaries propagate expiration as an explicit DEL/UNLINK to replicas so the whole cluster agrees on timing.
  • RDB and AOF reloads re-check expiration timestamps against current time, so expired keys never come back after a restart.

Practice what you learned

Was this page helpful?

Topics covered

#Redis#RedisStudyNotes#Database#KeyExpirationAndTTL#Key#Expiration#TTL#Setting#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse