Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* [FEATURE] Ruler: Add experimental support for federated rule groups. A rule group listing tenants in its `source_tenants` field is evaluated against those tenants while the resulting series and alerts are written to the tenant owning the rule group. Enabled with `-ruler.enable-federated-rules` (requires `-tenant-federation.enabled`), and restricted to selected tenants with `-ruler.allowed-federated-tenants` and `-ruler.disallowed-federated-tenants`. #7828
* [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873
* [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-<prefix>.oss.*` flags with `backend: oss`. #7907
* [FEATURE] Distributor: Add experimental client-identity ingestion rate limiting. A trusted `X-Scope-ClientID` header, set by the same gateway/proxy that already sets `X-Scope-OrgID`, can be rate-limited below the tenant level via `client_identity_ingestion_rate_limit`/`client_identity_ingestion_burst_size`/`client_identity_ingestion_tracked_clients_limit`. Disabled by default (0 = no behavior change); enforced cluster-wide via memberlist-gossiped counters across distributor replicas, needing no ring. See `docs/proposals/client-identity-ingestion-rate-limiting.md`.
* [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916
* [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #7973
* [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910
Expand Down
87 changes: 87 additions & 0 deletions docs/configuration/config-file-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3453,6 +3453,7 @@ The `consul_config` configures the consul client. The supported CLI flags `<pref
- _no prefix_
- `alertmanager.sharding-ring`
- `compactor.ring`
- `distributor.client-identity-rate-limit`
- `distributor.ha-tracker`
- `distributor.ring`
- `parquet-converter.ring`
Expand Down Expand Up @@ -3758,6 +3759,75 @@ ring:
# CLI flag: -distributor.ring.instance-interface-names
[instance_interface_names: <list of string> | default = [eth0 en0]]

client_rate_limit_kvstore:
# Backend storage to use for the ring. Supported values are: consul, dynamodb,
# etcd, inmemory, memberlist, multi.
# CLI flag: -distributor.client-identity-rate-limit.store
[store: <string> | default = "consul"]

# The prefix for the keys in the store. Should end with a /.
# CLI flag: -distributor.client-identity-rate-limit.prefix
[prefix: <string> | default = "distributor-client-identity-rate-limit/"]

# The consul_config configures the consul client.
# The CLI flags prefix for this block config is:
# distributor.client-identity-rate-limit
[consul: <consul_config>]

dynamodb:
# Region to access dynamodb.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.region
[region: <string> | default = ""]

# Table name to use on dynamodb.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.table-name
[table_name: <string> | default = ""]

# Time to expire items on dynamodb.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.ttl-time
[ttl: <duration> | default = 0s]

# Time to refresh local ring with information on dynamodb.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.puller-sync-time
[puller_sync_time: <duration> | default = 1m]

# Maximum number of retries for DDB KV CAS.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.max-cas-retries
[max_cas_retries: <int> | default = 10]

# Timeout of dynamoDbClient requests. Default is 2m.
# CLI flag: -distributor.client-identity-rate-limit.dynamodb.timeout
[timeout: <duration> | default = 2m]

# The etcd_config configures the etcd client.
# The CLI flags prefix for this block config is:
# distributor.client-identity-rate-limit
[etcd: <etcd_config>]

multi:
# Primary backend storage used by multi-client.
# CLI flag: -distributor.client-identity-rate-limit.multi.primary
[primary: <string> | default = ""]

# Secondary backend storage used by multi-client.
# CLI flag: -distributor.client-identity-rate-limit.multi.secondary
[secondary: <string> | default = ""]

# Mirror writes to secondary store.
# CLI flag: -distributor.client-identity-rate-limit.multi.mirror-enabled
[mirror_enabled: <boolean> | default = false]

# Timeout for storing value to secondary store.
# CLI flag: -distributor.client-identity-rate-limit.multi.mirror-timeout
[mirror_timeout: <duration> | default = 2s]

# EXPERIMENTAL: Length of the fixed window per-(tenant, client) request counters
# are kept over, and the interval they're gossiped to and pruned from other
# distributors at. See
# docs/proposals/client-identity-ingestion-rate-limiting.md.
# CLI flag: -distributor.client-identity-rate-limit.window
[client_rate_limit_window: <duration> | default = 1s]

# EXPERIMENTAL: Number of go routines to handle push calls from distributors to
# ingesters. When no workers are available, a new goroutine will be spawned
# automatically. If set to 0 (default), workers are disabled, and a new
Expand Down Expand Up @@ -3831,6 +3901,7 @@ The `etcd_config` configures the etcd client. The supported CLI flags `<prefix>`
- _no prefix_
- `alertmanager.sharding-ring`
- `compactor.ring`
- `distributor.client-identity-rate-limit`
- `distributor.ha-tracker`
- `distributor.ring`
- `parquet-converter.ring`
Expand Down Expand Up @@ -4540,6 +4611,22 @@ The `limits_config` configures default and per-tenant limits imposed by Cortex s
# CLI flag: -distributor.native-histogram-ingestion-burst-size
[native_histogram_ingestion_burst_size: <int> | default = 0]

# [Experimental] Per-client (X-Scope-ClientID) ingestion rate limit in samples
# per second, applied in addition to the per-tenant limit above. 0 disables this
# check (default; no behavior change).
# CLI flag: -distributor.client-identity-ingestion-rate-limit
[client_identity_ingestion_rate_limit: <float> | default = 0]

# [Experimental] Per-client allowed ingestion burst size (in number of samples).
# CLI flag: -distributor.client-identity-ingestion-burst-size
[client_identity_ingestion_burst_size: <int> | default = 0]

# [Experimental] Per-tenant cap on the number of distinct client identities
# tracked for ingestion rate limiting; oldest-used entries are evicted once this
# is reached.
# CLI flag: -distributor.client-identity-ingestion-tracked-clients-limit
[client_identity_ingestion_tracked_clients_limit: <int> | default = 1000]

# Flag to enable, for all users, handling of samples with external labels
# identifying replicas in an HA Prometheus setup.
# CLI flag: -distributor.ha-tracker.enable-for-all-users
Expand Down
1 change: 1 addition & 0 deletions docs/configuration/v1-guarantees.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ Currently experimental features are:
- Accept multiple HA pairs in the same request (enabled via `-experimental.distributor.ha-tracker.mixed-ha-samples=true`)
- Accept Prometheus remote write 2.0 request (`-distributor.remote-writev2-enabled=true`)
- Use a goroutine worker pool for query fan-out calls to ingesters (`-distributor.num-query-workers`)
- Per-client (`X-Scope-ClientID`) ingestion rate limiting (`-distributor.client-identity-ingestion-rate-limit`, see [Client-Identity Rate Limiting](../guides/client-identity-rate-limiting.md))
- Tenant Deletion in Purger, for blocks storage.
- Blocks storage user index
- Store Gateway max concurrent fetched data bytes limit
Expand Down
79 changes: 79 additions & 0 deletions docs/guides/client-identity-rate-limiting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: "Client-Identity Rate Limiting"
linkTitle: "Client-Identity Rate Limiting"
weight: 10
slug: client-identity-rate-limiting
---

Cortex rate limits at the tenant level: every request is identified only by `X-Scope-OrgID`. When several independent writers share one tenant, one noisy client can exhaust the whole tenant's budget. Client-identity rate limiting adds an optional second dimension *below* the tenant, so a single client is throttled without affecting the others.

This feature is **experimental**. It is disabled by default and changes nothing for tenants that don't opt in. See the [design proposal](../proposals/client-identity-ingestion-rate-limiting.md) for the full rationale.

## How it works

A request is subject to the per-client check only when **both** conditions hold:

1. The tenant has a non-zero per-client rate limit configured.
2. The request carries a non-empty `X-Scope-ClientID` header.

If either is false, the request is handled exactly as before. A missing header is never an error.

The per-client check runs *in addition to* the existing checks, never instead of them. The tenant-level ingestion rate limit is evaluated first and remains the hard ceiling for the tenant as a whole.

### Distributed enforcement

Each distributor counts requests per `(tenant, client)` over a short fixed window (`-distributor.client-identity-rate-limit.window`, default `1s`) and gossips its own counts through a memberlist-backed KV store. Every replica merges the other replicas' counts and admits a request only if `own count + latest known count of every other replica` stays within the window's capacity, `limit * window + burst`.

Counts are never fetched synchronously on the request path, and no ring or per-request RPC is involved. As a result:

- A replica's view of its peers lags by up to one window, so a client spread evenly across many replicas can briefly exceed the limit by about one window's worth of requests.
- If the KV store is unavailable, enforcement continues on local and last-known peer state. It fails open and never blocks traffic because of a gossip failure.

### Bounded memory

The number of distinct clients is bounded only by the `X-Scope-ClientID` values a gateway sends, so tracking is capped per tenant by `client_identity_*_tracked_clients_limit` (default `1000`) with least-recently-used eviction. An evicted client that reappears starts from zero and can issue a fresh burst. Watch `cortex_distributor_client_identity_tracked_clients_evicted_total` to tell whether the cap is sized correctly or you are seeing identity churn.

## Header trust boundary

**`X-Scope-ClientID` is trusted exactly the way `X-Scope-OrgID` is.** Cortex does not authenticate it. It assumes a gateway or reverse proxy in front of Cortex authenticates the caller, strips any caller-supplied `X-Scope-OrgID` and `X-Scope-ClientID`, and sets both itself.

If Cortex's HTTP or gRPC endpoints are reachable by untrusted clients, a caller can set an arbitrary identity, for example to evade throttling by rotating values, or to frame another client. This is the same risk `X-Scope-OrgID` already carries, and the same guidance applies: never expose Cortex directly to untrusted clients. The per-tenant tracked-clients cap bounds the worst case to cache churn rather than unbounded memory growth.

The value is an opaque string. What it represents (API key ID, service account, workload identity, job name) is up to your gateway. Prefer a per-service or per-team identity over a per-end-user one, to keep the number of tracked clients small.

## Configuration

Enable gossip through memberlist first. The KV store defaults to `consul` like every other Cortex KV config, so set it to `memberlist` and configure `memberlist` as you would for the ring (see [Gossip Ring Getting Started](./gossip-ring-getting-started.md)):

```yaml
distributor:
client_rate_limit_kvstore:
store: memberlist
```

The KV client is created lazily, the first time a tenant actually exercises the feature, so deployments that never opt in start no KV client or watch. On the write path, `X-Scope-ClientID` is read from the HTTP headers (remote write, OTLP over HTTP) or the gRPC metadata (OTLP over gRPC).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The OTLP/HTTP handler doesn't read X-Scope-ClientID. Can we read it there or drop OTLP/HTTP from this list?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. OTLPHandler now injects X-Scope-ClientID the same way the remote write handler does, so the doc stays accurate. Added TestOTLPHandler_InjectsClientID.


Per-tenant limits, defaulting to `0` (disabled), set through `limits` or the runtime overrides:

```yaml
overrides:
tenant-123:
# Samples per second and burst in samples.
client_identity_ingestion_rate_limit: 5000
client_identity_ingestion_burst_size: 10000
client_identity_ingestion_tracked_clients_limit: 1000
```

Related flags:

- `-distributor.client-identity-rate-limit.store`: set to `memberlist`.
- `-distributor.client-identity-rate-limit.window`: fixed window length, default `1s`.

## Observability

- Rejected requests return HTTP `429` and are counted in `cortex_discarded_samples_total{reason="client_rate_limited"}` (and the matching exemplar and metadata counters) per tenant.
- Per-client visibility (which client tripped the limit) is in the `429` error message and request logs, deliberately not a metric label, to avoid multiplying metric cardinality by the number of clients.

## Known limitations

- Enforcement is approximate across replicas, as described above. A strictly authoritative limit would need ring-based shard ownership.
Loading
Loading