Skip to content

Detecting a KPI anomaly in BigQuery with ARIMA_PLUS

BigQuery ML anomaly detection with ARIMA_PLUS fits a separate time series model for each KPI, market, and device. On the public GA4 sample, four segments flag 2021-01-06 while the total stays inside its band. This guide applies our guide to anomaly detection and forecasting on GA4 segment by segment.

Why train one series per segment rather than one total?

Training one series per segment catches anomalies that a total dilutes. The largest segments absorb the signal of the small ones. A market can break while the property looks normal.

An anomaly is a daily value of a KPI that falls outside the range its own history predicts, once trend and seasonality are accounted for; it is a statistical flag, not a diagnosis, and it says nothing by itself about the market, channel, or device that caused it. An expected range is the band around the predicted value, bounded by a chosen number of standard deviations or by a prediction interval, inside which a day is considered normal and outside which it is flagged. A z-score is the distance between a day's value and the mean of its reference window, counted in standard deviations of that window; a day above 2 or below -2 sits outside a two-sigma expected range.

The query scores the eight largest country and device segments of January 2021. Each day is compared with the 28 previous days of its own segment.

WITH daily AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS day,
    geo.country AS country,
    device.category AS device,
    COUNT(DISTINCT CONCAT(user_pseudo_id, '-', CAST((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING))) AS sessions
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201204' AND '20210131'
  GROUP BY day, country, device
),
top_segments AS (
  SELECT country, device
  FROM daily
  WHERE day >= '2021-01-01'
  GROUP BY country, device
  ORDER BY SUM(sessions) DESC
  LIMIT 8
),
scored AS (
  SELECT
    country, device, day, sessions,
    (sessions - AVG(sessions) OVER w) / STDDEV_SAMP(sessions) OVER w AS z
  FROM daily
  JOIN top_segments USING (country, device)
  WINDOW w AS (PARTITION BY country, device ORDER BY day ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING)
)
SELECT
  country,
  device,
  ROUND(AVG(sessions)) AS avg_daily_sessions,
  COUNTIF(ABS(z) > 2) AS flagged_days,
  STRING_AGG(IF(ABS(z) > 2, CAST(day AS STRING), NULL)) AS flagged_on,
  ROUND(MAX(ABS(z)), 1) AS max_abs_z
FROM scored
WHERE day >= '2021-01-01'
GROUP BY country, device
ORDER BY avg_daily_sessions DESC
CountryDeviceAverage daily sessionsDays flaggedFlagged onHighest absolute z-score
United Statesdesktop9790none1.8
United Statesmobile6690none1.5
Indiadesktop20912021-01-062.3
Canadadesktop1600none1.6
Indiamobile1390none1.7
Canadamobile11612021-01-062.2
United Kingdomdesktop6912021-01-062.6
United Kingdommobile4912021-01-063.0

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data). History starts on 2020-12-04, so every January day has 28 previous days. Averages are rounded to the unit.

Four segments flag Wednesday 2021-01-06, in three countries. On the same day, total sessions reach 6,002, a z-score of 1.7. The two US segments are the largest, stay inside their bands, and keep the total inside too. Segmenting adds noise: the UK mobile series averages 49 sessions a day. Below about 100 sessions a day, aggregate to the week or to the country.

How do you train ARIMA_PLUS with decomposition?

You train ARIMA_PLUS with decomposition by keeping DECOMPOSE_TIME_SERIES at TRUE, its default value. The segment columns go in TIME_SERIES_ID_COL, so one statement trains every series.

ARIMA_PLUS is a BigQuery ML time series model type that splits each series into trend, seasonal components, holiday effects, spikes and dips, step changes, and a residual, then forecasts it with a prediction interval; with TIME_SERIES_ID_COL, one statement fits one such model per series.

Stacking the KPIs in one column turns the KPI itself into an ID, next to market and device. The statement follows the CREATE MODEL reference updated on 2026-10-13. It is not executed here. CREATE MODEL writes a model object, and this article only runs read-only queries. No result table follows, on purpose.

