Cybersecurity & Information Security

How to Write an Analytics Rule in Microsoft Sentinel

7 min readPublished: August 5, 2026
Professional visual illustration on the topic of Analytics Rule in Microsoft Sentinel in the field of SIEM and detection
Quick answer

A good Analytics Rule in Microsoft Sentinel begins with the behavior to detect and the sources that can prove it. Then, write KQL that returns a clear investigative unit, define frequency and Lookback, map Entities, set Severity and MITRE, choose Grouping, and perform Test and Tuning. The goal of the rule is not to generate many Alerts, but to create Incidents that can be understood, verified, and acted upon.

It's easy to write a Query that returns rows. It's harder to turn it into a stable Detection. An Analytics Rule runs over time on changing data, generates Alerts, affects analyst workload, and sometimes triggers Automation. An error in defining a time window, Entity, or Threshold can create duplicates, misses, or an incorrect response.

Microsoft Sentinel supports several types of Analytics rules. Scheduled rules are the most common and are based on KQL that runs at intervals and examines a Lookback period. There are also NRT — Near Real-Time — and built-in templates or detections depending on the platform. This guide focuses on the Scheduled query rule, as it allows understanding all planning components.

The example is Password Spray in a lab environment. It is not intended for monitoring unauthorized individuals, and the Thresholds are not universal recommendations. They should be calibrated against the organization's Baseline, identity architecture, and VPN/Proxy.

Step 1: Write a Detection specification before KQL

A Use Case needs to answer clear questions: What behavior will we detect? Why is it dangerous? What Data sources are needed? What is the Expected benign activity? Who is the Owner? What will the analyst do when the rule is triggered? To which MITRE technique is it related?

ComponentExample for Password Spray
HypothesisOne source IP tries to fail against many users to find a valid password
SourceSignin logs with time, user, IP, and result
Result unitIP and time window with number of attempts and users
Expected exceptionsVPN, Red Team tests, old service or Identity provider
Analyst actionCheck users, successes, MFA, Reputation, and follow-up activity
Owner and ReviewDetection engineer; monthly review or after source change

Also define boundaries. A Rule does not prove Account compromise. It identifies a Pattern that requires investigation. If there is a success, it can raise the Priority, but the sequence and context still need to be verified.

Step 2: Ensure Data readiness

Open the table and check Sample events. Is ResultType a number or a string? Is IPAddress empty in some events? Do Service principals appear alongside users? What is the Ingestion delay? Are there any Tenant or Application that require exclusion?

A Rule that relies on an unstable field will break. Document Schema, Connector, Normalization, and Data health query. If the source stops sending, a Dashboard must alert; “no Alerts” is not necessarily a safe state.

Step 3: Write a Query that returns useful Evidence

A basic Query for Password Spray in the lab can group failures by IP and time window and require a number of unique users:

let Lookback = 15m;
let MinimumAttempts = 20;
let MinimumUsers = 5;
SigninLogs
| where TimeGenerated > ago(Lookback)
| where tostring(ResultType) != "0"
| summarize Attempts=count(),
            Users=dcount(UserPrincipalName),
            UserList=make_set(UserPrincipalName, 20),
            FirstSeen=min(TimeGenerated),
            LastSeen=max(TimeGenerated)
  by IPAddress, bin(TimeGenerated, 5m)
| where Attempts >= MinimumAttempts and Users >= MinimumUsers
| project TimeGenerated, IPAddress, Attempts, Users, UserList, FirstSeen, LastSeen

The result should contain the fields the analyst needs and the fields that will be mapped to Entities. In this case, IPAddress is a central Entity, and UserList is Context. A dynamic list of users is not necessarily suitable for mapping a single Account, so an Alert can be created by IP and Custom details added, or the result structure changed according to the Workflow.

Test the Query on several ranges: hour, day, and week. Manually tag True, False, and Benign Positives. See if it detects VPN activity or Health checks. Do not adjust the Threshold just to reach zero Alerts.

Step 4: Frequency and Lookback

Query frequency determines how often the rule runs. Query period or Lookback determines how far back it checks. If a Rule runs every five minutes and examines 15 minutes, the same Pattern can appear in several runs. Event grouping, Alert grouping, or Suppression mechanisms can reduce duplicates, but the impact must be understood.

Lookback should be long enough to cover Ingestion delay and detect the behavior, but not too wide. A slow Password Spray may require a larger window or a different Baseline. A too fast Rule can generate noise; a too slow Rule increases detection time.

SettingProfessional Question
Run everyHow fast should it detect and how much does it cost to run?
Lookup data from lastWhat is the duration of the behavior and what is the data Delay?
ThresholdHow many results constitute one Alert?
Start runningIs time needed for the initial data?
SuppressionWill temporary blocking hide a real change?

Step 5: Severity, MITRE, and Alert details

