API Throttling and Rate Limits

Validation requests (POST /{version}/validate) are limited per API key and per organisation, as a number of requests per rolling minute. A busy or misbehaving client can no longer use up the capacity every other client shares, and an organisation can't get around its limit by creating more keys.

This page is for both sides: clients that call the API, and operators who set the limits. The endpoint itself is described in API Documentation.

At a glance

  • Each request is checked against two limits: its API key's, and its organisation's (all the organisation's keys together). It is served only if it fits both.
  • A request over a limit is answered 429 with problem type rate-limited and a Retry-After header. Nothing is validated, and the refused request counts towards no limit.
  • Every response to a limited key carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset.
  • Limits are stored in the database and managed with the command line (fv-admin limit …). Changes apply on every instance within about 10 seconds, without a restart.
  • Never limited: keys of the system organisation (any role), and every request while access control is disabled (FV_GLOBAL_DISABLED_ACL_SECURITY=true). ADMIN keys of other organisations are limited.
  • Only POST /{version}/validate is limited. Package reads, administrative endpoints, health and metrics are not.

How the limits work

A rolling minute. A limit of N means at most N served requests in any 60-second period, not per calendar minute. A burst just before and just after a full minute does not get twice the limit.

Two levels, both must fit. A key's own limit stops one client; the organisation's limit stops an organisation with many keys. When a request fits its key's limit but not its organisation's (or the other way round) it is refused, and it uses up nothing at either level.

Own limit, else the default, else none. A key or organisation without a limit of its own gets the service-wide default for its level. If an operator removes a default, keys (or organisations) without their own limit are not limited at that level. A level with no limit at all is neither counted nor reported in the headers.

Starting values (a fresh installation; operators can change all of them):

What Requests per minute
Default for any key without its own limit 600
Default for any organisation without its own limit 1200
The trial organisation 60
The trial validator key (from FV_VALIDATOR_API_KEY) 30

The upgrade never overwrites a value an operator has changed or removed, and neither does a restart or a rotation of FV_VALIDATOR_API_KEY.

For clients

Reading the headers

Every response from POST /{version}/validate to a limited key carries three headers: on 200, on 4xx and 5xx, and on

  1. They describe whichever of the two limits (key or organisation) leaves the least room; on a tie, the key's.
Header Meaning
RateLimit-Limit The per-minute limit that currently leaves the least room
RateLimit-Remaining Requests still allowed in the current rolling minute, after this one
RateLimit-Reset Seconds until the allowance next grows (when the oldest counted request leaves the window)
Retry-After On 429 only: seconds to wait before a retry can be served

Browsers can read them: they are listed in Access-Control-Expose-Headers when CORS is configured.

curl -s -o /dev/null -D - -X POST http://localhost:8880/R4/validate \
  -H "Authorization: Bearer $FV_VALIDATOR_API_KEY" -H 'Content-Type: application/fhir+json' \
  --data '{"resourceType":"Patient"}'
HTTP/1.1 200 OK
RateLimit-Limit: 30
RateLimit-Remaining: 29
RateLimit-Reset: 61

The 429 response

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 61
RateLimit-Limit: 5
RateLimit-Remaining: 0
RateLimit-Reset: 61
{
  "type": "https://nazrulworld.github.io/fhir-validation-service/problems/rate-limited",
  "title": "Too many requests",
  "status": 429,
  "detail": "This API key's rate limit of 5 validation requests per minute was reached; retry after 61 s",
  "correlationId": "c5011932-1eef-443d-aecd-b01d680ee6c1",
  "scope": "key",
  "limit": 5,
  "retryAfterSeconds": 61
}
Field Meaning
scope key: the API key's own limit was reached; organisation: the organisation's limit (all its keys together)
limit The per-minute limit that was reached
retryAfterSeconds The same value as Retry-After

When both limits are reached, the response reports the key's, with the longer of the two waits. The response never names or counts the organisation's other keys.

A refused request is not parsed or validated, so it is answered quickly. It is also not written to the usage records (validation_usage); it is counted in the fv_throttle_refused_total metric instead.

Handling it in a client

  1. Watch RateLimit-Remaining. When it reaches 0, slow down instead of waiting for a 429.
  2. On 429, wait Retry-After seconds, then retry the same request. Don't retry sooner: an early retry is refused again and uses nothing, but it adds load.
  3. If the service runs as several instances, a burst may get a 429 with a short Retry-After (2 seconds by default) while there is still room in the minute. The instances are catching up with each other's counts; retry after the advised wait.
  4. If you need more, ask the operator for a higher limit for your key or organisation. Creating more keys doesn't help when the organisation's limit is the one you reach ("scope": "organisation").

A minimal retry loop:

while :; do
  code=$(curl -s -o result.json -D headers.txt -w '%{http_code}' -X POST http://localhost:8880/R4/validate \
    -H "Authorization: Bearer $KEY" -H 'Content-Type: application/fhir+json' --data @patient.json)
  [ "$code" != 429 ] && break
  sleep "$(grep -i '^retry-after:' headers.txt | tr -dc '0-9')"
done

For operators

Managing limits

Limits are managed with the administrative command line in the service jar and image. It uses the same FV_PG_* settings as the service:

APP="docker compose run --rm validator fv-admin"        # jar install: APP="sudo fv-admin"
$APP limit list                                        # defaults, every organisation and key, the limit in effect
$APP limit list --org acme                             # one organisation
$APP limit set --key acme-ci --per-minute 120          # a key's own limit
$APP limit set --org acme --per-minute 300             # an organisation's limit (all its keys together)
$APP limit set --default-key --per-minute 1000         # keys without a limit of their own
$APP limit set --default-org --per-minute 5000         # organisations without a limit of their own
$APP limit remove --key acme-ci                        # back to the default key limit
$APP limit remove --default-org                        # organisations without their own limit: not limited
  • --per-minute is a whole number from 1 to 1 000 000.
  • Exit codes:

    Code Meaning
    0 done
    2 a bad value or option
    3 the key or organisation doesn't exist, e.g. error: not-found: API key 'acme-ci' not found
    4 the system organisation or one of its keys (The system organisation and its keys are never rate limited)
  • Every change is logged with the old and the new value, e.g. cli: limit set key=acme-ci id=… old=none new=120.
  • A limit on a revoked key is kept (and allowed to be set); it has no effect while the key is refused.

limit list shows, for every organisation and key, its own limit and the one in effect, with its source: own, default, none (not limited at that level) or not-throttled (the system organisation and its keys):

{
  "defaults": { "key": 600, "organisation": 1200 },
  "organisations": [
    { "name": "trial", "id": "00000000-0000-0000-0000-100000000002", "perMinute": 60,
      "effective": { "perMinute": 60, "source": "own" },
      "keys": [ { "name": "trial validator", "role": "VALIDATE", "revoked": false, "perMinute": 30,
                  "effective": { "perMinute": 30, "source": "own" } } ] }
  ]
}

Running instances pick a change up within FV_THROTTLE_CAPS_REFRESH_MS (10 seconds by default). No restart is needed.

Several instances

Instances share their counts through PostgreSQL once a second, so a limit applies to the whole service, not to each instance, however the load balancer spreads the requests. No validation request waits for the database: each instance counts in memory and exchanges counts in the background.

  • One instance: a limit is exact.
  • Several instances: in any rolling minute the service serves at most the limit plus 10 % of it (at least one request). For example, at most 33 for a limit of 30, or 6 for a limit of 5. To keep that bound, each instance holds back room for what the others may have served but not yet shared, so a burst on one instance is spread over a few seconds (429 with a short Retry-After).
  • Very small limits on several instances may serve slightly fewer than the limit (a limit of 5 on 3 instances: about 4 a minute).
  • Accepted exception: a limit smaller than the number of instances (e.g. 1 on 3 instances) can be exceeded by up to the number of other instances.
  • A new instance reports not ready until the others count it: rate limits not loaded while it reads the limits, then rate limits warming up (waiting for the other instances to count this one) for about two seconds (two sync intervals). A load balancer that follows readiness sends it no requests before that, so adding an instance never takes the service past a limit. If the database can't be reached, warm-up ends at once (local mode, below).

The counts live in two UNLOGGED tables, throttle_counts and throttle_instances. Instances delete rows older than two minutes themselves, so nothing needs to be scheduled. Losing the tables (a database crash or failover) only resets the counts.

When the database can't be reached

Each instance keeps enforcing every limit on its own counts, with the last limits it read: local mode. Validation is never refused because counts can't be shared, but a client can then get up to the limit times the number of instances per minute.

The instance logs one WARN, throttle: cannot share request counts (…); enforcing caps on this instance's counts only, and sets fv_throttle_local_mode to 1. When sharing works again it logs throttle: request counts shared again after <s> s, and the bound applies again within a minute.

Monitoring

Metric Type Meaning
fv_throttle_checked_total counter Validation requests checked against a limit
fv_throttle_refused_total{scope,reason} counter 429s: scope is key or organisation; reason is cap (limit reached) or unconfirmed (several instances catching up)
fv_throttle_tracked_subjects gauge Keys and organisations whose recent counts are held in memory
fv_throttle_evictions_total counter Counts dropped because FV_THROTTLE_MAX_TRACKED was reached
fv_throttle_peers gauge Other live instances seen in the last 5 seconds
fv_throttle_local_mode gauge 1 while counts can't be shared
fv_throttle_sync_failures_total{step} counter Failed count-sharing statements (flush, heartbeat, read, caps, cleanup, start)
fv_throttle_sync_seconds timer Duration of one count-sharing round
fv_throttle_ticks_skipped_total counter Rounds skipped because the previous one was still running

No metric carries a key, organisation or instance id. Suggested alerts: fv_throttle_local_mode == 1 for more than a minute; rate(fv_throttle_evictions_total[5m]) > 0 (raise FV_THROTTLE_MAX_TRACKED).

Refusals are logged at most once a minute per key or organisation, with the request id of the first:

throttle: key 00000000-0000-0000-0000-200000000002 (org 00000000-0000-0000-0000-100000000002) refused 2 request(s) in the last minute (cap 5); request c5011932-…

Settings

Variable Default Meaning
FV_THROTTLE_SYNC_INTERVAL_MS 1000 How often instances share their counts (200–1000 ms)
FV_THROTTLE_CAPS_REFRESH_MS 10000 How often limits are reloaded from the database (1000–30000 ms)
FV_THROTTLE_MAX_TRACKED 100000 Keys plus organisations whose recent counts are kept in memory (1000–10 000 000)

There is no on/off switch: limits apply exactly when access control is enabled. To limit nothing, remove the two defaults and every own limit. Memory: at most about 560 bytes per tracked key or organisation, so about 56 MB at the default FV_THROTTLE_MAX_TRACKED.

Questions

Why did I get 429 when RateLimit-Remaining said there was room? With several instances, a burst sent faster than the instances share their counts is paced: reason="unconfirmed" in the metrics, and a short Retry-After. Retry after it.

Does a request that fails validation count? Yes. Every served request counts, whatever its result: a valid or invalid resource, a 400 for a bad ig or profile, a 5xx. Only 429s don't count.

Does a bundle count as one request? Yes, one request counts as one, whatever its size.

Are 401 and 403 responses counted? No. A request without a valid key, or with a forbidden one, is refused before the limits are checked.

Can organisations see or change their own limits? No. Limits are set by operators with the command line.

Reference