CREATE OR REPLACE MODEL `your_project.your_dataset.kpi_anomalies`
OPTIONS (
  MODEL_TYPE = 'ARIMA_PLUS',
  TIME_SERIES_TIMESTAMP_COL = 'day',
  TIME_SERIES_DATA_COL = 'value',
  TIME_SERIES_ID_COL = ['kpi', 'country', 'device'],
  DATA_FREQUENCY = 'DAILY',
  DECOMPOSE_TIME_SERIES = TRUE,
  CLEAN_SPIKES_AND_DIPS = FALSE,
  HORIZON = 30
) AS
WITH daily AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS day,
    geo.country AS country,
    device.category AS device,
    COUNT(DISTINCT CONCAT(user_pseudo_id, '-', CAST((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING))) AS sessions,
    COUNT(DISTINCT IF(event_name = 'purchase' AND ecommerce.transaction_id != '(not set)', ecommerce.transaction_id, NULL)) AS transactions
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201101' AND '20210130'
  GROUP BY day, country, device
)
SELECT day, 'sessions' AS kpi, country, device, sessions AS value FROM daily
UNION ALL
SELECT day, 'transactions' AS kpi, country, device, transactions AS value FROM daily;

Three options are decisions rather than defaults. The DATA_FREQUENCY option states the daily grain, so training does not infer it. The CLEAN_SPIKES_AND_DIPS option is TRUE by default. Training then replaces detected spikes and dips with interpolated values. Set to FALSE, the history stays raw, spikes included. Test both settings on your own series. The HORIZON = 30 setting keeps 30 forecast days per series. That covers new days until the next training.

With decomposition on, ML.EXPLAIN_FORECAST returns each historical day split into its components.

SELECT kpi, country, device, time_series_timestamp, time_series_data, trend, seasonal_period_weekly, spikes_and_dips, step_changes, residual
FROM ML.EXPLAIN_FORECAST(MODEL `your_project.your_dataset.kpi_anomalies`, STRUCT(7 AS horizon))
WHERE time_series_type = 'history' AND kpi = 'sessions' AND country = 'United Kingdom'
ORDER BY time_series_timestamp DESC;

A flagged day carried by its residual is unexplained. A flagged day carried by step_changes points to a lasting shift, such as a tagging release.

How does BigQuery ML anomaly detection set its threshold and interval?

BigQuery ML anomaly detection flags a point when its anomaly probability exceeds anomaly_prob_threshold, 0.95 by default. The same threshold sets the lower and upper bounds: a higher threshold gives a wider interval. The probability comes from the actual value, the predicted value, and the variance learned in training.

ML.DETECT_ANOMALIES works in two modes. On the training history, you pass the model alone, and decomposition must have been on at training. On new data, you pass the model, a threshold, and a query whose columns match the training names. The output keeps the names chosen at training, here day and value. Both statements follow the reference updated on 2026-10-13 and are not executed here.

SELECT kpi, country, device, day, value, lower_bound, upper_bound, anomaly_probability
FROM ML.DETECT_ANOMALIES(MODEL `your_project.your_dataset.kpi_anomalies`, STRUCT(0.95 AS anomaly_prob_threshold))
WHERE is_anomaly
ORDER BY anomaly_probability DESC;