Severity should reflect risk when the condition is met, not the final outcome of the investigation. A Password Spray without success may be Medium, but an attempt against Privileged accounts or success after failures may justify a different rating. Alert details override can be used to dynamically display IP, user, or Count in the title, while maintaining a readable title.

MITRE ATT&CK mapping helps explain adversary behavior and build a Coverage map. Choose Tactics and Techniques that match the actual logic. Do not map a long list just to appear comprehensive.

Custom details should provide Context that shortens Triage: Attempts, Users, FirstSeen, LastSeen, Application or Tenant. Avoid transmitting sensitive information that is not required.

Step 6: Entity mapping

Entity mapping allows Sentinel to identify IP, Account, Host, URL, and more. A quality Entity enables Investigation, Enrichment, UEBA, and linking to other Incidents. Ensure the field in the output is Scalar and in the appropriate format.

In the example, IP.Address is mapped to IPAddress. If the rule returns a single UserPrincipalName for each row, Account.FullName or AadUserId can be mapped according to the Schema. When a Query summarizes many users in a list, do not force a Mapping that does not represent a single Entity.

Step 7: Event grouping and Alert grouping

Event grouping determines whether each Query row will become a separate Alert or if all results will be aggregated. If each IP is a separate Case, a row for each IP and an Alert for each Result may make sense. If everything is aggregated into one Alert, an analyst might receive a huge Incident with unrelated IPs.

Alert grouping can attach Alerts to an Incident by Entities or details. Define a window and identify a true connection. Too aggressive Grouping hides development and mixes Scopes; too weak Grouping creates an Incident for each run.

Step 8: Automation and Tasks

Initially, automation can assign an Owner, add Tags, create Tasks, enrich IP, or send a Notification. Automated Containment actions require high Confidence, Exceptions, approval, and Rollback capability. A new Detection usually needs a Monitor period before significant automated response.

Include Tasks that guide the analyst: check successes from the same IP, check MFA, check Reputation, look for follow-up activity, and contact the account owner. This way, a Rule generates a process, not just an Alert.

Testing and Tuning

  1. Manually run the Query on historical data and mark results.
  2. Perform Unit test with simulated events representing Positive and Negative cases.
  3. Activate the Rule in monitoring mode without dangerous Automation.
  4. Measure Volume, True/False/Benign Positive, Triage time, and Context quality.
  5. Change Threshold, exclusions, or grouping with documented reasons.
  6. Perform Regression test after changing Parser, Connector, or Query.
  7. Set a Review date and Owner; a Rule without maintenance becomes a detection debt.

Checklist before activation

  • Use Case and hypothesis are documented.
  • Data source, Schema, and Delay have been checked.
  • Query returns a clear investigative unit.
  • Frequency and Lookback cover the behavior without abnormal duplication.
  • Severity and MITRE align with the logic.
  • Entities and Custom details are valid.
  • Grouping has been tested on several results.
  • Playbook, Owner, and Review date exist.
  • Privacy, cost, and permissions have been checked.
  • Rollback exists for changes and Automation.

Common mistakes

  • Starting from a Query found online without a local Use Case.
  • Mapping an Entity from a list or an unstable field.
  • Using overlapping Lookback without understanding duplicates.
  • Setting High severity for every Rule.
  • Excluding an IP or user permanently without Expiration.
  • Adding Suppression that hides activity escalation.
  • Activating automatic blocking before a Tuning period.
  • Not checking Data health and Schema changes.

Summary and CTA

Choose one Use Case in the lab and write a one-page Detection specification before KQL. Then build the Rule, run it on simulated data, and document three results: True, False, and Benign Positive. The most important improvement is not another condition in the Query, but an Incident that the next analyst can investigate quickly and consistently.

FAQ

What is the difference between a Scheduled rule and an NRT rule?

A Scheduled rule runs KQL at intervals and examines a Lookback. NRT is designed for near real-time detection with different limitations and settings. The choice depends on the Use Case and platform support.

How to choose a Threshold?

Start with behavior and risk, examine historical Baseline, and mark results. Threshold is a starting point for calibration, not a universal number.

Should every Query row be an Alert?

Not necessarily. Event grouping should match the investigative unit. Sometimes each IP or Host is a separate Alert; sometimes it's appropriate to aggregate.

Why is Entity mapping important?

Entities enable Context, Investigation, linking between Alerts, and Enrichment. A Rule without Entities may be harder to investigate.

When to enable automated response?

When Confidence, Impact, and Exceptions are understood, organizational approval and Rollback exist, and the Rule has undergone sufficient Test and Tuning.

Want to check if this track is right for you?

Leave your details and an HPI advisor will get back to you for a short, no-obligation fit call.

Your details are stored securely.

For SOC and cyber studies as part of the Cybersecurity & AI program

Want to hear the details? Leave your info and we'll get back to you.

Related articles