Join our Newsletter — 33% off our NHI Course
Home› Guides› Detection Logic Patterns Reference: Threshold, Sequence, First-Seen, Rarity…
Guide SOC & Detection Engineering

Detection Logic Patterns Reference: Threshold, Sequence, First-Seen, Rarity and Deviation Rules

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 15 min read
On this page

Most noisy or blind detections fail because the wrong logic pattern was chosen for the behaviour, not because the query was badly written. A brute force attempt is a count problem, an attack chain is an ordering problem, a new admin tool is a novelty problem and slow data theft is a baseline problem; each needs a different rule shape, different data and different tuning. This reference sets out five reusable patterns (threshold, sequence and correlation, first-seen, rarity and frequency, and deviation from baseline) with neutral pseudocode, false positive drivers, data needs, suppression windows, how each maps to Sigma correlation types, and how to test it with replayed data. It is written for detection engineers and SOC content developers who already know the detection lifecycle; for that lifecycle see the Detection Engineering Guide.

Key takeaways

  • Pick the pattern from the behaviour. Counting, ordering, novelty, rarity and deviation answer different questions; forcing a sequence problem into a threshold rule produces either noise or blind spots.
  • Every pattern has a grouping key and a window. The group-by fields and the time span decide what "the same activity" means, and most tuning is really changing those two settings.
  • Stateful patterns need history. First-seen, rarity and baseline rules depend on a learning period and a lookback that must be longer than the behaviour's natural cycle, or every month-end job becomes an alert.
  • Sigma covers counting and ordering, not novelty. Sigma correlation rules (specification 2.1.0) define event_count, value_count, temporal, temporal_ordered and value aggregation types; first-seen and baseline logic stays backend specific.
  • Test with replayed data before production. Replay known benign and malicious event sets through the rule, including events that straddle window boundaries, and record the results with the rule.

Why patterns matter

A detection rule is a hypothesis about how an attacker behaviour differs from normal activity. Naming the pattern up front forces three design decisions that are otherwise made by accident: what the unit of analysis is (user, host, source address, service principal), how long the evidence takes to accumulate, and what history the rule needs.

The Palantir Alerting and Detection Strategy (ADS) framework asks authors to document a strategy abstract, technical context, blind spots and assumptions, false positives and validation for every alert; the pattern name and its parameters belong in the strategy abstract. See the Detection Rule Documentation Template.

The five patterns at a glance

PatternDefinitionBest useFalse positive driversData needs
ThresholdCount events or distinct values per group within a window and alert above (or below) a fixed limitBrute force, password spraying, mass deletion, scanning, log source silenceBatch jobs, misconfigured clients retrying, shared NAT addresses, maintenance windowsOne event type with a reliable grouping field; no history
Sequence and correlationTwo or more conditions occur for the same entity within a window, optionally in a fixed orderFailed logons then success, account creation then privilege grant, download then executionLegitimate workflows that share the same steps (helpdesk resets, deployment pipelines)Several event types with a common entity field, consistent clocks
First-seenAlert when a value or combination has not appeared for that entity during a history windowNew process on a server, new country for a user, new API called by a service account, new parent and child process pairNew starters, new software rollouts, rebuilt hosts, short history windowsHistory of the field per entity, stable entity identifiers
Rarity and frequencyAlert on values that are uncommon across the population, or common values occurring at an unusual frequencyRare binaries or hashes across the estate, rare user agents, uncommon services installedSmall populations, niche business tools, long-tail admin utilitiesPopulation-wide counts over a lookback; normalised values (paths, hashes)
Deviation from baselineCompare a metric to the entity's own expected value and alert when it exceeds a statistical boundData volume out per user, API call volume per workload, logon hoursSeasonality, growth trends, holidays, incidents that legitimately change volumeWeeks of continuous metric history; consistent bucketing

Threshold rules