SELECT kpi, country, device, day, value, is_anomaly, lower_bound, upper_bound, anomaly_probability
FROM ML.DETECT_ANOMALIES(
  MODEL `your_project.your_dataset.kpi_anomalies`,
  STRUCT(0.95 AS anomaly_prob_threshold),
  (
    SELECT
      PARSE_DATE('%Y%m%d', event_date) AS day,
      'sessions' AS kpi,
      geo.country AS country,
      device.category AS device,
      COUNT(DISTINCT CONCAT(user_pseudo_id, '-', CAST((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING))) AS value
    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
    WHERE _TABLE_SUFFIX = '20210131'
    GROUP BY day, country, device
  ));
ModeWhat you passRequirementWhat it is for
Training historyThe model, threshold optionalDECOMPOSE_TIME_SERIES = TRUE at trainingAudit past flags and tune the threshold
New dataThe model, a threshold, a query or tableSame column names and ID types as trainingScore yesterday every morning
Unknown segment or dateA new ID value, or a day outside the horizonNoneis_anomaly and both bounds return NULL

A NULL is not a pass. A market launched after training has no model until the next training.

Which January 2021 days fall outside the norm on the public sample?

On the public sample, sessions stay inside their expected range every day of January 2021. Transactions leave it on six days. The query scores both KPIs with two read-only methods. The first is the 28-day band. The second compares each day with the same weekday of the four previous weeks.

WITH daily AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS day,
    COUNT(DISTINCT CONCAT(user_pseudo_id, '-', CAST((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING))) AS sessions,
    COUNT(DISTINCT IF(event_name = 'purchase' AND ecommerce.transaction_id != '(not set)', ecommerce.transaction_id, NULL)) AS transactions
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201204' AND '20210131'
  GROUP BY day
),
scored AS (
  SELECT
    day, sessions, transactions,
    (sessions - AVG(sessions) OVER w28) / STDDEV_SAMP(sessions) OVER w28 AS z_sessions_28d,
    (sessions - AVG(sessions) OVER wday) / STDDEV_SAMP(sessions) OVER wday AS z_sessions_weekday,
    (transactions - AVG(transactions) OVER w28) / STDDEV_SAMP(transactions) OVER w28 AS z_transactions_28d,
    (transactions - AVG(transactions) OVER wday) / STDDEV_SAMP(transactions) OVER wday AS z_transactions_weekday
  FROM daily
  WINDOW
    w28 AS (ORDER BY day ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING),
    -- same weekday over the four previous weeks
    wday AS (PARTITION BY EXTRACT(DAYOFWEEK FROM day) ORDER BY day ROWS BETWEEN 4 PRECEDING AND 1 PRECEDING)
)
SELECT
  day,
  FORMAT_DATE('%a', day) AS weekday,
  sessions,
  ROUND(z_sessions_28d, 1) AS z_sessions_28d,
  ROUND(z_sessions_weekday, 1) AS z_sessions_weekday,
  transactions,
  ROUND(z_transactions_28d, 1) AS z_transactions_28d,
  ROUND(z_transactions_weekday, 1) AS z_transactions_weekday
FROM scored
WHERE day >= '2021-01-01'
  AND GREATEST(ABS(z_sessions_28d), ABS(z_sessions_weekday), ABS(z_transactions_28d), ABS(z_transactions_weekday)) > 2
ORDER BY day
DayWeekdaySessionsz, 28-day bandz, same weekdayTransactionsz, 28-day bandz, same weekday
2021-01-20Wed4,8181.50.4834.32.2
2021-01-22Fri4,1010.50.8914.04.8
2021-01-23Sat3,144-0.60.6410.55.3
2021-01-24Sun2,977-0.90.7340.15.4
2021-01-25Mon3,9190.21.2531.13.5
2021-01-28Thu4,2280.50.15-1.4-2.1

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data). z-scores rounded to one decimal; transactions exclude the (not set) ID. Removing the last filter lists every January day.

The 28-day band flags 2021-01-20 and 2021-01-22, at 83 and 91 transactions. The weekday comparison also flags the weekend after and Monday 2021-01-25. The band misses Saturday's 41 transactions because it mixes weekdays; the weekday comparison scores it 5.3.

The end of the month shows the opposite failure. Transactions fall to 5 on 2021-01-28, then 6, 5, and 0 on 2021-01-31. Only the weekday comparison flags one of those days, at -2.1. The spike of the previous week widened both bands, so the other days score between -1.1 and -1.7. The sample does not say why. On your own property, check that shape against a tagging release first. Which market or channel carries the spike is the next question, covered in decomposing a KPI change by market, channel, and device.

