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

# Rate Limiting & Throttling — Integration

> Status: ✅ Complete — 2026-03-06 (Phase 1–3) Spec Reference: PF-42 Rate Limiting & Throttling Last Updated: 2026-03-04

**Status:** ✅ Complete — 2026-03-06 (Phase 1–3)
**Spec Reference:** [PF-42 Rate Limiting & Throttling](../../../specs/pf/specs/PF-42-rate-limiting-throttling.md)\
**Last Updated:** 2026-03-04

***

## Purpose

PF-42 provides a centralized rate limiting and throttling framework. This document captures integration points: PF dependencies (PF-01, PF-04, PF-10), the event published on rate limit violation, and the database/edge API consumed by edge functions and client hooks.

***

## PF Dependencies

| Dependency            | Use                                            | Type                  |
| --------------------- | ---------------------------------------------- | --------------------- |
| PF-01 (Organizations) | Rate limits scoped by `organization_id`        | Data / tenant context |
| PF-04 (Audit Logging) | All rate limit configuration changes audited   | Platform integration  |
| PF-10 (Notifications) | Violation alerts sent when thresholds exceeded | Event consumer        |

***

## Event Contract: `pf_rate_limit_violated`

**Event:** `pf_rate_limit_violated` (canonical identifier; subscribe to this name)\
**Publisher:** PF-42 (Rate Limiting Framework)\
**Subscribers:** PF-10 (Notifications), PF-48 (Security Event Monitoring — future)\
**Status:** 📝 Planned

### Purpose

Notify platform admins and security monitoring when a rate limit is exceeded so they can respond to abuse and adjust limits.

### Trigger Conditions

* After `pf_check_rate_limit()` returns `allowed = false` and a row is inserted into `pf_rate_limit_violations`.

### Payload Schema

**Canonical payload fields** (single source of truth for `pf_rate_limit_violated`):

| Field            | Type          | Required | Description                                      |
| ---------------- | ------------- | -------- | ------------------------------------------------ |
| `organizationId` | string (UUID) | Yes      | Organization the limit applies to                |
| `userId`         | string (UUID) | No       | Authenticated user when applicable               |
| `ipAddress`      | string        | No       | Client IP when applicable                        |
| `endpoint`       | string        | No       | API/route when scope is endpoint                 |
| `rateLimitId`    | string (UUID) | Yes      | Reference to `pf_rate_limits.id`                 |
| `limitType`      | string        | Yes      | One of: `per_minute`, `per_hour`, `per_day`      |
| `limitValue`     | number        | Yes      | Configured limit value                           |
| `actualCount`    | number        | Yes      | Count that caused the violation                  |
| `violatedAt`     | string        | Yes      | ISO 8601 timestamp (e.g. `2026-03-04T12:00:00Z`) |

**TypeScript shape:**

```typescript theme={null}
/** Canonical payload for pf_rate_limit_violated event (PF-42). */
export interface PfRateLimitViolatedPayload {
  organizationId: string;
  userId?: string;
  ipAddress?: string;
  endpoint?: string;
  rateLimitId: string;
  limitType: 'per_minute' | 'per_hour' | 'per_day';
  limitValue: number;
  actualCount: number;
  violatedAt: string; // ISO 8601
}
```

Event envelope may include `event_type: 'pf_rate_limit_violated'` and `timestamp`; consumers MUST use the fields above for canonical interpretation.

### Consumer Actions

| Consumer | Action                                                   | Status |
| -------- | -------------------------------------------------------- | ------ |
| PF-10    | Send notification to platform admins per alert threshold | 📝     |
| PF-48    | Ingest security event for monitoring/analytics           | 📝     |

***

## Database Function API: `pf_check_rate_limit`

**Function:** `pf_check_rate_limit()`\
**Provider:** PF-42\
**Consumers:** Edge functions (API rate limiting), server-side callers\
**Status:** ✅ Implemented (Phase 1 migration 20260306114910)

### Function Signature

See spec Data Model § Database Functions. Parameters: `p_organization_id`, `p_user_id`, `p_ip_address`, `p_endpoint`, `p_limit_type`. Returns: `allowed`, `remaining`, `reset_at`, `rate_limit_id`.

### Security

* `SECURITY DEFINER`; `SET search_path = public`. Callers must pass validated IP (see spec FR-3.2 for `getValidatedIPAddress` and trusted proxy whitelist).

***

## Platform Integration Layer (Consumed by Cores)

* **Rate limit check (client):** `useRateLimit` hook (see spec API Design). Cores use this for UI-level rate limit checks.
* **Rate limit check (server):** Edge functions call `pf_check_rate_limit()` at request entry; return 429 with `Retry-After` when not allowed.

***

## API Contract: Check Rate Limit (Edge)

**Endpoint:** Edge function `check-rate-limit` (or equivalent)\
**Method:** POST\
**Provider:** PF-42\
**Consumers:** Client `useRateLimit`, other edge functions that need to check limits\
**Status:** 📝 Planned

### Request / Response

See spec § API Design — Backend Edge Functions. Request: `organizationId`, `userId?`, `ipAddress?`, `endpoint?`, `limitType?`. Response: `allowed`, `remaining`, `resetAt`, `rateLimitId`.

### Error

* 429 Too Many Requests with `Retry-After` header when rate limited.

***

## References

* [PF-42 Spec](../../../specs/pf/specs/PF-42-rate-limiting-throttling.md)
* [EVENT\_CONTRACTS.md](./EVENT_CONTRACTS.md) — add `pf_rate_limit_violated` to registry when implemented
* [PLATFORM\_INTEGRATION\_LAYERS.md](./PLATFORM_INTEGRATION_LAYERS.md) — rate limiting as platform capability