Threshold rules are the simplest stateful pattern: count something per group within a window and compare it to a number. There are two variants. An event count asks "how many times?" A distinct value count asks "how many different things?", which is what separates password spraying (one source, many accounts, ATT&CK T1110.003) from password guessing against one account (T1110.001).

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
PATTERN threshold
  FROM   auth_events WHERE outcome = "failure"
  GROUP  BY source_ip
  WINDOW 30m
  MEASURE distinct_count(target_user) AS users
  ALERT  WHEN users >= 20
  SUPPRESS same source_ip FOR 2h
  • Choosing the limit: measure the distribution first. Take the 99th or 99.9th percentile of the measure per group over a representative month, then set the limit above it and record the value and date in the rule documentation.
  • Window boundaries: a tumbling window of 30 minutes can split an attack across two buckets so neither crosses the limit. Prefer sliding windows where the platform supports them; the Sigma correlation specification warns that some backends only evaluate within static time boundaries.
  • Grouping traps: grouping by source address undercounts distributed attacks and overcounts behind a shared proxy. Consider a second rule grouped by target.

For identity-specific spraying logic, see the Password Spraying and Credential Stuffing Defence Guide.

Sequence and correlation rules

Sequence rules detect that several things happened to the same entity close together. Unordered correlation (all of A, B and C within the window) suits reconnaissance bursts where order varies. Ordered correlation (A then B) suits causal chains where order carries the meaning, such as many failures followed by a success for the same account.

Sample 1
PATTERN sequence_ordered
  STEP 1 many_failed_logons   (threshold rule: >= 10 failures per user in 10m)
  STEP 2 successful_logon     (outcome = "success")
  JOIN ON user
  WITHIN 1h
  ORDERED true
  ALERT  WHEN step 2 follows step 1
  • Entity alignment: the same person or host often appears under different field names in different sources (a source address in one log, a destination address in another). Normalise first, or use field aliases; Sigma correlation rules support an aliases attribute for exactly this case.
  • Risk accumulation instead of strict sequences: where steps are loosely related, attaching risk scores to entities and alerting on the total is often more robust. See the Correlation Rules and Risk Based Alerting Guide.

First-seen rules

First-seen rules alert on novelty: a value, or combination of values, that has not been seen for an entity during a history window. They suit environments that are stable per entity, such as servers, service accounts and workloads, and they are among the most useful patterns for non-human identities, whose behaviour is far more predictable than a person's.

Sample 1
PATTERN first_seen
  FROM   cloud_api_events
  ENTITY service_principal_id
  TERMS  (api_operation, source_asn)
  HISTORY 30d EXCLUDING current window
  ALERT  WHEN (entity, terms) NOT IN history
  SUPPRESS same entity and terms FOR 7d
  • History window: the history must cover the behaviour's natural cycle. A 7-day history alerts on every monthly job; 30 to 90 days is a common starting point for servers and service accounts. Elastic's documentation for its new terms rule type notes that windows of 1 to 7 days may produce more false positives.
  • Combinations: two individually familiar values can be a novel pair, for example a familiar user on a familiar host but never via remote desktop (T1021.001). Keep combinations to two or three fields so the history stays meaningful.
  • Cold start and churn: a new host or account has no history, so everything is new. Exclude entities younger than the history window, or route their alerts to a lower severity, and reset history when hosts are rebuilt with new identifiers.

For workload and service account baselines, see the Detection Engineering for Non-Human Identities Guide.

Rarity and frequency rules

Rarity rules look across the whole population rather than one entity's history: a binary running on two hosts out of twenty thousand, a service name installed once (T1543.003), a user agent seen in one session. They are strong hunting starting points and, with tuning, durable alerts.

