Skip to main content

Gateway Policy & Security

Per-API gateway policy for API Builder: rate limits, size caps, concurrency, request validation, caller identity, masking, headers, CORS, Idempotency-Key, deprecation and partner access tokens (JWT), plus the instance host allow-list and network protections.

Each API has a gateway policy that controls how the API Gateway treats its calls. Set it in the Gateway policy card on the API's edit page (while the API is in Draft or Rejected), or as gateway_policy in the API.

The defaults are deliberately safe for existing APIs: limits are generous, and the strict checks are opt-in per API.

Settinggateway_policy keyDefaultWhat it does
Calls per minute (API)rate_limit_per_minute600Total calls to this API per minute, across all users
Calls per minute (per user)user_rate_limit_per_minute120Calls per signed-in user per minute (needs a caller identity)
Max request sizemax_request_bytes5 MBLarger request bodies are refused with 413
Max response sizemax_response_bytes10 MBLarger upstream responses are refused with 502
Validate requests against the specvalidate_requestsOffRefuse calls that don't match the OpenAPI spec (400)
Require a signed caller identityrequire_caller_identityOffRefuse calls that don't carry a caller token (401)
Mask sensitive datamaskingNoneMask PAN, Aadhaar, card numbers, emails, mobile numbers or custom patterns in responses
Validate responses against the specvalidate_responsesOffwarn: pass through and flag; enforce: return 502 when the upstream breaks its contract
Cache GET (seconds)cache_ttl_seconds0 (off)Serve repeated successful GETs from cache, up to 3600 s
Pause after failuresbreaker_failure_threshold5Consecutive upstream failures before calls are paused (0 = never)
Pause for (seconds)breaker_cooldown_seconds30How long calls stay paused before a trial call
Alert webhookalert_webhook_urlNoneGets a JSON (Slack-compatible) message when calls pause and when they resume
Upstream timeout (seconds)upstream_timeout_seconds60How long the upstream may take to answer each attempt, up to 600 s; then 504 upstream_timeout
Calls at once (per worker)max_concurrent_calls100Upstream calls to this API in progress at once, per gateway worker; more wait up to a second, then get 503 upstream_busy (0 = no limit). See Concurrency and overload
Idempotency-Key kept (seconds)idempotency_ttl_seconds0 (off)A POST or PATCH repeated with the same Idempotency-Key header gets the first response, up to 86400 s. See Idempotency-Key
Web pages that may call this APIcors_allowed_originsStudio's settingThe sites whose pages may call the API from a browser. See CORS for web pages
Caller headers passed to the upstreamforward_request_headersSee HeadersCaller headers the upstream receives
Upstream headers returned to callersforward_response_headersSee HeadersUpstream headers callers receive
Deprecated from, Sunset ondeprecated_at, sunset_atNoneDates sent as Deprecation and Sunset headers. See Deprecation and sunset
Migration guide URLdeprecation_linkNoneSent as a Link header with every response
Partner access tokensjwt_authOffAccept access tokens (JWTs) from the partner's own identity provider. See Partner access tokens

Leave a limit empty to use the instance default. Instance defaults come from environment variables (see Configuration).

