BACK
Use casesBuffer analytics — batching events
Use cases · 58

Buffer analytics — batching events

Pattern

Telemetry — clicks, views, micro-events. Hundreds per minute. Sending each as its own HTTP request is wasteful for the network and the backend. The fix: accumulate into a batch for 30 seconds, send it in one request.

The problem it solves

An imperative array + setInterval breaks quickly: you forget to flush on destroy, you can't handle send errors (what do you do with a lost batch?), and it tests poorly.

Operators and why they matter

  • bufferTime(N) — accumulate events over an N-ms window and emit an array.
  • filter(batch => batch.length > 0) — don't send empty batches.
  • mergeMap — send the batch as an HTTP request.

Gotchas

  • bufferTime on a long-lived source without unsubscribe — the timer runs for the whole life of the service. That's fine, but on page hide you must flush explicitly.
  • concatMap instead of mergeMap — if batch order matters. Otherwise mergeMap is faster.
  • Don't forget a batch-size limit. If 10,000 events pile up in 30 seconds, split them across several HTTP requests rather than one giant payload.

What you get

An avalanche of small events turns into a few controlled network sends. The backend isn't choked.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...