Skip to content

Rate Limiting Reference

Kirak enforces active rate limiting across all CRUD routes by default. Rather than requiring developers to manually configure rate limits on every model, Kirak applies a secure global baseline (100 requests per 60 seconds per IP address) unless explicitly customized or overridden.

Limits are evaluated before access control policies or lifecycle hooks execute, shielding database connections, bcrypt hashing, and business logic from resource exhaustion attacks.


The following diagram illustrates how Kirak evaluates, resolves, and enforces rate limits on every incoming request:

flowchart TD
REQ["Incoming HTTP / GraphQL Request"] --> GATE{"Rate Limiting Enabled?<br/>(kirak.json rate_limit.enabled)"}
GATE -->|false| ALLOW["Pass to Access Policy Engine"]
GATE -->|true| MODEL_CHECK{"Model Rate Limit Configured?"}
MODEL_CHECK -->|"enabled: false"| ALLOW
MODEL_CHECK -->|"per-op or flat override"| RESOLVE_CFG["Apply Model Specific Quota"]
MODEL_CHECK -->|"absent or empty"| GLOBAL_CFG["Apply Global Default Quota<br/>(100 req / 60s)"]
RESOLVE_CFG --> SCOPE{"Determine Counter Scope<br/>(per: ip | user | model)"}
GLOBAL_CFG --> SCOPE
SCOPE -->|"per: 'ip'"| IP_EXTRACT["Extract Real Client IP<br/>(Apply trusted_proxy_ips check)"]
SCOPE -->|"per: 'user'"| USER_EXTRACT["Extract Authenticated User ID<br/>(JWT / API Key / Cookie; Guest -> IP)"]
SCOPE -->|"per: 'model'"| GLOBAL_KEY["Build Shared Model:Op Key"]
IP_EXTRACT --> BUILD_KEY["Generate Rate Limit Key"]
USER_EXTRACT --> BUILD_KEY
GLOBAL_KEY --> BUILD_KEY
BUILD_KEY --> BACKEND{"Backing Store Available?"}
BACKEND -->|"KIRAK_REDIS_URL Set"| REDIS["Check Redis Window"]
BACKEND -->|"No Redis"| DB["Check Database Table<br/>(Atomic INSERT ... ON CONFLICT)"]
REDIS --> RESULT{"Quota Exceeded?"}
DB --> RESULT
REDIS -.->|Connection Timeout / Crash| FAIL_OPEN["Fail-Open Resilience<br/>(Log Warning & Permit Request)"]
DB -.->|Database Error| FAIL_OPEN
FAIL_OPEN --> ALLOW
RESULT -->|No| HEADERS["Attach Quota Headers<br/>(X-RateLimit-Limit, Remaining, Reset)"]
HEADERS --> ALLOW
RESULT -->|Yes| BLOCK["Return 429 Too Many Requests<br/>(Retry-After Header + Error Envelope)"]

Configure global defaults in the rate_limit block of kirak.json:

{
"rate_limit": {
"enabled": true,
"default_max_requests": 100,
"default_window_seconds": 60,
"trusted_proxy_ips": [
"127.0.0.1",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16"
]
}
}
Setting Type Default Description
enabled boolean true Master kill switch. When false, disables rate limits across CRUD routes, GraphQL operations, and MCP tools. Cost-sensitive modules (AI, Payments, SMS) maintain independent limits.
default_max_requests integer 100 Maximum requests permitted within the rolling window for any model that lacks an explicit override.
default_window_seconds integer 60 Duration of the rolling rate limit window in seconds.
trusted_proxy_ips list[string] [] List of upstream reverse proxy IPs or CIDR blocks permitted to populate X-Forwarded-For.
client_ip_header string "" A header a trusted proxy sets to the client’s IP (e.g. cf-connecting-ip), read before X-Forwarded-For.

Models can customize rate limits using either flat format (applying the same limit across all operations) or per-operation format (differentiating reads from writes).

Applies to all CRUD operations on the model:

{
"table": "products",
"schema": { "..." },
"rate_limit": {
"max_requests": 60,
"window_seconds": 60,
"per": "user"
}
}

Sets granular limits per lifecycle operation, with an optional default fallback:

{
"table": "orders",
"schema": { "..." },
"rate_limit": {
"default": { "max_requests": 100, "window_seconds": 60, "per": "ip" },
"fetch": { "max_requests": 120, "window_seconds": 60, "per": "user" },
"create": { "max_requests": 10, "window_seconds": 60, "per": "user" },
"delete": { "max_requests": 5, "window_seconds": 3600, "per": "user" }
}
}

