anomaly detection with nothing but math and a key-value store

Try anomalisa

I run a lot of projects. Things break in all of them, and I wanted a single service that would email me when something weird happens, without having to configure what "weird" means for each one.

The result is anomalisa, an open source event anomaly detector. You send events, it learns what normal looks like, and emails you when something deviates. No thresholds, no dashboards, no time-series database. It started on Deno KV and now runs on Cloudflare Workers, Turso (libSQL), and InstantDB, keeping the exact same key-value stats model.

This post is about how the detection works.

the core problem

You have a stream of events. "signup", "purchase", "error", whatever. They come in at some rate that varies by hour. You want to know when that rate is significantly different from what's normal, but you don't want to store every data point, and you don't want to configure anything upfront.

The answer is an online algorithm that maintains a running statistical model and updates it incrementally.

welford's algorithm

The textbook way to compute variance is to collect all values, compute the mean, then compute the sum of squared deviations. That requires storing every value.

Welford's algorithm does it in a single pass with constant memory. You maintain three numbers: n (count), mean, and M2 (sum of squared deviations from the running mean), plus an exponential decay factor (0.98) so old traffic patterns fade out as your app evolves:

const updateStats = (
  stats: Stats,
  value: number,
  decay = 1.0,
): Stats => {
  const n = stats.n * decay + 1;
  const delta = value - stats.mean;
  const mean = stats.mean + delta / n;
  const delta2 = value - mean;
  const m2 = stats.m2 * decay + delta * delta2;
  return { mean, m2, n, lastBucket: stats.lastBucket };
};

Standard deviation is then sqrt(M2 / (n - 1)). That's Bessel's correction for sample variance, which matters when you have few data points.

The key insight is that delta is computed before updating the mean, and delta2 is computed after. This is what makes the numerics stable. A naive running variance that tracks sum and sum-of-squares separately accumulates floating point error. With statsDecay = 0.98, the effective window stays around 50 hours instead of letting months-old history drown out recent behavior.

With these three numbers you can compute z-scores on the fly.

hourly buckets

Events get counted in hourly UTC buckets. Each hour, the total count for the previous hour gets fed into the Welford model. The bucket key is just the ISO timestamp truncated to the hour: 2026-04-05T14.

This gives you a natural unit of measurement. "Your signup event usually gets ~50 per hour, this hour it got 3." The alternative is sliding windows, which are more responsive but harder to reason about and more expensive to maintain.

When a new hour starts and no events have come in, that's important information. Zero is a valid count that should update the model. But what if there are gaps where no events arrive for multiple hours? The system backfills zeros:

const updateStatsWithZeros = (
  stats: Stats,
  count: number,
  decay = 1.0,
): Stats =>
  Array.from({ length: count }).reduce<Stats>(
    (s) => updateStats(s, 0, decay),
    stats,
  );

If the last bucket was 3 hours ago, two zeros get fed in before the current count. This prevents the model from ignoring quiet periods and keeps the mean honest. We also maintain per-hour-of-day baselines (byHour:<HH>) so predictable daily traffic rhythms don't look like anomalies.

four detection modes from one stream

Every event that comes in feeds four independent checks:

Total count (totalCount). The primary rate check, after minDataPoints = 3 buckets. When an event's variance is roughly Poisson (stdDev <= max(1, sqrt(mean))), it uses an exact two-sided Poisson tail test (p < 1e-3). When traffic is overdispersed (stdDev > max(1, sqrt(mean))), it falls back to a 3σ Welford z-score threshold. During cold start (n < 3), a burst threshold (count >= 5) still catches immediate floods. Live mid-hour spike checks also run on incoming events so spikes don't wait for the hour boundary.

Percentage spike (percentageSpike). Fires when an hourly count jumps >100% above the Welford mean (mean >= 10, diff >= 3, z >= 2.5) and isn't explained by byHour:<HH> seasonality (gated by the global 3σ / Poisson elevation check when hourly baselines exist).

Percentage drop (percentageDrop). Catches both sharp single-hour drops (>50% below the mean when mean >= 30, diff >= 3, z >= 1.05) and rolling multi-hour drops compared against the same window across the prior 3 to 6 days (z >= 2.5, skipped for error/failure events), gated by the global 3σ depression check when byHour:<HH> baselines exist. That includes a 2-hour blackout window (90%+ drop), plus 6-hour (75%+) and 24-hour (70%+) windows, so a silent outage on a medium-volume event is caught in 2 hours instead of waiting all day.

