Memcached Expiration: Transitioning from Relative TTL to Absolute Unix Timestamps
0 reputation · 16 Sept 2025, 06:52 UTC
0 reputation · 16 Sept 2025, 06:52 UTC
Memcached manages item expiration using a 32-bit unsigned integer. The system distinguishes between a relative offset and an absolute timestamp based on a specific threshold: values under 2,592,000 seconds (30 days) are treated as relative TTLs, while values exceeding this limit are interpreted as Unix epoch timestamps.
When migrating data structures or adjusting cache durations, there is uncertainty regarding how the slab allocator and lazy expiration process handle items that cross this 30-day boundary. Because Memcached treats stored values as opaque blobs, the internal expiration logic relies entirely on the integer passed during the set or add command.
If a client application provides a timestamp that is slightly off due to clock drift across a distributed cluster, the behavior of the item's lifecycle becomes unpredictable.
31275 reputation · 16 Sept 2025, 18:11 UTC
Lazy expiration works identically for relative TTLs and absolute Unix timestamps because Memcached converts the supplied 32‑bit value to an absolute timestamp at store time. When multiple clients set the same key with differing timestamps, the most recent set (or add) wins; the item’s expiration reflects the timestamp from that last write.
Memcached does not keep the original expiration format; it stores a single absolute Unix epoch time. The lazy expiration mechanism (checked on get or during slab allocation) simply compares that stored time with the current server time, so the path taken during storage does not affect the check.
absolute = now + offset.current_time.memcached -p 11211 -decho -e "set key 0 0 1\r\nvalue\r\n" | nc localhost 11211
Immediately get to confirm it exists, wait >1 s, then get again to see a miss.current_time + 1 second (obtain current_time with date +%s):
NOW=$(date +%s); ABS=$((NOW+1)); echo -e "set key 0 $ABS 1\r\nvalue\r\n" | nc localhost 11211
Verify identical expiration behavior as in step 2.stats items; the age or expire field will show the same absolute timestamp for both approaches.set with an absolute timestamp, and observe that expiration follows the server’s time, not the client’s offset.Are all memcached servers in your cluster synchronized via NTP (or equivalent)? Significant drift can cause items to appear expired prematurely or persist longer than intended, which would affect the reliability of the above behavior.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.