# Custom rules

Updated Nov 22, 2026 · today

Epok has two kinds of user-defined rule. **Threshold rules** watch one query and fire when its measurement crosses a number over a window. **Composite rules** evaluate a boolean expression over several signals and fire when the whole expression is true. Both are plain JSON, both are evaluated every 60 seconds, and both run alongside the built-in detectors rather than instead of them.

## Read this before you pick one

The names invite you to assume a composite rule is a threshold rule with extra powers. It is not. **A composite rule is missing two things a threshold rule has**, and both omissions bite in production:

- **No flap guard.** Composite rules have no `for_duration_seconds`. The expression is re-evaluated every 60 seconds and the rule fires the first cycle it comes out true, so a sixty-second blip pages you. Your only damper is `cooldown_seconds`, which limits how often it re-fires but cannot stop the first one. If you need "true for five minutes, then tell me", that is a threshold rule.
- **No metrics.** A `threshold` leaf inside a composite expression counts matching log events. It cannot evaluate a metric expression. Metric monitors exist only as threshold rules with `rule_type: "metric"`.

What a composite rule gives you in exchange is the only thing a threshold rule cannot express: **correlation between independent signals**: AND / OR / NOT across log counts, currently-firing alerts, and detector health.

**Rule of thumb.** Use a threshold rule for one question about one query. Use a composite rule for two or more independent conditions that must hold simultaneously. A composite rule with a single leaf should have been a threshold rule; you gave up the flap guard for nothing.

## How rules interact with the built-in detectors

