CORTEXFLOW · FREE FOREVER

Automation

KPI Anomaly Watchdog

↓ Download workflow JSON

Import in n8n: Workflows → ⋯ → Import from file, then add your credentials. Free download with a free account.

How it works

A morning watchdog for your business numbers that separates detection from explanation — statistics find the anomalies, AI explains them:

  1. STEP 1 — Daily trigger + config + read KPIs — a daily 8 AM schedule trigger fires, CONFIG — Watchdog Settings sets your thresholds and KPI columns, CONFIG — Google Sheets points at your spreadsheet, and Read KPI Metrics pulls every row from your Metrics tab.
  2. STEP 2 — Statistical anomaly detection (no AI) — Compute Anomaly Scores builds a 7-day mean/std baseline per metric, then computes a z-score and day-over-day change. Metrics crossing your thresholds become CRITICAL, WARNING, or WATCH; quiet metrics emit nothing. This runs before any AI call, so quiet days cost you zero OpenAI tokens.
  3. STEP 3 — Log + AI explains — each anomaly is appended to the Anomalies tab with status NEW, then AI Agent — Explain Anomaly explains it with a Structured Output Parser: plain-English summary, ranked probable causes (each with supporting evidence and where to check), one recommended action, and a confidence score. The sheet flips to TRIAGED.
  4. STEP 4 — Route by severity → Telegram — CRITICAL anomalies fire an instant Telegram alert with the stats and the AI’s explanation; WARNING anomalies are collected by Build Warning Digest into one daily digest message; WATCH anomalies stay in the audit sheet for your weekly review (flip those rows to RESOLVED manually once reviewed).

Status flow in Sheets: NEW → TRIAGED → RESOLVED

Set up steps

You’ll need:

  • n8n (self-hosted or cloud) — n8n.io
  • An OpenAI API key — platform.openai.com → API keys
  • Google Sheets OAuth2 credentials — n8n Credentials → Google Sheets OAuth2; a spreadsheet with two tabs: Metrics and Anomalies — sheets.google.com
  • A Telegram bot — message @BotFather, send /newbot, copy the token; get your chat ID from @userinfobot

Your Metrics tab needs these headers (add your own KPI columns to the right if you track more):

Date | Revenue | Orders | Ad Spend | Sessions

Your Anomalies tab needs these headers (the workflow fills them; copy-paste this row):

Anomaly ID | Date | Business | Metric | Latest Value | Previous Value | Baseline Mean | Baseline Std | Z-Score | DoD Change % | Direction | Severity | AI Summary | Probable Causes | Confidence | Recommended Action | Status

Steps:

  1. Import the workflow — in n8n, Workflows → Import from File → select kpi-anomaly-watchdog.json.
  2. CONFIG — Watchdog Settings — open the Set node and fill in:
    • business_name — your business name (appears in alerts)
    • kpi_columns — comma-separated exact headers of your numeric KPI columns (default: Revenue,Orders,Ad Spend,Sessions)
    • warning_z / critical_z — z-score thresholds (defaults: 2 / 3)
    • warning_pct / critical_pct — day-over-day % thresholds (defaults: 20 / 40)
    • lookback_days — baseline window in days (default: 7)
  3. CONFIG — Google Sheets — paste your spreadsheet ID into spreadsheet_id, then select your Google Sheets OAuth2 credential in the three Sheets nodes. If you renamed the tabs, update metrics_sheet_name and anomalies_sheet_name in CONFIG — Watchdog Settings and the sheet names in the Sheets nodes to match.
  4. CONFIG — AI Analysis — pick your model (gpt-4o-mini is the cost-efficient default), then select your OpenAI credential in the OpenAI Chat Model — Anomaly Explainer node.
  5. CONFIG — Notifications — paste your Telegram chat ID into telegram_chat_id, select your Telegram credential in both Telegram nodes, and activate the workflow.

