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

# Rules engine

> Guide to using the Tracer rules engine to build dynamic, expression-based validation logic.

The **Tracer rules engine** lets you build powerful validation logic without writing code. Using **CEL (Common Expression Language)**—a type-safe expression language developed by Google—you can create sophisticated rules that evaluate in under 1ms, automate complex business decisions, and adapt quickly to new requirements.

## Why use the rules engine

***

* **Flexibility**: Create and modify rules without code deploys
* **Performance**: Compiled expressions evaluate in under 1ms each
* **Type safety**: Expression syntax validated at rule creation
* **Complete evaluation**: All active rules evaluated for comprehensive audit trail
* **Scope-based**: Apply rules to specific segments, accounts, or transaction types

By the end of this guide, you will:

* Understand rule engine concepts and evaluation flow
* Create and test expression-based rules
* Manage the rule lifecycle (DRAFT, ACTIVE, INACTIVE, DELETED)
* Apply best practices for rule management

***

## What is the rules engine

***

The rules engine is the Tracer component responsible for evaluating expressions during transaction validation. It enables fraud analysts and risk managers to configure business logic that executes in real time—without requiring code deployments or engineering support.

### How it works

<Frame caption="Figure 1. Rules engine evaluation flow">
  <img src="https://mintcdn.com/lerian-49cb71fc/Mx6bI7Rs1ieyNuQg/images/en/docs/how-rules-works.jpg?fit=max&auto=format&n=Mx6bI7Rs1ieyNuQg&q=85&s=86fd8057bb12922dda5b770faeb712d6" alt="" width="8180" height="1955" data-path="images/en/docs/how-rules-works.jpg" />
</Frame>

In this flow:

* **Load rules** fetches all active rules from cache (or database on cache miss)
* **Evaluate expressions** runs all CEL expressions against the transaction context
* **Collect matches** gathers all rules that matched and determines the decision

### Evaluation pattern

All active rules are evaluated against every transaction. There is no priority ordering or short-circuit evaluation. This ensures:

* Complete audit trail (all matching rules recorded)
* No information loss (analysts can see all triggers)
* Simple logic (no priority conflicts)

**Decision precedence:**

* If **any DENY rule matches**, Tracer returns a DENY decision
* If only **ALLOW rules match**, Tracer returns an ALLOW decision
* If **no rules match**, Tracer returns the configured default (typically ALLOW for fail-open behavior)

<Note>
  Tracer returns decisions; it does not block transactions directly. Your system receives the decision and is responsible for taking the appropriate action (e.g., blocking, allowing, or queuing for review).
</Note>

***

## Core concepts

***

Before creating rules, understand the foundational elements.

### Rules

A rule is a unit of business logic composed of:

* **Expression** - A type-safe expression that evaluates to true or false
* **Action** - What decision to return when the expression is true
* **Scopes** - Which transactions the rule applies to
* **Status** - The rule's lifecycle state

### Expressions

Expressions are written in **CEL (Common Expression Language)**, a type-safe language that evaluates transaction context and returns a boolean value (true or false). CEL provides compile-time validation, so syntax errors are caught when you create the rule—not when transactions are being processed.

Example expressions:

```
amount > 10000
```

```
account.segmentId == "high-risk-segment" && amount > 5000
```

```
merchant.category == "gambling"
```

Expressions have access to the full validation request context including:

* `amount` - Transaction amount in cents (smallest currency unit)
* `transactionType` - CARD, WIRE, PIX, CRYPTO
* `subType` - Transaction subtype (e.g., debit, credit, international)
* `currency` - ISO 4217 currency code
* `transactionTimestamp` - When the transaction occurred
* `account` - AccountId, segmentId, portfolioId
* `segment` - SegmentId and segment metadata
* `portfolio` - PortfolioId and portfolio metadata
* `merchant` - MerchantId, category, country, riskLevel (optional)
* `metadata` - Custom fields passed in the request

### Expression examples by use case

Here are practical examples organized by business scenario:

#### Amount-based rules

```cel theme={null}
// Block transactions above a threshold
amount > 10000

// Block high-value international transfers
transactionType == "WIRE" && subType == "international" && amount > 50000

// Review large cryptocurrency transactions
transactionType == "CRYPTO" && amount > 5000
```

#### Merchant-based rules

