> ## Documentation Index
> Fetch the complete documentation index at: https://docs.prelude.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Count your events for your rules

> **Beta.** The request and response shapes may still change.

Define a counter over the events you send with [Dispatch events](/watch/v2/api-reference/dispatch-events). Each event that matches the filter is counted, over a sliding window, into the counter of its key value. A rule reads the counter of the evaluated identifier as `aggregate.custom.<name>`.

The name must be unique among your aggregates: a name already in use answers `409` with `aggregate_already_exists`. You can have at most 20 aggregates: one more answers `409` with `aggregate_limit_reached`. Only the description can change after creation.

An aggregate counts the events you send with [Dispatch events](https://docs.prelude.so/watch/v2/api-reference/dispatch-events.md). It keeps one counter for each value of its **key**, over a sliding **window**. A rule reads the counter of the evaluated identifier as `aggregate.custom.<name>`.

This aggregate counts the confirmed fraud reports for each phone number over the last 14 days:

```json theme={null}
{
  "name": "fraud_reports",
  "description": "Confirmed fraud reports per phone number.",
  "measure": "COUNT",
  "key": ["target.phone_number"],
  "window": "14d",
  "source": {
    "event": {
      "filter": "event.label == \"account.banned\" && event.confidence == \"minimum\""
    }
  }
}
```

A rule with the expression `aggregate.custom.fraud_reports > 3` then triggers for a phone number with more than 3 such events in the last 14 days.

## What you can count

| Field | Values |
| - | - |
| `measure` | `COUNT` counts the matching events. `COUNT_DISTINCT` counts the different values of `distinct` in them. |
| `key`, `distinct` | `target.phone_number`, `target.email_address`, `target.phone_prefix_7`, `target.phone_prefix_9` |
| `window` | `10m`, `1h`, `3h`, `24h`, `14d` |

An event has one target. An aggregate therefore reads either the email address or the phone number fields, not both.

A `COUNT_DISTINCT` counter keeps at most 10,000 values. Past this, the values seen least recently are dropped, so the count stops at 10,000.

## Limits

You can have at most 20 aggregates. One more answers `409` with `aggregate_limit_reached`: [delete one](https://docs.prelude.so/watch/v2/api-reference/management/aggregates/delete-aggregate.md) first.

Your aggregates also share a limit on how many counters they hold: see [Limits](https://docs.prelude.so/watch/v2/documentation/rules-recipes-flows.md#limits).

Only the description can change after creation. Choose the key, the window and the filter with care: to change them, you create a new aggregate, which starts from zero.

A new aggregate does not count past events: it counts the events you send after it is created. Until a full window has passed since it counted its first event, a rule reading it reports `NOT_EVALUATED`. For a `14d` window, this is 14 days after the first counted event. An aggregate that has not counted an event yet, for example because no event matched its filter, stays `NOT_EVALUATED`. See [Aggregates](https://docs.prelude.so/watch/v2/documentation/rules-recipes-flows.md#aggregates).


## OpenAPI

````yaml post /v2/watch/management/aggregates
openapi: 3.1.0
info:
  title: Prelude API
  version: 2.0.0
  description: The Prelude API allows you to send messages to your users.
  contact:
    email: support@prelude.so
servers:
  - url: https://api.prelude.dev
    description: Production server
security:
  - apiToken: []
tags:
  - name: Notify
    description: Send transactional and marketing messages with compliance enforcement.
  - name: Transactional
    description: Send transactional messages (deprecated - use Notify API instead).
  - name: Verify
    description: Verify phone numbers.
  - name: Watch
    description: Evaluate email addresses and phone numbers for trustworthiness.
  - name: Lookup
    description: >-
      Retrieve detailed information about a phone number including carrier data,
      line type, and portability status.
paths:
  /v2/watch/management/aggregates:
    post:
      tags:
        - Watch
      summary: Create an aggregate
      description: >-
        **Beta.** The request and response shapes may still change.


        Define a counter over the events you send with [Dispatch
        events](/watch/v2/api-reference/dispatch-events). Each event that
        matches the filter is counted, over a sliding window, into the counter
        of its key value. A rule reads the counter of the evaluated identifier
        as `aggregate.custom.<name>`.


        The name must be unique among your aggregates: a name already in use
        answers `409` with `aggregate_already_exists`. You can have at most 20
        aggregates: one more answers `409` with `aggregate_limit_reached`. Only
        the description can change after creation.
      operationId: createWatchAggregate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WatchAggregateRequest'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WatchAggregate'
        '400':
          description: KO
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Error'
                example:
                  code: invalid_aggregate
                  message: >-
                    The provided aggregate is invalid. See `details` field for
                    more information.
                  type: bad_request
                  param: aggregate
                  details:
                    - path: window
                      message: >-
                        The window must be one of '10m', '1h', '3h', '24h',
                        '14d'.
                  request_id: 3d19215e-2991-4a05-a41a-527314e6ff6a
        '409':
          description: Conflict
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Error'
                example:
                  code: aggregate_limit_reached
                  message: >-
                    The maximum number of aggregates is reached. Delete one
                    before creating another.
                  type: conflict
                  request_id: 3d19215e-2991-4a05-a41a-527314e6ff6a
components:
  schemas:
    WatchAggregateRequest:
      type: object
      properties:
        name:
          type: string
          maxLength: 64
          pattern: ^[a-z][a-z0-9_]*$
          description: >-
            The name a rule reads the aggregate by, as
            `aggregate.custom.<name>`. It starts with a lowercase letter and
            contains only lowercase letters, digits and underscores. It must be
            unique among your aggregates.
          examples:
            - fraud_reports
        description:
          type: string
          maxLength: 1024
          description: >-
            A free-text explanation of the aggregate, for the people who
            maintain it. Optional. Omitting it on an update clears it. It is the
            only field you can change after creation.
          examples:
            - Confirmed fraud reports per phone number.
        measure:
          type: string
          enum:
            - COUNT
            - COUNT_DISTINCT
          description: |
            What the aggregate counts for each value of `key`.
             * `COUNT` - The number of matching events.
             * `COUNT_DISTINCT` - The number of different values of `distinct` in the matching events. A counter keeps at most 10,000 values: past this, the values seen least recently are dropped, so the count stops at 10,000.
          examples:
            - COUNT
        key:
          type: array
          items:
            type: string
            enum:
              - target.phone_number
              - target.email_address
              - target.phone_prefix_7
              - target.phone_prefix_9
          description: >
            The event values that select a counter: there is one counter for
            each combination of their values. At least one, and each one only
            once.


            * `target.phone_number` - The phone number of the event target.

            * `target.email_address` - The email address of the event target.

            * `target.phone_prefix_7` and `target.phone_prefix_9` - The first 6
            or 8 digits of the phone number of the event target: its first 7 or
            9 characters, without the leading `+`. For `+33612345678`, they are
            `336123` and `33612345`.


            An event has one target, so `key` and `distinct` together read
            either the email address or the phone number fields, not both. An
            event that has no value for one of them is not counted.
          examples:
            - - target.phone_number
        distinct:
          type: string
          enum:
            - target.phone_number
            - target.email_address
            - target.phone_prefix_7
            - target.phone_prefix_9
          description: >-
            The event value a `COUNT_DISTINCT` aggregate counts the different
            values of. Required for `COUNT_DISTINCT`, refused for `COUNT`. It
            takes the same values as `key`.
          examples:
            - target.phone_number
        window:
          type: string
          enum:
            - 10m
            - 1h
            - 3h
            - 24h
            - 14d
          description: >-
            How far back the aggregate counts. The window slides, so an event
            stops being counted when it is older than the window.
          examples:
            - 14d
        source:
          $ref: '#/components/schemas/WatchAggregateSourceRequest'
      required:
        - name
        - measure
        - key
        - window
        - source
    WatchAggregate:
      type: object
      properties:
        id:
          type: string
          examples:
            - agg_01jc0t6fwwfgfsq1md24mhyztj
          description: The aggregate identifier.
        name:
          type: string
          examples:
            - fraud_reports
        description:
          type: string
          examples:
            - Confirmed fraud reports per phone number.
        type:
          type: string
          enum:
            - CUSTOM
          description: >-
            Always `CUSTOM`. An aggregate you define is your own, and only your
            rules can read it.
        measure:
          type: string
          enum:
            - COUNT
            - COUNT_DISTINCT
        key:
          type: array
          items:
            type: string
          examples:
            - - target.phone_number
        distinct:
          type: string
          description: Only on a `COUNT_DISTINCT` aggregate.
          examples:
            - target.phone_number
        window:
          type: string
          enum:
            - 10m
            - 1h
            - 3h
            - 24h
            - 14d
          examples:
            - 14d
        source:
          type: object
          properties:
            event:
              type: object
              properties:
                filter:
                  type: string
                  description: Absent when the aggregate counts every event.
                  examples:
                    - >-
                      event.label == "account.banned" && event.confidence ==
                      "minimum"
                key:
                  type: array
                  items:
                    type: string
                  description: >-
                    The event values the counter is selected by. Always the same
                    as `key`.
                  examples:
                    - - target.phone_number
                distinct:
                  type: string
                  description: The event value counted. Always the same as `distinct`.
                  examples:
                    - target.phone_number
              required:
                - key
      required:
        - id
        - name
        - description
        - type
        - measure
        - key
        - window
        - source
    Error:
      type: object
      properties:
        code:
          type: string
          description: The error code.
          examples:
            - invalid_phone_number
        message:
          type: string
          examples:
            - >-
              The provided phone number is invalid. Provide a valid E.164 phone
              number.
          description: A human-readable message describing the error.
        type:
          type: string
          examples:
            - bad_request
          description: The error type.
        request_id:
          type: string
          examples:
            - 3d19215e-2991-4a05-a41a-527314e6ff6a
          description: >-
            A string that identifies this specific request. Report it back to us
            to help us diagnose your issues.
        param:
          type: string
          examples:
            - phone_number
          description: The parameter the error refers to, when it applies to a single one.
      required:
        - code
        - message
        - type
    WatchAggregateSourceRequest:
      type: object
      description: What feeds the aggregate.
      properties:
        event:
          type: object
          description: >-
            The aggregate counts the events you send with [Dispatch
            events](/watch/v2/api-reference/dispatch-events). It is required.
          properties:
            filter:
              type: string
              description: >
                A condition, written in [CEL](https://cel.dev), that an event
                must meet to be counted. Omit it to count every event. It must
                return a boolean, and it is compiled before it is stored: a
                filter that does not compile is refused.


                It can read `event.label`, `event.confidence`, `event.target`
                (the phone number or email address of the target),
                `target.phone_number`, `target.email_address`,
                `target.phone_prefix_7` and `target.phone_prefix_9`.
                `event.confidence` is a string: `minimum`, `low`, `neutral`,
                `high` or `maximum`. To match several confidence levels, list
                them, as in `event.confidence in ["minimum", "low"]`.


                An event the filter cannot answer for, because it reads a value
                the event does not have, is not counted.
              examples:
                - >-
                  event.label == "account.banned" && event.confidence ==
                  "minimum"
      required:
        - event
  securitySchemes:
    apiToken:
      type: http
      scheme: bearer

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.