Community JavaScript Snippet

Streaming Aggregations With a Single Pass (JS)

Welford's online algorithm for mean and variance, plus a 30-line streaming p99 estimator. The version I use when the data does not fit in memory or arrives over WebSocket.

Streaming Aggregations With a Single Pass (JS)

Welford's online algorithm for mean and variance, plus a 30-line streaming p99 estimator. The version I use when the data does not fit in memory or arrives over WebSocket.

JavaScript
Frontend
3 snippets
stream-processing
performance
code-template
ryancastillo

By @ryancastillo

May 9, 2026

·

Updated May 18, 2026

851 views

26

4.2 (12)

The traditional formula variance = mean(x^2) - mean(x)^2 is mathematically correct and numerically unstable: when mean(x^2) and mean(x)^2 are close in magnitude, you lose most of your precision to subtractive cancellation. Welford's update sidesteps that by tracking m2, the sum of squared deltas from the running mean, which never has to compute the dangerous difference. Memory is O(1) regardless of sample size, which is what makes it suitable for an unbounded stream. I keep this class in every metrics-collection layer; the summary() method is what gets pushed to the dashboard once a second.