TTL jitter

TTL jitter adds a random duration to a cache entry's configured expiration time. It prevents entries written together from consistently expiring together, spreading cache rebuild work over a wider time interval.

Minimal example

go
func WithJitter(ttl, jitter time.Duration) time.Duration {
	if jitter <= 0 {
		return ttl
	}
	return ttl + time.Duration(rand.Int64N(int64(jitter)))
}

Learn this concept

Lesson 6.1 · Cache-aside with jitter and singleflight

Used in exercises

Exercise 6.2 · Menu cache and stock updater Exercise 6.17 · XFetch cache refresh decider
Prerequisite conceptsRedis TTL