The dashboard says the API handled 20 requests between 10:00 and 10:05, then 29 between 10:05 and 10:10. The alert says 44 requests in five minutes. You open the alert settings to find out who taught it arithmetic.
Before changing anything, look at the minute-by-minute counts. Each row pairs a minute from the first dashboard bar with a minute from the second. The count at 10:03 covers the minute starting at 10:03.
| First bar | Requests | Second bar | Requests |
|---|---|---|---|
| 10:00 | 1 | 10:05 | 10 |
| 10:01 | 1 | 10:06 | 9 |
| 10:02 | 1 | 10:07 | 8 |
| 10:03 | 8 | 10:08 | 1 |
| 10:04 | 9 | 10:09 | 1 |
Start at 10:03 and count five minutes: 8 + 9 + 10 + 9 + 8 = 44. The busiest stretch straddles the line between the bars. The dashboard answered “How many requests were in each of these two blocks?” The alert answered “Did any five consecutive minutes reach 40 requests?” Both got full marks for arithmetic.
Let’s build the function behind the second question. By the end we’ll know which five minutes to show on the incident report, what to do if two intervals tie, and how to keep updating the total when new minutes arrive.
First, decide what the answer looks like
The input is a Go slice, []int64{1, 1, 1, 8, 9, 10, 9, 8, 1, 1}. Each position represents one complete minute, in time order. Give the function a width of 5 and it should return start index 3, total 44. If several windows tie, the report should show the earliest one. If the input contains only four minutes, there’s no complete five-minute window to report.
It helps to write down where the winning interval ends. It includes positions 3, 4, 5, 6, and 7. In Go that slice is counts[3:8]. Index 8 is the first position after the window. The corresponding clock interval starts at 10:03 and ends just before 10:08. A request timestamped exactly 10:08 belongs to the next minute.
There’s one assumption hiding in the input. If your log lists individual requests, assemble the one-minute counts first. A known quiet minute gets a zero. If the collector went offline, you have a gap in your observations; calling that zero traffic would give the incident report a confidence it hasn’t earned. With only per-minute totals we can examine every minute-aligned start. Finding a peak that begins at 10:03:27 requires finer timestamps.
Use the slow version as a reference
For ten buckets and a five-bucket window, there are six starting positions. List them: 0, 1, 2, 3, 4, 5. Starting at 5 still works because positions 5 through 9 are all present. A surprisingly effective way to lose an afternoon is to write a loop that stops just before that last start.
Here’s the part of a straightforward solution that computes each total. Assume width has already been checked and is between 1 and len(counts).
for start := 0; start <= len(counts)-width; start++ { var total int64 for _, count := range counts[start : start+width] { total += count } fmt.Println(start, total) } The totals from our ten minutes are 20, 29, 37, 44, 37, 29. This little loop is worth keeping. It states the problem so directly that we can use it later to check a faster implementation.
Now look at how it gets from 20 to 29. The first calculation reads positions 0 through 4. The next one reads positions 1 through 5. Four of those five numbers are the same entries we just added. If somebody handed you the first total and the two numbers at the edges, would you really add those four middle entries again?
Move one minute to the right
The first five minutes sum to 20. Sliding the window one step drops the 1 at 10:00 and picks up the 10 at 10:05. The new total is 20 - 1 + 10 = 29. The next step drops the 1 at 10:01 and picks up the 9 at 10:06. Now it’s 37.
| New start | Minute leaving | Minute entering | Current total | Best total so far |
|---|---|---|---|---|
| 0 | — | First five minutes | 20 | 20 |
| 1 | 10:00 (1) | 10:05 (10) | 29 | 29 |
| 2 | 10:01 (1) | 10:06 (9) | 37 | 37 |
| 3 | 10:02 (1) | 10:07 (8) | 44 | 44 |
| 4 | 10:03 (8) | 10:08 (1) | 37 | 44 |
| 5 | 10:04 (9) | 10:09 (1) | 29 | 44 |
Pay particular attention to the last row. It starts with the current total of 37 and computes 37 - 9 + 1 = 29. The record of 44 belongs to an older window. If you reuse the record as the running total, you start subtracting minutes from a window they may never have been in.
That gives us two pieces of state with different jobs. The running sum tracks what’s inside the window now. The best window remembers a start and a total for the incident report. Only one of them is allowed to go down.
A complete Go implementation
Save this as main.go and run go run main.go, or paste it into the Go Playground. We use int64 for counts and totals, and assume each complete window’s total fits that type. Traffic counts are nonnegative.
package main import "fmt" type Window struct { Start int Total int64 } func peakWindow(counts []int64, width int) (Window, bool) { if width <= 0 || width > len(counts) { return Window{}, false } var running int64 for _, count := range counts[:width] { running += count } best := Window{Start: 0, Total: running} for incoming := width; incoming < len(counts); incoming++ { outgoing := incoming - width running -= counts[outgoing] running += counts[incoming] if running > best.Total { best = Window{Start: outgoing + 1, Total: running} } } return best, true } func main() { counts := []int64{1, 1, 1, 8, 9, 10, 9, 8, 1, 1} const width = 5 best, ok := peakWindow(counts, width) if !ok { fmt.Println("No complete window") return } fmt.Printf("Buckets [%d, %d): %d requests\n", best.Start, best.Start+width, best.Total) } Expected output
Buckets [3, 8): 44 requests There’s a way to reconstruct the index arithmetic if you forget it. Let incoming be 5 on the first slide. The old window is [0, 5). The new window is [1, 6). Bucket 0 leaves, so outgoing = incoming - width. Bucket 1 becomes the new start, so the index to save is outgoing + 1. Pick a width small enough to draw and the formulas tend to write themselves.
Why trust this for the rest of the slice? The initial sum covers the first window exactly. On every slide the windows share all their middle entries. Removing the single entry that leaves and adding the single entry that arrives therefore gives the exact next sum. Since we compare the first window and every following window, the record at the end must be a maximum. The strict comparison > keeps the first such maximum. Change it to >= and you’ve made an editorial decision: the dashboard will now highlight the last tied window.
How much work did that save?
For n buckets and a valid width k there are n - k + 1 windows. The reference loop adds k values for each one. The sliding loop reads k values to start, then reads two values per slide. Here are the counts for exactly 1,440 one-minute buckets and a 60-minute window.
| Method | Bucket values read to compute sums |
|---|---|
| Sum each hour from scratch | 1,381 × 60 = 82,860 |
| Slide one minute at a time | 60 + 2 × 1,380 = 2,820 |
The table counts reads. Actual timings also depend on the machine and the data. For a width permanently fixed at five, even the straightforward version grows linearly as you add more minutes. The advantage of the sliding version is that each move still costs one subtraction and one addition when the customer changes “five minutes” to “one hour.” Across all valid widths it takes O(n) time and O(1) extra space when the input slice is already available.
An empty window and a quiet window are different results
Suppose a dashboard shows 0 requests. Did the service have no traffic for five minutes, or has it only been running for four? That’s the reason for the boolean return. Try these cases before trusting a chart built from the function.
| Counts | Width | Expected result |
|---|---|---|
[] | 5 | No complete window |
[4, 8] | 0 | Invalid width |
[4, 8] | 3 | No complete window |
[0, 0, 0] | 2 | Start 0, total 0, success |
[2, 9, 9] | 1 | Start 1, total 9 |
[2, 3, 5] | 3 | Start 0, total 10 |
[1, 1, 9] | 2 | Start 1, total 10 |
The last case is a cheap test for that easily missed final window. The two 9s in the width-one case check the tie rule. If the wrong start and the right total look identical in your tests, your tests won’t notice the chart pointing to the wrong minute.
Here’s a Go test that checks both fields against sums computed from scratch. Save it as main_test.go next to the program. In a fresh directory, run go mod init example.com/peakminute once, then go test -v.
package main import "testing" func TestPeakWindowAgainstFreshSums(t *testing.T) { samples := [][]int64{ {0, 0, 0}, {2, 9, 9}, {1, 1, 9}, {1, 1, 1, 8, 9, 10, 9, 8, 1, 1}, } for _, counts := range samples { for width := 1; width <= len(counts); width++ { var want Window for start := 0; start <= len(counts)-width; start++ { var sum int64 for _, count := range counts[start : start+width] { sum += count } if start == 0 || sum > want.Total { want = Window{Start: start, Total: sum} } } got, ok := peakWindow(counts, width) if !ok || got != want { t.Fatalf("counts=%v width=%d: got %+v, ok=%t; want %+v", counts, width, got, ok, want) } } } } What if the next minute hasn’t happened yet?
Our function can find the outgoing value by looking back into counts. A live dashboard might receive one number at a time and discard the old input. Keeping only the running sum is then insufficient. Imagine the last three counts were either [1, 2, 3] or [3, 2, 1]. Both sum to 6. The next count is 4. The new total is 9 in the first case and 7 in the second. The old sum can’t tell you which bucket is about to leave.
For a live feed, keep the last k counts in a circular buffer. Fill its slots in order. When all slots are full, the next write position holds the oldest value. Subtract that value, overwrite its slot with the new count, add the new count, and advance the write position, wrapping to zero at the end. You can produce the first total as soon as the buffer fills. Each later minute needs constant work and the buffer uses O(k) space. That extra storage does the job that the input slice did for free in the batch program.
One last question for the incident report: what if it asks for the highest average requests per minute over five minutes? For a fixed width, every candidate sum is divided by the same positive number. The winning start stays at 10:03. Divide the winning total just once: float64(best.Total) / float64(width) gives 8.8 requests per minute. Using integer division would give you 8, which would be a disappointing way to lose part of the spike after all that work finding it.
If you enjoyed tracking down those 44 requests, you’ll find more hands-on posts about Go internals, algorithms, and concurrency on my blog, PushPopGo.