Customize it

  • More KPIs — add a column to the Metrics tab (e.g. Refunds, Signups, CAC) and append its exact header name to kpi_columns. The baseline math handles it automatically.
  • Smarter vs. quieter — lower warning_z to 1.5 for early warning on volatile metrics, or raise critical_pct to 60 if day-over-day noise triggers too many critical alerts.
  • Richer explanations — add context the agent can use (e.g. “we run weekly flash sales”, “marketing spends peak on weekends”) to the system message in AI Agent — Explain Anomaly — better context means sharper probable causes.
  • Watch-tier digest — route the WATCH branch (the empty output of IF — Severity is WARNING) into a second digest node for a weekly Friday summary instead of relying on the sheet.
  • Auto-resolution — add a second scheduled flow that flips TRIAGED rows to RESOLVED when the metric returns to baseline for 3 consecutive days.
  • Alert fatigue guard — insert a dedupe step (like the job-hunt template’s seen-URLs filter) so a multi-day anomaly only alerts once: skip metrics whose Anomaly ID already exists in the sheet with status NEW or TRIAGED.

Workflow nodes

This workflow is built from 17 nodes. Here's what each one does:

#NodeTypeWhat it does
1 Daily 8AM Trigger Schedule Trigger Starts the workflow automatically on a schedule.
2 CONFIG — Watchdog Settings Set Holds editable configuration values — fill in your own settings here before activating.
3 CONFIG — Google Sheets Set Holds editable configuration values — fill in your own settings here before activating.
4 Read KPI Metrics Google Sheets Reads from or writes to a Google Sheet — this workflow's log and state store.
5 Compute Anomaly Scores Code Runs custom JavaScript to transform, filter, or compute data between steps.
6 Log Anomalies — Status NEW Google Sheets Reads from or writes to a Google Sheet — this workflow's log and state store.
7 CONFIG — AI Analysis Set Holds editable configuration values — fill in your own settings here before activating.
8 AI Agent — Explain Anomaly AI Agent The AI brain — reasons over the task and calls tools to get it done.
9 OpenAI Chat Model — Anomaly Explainer OpenAI Chat Model The language model powering the AI agent.
10 Structured Output Parser — Anomaly Explanation Structured Output Parser Forces the AI to return clean, structured JSON instead of free text.
11 Update Sheet — Status TRIAGED Google Sheets Reads from or writes to a Google Sheet — this workflow's log and state store.
12 IF — Severity is CRITICAL IF Splits the flow into branches based on a condition.
13 CONFIG — Notifications Set Holds editable configuration values — fill in your own settings here before activating.
14 Telegram — Send Critical Alert Telegram Sends you a Telegram message or alert.
15 IF — Severity is WARNING IF Splits the flow into branches based on a condition.
16 Build Warning Digest Code Runs custom JavaScript to transform, filter, or compute data between steps.
17 Telegram — Send Warning Digest Telegram Sends you a Telegram message or alert.

Setup instructions

1. Add your credentials

In n8n go to Credentials → New, create each credential below, then open the named node and select it:

NodeCredential to add
Read KPI Metrics Google Sheets OAuth2
Log Anomalies — Status NEW Google Sheets OAuth2
OpenAI Chat Model — Anomaly Explainer OpenAI API
Update Sheet — Status TRIAGED Google Sheets OAuth2
Telegram — Send Critical Alert Telegram Bot API
Telegram — Send Warning Digest Telegram Bot API

2. Fill in your config values

Open the config node listed below and replace each placeholder with your own value before activating the workflow:

NodeFieldWhat to paste
CONFIG — Watchdog Settings business_name PASTE_YOUR_BUSINESS_NAME
Your business name
CONFIG — Google Sheets spreadsheet_id PASTE_YOUR_SPREADSHEET_ID
Your spreadsheet id
CONFIG — Notifications telegram_chat_id PASTE_YOUR_TELEGRAM_CHAT_ID
Your telegram chat id

How this workflow starts

  • Schedule Trigger: Runs every hours.

Use cases

