Module 02 · From Scratch · Redis · with code: Go · about 20 min to read
Continue where you left off ×
Keys That Die (Expiry)
Keys That Die (Expiry) · Open board
The depth behind one paragraph of Build Your Own Redis, From Scratch : what actually happens the instant a key’s time runs out.
Before you start. Redis: One Thread, Many Clients set the rule this whole lesson bends around: Redis answers every request through one worker, and that worker can never be made to wait on anything slow. The only maths you need here is a rate, so many things per second, and a fraction of a small handful.
The idea in 30 seconds
A TTL is a note on a key saying when it stops being trusted, not a scheduled alarm, nothing fires when the time passes.
Redis checks that note lazily, on every read, folded into a lookup it was already doing, so nobody is ever handed a jar past its date.
Lazy checking alone leaks memory: a key nobody ever asks for again never gets checked, so it never gets thrown out.
A background reaper grabs a random handful of keys with a TTL, ten times a second, and speeds up exactly when the handful comes back mostly spoiled.
Only the primary copy is allowed to decide a key is dead. A replica waits for that word instead of using its own clock, even though it holds the exact same note.
Read the story
Lesson 8 of 117 in From Scratch
The rest of this lesson is part of a plan.
A plan opens every lesson, board, video, lab and paper on chalk. Yearly is $39/year .
See plans Already a member? Sign in
Or start free : a free account opens lessons 2 and 3 of every track.
In this lesson 2003: a note with no alarm clock The fridge that only looks when you reach in Twelve years of a smell nobody noticed Once a tick, somebody checks a handful The shop with two rooms Why 25% TTL under replication Small print worth carrying Terms it explains: TTL, Lazy expiry, active expiry, reaper, replica, absolute, from `db->expires`, without deleting it.
Review From Scratch
Mark as read Saved in this browser, and to your account when you sign in.