Exercise 3: rate() and a Mid-Window Counter Reset — Possible Solution ==================================================================== -- What rate() does when a counter resets mid-window -- -- -- rate() is specifically designed to detect a counter reset -- a -- sudden drop in a counter's value between two consecutive samples, -- which can only mean the process restarted and the counter began -- counting again from zero, since ordinary counters are never allowed -- to decrease any other way. When rate() detects this kind of drop -- within its own window, it compensates for it automatically: instead -- of treating the drop as a real negative change, it counts the -- pre-reset portion and the post-reset portion as two separate -- segments of genuine increase, and combines them into one correct, -- still-positive average rate for the whole window. The service -- restarting doesn't produce a nonsensical result -- it's handled as -- a normal, expected event. -- Why "current value minus value five minutes ago" would fail -- -- -- A naive manual calculation has no such reset-awareness built in -- -- it just subtracts the value from five minutes ago from the current -- value, with no concept of "this counter might have been reset in -- between." If the counter was, say, at 50,000 five minutes ago, -- dropped to 0 on restart partway through the window, and has since -- climbed back up to 8,000, that naive subtraction computes -- 8,000 - 50,000 = -42,000 -- a clearly wrong, negative result for a -- value (request count) that can never actually decrease. This is -- exactly the failure case the chapter names rate()'s own -- reset-handling as solving: rate() would instead correctly report a -- positive rate reflecting the real traffic that occurred both before -- and after the restart, while the manual subtraction produces a -- meaningless negative number with no correct interpretation at all. WHY THIS WORKS AS AN ANSWER ------------------------------ This explains rate()'s own reset-detection mechanism concretely (treating pre- and post-reset segments as separate genuine increases), then works through a specific numeric example showing exactly how a naive subtraction produces an impossible negative result, directly demonstrating why rate()'s reset-awareness genuinely matters rather than just being a nice-to-have detail.