Scaling Prometheus: Federation, remote_write, Thanos, Mimir, VictoriaMetrics
Why One Prometheus Hits a Wall
- Memory is proportional to active series. Every active series holds an in-memory head series with its labels, index postings and the current chunk (see Prometheus). A rough planning figure is a few KB per active series, so a server with a few million series needs tens of GB; there is no sharding inside one process.
- One writer, one disk. The TSDB is local and single-writer. Local retention is bounded by one disk (default 15 days), and losing the disk loses history.
- No built-in HA or global view. Two Prometheus servers running the same config scrape independently and hold slightly different data (different scrape phases). Nothing merges them, and a query cannot span servers.
- Long-range queries are slow: a year of data at 15 s resolution is 2 million samples per series.
The first three moves stay inside plain Prometheus.
HA Pairs, Sharding, Federation
HA pair
Run two identical servers scraping the same targets, each with a distinct external label (replica: a / b). If one dies, the other has the data and keeps alerting (both alert; Alertmanager dedups, see Alerting and SLOs). Cost: twice the storage and scrape load. Anything that queries them must deduplicate by dropping the replica label and picking a series, which plain Prometheus cannot do and Thanos, Mimir and VictoriaMetrics all can.
Sharding by hashmod
Split the targets across N servers with relabeling: each keeps only the targets whose address hashes to its shard number. Each server then holds 1/N of the series. A global query needs an aggregation layer on top.
scrape_configs:
- job_name: pods
kubernetes_sd_configs: [{role: pod}]
relabel_configs:
- source_labels: [__address__]
modulus: 4 # 4 shards
target_label: __tmp_hash
action: hashmod
- source_labels: [__tmp_hash]
regex: "1" # THIS server is shard 1
action: keepFederation lets one Prometheus scrape another's /federate endpoint, which returns the latest sample of series chosen by match[] selectors, for example in a hierarchy where a global server scrapes pre-aggregated job:* recording rules from each regional server.
- job_name: federate
honor_labels: true # keep the source's job/instance labels
metrics_path: /federate
params: {'match[]': ['{__name__=~"job:.*"}']} # only recording-rule outputs
static_configs: [{targets: ['prom-eu:9090', 'prom-us:9090']}]Federation is discouraged for bulk copying: the federating server scrapes it like a target, so it only sees the latest sample per interval (no backfill if the link is down), it gets new timestamps and staleness semantics, the response is one large text payload that must fit in a scrape timeout, and the global server ends up needing the memory it was meant to avoid. Use it for a small set of pre-aggregated series only.
remote_write and Prometheus Agent Mode
remote_write streams samples to an external system as they are ingested. A queue manager per destination tails the WAL (it does not read the TSDB blocks), decodes the series, and distributes samples across shards, each a goroutine with its own queue that batches samples into protobuf+snappy HTTP requests. The shard count adapts automatically between min_shards and max_shards based on incoming rate versus send rate.
remote_write:
- url: https://mimir.example.com/api/v1/push
queue_config:
capacity: 10000 # samples buffered per shard; aim for 3-10x max_samples_per_send
max_shards: 50 # ceiling on parallel senders
min_shards: 1
max_samples_per_send: 2000 # batch size
batch_send_deadline: 5s # send a partial batch after this
min_backoff: 30ms # doubles on each retry up to max_backoff
max_backoff: 5s
write_relabel_configs: # drop what you won't query remotely
- source_labels: [__name__]
regex: "go_.*|process_.*"
action: dropBackpressure: if a shard's queue fills, Prometheus stops reading the WAL for all shards, so one slow endpoint stalls the whole stream. Failed requests (5xx, 429) are retried with exponential backoff; 4xx other than 429 are dropped as unrecoverable. Memory cost is about shards × (capacity + max_samples_per_send) samples, plus roughly 25% more RSS overall from the series cache.
Remote Write 2.0 is a revised protocol (content type application/x-protobuf;proto=io.prometheus.write.v2.Request) that deduplicates label strings through a symbols table (large bandwidth savings), carries metric type, help and unit metadata per series, supports native histograms and created timestamps, and lets receivers report exactly how many samples were accepted via response headers. As of this writing the spec is still labelled experimental (release candidate), so confirm that your sender and receiver both support it before enabling it. For sending native histograms (stable in Prometheus since v3.8 for storage and scrape, see Metrics) over remote write v1, set send_native_histograms: true on the remote_write block; otherwise the histograms are stored locally but never leave.
Agent mode (prometheus --agent) is Prometheus stripped to a scraper-forwarder: it scrapes, writes to a WAL, remote_writes, and truncates the WAL once data is acknowledged. It has no local query API, no alerting or recording rules, and no long-term blocks, so it uses far less disk and memory. It suits edge clusters feeding a central Thanos Receive, Mimir or VictoriaMetrics. Grafana Alloy and the OpenTelemetry Collector's Prometheus receiver can play the same role.
Thanos
Thanos turns a fleet of Prometheus servers into one queryable, long-retention system with object storage as the cold tier. Prometheus remains the place where scraping and the first 2 hours live.
- Sidecar: runs beside each Prometheus, uploads each newly cut 2-hour block to the bucket, and serves the recent head/WAL data to queriers over the StoreAPI (gRPC). Prometheus must be run with
--storage.tsdb.min-block-duration=2handmax-block-duration=2h(local compaction disabled), so that blocks are uploaded uncompacted and Thanos compacts them itself. - Store Gateway: serves blocks from object storage, caching only block index headers locally and fetching chunk byte ranges on demand.
- Querier: stateless; it fans a PromQL query out to every StoreAPI endpoint (sidecars for recent data, Store Gateways for old), merges the series, and deduplicates on the labels you name with
--query.replica-label=replica(it treats series that differ only in that label as one and fills gaps from the other replica). - Query Frontend: splits long range queries by interval and caches results, as in Cortex.
- Compactor: the only component that writes to the bucket's old data. It merges blocks (2 h → 8 h → 2 d → 14 d), applies retention, and downsamples: a 5-minute-resolution copy for blocks older than about 40 hours and a 1-hour copy for blocks older than about 10 days. Each downsampled sample stores several aggregates (count, sum, min, max, counter) so
rate()and averages still work. Downsampling does not save space (the raw blocks stay unless you set shorter--retention.resolution-raw); it makes year-long queries fast. There must be exactly one compactor per bucket. - Ruler: evaluates recording and alerting rules against the Querier (so rules can see global data) and sends alerts to Alertmanager.
- Receive: the push-based alternative. Prometheus remote_writes into Receive, which stores the data in its own TSDB, replicates it among Receive nodes via a hashring, and uploads blocks. Use it where a pull from the sidecar is impossible (edge, multi-tenant, agent mode).
Cortex to Grafana Mimir
Cortex is the original horizontally-scaled, multi-tenant, remote_write-fed Prometheus backend (CNCF). Grafana Mimir is a fork of Cortex announced in March 2022 under AGPLv3 and run by Grafana Labs. Cortex remains a CNCF project; Mimir has since diverged substantially. Mimir stores per-tenant TSDB blocks in object storage, like Thanos, but in a push-based, microservices design with a hash ring for distribution.
Write path
A distributor authenticates the tenant (X-Scope-OrgID), validates and rate-limits samples, deduplicates HA pairs using the HA tracker (a KV store elects one replica per cluster), and shards each series by a hash of its labels. In the classic architecture, the hash selects 3 ingesters on a consistent hash ring (replication factor 3, zone-aware), and the write succeeds when a quorum of 2 acknowledges. Each ingester holds the recent window in a per-tenant in-memory TSDB with a WAL and, every 2 hours, cuts a block and uploads it to object storage.
What changed in Mimir 3.0
Mimir 3.0 (late 2025) made the ingest storage architecture the preferred design (classic is still supported; it is opt-in and must be enabled in all components). Distributors now write to a Kafka topic instead of directly to ingesters; each ingester consumes exactly one partition (per zone) and builds its own TSDB, so Kafka, not the ingester ring, provides replication and durability. Writes and reads are decoupled: a burst of queries can no longer slow ingestion, and ingesters can restart and resume from their stored offset. The price is a new stateful dependency (Kafka brokers, retention, lag alerts). The same release removed the experimental read-write deployment mode.
Read path
The query-frontend splits long queries by time, shards them, and caches results; queued sub-queries (optionally via a query-scheduler) are pulled by queriers, which merge recent data from ingesters and older blocks from store-gateways (which are sharded over the block set by their own hash ring and cache index headers). The compactor merges the small per-ingester blocks into larger per-tenant ones and removes duplicate samples left by replication. In ingest storage mode, reads are eventually consistent by default; a strong-consistency header makes ingesters first catch up to the latest Kafka offset (the ruler uses this for rules that depend on each other).
VictoriaMetrics
VictoriaMetrics (VM) is an independent Prometheus-compatible TSDB, not a Thanos or Cortex derivative, with its own compression and storage engine (MergeTree-style, with typically lower memory and disk use per series than Prometheus). Single-node VM is one binary that accepts remote_write, scrapes with Prometheus configs (via vmagent), and serves PromQL and its superset MetricsQL; it vertically scales a long way and is the simplest option here. Cluster VM splits into vminsert (stateless; hashes series to storage nodes), vmstorage (stateful, shared-nothing, owns a subset of the data) and vmselect (stateless; queries all vmstorage nodes and merges). Replication across vmstorage nodes is done by vminsert writing each sample to N nodes (-replicationFactor) and vmselect deduplicating (-dedup.minScrapeInterval). There is no object-storage tier in the open-source core; it relies on local disks (cheap, fast) and backups via vmbackup.
Choosing: Comparison
| Option | Ingest | Long-term storage | HA / dedup | Operational weight | Notable |
|---|---|---|---|---|---|
| Thanos | Sidecar (pull of blocks) or Receive (remote_write) | Object storage blocks; downsampling 5m / 1h | Querier dedup on replica label | Many small components; Prometheus stays the hot store | Smallest step from an existing Prometheus; global view by fan-out |
| Mimir | remote_write (and OTLP) only | Object storage blocks; per-tenant | HA tracker in distributors; ring replication or Kafka | Heaviest: microservices, ring, now Kafka | Multi-tenant at very large scale, strong limits and isolation |
| VictoriaMetrics | remote_write, vmagent, many protocols | Local disk (no object tier in OSS) | Replication factor + dedup on read | Lightest: single binary or 3 component types | Efficient storage; MetricsQL differs from PromQL in places |
| Amazon Managed Service for Prometheus | remote_write, OTLP | Managed, fixed retention | Handled by AWS (HA pair dedup via labels) | None to run; pay per sample ingested/stored/queried | Pairs with AWS-managed Grafana |
| Grafana Cloud (Mimir) | remote_write, OTLP, Alloy | Managed Mimir | Managed | None to run; billed per active series | Cardinality is the bill (see Cost and vendors) |
| Google Managed Service for Prometheus | Managed collectors or self-deployed | Monarch (Google's global TSDB) | Managed | None to run; billed per sample | PromQL over Cloud Monitoring data; very long retention |
Rule of thumb: stay on one Prometheus (or an HA pair) until you hit memory or retention limits; add Thanos if you already have many Prometheus servers and want a global view without migrating; choose Mimir (or Grafana Cloud) when you need multi-tenancy and a central ingest tier; choose VictoriaMetrics when you want the least infrastructure per series; choose a managed service when the team cannot afford to run a TSDB.
The Invariants
- Guarantees: A Prometheus pair keeps scraping when one dies; remote_write retries failed sends in order for as long as the WAL still holds the data (about 2 h); Thanos and Mimir queries return the union of live and bucket data with replicas collapsed by a dedup label; blocks in object storage are immutable once uploaded.
- Does not guarantee: That remote_write is lossless past ~2 h of outage; that HA replicas hold identical samples (they differ by scrape phase, so dedup picks one and deduped values may jitter); that federation can carry bulk data; that unnamed label differences are merged (a mislabeled replica double-counts); that downsampling saves storage.