Sample 1
PATTERN rarity
  FROM   process_events
  KEY    normalised_image_hash
  LOOKBACK 14d
  MEASURE host_count = distinct_count(host) PER key
  ALERT  WHEN host_count <= 2
         AND first_observed within last 24h
         AND signer NOT IN trusted_signers
  • Normalise before counting: paths containing user names, version numbers or random directories make every value rare. Use hashes, signer names or path templates.
  • Population size: rarity means little in a population of fifty hosts. Scope rare-value rules to large, homogeneous groups (all workstations, all web servers) rather than the whole estate.

Deviation from baseline rules

Baseline rules compare a numeric measure for an entity to what is expected for that entity at that time, and alert when the difference exceeds a statistical bound. They catch slow or volumetric behaviour that fixed thresholds miss, such as data leaving through a web service (T1567) at three times a user's normal rate.

Sample 1
PATTERN deviation
  FROM   proxy_events
  ENTITY user
  METRIC sum(bytes_out) PER 1h bucket
  TRAIN  28d, seasonality = weekly, trend = linear
  BOUND  residual outside fence k = 2.5
  ALERT  WHEN metric > expected AND metric > 500 MB
  SUPPRESS same user FOR 24h
  • Method: simple bounds use mean plus a multiple of the standard deviation, which outliers distort. Percentile-based fences are more robust; Microsoft's Kusto series_decompose_anomalies() function, for example, decomposes a series into seasonal, trend and residual components and applies a Tukey fence test to the residuals, with a default threshold of 1.5.
  • Seasonality and trend: working hours, weekends and month-end all shape volume. Train over at least several full cycles, and model trend for metrics that grow.
  • Absolute floor: a user who normally sends 1 MB and now sends 10 MB is a large deviation but not a meaningful one. Always add an absolute minimum, as in the example.

For behaviour analytics products that automate this pattern, see the UEBA Guide.

Choosing and combining patterns

Question the detection asksPatternSigma correlation type
Did this happen too many times?Threshold, event countevent_count
Did this touch too many different things?Threshold, distinct countvalue_count with a field
Did these things all happen together?Sequence, unorderedtemporal
Did these things happen in this order?Sequence, orderedtemporal_ordered
Did the total or average of a number exceed a fixed limit?Threshold on a numeric fieldvalue_sum, value_avg, value_percentile
Has this entity never done this before?First-seenNo correlation type; backend feature or lookup table
Is this value uncommon across the estate?RarityNo correlation type; backend aggregation
Is this more than this entity normally does?Deviation from baselineNo correlation type; backend statistics or UEBA

In Sigma correlation rules every type needs a group-by and a timespan (lowercase units: s, m, h, d), counting and value types need a condition such as gte: 100, and rules can be chained by referring to another correlation rule by id or name. The specification requires a conversion backend to raise an error rather than generate a query when the target cannot honour a mandatory feature, and to warn where, for example, it cannot enforce event order. See the Sigma Rules Guide.

Combining patterns

  • Layer for precision: rarity plus first-seen plus a risky attribute (unsigned, user-writable path) is far more precise than any one of them.
  • Team size: small teams should start with threshold and ordered-sequence rules, which need no history store; larger teams should invest in shared history tables (first-seen terms, population counts, entity baselines) that many rules reuse, rather than each rule computing its own.

Tuning and suppression windows

SettingWhat it controlsStarting point
Detection windowHow long evidence may take to accumulateJust longer than the behaviour's observed duration; measure it from test data
Run frequency and lookbackHow often the rule runs and how far back it readsLookback at least run interval plus ingestion delay, so late events are not skipped
Suppression windowHow long repeat alerts for the same group are held backRoughly the time an analyst needs to triage; keep the suppression key as narrow as the group-by
Allow lists and global filtersKnown benign entities removed before evaluationEvery entry with an owner, reason and review date; Sigma filters apply one tuning to many rules
History or training windowWhat counts as normal for stateful patternsAt least one full business cycle; 30 days or more for monthly patterns

Suppression hides repeats; it should never be the fix for a rule that is wrong. If a rule is suppressed most of the time, change its grouping, limit or pattern instead. See the Alert Fatigue Reduction Guide.

