13/29
Part 3 of 6 · Time windowsLearn and do

Time windows are half-open

Level 3 adds time: every call carries a timestamp, and a record can expire.

A record written at 10 with a TTL of 5 is gone at 15

Written at 10 with a TTL of 5Interactive
891011121314151617
x
● the start is in. ○ the end is out.
10 <= 15 < 15 is false, so at 15 it's gone.

A record with a TTL lasts that long after its write. Every timed level asks the same question at its edges: is the record still there at 15?

Write every window as half-open, start <= now < end. The start is in. The end is out. When the spec spells out its own inequality, follow that one.

Half-open windows add up and line up

[0, 10) and [10, 20) share the boundary 10Interactive
02468101214161820
[0, 10)
[10, 20)
● the start is in. ○ the end is out.
At 10, 1 of 2 is in their window: [10, 20).

Half-open keeps the arithmetic honest:

  • The length is end - start. A TTL of 5 written at 10 covers 10, 11, 12, 13 and 14: five times.
  • Windows tile. [0, 10) and [10, 20) share the boundary 10, and every time falls in exactly one of them.
  • Python already works this way. range(10, 15) and s[10:15] both stop before 15.

Dijkstra made the case in 1982. With this convention, the difference between the two bounds is the length, and two ranges side by side share a bound. He also reported how the other conventions went in Mesa, a language from Xerox PARC that offered all four: they were "a constant source of clumsiness and mistakes."

In the editor, write that one time check: is a record written at written with a TTL of ttl alive at now?