Per-user spikes (userSpike). Tracks max_user_counts (the highest single-user count per hour) in a separate "perUser" Welford model (with 0.98 decay), and checks every incoming event against a 3.5σ threshold (minDataPoints = 3, count >= 3, and count >= 5 when 0 < mean < 1). One user generating way more than the normal per-user peak gets caught mid-hour, whether it's a bug, a bot, or abuse.

Each mode reads from the same keyed stats model (total, perUser, and byHour:<HH>). Bucket-transition checks (percentageDrop and closed-hour evaluations) run when the hour rolls over or via cron for silent events, while userSpike and live totalCount / percentageSpike checks run on every event.

why a key-value stats model is enough

Anomalisa started on Deno KV and now runs on Cloudflare Workers, Turso (libSQL), and InstantDB. InstantDB handles auth and user/project metadata, while Turso keeps the exact same key-value stats model backed by primary-keyed tables instead of Deno KV prefixes:

  • counts (project_id, event_name, bucket) → hourly event count
  • stats (project_id, event_name, type) → Welford state (total, perUser, byHour:<HH>)
  • user_counts (project_id, event_name, bucket, user_id) → per-user hourly count
  • max_user_counts (project_id, event_name, bucket) → max single-user count in that hour
  • anomalies (project_id, event_name, bucket, metric, user_id) → detected anomaly
  • cooldowns (project_id, event_name, metric, direction, user_id) → 48-hour alert cooldown
  • email_rate_limits (to_email, project_name, event_name, day_bucket) → max 5 alerts per day per event and recipient

No joins. No time-series query language. The Welford state is still just 4 numbers (mean, m2, n, last_bucket). Everything else is keyed counters and flags.

The anomaly primary key includes the bucket, metric type, and user, so the same anomaly can't be recorded twice. Writes deduplicate atomically with ON CONFLICT DO NOTHING:

const storeAnomaly = async (anomaly: Anomaly): Promise<boolean> => {
  const result = await getTurso().execute({
    sql:
      `INSERT INTO anomalies (project_id, event_name, bucket, metric, user_id, expected, actual, z_score, detected_at, trend, created_at)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          ON CONFLICT (project_id, event_name, bucket, metric, user_id) DO NOTHING;`,
    args: [
      anomaly.projectId,
      anomaly.eventName,
      anomaly.bucket,
      anomaly.metric,
      anomaly.userId ?? "_",
      anomaly.expected,
      anomaly.actual,
      anomaly.zScore,
      anomaly.detectedAt,
      anomaly.trend ?? null,
      Date.now(),
    ],
  });
  return result.rowsAffected > 0;
};

If two concurrent requests both detect the same anomaly, only one insert succeeds. After deduplication, a 48-hour cooldown per event, metric, direction, and user suppresses repeat emails for an ongoing issue unless the count escalates by more than 2x, and a daily rate limit caps alerts at 5 per day per event and recipient.

the tradeoffs

The thresholds are hardcoded: 3σ (or Poisson p < 1e-3) for totalCount and global spike/drop gates, 3.5σ for userSpike, statsDecay = 0.98, minDataPoints = 3 (with >= 5 cold-start burst detection), 2-hour blackout detection, a 48-hour alert cooldown, and a max of 5 alerts per day. Earlier versions used 2σ, which was roughly a 5% false positive rate, way too noisy once you have dozens of events across multiple projects. Event counts also aren't Gaussian at low volume, which is why the Poisson tail test and byHour seasonality matter. I tried making thresholds configurable and realized that nobody, including me, wants to tune them. The whole point is zero config.

The first 3 hours (minDataPoints = 3) are a short learning period (other than obvious cold-start bursts of 5+ events) because alerting on "your second data point is different from your first" would be useless.

It won't catch everything. If your system fails in a way that doesn't affect event counts, you're on your own. But most real failures do show up as something spiking or dropping, and the simplicity of the approach means there's almost nothing to debug when it doesn't work as expected.

The entire detection engine is one file. That's the best argument for this design. When your anomaly detection system itself breaks, you want to be able to read the whole thing in five minutes.

try it

anomalisa is free and open source. Install from npm:

npm i anomalisa

Three lines to integrate (plus optional automatic browser error tracking):

import { captureClientErrors, sendEvent } from "anomalisa";

captureClientErrors({ token: "your-token" });

await sendEvent({
  token: "your-token",
  userId: "user-123",
  eventName: "purchase",
});
All posts