```cel theme={null}
// Block gambling merchants
merchant.category == "7995"

// Block high-risk merchant categories
merchant.category in ["7995", "5967", "5966"]

// Review transactions from new merchant countries
merchant.country != "BR" && amount > 1000
```

#### Account-based rules

```cel theme={null}
// Block suspended accounts
account.status == "suspended"

// Review transactions from newly created accounts
metadata.accountAgeDays < 30 && amount > 500

// Block closed accounts
account.status == "closed"
```

#### Combined conditions

```cel theme={null}
// High-value transaction from high-risk segment
account.segmentId == "high-risk-segment-uuid" && amount > 5000

// International PIX above threshold
transactionType == "PIX" && subType == "international" && amount > 10000

// Large card transaction to foreign merchant
transactionType == "CARD" && merchant.country != "BR" && amount > 3000
```

#### Using metadata

```cel theme={null}
// Block transactions from untrusted devices
metadata.deviceTrust == "untrusted"

// Review first-time purchases above threshold
metadata.isFirstPurchase == true && amount > 1000

// Block transactions outside business hours (using metadata)
metadata.isBusinessHours == false && amount > 5000

// VIP customers bypass certain restrictions
metadata.customerTier == "vip" && amount < 50000
```

<Note>
  Metadata fields are provided by your integration. Design your payload to include the context your rules need.
</Note>

### Actions

Actions determine the decision when an expression evaluates to true:

| Action   | Description            |
| -------- | ---------------------- |
| `ALLOW`  | Allow the transaction  |
| `DENY`   | Deny the transaction   |
| `REVIEW` | Route to manual review |

### Scopes

Scopes define which transactions a rule applies to. A rule only evaluates against transactions that match at least one of its scopes.

Scope fields (all optional):

* `segmentId` - Match transactions from a specific segment
* `portfolioId` - Match transactions from a specific portfolio
* `accountId` - Match transactions from a specific account
* `merchantId` - Match transactions to a specific merchant
* `transactionType` - Match specific transaction types (CARD, WIRE, PIX, CRYPTO)
* `subType` - Match specific subtypes (debit, credit, instant, etc.)

If a scope field is not specified, it matches any value for that field.

***

## Rule lifecycle

***

Rules progress through a defined lifecycle to ensure safe deployment.

<Frame caption="Figure 2. Rules lifecycle and status transitions">
  <img src="https://mintcdn.com/lerian-49cb71fc/8leb2Q6OJnXkKkXw/images/en/docs/rules-limits-lifecycle-tracer.jpg?fit=max&auto=format&n=8leb2Q6OJnXkKkXw&q=85&s=496d7cc1759133be56df41608e96147d" alt="" width="4338" height="3688" data-path="images/en/docs/rules-limits-lifecycle-tracer.jpg" />
</Frame>

### States

| State      | Description                                                           |
| ---------- | --------------------------------------------------------------------- |
| `DRAFT`    | Not evaluated; expression can be modified freely                      |
| `ACTIVE`   | Evaluated during validations; expression is immutable                 |
| `INACTIVE` | Not evaluated; preserved for audit trail; can be reactivated          |
| `DELETED`  | Permanently removed; does not appear in listings; cannot be recovered |

### Transitions

| Transition   | From            | To       | Description                                               |
| ------------ | --------------- | -------- | --------------------------------------------------------- |
| `activate`   | DRAFT, INACTIVE | ACTIVE   | Start evaluation (validates expression)                   |
| `deactivate` | ACTIVE          | INACTIVE | Stop evaluation                                           |
| `draft`      | INACTIVE        | DRAFT    | Re-edit a previously deactivated rule before reactivating |
| `delete`     | DRAFT, INACTIVE | DELETED  | Permanent removal (cannot delete ACTIVE rules)            |

<Note>
  Active rules must be deactivated before deletion. This prevents accidental removal of rules that are currently being evaluated.
</Note>

***

## Create a rule

***

Create rules using `POST /v1/rules`. Rules are created in `DRAFT` status by default.

A rule requires:

* **name**: A unique, descriptive name
* **expression**: A CEL expression that evaluates to true or false
* **action**: The decision to return when the expression matches (ALLOW, DENY, or REVIEW)
* **scopes** (optional): Limit which transactions the rule applies to