Most businesses discover problems in the monthly report — weeks after the money leaked. This template watches your numbers every morning and separates detection from explanation: Daily 8AM Trigger fires, Read KPI Metrics pulls your Metrics tab (Date, Revenue, Orders, Ad Spend, Sessions, plus any columns you add), and Compute Anomaly Scores builds a 7-day mean/std baseline per metric, then computes a z-score and day-over-day change — pure statistics, no AI, so quiet days cost zero OpenAI tokens. Metrics crossing your thresholds become CRITICAL, WARNING, or WATCH; quiet metrics emit nothing. Each anomaly is logged as NEW, then AI Agent — Explain Anomaly writes a structured explanation — summary, ranked probable causes with evidence, one recommended action, a confidence score — and the row flips to TRIAGED. CRITICAL fires an instant Telegram alert with the stats and the explanation; WARNING rolls into a daily digest; WATCH stays in the sheet for your weekly review until you flip it to RESOLVED.

Ecommerce store catching revenue drops on day one

A store doing $20k a day can't wait for the weekly report to learn that checkout broke on mobile. With Revenue, Orders, Ad Spend, and Sessions tracked daily, a 40% day-over-day revenue drop trips the critical threshold (z-score 3, DoD 40% by default) and the Telegram alert lands with the AI's explanation — probable causes ranked with evidence ("Sessions normal, conversion collapsed → check checkout, not traffic") and exactly where to look. That turns a "revenue is down, investigate everything" morning into a 20-minute targeted check. Practical tip: feed the agent context in its system message — "we run flash sales every Friday," "ad spend peaks on weekends" — and the probable causes get dramatically sharper, because the AI stops flagging your normal patterns.

SaaS founder watching signups, activation, and CAC

A SaaS founder's dashboard is signups, trials, conversions, churn, and CAC — add them as columns to the Metrics tab and append the exact headers to kpi_columns in CONFIG — Watchdog Settings; the baseline math handles them automatically. The two-tier alerting fits SaaS rhythms: a CRITICAL signup collapse pages you instantly, while a WARNING on rising CAC arrives in the digest for calm analysis. Because detection runs before any AI call, a quiet week costs nothing — the workflow only spends tokens on days something actually moved. Tip: lower warning_z to 1.5 for volatile early-stage metrics so you get early warning instead of learning about a trend after it's entrenched; raise critical_pct if day-over-day noise keeps paging you for normal variance.

Marketing agency monitoring client ad accounts

An agency managing $100k/month in client spend needs to spot a broken campaign before the client does. Track Ad Spend and Sessions (or revenue/conversions per client) in the Metrics tab, and the watchdog becomes the account manager's morning scan: CRITICAL on a spend spike with zero conversions means a campaign misconfiguration caught within hours, not at the end-of-month report. The structured explanation — summary, ranked causes with evidence, one recommended action, confidence score — is client-communication-ready: it tells the account manager what happened and what to check before the client even asks. Practical variation: add the dedupe guard from the guide (skip metrics whose Anomaly ID already exists as NEW or TRIAGED) so a three-day anomaly alerts once instead of three times — alert fatigue is how real alerts get ignored.

Subscription box or membership business watching churn signals

Subscription businesses die slowly: a creeping refund rate or softening reorder rate that nobody notices for a quarter. Add Refunds, Cancellations, or Reorders columns and the watchdog's 7-day baseline catches the drift while it's still small — a WATCH today is a WARNING next week, and the sheet's audit trail shows the progression. The WATCH tier is designed for exactly this: anomalies that don't deserve a Telegram ping but deserve a Friday review. Flip rows to RESOLVED manually once reviewed, and the Anomalies tab becomes the institutional memory of every scare — what moved, what the AI thought, what you did.

Multi-location or multi-brand operator comparing units

An operator running five cafés or three Shopify stores can track per-location revenue columns in one Metrics tab — the watchdog scores each column against its own 7-day baseline, so a slow Tuesday at one location doesn't get masked by the group average. This is the use case where statistics beat gut feel hardest: humans can't hold five baselines in their head, but z-scores don't get tired. Practical tip: start with the default thresholds for two weeks, then tune per metric — a high-variance location needs a higher warning_pct to stay quiet, while a stable flagship can run tighter thresholds for earlier warning.

← All templates