Supported operations: fetch, search, count, exists, create, update, upsert, delete, destroy, restore.

To opt a high-frequency internal or read-heavy model out of rate limiting:

{
"table": "system_heartbeats",
"rate_limit": {
"enabled": false
}
}

The per property determines how rate limit keys are partitioned:

Scope Key Pattern Description
"ip" (default) crud:{model}:{operation}:ip:{ip_address} Counters partitioned by remote client IP address. Recommended for public endpoints.
"user" crud:{model}:{operation}:user:{user_id} Counters partitioned by authenticated user ID (Bearer JWT, API key, or session cookie). Unauthenticated guests fall back to IP scoping.
"model" crud:{model}:{operation} Shared global counter across all callers. Recommended for expensive aggregate endpoints or bounded global quotas.

When deployed behind load balancers or CDNs (Cloudflare, AWS ALB, Nginx), client IPs arrive via headers. Directly trusting X-Forwarded-For creates an IP-spoofing vulnerability.

Kirak solves this using trusted_proxy_ips:

  1. If the socket connection IP is not in trusted_proxy_ips, Kirak strictly uses the socket IP (request.client.host). Header values are ignored.
  2. If the socket connection IP is in trusted_proxy_ips, Kirak inspects X-Forwarded-For from right to left, selecting the rightmost untrusted IP. This guarantees the IP cannot be spoofed by client header injection.

A CDN’s client IP header (client_ip_header). When a CDN sits in front of a load balancer, X-Forwarded-For ends in the load balancer’s own address, so trusted_proxy_ips must list it and follow it when it changes. A CDN that sets its own header to the client’s IP (Cloudflare’s CF-Connecting-IP) avoids that:

"rate_limit": {
"trusted_proxy_ips": ["169.254.169.126"],
"client_ip_header": "cf-connecting-ip"
}

On a request from a trusted address Kirak reads that header first; a missing or invalid value falls back to the X-Forwarded-For rule above. The header is only trustworthy when every request reaches the app through the CDN (for example, the origin accepts only the CDN’s client certificate). If the app can also be reached directly, a client can send the header and choose its own IP.


When KIRAK_REDIS_URL is set in .env, Kirak stores rate-limit counters in Redis with native sliding-window expiration. This provides sub-millisecond overhead and synchronizes limits across multi-instance horizontal deployments.

When Redis is not configured, Kirak automatically utilizes the application database via the kirak_rate_limits table:

CREATE TABLE kirak_rate_limits (
key VARCHAR(255) PRIMARY KEY,
count INT NOT NULL DEFAULT 1,
window_start TIMESTAMP NOT NULL
);

Kirak executes rate-limit increments using an atomic upsert statement:

INSERT INTO kirak_rate_limits (key, count, window_start)
VALUES ($1, 1, $2)
ON CONFLICT (key) DO UPDATE SET
count = CASE WHEN kirak_rate_limits.window_start <= $3 THEN 1 ELSE kirak_rate_limits.count + 1 END,
window_start = CASE WHEN kirak_rate_limits.window_start <= $3 THEN $2 ELSE kirak_rate_limits.window_start END
RETURNING count, window_start;

This single atomic query eliminates race conditions without opening transactions or acquiring row-level database locks.


Kirak prioritizes service availability over strict throttling. The request is counted by the first backend that answers:

  1. Redis, when KIRAK_REDIS_URL is set. If Redis is unreachable, a warning is written to kirak.log ([RATE_LIMIT] Redis unreachable, counting in the database: <details>) and the request is counted in the database instead.
  2. The database (kirak_rate_limits). If it cannot count either, a warning is written ([RATE_LIMIT] Backend error (fail-open): <details>) and the request is permitted to proceed.

Auth routes are the exception. Sign-in, registration, password, email, phone and MFA routes are security controls, so when neither backend can count, they refuse the request with 503 AUTH_UNAVAILABLE (logged as [RATE_LIMIT] No backend could count ...; refusing (fail-closed)) instead of allowing it.

Under no circumstances will a rate-limiting infrastructure failure return 500 INTERNAL_ERROR to end users.


When a request is within quota, Kirak attaches standard rate-limiting headers to the HTTP response:

HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 84
X-RateLimit-Reset: 1731000000

When quota is exhausted, Kirak immediately terminates processing and returns:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 34
{
"statusCode": 429,
"status": "error",
"error": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests. Please try again later.",
"data": null
}