In the API, sizes are in bytes (the form shows MB: 10 MB = 10485760), validate_responses is off, warn or enforce, and masking is {"presets": [...], "custom": [{"pattern": "...", "replacement": "..."}]} with the presets pan_in, aadhaar, card_number, email and phone_in. Saving a policy through the API replaces the whole of it (the form keeps the keys it doesn't show); any other key is refused with 422 Unknown gateway_policy keys, which lists the valid ones. For example, 650 calls a minute, 200 per user and 10 MB both ways:

json
{
  "rate_limit_per_minute": 650,
  "user_rate_limit_per_minute": 200,
  "max_request_bytes": 10485760,
  "max_response_bytes": 10485760
}

Rate Limits​

Two rolling one-minute limits apply to every call: one for the whole API and one per caller (the signed-in user, the consumer key, or the subject of a partner access token). A call over either limit gets:

HTTP/1.1 429 Too Many Requests
Retry-After: 6

{"error": "rate_limited", "message": "Rate limit exceeded for this API (600 calls per minute). Retry shortly.", "reference": "..."}

Limits are counted in Redis when it's configured, in one round trip per call (so they hold across multiple Hrida.ai replicas and gateway pods), and in memory otherwise. Refused calls count toward the limit, so a looping agent can't hammer the upstream by retrying instantly.


Size Caps​

  • Requests — checked from Content-Length before the body is read, and again while it's read.
  • Responses — read in chunks; the read stops as soon as the cap is passed, so a single huge upstream response can't exhaust server memory.
  • JSON nesting depth (max_json_depth, off by default) — a JSON request body nested deeper than this many levels of objects and arrays is refused with 400 request_too_deep before anything parses it, so a small crafted body can't exhaust the parser or a mapper. Brackets inside strings don't count, and bodies that aren't JSON aren't checked. 32 suits nearly every API; the maximum is 1000. An admin can set it for a whole gateway under Admin › API Platform.

Request Validation​

With Validate requests against the OpenAPI spec on, the gateway checks each call before it reaches any mapper or the upstream:

  • Path and query parameters — required parameters present, values match their schema type (integers, numbers, booleans) and constraints.
  • JSON request body — validated against the operation's requestBody schema, including $refs into components (OpenAPI 3) or definitions (Swagger 2), and OpenAPI 3.0 nullable.
json
{
  "error": "request_invalid",
  "message": "Request does not match the API specification: body.amount: 0 is less than the minimum of 1; body: 'currency' is a required property",
  "reference": "..."
}

The message lists up to 20 problems so the calling agent can correct its request. Turn it on once your spec accurately describes the upstream — a loose or incomplete spec will refuse valid calls.


Mock Responses​

With Mock responses on (mock_responses: true), the gateway answers every operation from the spec and never calls the upstream. Use it to build, test and demo agents before the backend exists, or while it's down for maintenance.

The answer is the operation's first success response (2xx, else default):

  1. its example: OpenAPI 3 example, the first of examples, or Swagger 2 examples for application/json;
  2. otherwise a sample built from its schema: the schema's own example or default, an enum's first value, a value fitting the format (dates, UUIDs, emails…), every property, and one array item, following $refs and stopping at recursion;
  3. otherwise no body, e.g. for 204.

Everything before the upstream still runs: authentication, rate limits, quotas, and request validation when it's on. Masking applies to the mocked answer. Responses carry X-Hrida-Mock: true and X-Hrida-Warning: mock, and the call log marks the calls mock.

The API's page shows a Mock responses on badge while it's on. Like the rest of the policy, it applies to every environment, prod included, as soon as you save, even while the API is a draft being revised. Turn it off before real use: agents get sample data, not real data.


Caller Identity​

With Require a signed caller identity on, the API only accepts calls made by Hrida.ai agents on behalf of a signed-in user. Every call is then attributed to a user in the call log, counted against the per-user limit, and re-checked against the API's access grants.

Leave it off for APIs that automations or scheduled jobs call without a user context. When it's off, a caller token is still verified and enforced if one is sent. See Caller identity for how the token works.


Response Masking​

Masking replaces sensitive values in responses before they reach the agent (and therefore the model). It applies to every string in a JSON response, including nested values, and to text responses such as XML or CSV.

PresetExample inputMasked
PAN (India)ABCDE1234FAB******4F
Aadhaar2345 6789 0123XXXX XXXX 0123
Card numbers4111 1111 1111 1111**** **** **** 1111
Email addressesasha.rao@bank.ina***@bank.in
Mobile numbers (India)+91 98765 43210******3210
  • Card numbers are only masked when they pass the Luhn checksum, so other long numbers (order ids, references) are left alone.
  • Aadhaar ignores 12-digit runs that are part of a longer number.
  • Custom rules take a regular expression (up to 200 characters, checked when you save) and a replacement, for example ACC-\d+ → ACC-****.
  • Custom patterns are time-limited: each runs for at most 50 ms on a value. One that takes longer masks the whole value (****) rather than holding up the call, and a pattern that backtracks badly on some inputs, such as (a+)+$, is refused when you save.

Masking runs after the response mappers, so it also covers fields a mapper adds. Individual strings over 100 KB are not masked.


Response Validation​

With Validate responses on, every successful JSON response is checked against the schema the spec declares for that status code (exact code, then 2XX, then default). Responses with no declared schema are not checked. The check runs after the operation's response mappers, on what the agent will receive — the spec describes the agent-facing shape, the same one request validation checks.

ModeWhen the response doesn't match
WarnIt is returned unchanged; the call log shows ⚠ response_invalid and the response carries X-Hrida-Warning: response_invalid
EnforceThe caller gets 502 response_invalid listing where and which rule failed

Messages name the field and the rule (response.id: fails "type"), never the value, so validation can't leak data that masking would have hidden. Validation runs on the upstream's shape, before response mappers.

GET Response Cache​

Set Cache GET (seconds) to serve repeated successful GET calls without calling the upstream. The key is the API, environment, version, path and query string, so a new version never serves an old version's responses.

  • Only 2xx responses up to 1 MB are cached.
  • The raw upstream response is cached: mappers and masking still run on every call, so changing them takes effect at once.
  • Rate limits still apply to cached calls.
  • The response carries X-Hrida-Cache: HIT or MISS, and the call log marks cached calls.
  • Shared across replicas through Redis when it's configured, otherwise per process.

Only use it for data that may be up to the TTL old.

Circuit Breaker and Alerts​

When the upstream fails several times in a row — unreachable, timing out, or answering 5xx after the gateway's own retries — the gateway pauses calls for the cooldown instead of piling more load on a struggling service:

  • Paused calls get 503 upstream_circuit_open with a Retry-After header, and the upstream isn't called. Cached responses are still served.
  • After the cooldown, exactly one trial call is let through, across all replicas, while the others keep getting 503: success resumes normal traffic, failure pauses again.
  • With Redis, failures from every replica count together and each update is atomic. A worker that last found the upstream healthy checks again at most every second (API_GATEWAY_BREAKER_SYNC_SECONDS), so a pause decided elsewhere reaches it within about a second, and a healthy API costs no Redis round trips.
  • 4xx responses never count; they're the caller's problem, not the upstream's.
  • Each environment has its own breaker.

With an Alert webhook set, the gateway POSTs a JSON message when calls pause and when they resume:

json
{"text": ":red_circle: API \"Customers\" (prod): upstream failing — gateway paused calls for 30s after 5 failures in a row. Last error: HTTP 503",
 "event": "breaker_opened", "api_definition_id": "…", "environment": "prod", "failures": 5, "cooldown_seconds": 30, "last_error": "HTTP 503"}

The text field works with Slack and Teams incoming webhooks. The URL must be public; internal and metadata addresses are refused.

The Environments card shows each environment's breaker (failures in a row, last error) with a Reset button to resume calls at once. Also available as GET /api/v1/api-definitions/{id}/gateway-health and POST …/gateway-health/reset.

Concurrency and Overload​

A slow or hung upstream shouldn't take every connection and worker down with it. Three limits protect the gateway, each per gateway worker process:

LimitSettingDefaultPast it
Calls to one API at onceCalls at once (max_concurrent_calls)100The call waits up to API_GATEWAY_QUEUE_TIMEOUT_MS (1 second) for a slot, then gets 503 upstream_busy with Retry-After: 1
Gateway calls at once, all APIsAPI_GATEWAY_MAX_IN_FLIGHT1000503 overloaded at once, with Retry-After: 1, instead of queueing until every call times out
RetriesAPI_GATEWAY_RETRY_BUDGET_RATIO0.2Retries spend a budget that calls earn, one retry per five calls by default, so retries can't multiply the load on a failing upstream. Past it, the failure is returned

Retries wait an exponential backoff with random jitter, so callers that failed together don't all retry at the same moment. A response streamed to the caller keeps its slot until it ends. Identical GETs that miss the cache at the same moment share one upstream call.

Headers​

By default the gateway passes these caller headers to the upstream:

Accept-Language, If-Match, If-None-Match, If-Modified-Since, If-Unmodified-Since, Idempotency-Key, Prefer, X-Request-Id

and returns these upstream headers to the caller:

Location, Content-Location, Content-Disposition, Content-Language, ETag, Last-Modified, Cache-Control, Expires, Link, Retry-After, RateLimit, RateLimit-Policy, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-Total-Count, Deprecation, Sunset, Preference-Applied

Set Caller headers passed to the upstream and Upstream headers returned to callers (forward_request_headers, forward_response_headers, at most 50 names each) to change the lists; leave them empty for the defaults.

  • Upstream URLs in Location, Content-Location and Link are rewritten to the gateway URL the caller used, so callers keep going through the gateway and never see the upstream's address.
  • Some headers can't be listed, because the gateway owns them: credentials and cookies (Authorization, Cookie, Set-Cookie, WWW-Authenticate), framing and connection headers (Host, Content-Length, Content-Type, Transfer-Encoding, …), trace context, security headers, anything starting with Access-Control-, Proxy- or X-Hrida-.

Idempotency-Key​

Payment and order APIs often take an Idempotency-Key header, so a client that lost the answer can safely send the request again. Set Idempotency-Key kept (seconds) to have the gateway guarantee it, whatever the upstream does:

  • A POST or PATCH repeated with the same Idempotency-Key by the same caller within that time gets the first response again, marked Idempotent-Replayed: true. The upstream isn't called a second time.
  • A repeat while the first is still running gets 409 idempotency_in_progress with Retry-After: 1.
  • The same key with a different request (method, path, query or body) gets 422 idempotency_key_reused.
  • 5xx responses and failed calls aren't kept, so the caller can retry with the same key. Neither are responses over 1 MB or streamed ones.
  • Keys belong to their caller: two consumer keys using the same Idempotency-Key value never collide. A key over 255 characters gets 400 idempotency_key_invalid.

Keys are kept in Redis when it's configured, so every replica and gateway pod sees them. Without Redis each process keeps its own, which is only a best effort.

CORS for Web Pages​

A browser lets a web page on another site call your API only if the gateway allows that site (CORS). Web pages that may call this API (cors_allowed_origins) sets it per API:

Settingcors_allowed_originsEffect
Studio's settingnot setThe instance's CORS_ALLOW_ORIGIN, as before this setting existed
None[]No web page on another site may call the API
Only these sites["https://app.example.com"]Exactly these origins (scheme://host[:port]), or ["*"] for any site
  • The gateway answers the browser's preflight (OPTIONS) itself, per API. It never reaches the upstream and isn't logged.
  • Allowed responses, errors included, carry Access-Control-Allow-Origin and let the page read the gateway's headers and the forwarded ones. Cookies are never allowed (Access-Control-Allow-Credentials is never sent): callers authenticate with a Bearer token.
  • Calls from servers, scripts and agents aren't affected: CORS only concerns browsers.
Keys in web pages

Anyone who opens a page can read a consumer key in it. For browser apps, prefer partner access tokens, which expire, or restrict the key with allowed addresses and quotas.

Deprecation and Sunset​

When an API is going away, tell its callers in every response, errors included:

  • Deprecated from (deprecated_at) → Deprecation: @1767225600 (RFC 9745). The date may be in the past or the future.
  • Sunset on (sunset_at) → Sunset: Wed, 30 Jun 2027 00:00:00 GMT (RFC 8594).
  • Migration guide URL (deprecation_link) → Link: <https://docs.example.com/migrate>; rel="deprecation"; type="text/html".

Dates are YYYY-MM-DD (midnight UTC), or a full ISO 8601 date and time through the API, and the sunset can't be before the deprecation. Calls keep working after the sunset date: unpublish the API, or move its callers to a new version, to stop them.

Partner Access Tokens (JWT)​

Instead of a consumer key, a partner's systems can call the API with an access token from the partner's own identity provider: Microsoft Entra ID, Okta, Auth0, Keycloak and the like. Turn on Accept access tokens from the partner's identity provider (JWT) and set:

Fieldjwt_auth keyExample
Issuerissuerhttps://login.example.com/: the token's iss claim must equal it
Audienceaudienceorders-api: the token's aud must include it
JWKS URLjwks_urlhttps://login.example.com/.well-known/jwks.json: the provider's published signing keys
Required scopesrequired_scopesorders:read: every token must carry them in scope (or scp)

The caller sends the token as Authorization: Bearer <token>. The gateway checks:

  • the signature, against the provider's keys. Only asymmetric algorithms are accepted (RS*, PS*, ES*, EdDSA); none and HMAC are refused;
  • the issuer, audience, expiry and not-before, with 60 seconds of clock leeway;
  • the required scopes: a token without them gets 403 insufficient_scope, with a WWW-Authenticate header naming them.

A token that fails a check gets 401 unauthorized and counts as a failed login. The caller is known by the token's subject (sub): it gets its own per-caller rate limit, and the call log shows it as jwt:<subject>. A token can also read the spec at the gateway URL. As with consumer keys, an API that requires a signed caller identity refuses partner tokens.

The signing keys are fetched through the gateway's own connection pool, with the same address checks and host allow-list as upstreams, and kept for 10 minutes (API_GATEWAY_JWKS_CACHE_SECONDS). A token signed with a key the gateway doesn't have makes it fetch them again, at most every 30 seconds, so the provider's key rotation is picked up at once. If the provider can't be reached and no keys are cached, calls get 503 jwks_unavailable.

Failed Logins​

A made-up consumer key costs the gateway little: it's recognised in memory, without a database query. To keep floods of guesses out of the call log too, an address with more than API_GATEWAY_AUTH_FAILURES_PER_MINUTE (30) failed logins in a minute gets 429 auth_throttled with Retry-After: 60 for further failures, and those aren't logged. A failed login is a wrong or unknown consumer key, gateway secret or partner token. Only failures count: a valid credential keeps working from that address, since several callers can share one address behind NAT.

The address is the client's as the gateway sees it, from X-Forwarded-For: see client addresses behind a load balancer for what to trust.

Upstream Host Allow-List​

Admins can restrict which hosts any API's upstream may point at. Open API Builder → Gateway settings (admins only) and list one host per line:

api.partner.com
*.bank.internal
  • *.bank.internal matches any subdomain of bank.internal, but not bank.internal itself.
  • An empty list allows any host (subject to the network protections below).
  • The list is checked when an API is saved, when it's published, and on every gateway call — tightening the list immediately blocks published APIs on hosts that are no longer allowed (502 upstream_blocked).

The initial value can come from API_BUILDER_UPSTREAM_ALLOWED_HOSTS (comma-separated); after that it's managed in the UI.


Network Protections​

These apply to every API regardless of policy:

  • Upstream URLs must be absolute http/https URLs with no credentials embedded (put credentials in the auth settings).
  • Internal addresses are blocked — loopback (localhost, 127.0.0.1, ::1), link-local and cloud-metadata addresses (169.254.0.0/16, including 169.254.169.254), unspecified and multicast addresses. Private networks such as 10.x and 192.168.x stay allowed, since internal enterprise APIs are a primary use case.
  • Every new connection checks the addresses the upstream's host name resolves to, so a host name that later starts resolving to a blocked address (DNS rebinding) is still refused.
  • Path tricks — . and .. segments are refused, and only operations in the spec are reachable.
  • XML from upstreams and samples is parsed with protections against entity-expansion and external-entity attacks.

API_BUILDER_ALLOW_LOCAL_UPSTREAMS=true allows loopback upstreams for local development. Link-local and metadata addresses stay blocked even then.


Configuration​

Environment variableDefaultPurpose
API_GATEWAY_RATE_LIMIT_PER_MINUTE600Default calls per minute per API
API_GATEWAY_USER_RATE_LIMIT_PER_MINUTE120Default calls per minute per user
API_GATEWAY_MAX_REQUEST_BYTES5242880Default max request body (bytes)
API_GATEWAY_MAX_RESPONSE_BYTES10485760Default max upstream response (bytes)
API_GATEWAY_CALLER_TOKEN_TTL_SECONDS900Lifetime of caller identity tokens
API_GATEWAY_CALL_LOG_RETENTION_DAYS30How long call log rows are kept
API_GATEWAY_BREAKER_FAILURES5Default consecutive failures before calls pause (0 = off)
API_GATEWAY_BREAKER_COOLDOWN_SECONDS30Default pause length
API_GATEWAY_UPSTREAM_TIMEOUT_SECONDS60Default upstream timeout per attempt, in seconds. When unset, AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER is used if set
API_GATEWAY_MAX_CONCURRENT_CALLS100Default calls to one API at once, per gateway worker (0 = no limit)
API_GATEWAY_MAX_IN_FLIGHT1000Gateway calls at once per worker, all APIs, before 503 overloaded (0 = no limit)
API_GATEWAY_QUEUE_TIMEOUT_MS1000How long a call waits for a slot of its API before 503 upstream_busy
API_GATEWAY_RETRY_BUDGET_RATIO0.2Retries each call earns (0.2 = one retry per five calls)
API_GATEWAY_STREAM_THRESHOLD_BYTES1048576A response nothing changes is streamed to the caller when it is larger than this, or doesn't declare its length
API_GATEWAY_AUTH_FAILURES_PER_MINUTE30Failed logins per address and minute before 429 auth_throttled (0 = no limit)
API_GATEWAY_CLIENT_CERT_HEADER(unset)The header your TLS-terminating proxy passes the client certificate in, for keys bound to a certificate
API_GATEWAY_BREAKER_SYNC_SECONDS1How long a worker trusts that an upstream is healthy before checking the shared breaker again (0 = on every call)
API_GATEWAY_JWKS_CACHE_SECONDS600How long partner identity providers' signing keys are kept
SAFE_EVAL_MAX_STEPS250000Steps one mapper expression may take; past it the mapping fails instead of holding up the worker
REDIS_URL(unset)Shares rate limits, cache and breaker state across replicas; without it each process keeps its own (a warning is logged at startup)
API_BUILDER_UPSTREAM_ALLOWED_HOSTS(empty)Initial host allow-list, comma-separated
API_BUILDER_ALLOW_LOCAL_UPSTREAMSfalseAllow loopback upstreams (local development only)
ENABLE_API_BUILDERtrueTurn API Builder on or off for the whole instance

The features.api_builder user permission controls which non-admin users can use API Builder. Both it and ENABLE_API_BUILDER are enforced by the server, not just by hiding the menu.


Hrida.ai is proprietary software of Zlabs Innovation. See the license for terms. © 2026 Zlabs Innovation.