A custom rule is **purely additive**. It does not replace, tune, or silence any [built-in detector](https://epok.cloud/docs/detectors). Writing a rule for "error rate above 2%" does not stop the error-rate detector from also alerting on the same incident. You get both, from two sources, and they de-duplicate only insofar as the alert manager groups them. If a detector is too noisy, use suppression or a mute schedule instead of a competing rule.

The productive pattern is the opposite: use a rule to express something the detectors cannot know, such as a business threshold, a contractual limit, or a value only your domain gives meaning to. Refunds over a currency amount. A queue depth your ops runbook cares about. A specific log line that means a manual process is stuck.

## Threshold rules

A threshold rule takes one measurement every 60 seconds and compares it to a number. For a `log` rule the measurement is the count of events matching your search over `window_seconds`. For a `metric` rule it is the value your metric expression evaluates to. If the comparison holds for `for_duration_seconds` and the rule is outside its cooldown, it fires an alert titled *Threshold rule 'name' triggered* (or *Metric rule …*).

### Create one

```
curl -X POST https://app.epok.cloud/api/v1/tenants/ACCOUNT_ID/rules \
  -H 'X-API-Key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Auth-failure burst",
    "rule_type": "log",
    "query": "level:warn AND _msg:\"auth failed\"",
    "condition_op": "gt",
    "condition_value": 50,
    "window_seconds": 60,
    "for_duration_seconds": 120,
    "cooldown_seconds": 900,
    "severity": "critical"
  }'
```

`ACCOUNT_ID` is your numeric account id. Your credential is bound to one account. A mismatched id in the path returns 403 and cannot reach someone else's data. The key must have write scope (or you must be signed in as owner/admin).

### Every field

| Field | Type | Default | Meaning |
| --- | --- | --- | --- |
| name | string | required | 1–256 characters. Appears verbatim in the alert title: "Threshold rule '<name>' triggered". |
| rule\_type | "log" \| "metric" | "log" | log: the query is a search and Epok counts matching events. metric: the query is a metric expression evaluated against the metrics store to a single number. Nothing else is accepted (422). |
| query | string | required | 1–10,000 characters. Validated at create time: a log query is run for one second, a metric expression is evaluated once. Bad syntax returns 400 rather than saving a rule that can never fire. |
| condition\_op | enum | "gt" | gt (greater than), gte (greater or equal), lt (less than), lte (less or equal), eq (exactly equal). Any other value is rejected with 422. |
| condition\_value | number | required | The number the measurement is compared against. For log rules this is a count of matching events; for metric rules it is the value of the expression. |
| window\_seconds | integer | 300 | Look-back window for the measurement. Minimum 10, maximum 86400 (24h). |
| severity | enum | "warning" | info, warning or critical. Drives notification routing and per-channel severity filters. Any other value is rejected with 422. |
| for\_duration\_seconds | integer | 0 | The condition must stay true for this long before the rule fires. 0 means fire on the first cycle it is true. Range 0–86400. This is the flap guard. Set it on anything rate- or latency-shaped. |
| cooldown\_seconds | integer | 0 | Minimum gap between two fires of this rule. 0 means no cooldown. Range 0–86400. Survives a restart, because the last fire time is persisted rather than held only in memory. |
| channel\_ids | integer\[\] | \[\] | Firing-time destination snapshot when rule-channel pin enforcement is enabled for your project; otherwise stored only (see below). Each id is validated against your account; an id you do not own returns 400. List your ids with GET /api/v1/tenants/{account\_id}/channels. |

**There is no `enabled` field on create.** Rules are created enabled. Sending `enabled` in the create body is silently ignored, which catches people who POST the same JSON they exported. To disable a rule without deleting it, PATCH it (below).

**`channel_ids` routing is opt-in per project.** With rule-channel pin enforcement enabled, threshold and composite rules snapshot their channel IDs when they fire. Valid pins restrict delivery to those enabled channels. If any pinned channel is missing or disabled, delivery falls back to all enabled channels in the same project and records a fallback. Channel filters still apply. While the feature is off or in shadow, ordinary tenant routing stays active. Explicit escalation-policy targets take precedence over pins. Ask your operator to confirm the effective mode before relying on routing.

**A rule that keeps failing turns itself off.** If evaluation raises five times in a row (the query stops being valid, or it times out repeatedly), Epok sets `enabled = false` on the rule rather than retrying forever. It stops firing, and because the plan limit counts only enabled rules it also stops consuming a slot. Nothing notifies you, so if a rule has gone quiet, check its `enabled` flag with `GET .../rules` before assuming the condition never held.

### A metric monitor

Same shape, different `rule_type`. The query is a Prometheus-compatible expression evaluated against the metrics store; the first finite series it returns is the measured value. Metric monitors require the metrics data plane. Without it, create returns 400 and an existing rule is skipped rather than firing on absent data.

```
{
  "name": "Checkout p99 over budget",
  "rule_type": "metric",
  "query": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_milliseconds_bucket{service=\"checkout\"}[5m])))",
  "condition_op": "gt",
  "condition_value": 800,
  "window_seconds": 300,
  "for_duration_seconds": 300,
  "severity": "warning"
}
```

### Worked examples

Auth-failure burst

query: level:warn AND \_msg:"auth failed"
fires: count > 50 in 60s, for 120s, critical

Credential stuffing. The two-minute for\_duration keeps a single bad deploy of a login form from paging you.

Connection storm

query: service:checkout AND \_msg:"connection refused"
fires: count > 10 in 60s, for 60s, critical

Pool exhausted or the upstream is gone. Short window because this one is worth waking up for quickly.

Refund guard

query: service:payment AND \_msg:"refund issued" AND amount:>1000
fires: count > 5 in 300s, critical

A business threshold no detector can infer. Exactly the kind of thing custom rules are for.

Batch job went quiet

query: service:nightly-etl AND \_msg:"job complete"
fires: count lt 1 in 86400s, warning

Absence-shaped. lt with a 24h window is how you assert something should have happened.

### Manage them

| GET | /api/v1/tenants/{account\_id}/rules | List every rule, enabled or not. |
| --- | --- | --- |
| POST | /api/v1/tenants/{account\_id}/rules | Create. Validates the query before saving. |
| PATCH | /api/v1/tenants/{account\_id}/rules/{rule\_id} | Update any subset of name, query, condition\_op, condition\_value, window\_seconds, severity, channel\_ids, enabled, cooldown\_seconds, for\_duration\_seconds. |
| DELETE | /api/v1/tenants/{account\_id}/rules/{rule\_id} | Remove. 404 if it is not yours. |

Because rules are JSON over a plain REST surface, keeping them in your repo and applying them from CI works: `GET` to export, `POST` to apply. Alert config then ships in the same commit as the service change that needs it.

**There is no dry-run endpoint.** Backtesting a threshold rule is a UI feature: in the app, open **Alerting, then Threshold rules** and use the dry-run control in the rule form. It replays the last hour of history and tells you how many times the rule would have fired. Metric monitors are not backtestable because they evaluate live values, so save the rule and watch the next cycle.

## Composite rules

A composite rule is a boolean expression tree. Every 60 seconds Epok walks the tree, evaluates each leaf, combines them with the branch operators, and fires one alert (*Composite rule triggered: name*) if the root comes out true. The evidence attached to the alert includes each leaf's result, so you can see which condition was the one that flipped.

```
curl -X POST https://app.epok.cloud/api/v1/tenants/ACCOUNT_ID/composite-rules \
  -H 'X-API-Key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Checkout 5xx while the DB detector is already firing",
    "expression": {
      "op": "and",
      "conditions": [
        {
          "op": "threshold",
          "query": "service:checkout AND status_code:>=500",
          "comparator": "gt",
          "value": 10,
          "window_seconds": 300
        },
        {
          "op": "alert_firing",
          "detector_type": "database_intelligence"
        }
      ]
    },
    "severity": "critical",
    "cooldown_seconds": 900,
    "enabled": true
  }'
```

### Top-level fields

| Field | Type | Default | Meaning |
| --- | --- | --- | --- |
| name | string | required | Non-empty after trimming. Appears in the alert title. |
| expression | object | required | The root node of the tree. Must have an op. Validated on create, update, and test. |
| severity | enum | "warning" | info, warning or critical. Unlike threshold rules, an unrecognised value is not rejected. It silently falls back to warning. |
| cooldown\_seconds | integer | 300 | Minimum gap between fires. Note the default is 300 here, unlike threshold rules where it is 0. |
| channel\_ids | integer\[\] | \[\] | Stored, but not used for routing (see the note under threshold rules). Unlike threshold rules, the ids are not validated here: an id you do not own is accepted and silently ignored. |
| enabled | boolean | true | Unlike threshold rules, enabled IS honoured on create. |

### Leaf operators: the three things you can measure

There are exactly three. Anything else is rejected with `400 Invalid operator`.

threshold

Counts log events matching a search over a window and compares the count to a number. **Log only**; there is no metric variant of this leaf.

- `query`: string, **required**. The search whose hits are counted.
- `value`: number, **required**. Omitting either query or value returns 400.
- `comparator`: `gt`, `gte`, `lt`, `lte`, `eq`. Defaults to `gt`. An unrecognised comparator evaluates to false rather than erroring, so a typo here produces a rule that never fires.
- `window_seconds`: integer, default 300, floored at 10.

alert\_firing

True when at least one alert on your account is currently in the `firing` state. This is the leaf you want for "a detector found something".

- `detector_type`: string, optional. Match only alerts from this detector, e.g., `error_rate`.
- `service`: string, optional. Substring match against the alert's stream or title.
- Both filters are ANDed. With neither, the leaf matches any firing alert. That is what makes `not` + `alert_firing` a usable "nothing else is wrong" guard.

detector\_active

**This means "the detector is running and healthy", not "the detector found something".** It reads detector health: enabled, status `running` or `idle`, and a recent run. If you want "this detector is alerting", use `alert_firing` with a `detector_type` instead. Confusing the two is the most common way to build a composite rule that silently never fires.

- `detector_type`: string, **required**. Missing it returns 400.
- `max_stale_seconds`: integer, default 180. How recently the detector must have run to count as active. 180 is three times the usual cadence, so a quiet cycle does not flag it.

### Branch operators: the three ways to combine

- `and` is true when every child is true. Takes a non-empty `conditions` array.
- `or` is true when any child is true. Takes a non-empty `conditions` array.
- `not` inverts its single child. Takes **exactly one** entry in `conditions`; two or zero returns 400.

Two structural limits, both enforced at create/update/test time: **nesting is capped at 5 levels** and the serialised expression at **10 KB**. If you are approaching either, you are writing a program rather than an alert.

A worked `not` example pages on worker errors only when the queue is *not* already alerting, so the queue incident does not generate two pages:

```
{
  "op": "and",
  "conditions": [
    {
      "op": "threshold",
      "query": "service:worker AND level:error",
      "comparator": "gt",
      "value": 25,
      "window_seconds": 300
    },
    {
      "op": "not",
      "conditions": [
        { "op": "alert_firing", "service": "queue" }
      ]
    }
  ]
}
```

### Test an expression before you save it

Composite rules, unlike threshold rules, have a real dry-run endpoint. It evaluates the expression right now, returns whether it would fire and which leaves matched, and persists nothing. No alert is emitted and no cooldown is consumed.

```
curl -X POST https://app.epok.cloud/api/v1/tenants/ACCOUNT_ID/composite-rules/test \
  -H 'X-API-Key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "expression": {
      "op": "and",
      "conditions": [
        { "op": "threshold", "query": "level:error", "value": 50, "window_seconds": 300 },
        { "op": "alert_firing", "detector_type": "error_rate" }
      ]
    }
  }'

# returns {"met": false,
#    "op": "and",
#    "details": [
#      {"met": true,  "op": "threshold", "query": "level:error",
#       "actual": 91, "threshold": 50, "comparator": "gt"},
#      {"met": false, "op": "alert_firing",
#       "detector_type": "error_rate", "service": null, "firing_count": 0}
#    ]}
```

### Manage them

| GET | /api/v1/tenants/{account\_id}/composite-rules | List all composite rules. |
| --- | --- | --- |
| GET | /api/v1/tenants/{account\_id}/composite-rules/{rule\_id} | Fetch one. |
| POST | /api/v1/tenants/{account\_id}/composite-rules | Create. |
| POST | /api/v1/tenants/{account\_id}/composite-rules/test | Dry-run an expression. Nothing is saved. |
| PATCH | /api/v1/tenants/{account\_id}/composite-rules/{rule\_id} | Update any subset of name, expression, severity, channel\_ids, cooldown\_seconds, enabled. |
| DELETE | /api/v1/tenants/{account\_id}/composite-rules/{rule\_id} | Remove. |

The same rules are editable in the app under **Alerting, then Composite rules**, which wraps the test endpoint in a builder if you would rather not hand-write the tree.

## Limits

These are the limits configured per plan. What the create endpoints enforce today is narrower on some plans. The two bullets under the table describe the behavior you will actually hit, and they win.

| Plan | Threshold rules | Composite rules |
| --- | --- | --- |
| Free (legacy) | 3 | 2 |
| Observe trial | 20 | 5 |
| Observe | 20 | 5 |
| Detect (coming soon) | 20 | 5 |
| Investigate (coming soon) | 20 | 5 |
| Enterprise | per contract | per contract |

Three details that surprise people:

- **The threshold-rule limit counts only enabled rules.** Disabling a rule frees a slot; you can keep an archive of disabled rules at no cost. The composite-rule limit counts *every* stored rule, enabled or not, so there you have to delete.
- **Every plan, trial included, can create rules over the API.** If you see `403 This feature requires a paid plan` on a plan listed above, it is us, not your request; contact support and we will lift it. Separately, being over the limit returns 403 for threshold rules and 429 for composite rules.
- **An uncapped plan is not yet uncapped for composite rules.** Plans configured with no composite cap are compared against the raw limit without special-casing it, so the check fails on the very first rule and returns `429 Composite rule limit reached`. Until that is fixed, treat the published per-plan numbers as the real ones and talk to support if you need more.

## "My rule fires too much"

Work through these in order, because each one is cheaper than the next:

1. **Raise `for_duration_seconds`** on a threshold rule. Most "noisy rule" reports are a rule with the default 0, firing on single-cycle blips.
2. **Raise `cooldown_seconds`**. This does not stop the first page, but it stops the next nine. Composite rules already default to 300; threshold rules default to 0.
3. **Narrow the query.** For a log rule, run the query in Explore over the last 24 hours first. The hit count Explore shows you over your window is the same measurement the rule compares against.
4. **Suppress at the alert layer.** Mute schedules, maintenance windows and suppression rules live in [alerting](https://epok.cloud/docs/alerting) and apply to detector output and custom rules alike. Use these for known-noisy periods rather than deleting a rule you will want back.

One anti-pattern worth naming: do not write rules against high-volume `level:info` patterns. That is what the detectors are for, and they learn a baseline instead of comparing to a number you guessed.

Next

- [Alerting](https://epok.cloud/docs/alerting): channels, routing, suppression, mute schedules, maintenance windows.
- [Detectors](https://epok.cloud/docs/detectors): what fires without you writing anything, and the `detector_type` values your composite leaves can reference.
- [API reference](https://epok.cloud/docs/api): full endpoint list, auth, error codes, and the raw OpenAPI spec.
- [Send metrics](https://epok.cloud/docs/install/metrics), required before `rule_type: "metric"` will work.