For complete payload structure and field details, see the [API reference](/en/reference/tracer/create-rule).

***

## Activate and deactivate rules

***

After creating a rule, activate it to start evaluation. Deactivate rules to stop evaluation without deleting them.

| Operation  | Endpoint                         | Description                           |
| ---------- | -------------------------------- | ------------------------------------- |
| Activate   | `POST /v1/rules/{id}/activate`   | Start evaluating this rule            |
| Deactivate | `POST /v1/rules/{id}/deactivate` | Stop evaluating (preserves for audit) |

<Note>
  Deactivating a rule preserves it for audit purposes. Use delete only when you want to permanently remove a rule.
</Note>

***

## List and query rules

***

Query rules for management and auditing using `GET /v1/rules`.

### Query parameters

| Parameter   | Type    | Description                                |
| ----------- | ------- | ------------------------------------------ |
| `status`    | string  | Filter by status (DRAFT, ACTIVE, INACTIVE) |
| `pageSize`  | integer | Items per page (default: 100, max: 1000)   |
| `pageToken` | string  | Pagination token                           |

### Get a specific rule

Use `GET /v1/rules/{id}` to retrieve the full rule definition including expression and scopes.

***

## Update a rule

***

Update rules using `PATCH /v1/rules/{id}`. Rules can be updated in any status, with one important restriction:

<Warning>
  The `expression` field cannot be updated while a rule is ACTIVE. Deactivate the rule first to modify its expression.
</Warning>

***

## Delete a rule

***

Delete rules that are no longer needed. Only DRAFT and INACTIVE rules can be deleted. ACTIVE rules must be deactivated first.

```http theme={null}
DELETE /v1/rules/{id}
X-API-Key: {api_key}
```

<Warning>
  Deletion is permanent. Deleted rules cannot be recovered and do not appear in any listings.
</Warning>

***

## Best practices

***

Follow these practices for effective, maintainable rules.

### Naming

* **Use descriptive names** - The name should clearly state what the rule does
* **Include context** - Mention the scenario or transaction type
* **Avoid abbreviations** - Prefer clarity over brevity

| Less clear   | More clear                                 |
| ------------ | ------------------------------------------ |
| `Rule 1`     | `Block night transactions above BRL 5,000` |
| `Block high` | `Deny high-value weekend transactions`     |
| `PIX rule`   | `Review PIX transfers to new recipients`   |

### Expression design

* **Keep expressions simple** - Complex logic is harder to maintain
* **Use scopes for filtering** - Don't repeat scope conditions in expressions
* **Test edge cases** - Consider boundary values and null fields

### Lifecycle management

* **Start in DRAFT** - Test before activating
* **Deactivate before editing** - Never edit active rules
* **Archive unused rules** - Keep audit trail intact
* **Delete only when certain** - Deletion is permanent

### Monitoring

* **Review matched rules** - Check which rules are triggering
* **Monitor DENY rates** - High deny rates may indicate overly aggressive rules
* **Audit regularly** - Ensure rules still align with business requirements

***

## Quick reference

***

Key endpoints, actions, and status information.

### Endpoints

| Operation       | Method | Endpoint                    |
| --------------- | ------ | --------------------------- |
| Create rule     | POST   | `/v1/rules`                 |
| List rules      | GET    | `/v1/rules`                 |
| Get rule        | GET    | `/v1/rules/{id}`            |
| Update rule     | PATCH  | `/v1/rules/{id}`            |
| Delete rule     | DELETE | `/v1/rules/{id}`            |
| Activate rule   | POST   | `/v1/rules/{id}/activate`   |
| Deactivate rule | POST   | `/v1/rules/{id}/deactivate` |

### Actions

| Action   | Description            |
| -------- | ---------------------- |
| `ALLOW`  | Allow the transaction  |
| `DENY`   | Deny the transaction   |
| `REVIEW` | Route to manual review |

### Statuses

| Status     | Evaluated | Editable                       | Can delete            |
| ---------- | --------- | ------------------------------ | --------------------- |
| `DRAFT`    | No        | Yes                            | Yes                   |
| `ACTIVE`   | Yes       | Partial (expression immutable) | No (deactivate first) |
| `INACTIVE` | No        | Yes                            | Yes                   |
| `DELETED`  | No        | No                             | N/A                   |