Query language constructs for each pattern

The pseudocode above is deliberately neutral. Platforms are listed alphabetically; each provides its own constructs, described here from its documentation.

  • Elastic Security: detection rule types include threshold, event correlation (EQL), new terms, ES|QL and machine learning. New terms rules accept one to three fields and alert when a value or combination has not appeared during the configured history window; alert suppression groups repeated alerts on one or more fields.
  • Microsoft Sentinel and KQL: scheduled analytics rules run every 5 minutes to 14 days with a lookback in the same range, support an alert threshold on result count, and can stop running for up to 24 hours after an alert as suppression. KQL's series_decompose_anomalies() supports baseline deviation with seasonality and trend parameters.
  • Splunk SPL: streamstats computes running statistics per BY group with a time_window option for sliding windows, and rare returns the least common values of a field (10 by default), optionally within groups.

Testing with replayed data

  1. Build a true positive set: capture events from an authorised emulation of the behaviour in a lab or test tenant, labelled with the expected alert.
  2. Build a benign set: export a representative week of production events for the same sources, including known noisy periods such as patch nights and month-end.
  3. Add edge cases: events that straddle window boundaries, out-of-order timestamps, the same entity under two field names and an entity with no history.
  4. Replay through the translated rule in a test index or workspace, never production, and record alerts raised, missed and false.
  5. Store the data and results with the rule in version control, and rerun them in CI on every change. See the Detection Validation and Testing Guide and the Detection as Code Guide.
  6. Roll out in stages: run the rule silently (logging matches without alerting) for a week or two, compare against the replay results, then enable alerting. Roll back by disabling the alert action while keeping the silent rule running.

Measuring pattern quality

  • True positive rate per rule: share of triaged alerts confirmed as malicious or policy-relevant.
  • Alerts per rule per week: trend it; sudden rises usually mean a data or environment change, not an attack wave.
  • Suppression ratio: suppressed matches divided by raised alerts; a high ratio flags a grouping problem.
  • Replay pass rate: share of rules whose stored test cases still pass after the last change.

See the Detection Engineering Metrics and KPIs Guide.

Common failure patterns

  • Grouping on unstable keys: dynamic addresses, host names that change on rebuild and session IDs break counts, sequences and history alike.
  • History shorter than the cycle: first-seen rules with a week of history alert on every monthly process.
  • Silent backend downgrades: an ordered sequence translated to a backend that cannot enforce order becomes unordered. Read conversion warnings.
  • Baselines that absorb the attacker: training over a period that includes the intrusion makes it normal.

Framework mapping

FrameworkReferenceRelevance
NIST CSF 2.0DE.CM-01, DE.AE-02, DE.AE-03Monitoring for adverse events, analysis of events, correlation of information from multiple sources
NIST SP 800-53 Rev. 5SI-4, AU-6System monitoring; audit record review, analysis and reporting
MITRE ATT&CK v20T1110.001, T1110.003, T1078, T1021.001, T1543.003, T1567Example techniques used in this reference for threshold, sequence, first-seen, rarity and baseline patterns

Practitioner checklist

  • Name the pattern, grouping key and window in every rule's documentation before writing the query.
  • Set threshold limits from a measured distribution and record the value and date.
  • Normalise entity fields across sources before writing sequence rules, or use aliases.
  • Give stateful rules a history window longer than the behaviour's business cycle and handle new entities explicitly.
  • Add an absolute floor to every baseline deviation rule.
  • Express counting and ordering logic in Sigma correlation rules where possible and read every conversion warning.
  • Keep suppression keys as narrow as the group-by and review allow lists on a schedule.
  • Store replay data and expected results with each rule and run them on every change.

Standards and references

Related NHI Mgmt Group resources: Detection Engineering Guide · Sigma Rules Guide · Correlation Rules and Risk Based Alerting Guide · Detection Validation and Testing Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.