How do weekly seasonality, promotions, and holidays change the flags?

Weekly seasonality changes the flags most, because a weekday profile is wider than a two-sigma band. On the same 92 days of the public sample, Sunday runs 26.1% below the daily average. Tuesday runs 19.3% above it. A band blind to the weekday reads every weekend as a dip.

ARIMA_PLUS handles this through SEASONALITIES, set to AUTO by default. That value infers seasonalities from the data frequency. A daily series gets a weekly component that the moving band lacks. A yearly component is another matter. Ninety-two days contain one December and no prior one to compare it with.

Holidays follow a stricter rule. The HOLIDAY_REGION option is off by default and accepts an array of regions, one per market. Per Google's reference, holiday modeling needs a daily or weekly series longer than a year. On the public sample, the option therefore changes nothing.

Promotions are your own calendar, and the model cannot guess them. A custom holiday query declares them: a holiday_name, a primary_date, and a window of days before and after. The query returns at most 50,000 rows and works on daily series. The reference does not state the one-year condition for custom holidays, so test them on your history. A declared promotion stops flagging as an anomaly; an undeclared one keeps flagging every year. GA4's automatic alerts take no such calendar in their documented method, one of the gaps listed in GA4's automatic anomaly alerts: what they catch, what they miss.

What does training cost, and how often should you retrain?

Training ARIMA_PLUS is billed on the bytes of its input query, multiplied by the number of candidate models. At the default AUTO_ARIMA_MAX_ORDER of 2, that means six candidate models. It means twelve when the series needs a non-seasonal differencing order of 1.

Three levers follow from Google's reference. Train on a daily aggregate table, not on the raw export. The multiplied bytes are then those of a small table. This article's example reads the export directly, for readability only. Lower AUTO_ARIMA_MAX_ORDER to 1: training time falls by more than half. Accuracy may drop slightly. Cap the history: training time per series grows linearly with its length. For a first run on many segments, Google suggests testing on about 1,000 series.

Detection and training run at different rhythms. Scoring yesterday with ML.DETECT_ANOMALIES reads one day of new data per run. Training reads the whole history. A weekly retraining, with a horizon longer than a week, keeps every new day inside the forecast. Retrain sooner after a known break: a new market, a tagging release, or a lasting step change. The same model also forecasts each series, which is where forecasting the month-end landing with a confidence interval starts.

FAQ

Can BigQuery detect anomalies without training a model?

BigQuery can detect anomalies with a moving band in plain SQL, which needs no model. One window function computes a mean and a standard deviation per day. BigQuery ML also documents anomaly detection with TimesFM, which needs no training. ARIMA_PLUS adds what the band lacks: a weekly component, step changes, and a stored decomposition per series.

How much history does ARIMA_PLUS need for GA4 data?

ARIMA_PLUS trains on a few months of daily data, and 92 days already show the weekly pattern. Holiday modeling needs a daily or weekly series longer than a year, per Google's reference. A yearly component needs at least one full season seen before. Start with the history you have and retrain as it grows.

Should a conversion rate get its own anomaly model?

A conversion rate is better watched through its two counts than through its own model. It jumps when sessions drop, even with stable orders. Train the numerator and the denominator as two KPIs in the same model. Flag the rate only when the numerator moves without its denominator.

Does anomaly detection work on a KPI with a few orders a day?

It works, but the flags become noise. On the public sample, January 2021 transactions range from 0 to 91 a day. The same-weekday comparison scores Sunday 2021-01-24, at 34 transactions, at 5.4. Aggregate sparse series to the week or to the country before training.

The Anomaly detection and forecasting on GA4: from signal to explanation guide places this model between the moving band and the decomposition. Want the next methods like this one as they ship? Get new analyses as they ship.

Sources