Batcher Flushes On Size Or Deadline

Collect channel events into batches that flush when full or when a resettable timer deadline expires, so bursts neither pile up unbounded nor drop.

GoResilience

Code

gosnippet
59 lines
package main

import (
	"fmt"
	"time"
)
// batcher 攒批:满 maxBatch 条立即落批,flushAfter 超时兜底落批
func batcher(events <-chan string, maxBatch int, flushAfter time.Duration) <-chan []string {
	out := make(chan []string)
	go func() {
		defer close(out)
		batch := make([]string, 0, maxBatch)
		timer := time.NewTimer(flushAfter)
		defer timer.Stop()
		flush := func(reason string) {
			if len(batch) == 0 {
				return
			}
			fmt.Printf("flush (%s): %v\n", reason, batch)
			batch = make([]string, 0, maxBatch)
		}
		for {
			select {
			case event, ok := <-events:
				if !ok {
					flush("closed")
					return
				}
				batch = append(batch, event)
				if len(batch) == maxBatch {
					flush("full")
					if !timer.Stop() {
						<-timer.C // Stop 返回 false 说明信号已发出:先排空再复位
					}
					timer.Reset(flushAfter)
				}
			case <-timer.C:
				flush("deadline")
				timer.Reset(flushAfter)
			}
		}
	}()
	return out
}
func main() {
	events := make(chan string)
	go func() {
		defer close(events)
		for i, e := range []string{"a", "b", "c", "d", "e"} {
			if i == 3 {
				time.Sleep(150 * time.Millisecond) // 静默期逼出 deadline 落批
			}
			events <- e
		}
	}()
	for batch := range batcher(events, 3, 100*time.Millisecond) {
		fmt.Println("got:", batch)
	}
}

Inside the snippet

Batcher Flushes On Size Or Deadline comes down to the functions batcher and main.

The file repeats itself only inside for. The goroutine/channel pair splits producer and consumer while keeping the handoff race-free. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Watch out for

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Putting it to use

The primary signature, spelled out, is func batcher(events <-chan string, maxBatch int, flushAfter time.Duration) <-chan []string

The demo output is labeled (flush (, got:), so each line traces straight back to the statement that printed it.

main sequences batcher; executing the file runs that flow once.

Core lines under the microscope

for batch := range batcher(events, 3, 100*time.Millisecond) {
	fmt.Println("got:", batch)
}
for i, e := range []string{"a", "b", "c", "d", "e"} {
	if i == 3 {
		time.Sleep(150 * time.Millisecond) // 静默期逼出 deadline 落批
	}
	events <- e
}
<-timer.C // Stop 返回 false 说明信号已发出:先排空再复位

Interactive Tools for This Topic

FAQ

What does Batcher Flushes On Size Or Deadline print when run?
The script runs standalone; its 2 labeled outputs include `flush (`, `got:`.