Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(capture-apm): accept victoriametrics remote write on the prometheus route (#102188)

Frank Hamand47ba57306b1b
diff --git a/rust/capture-apm-metrics/README.md b/rust/capture-apm-metrics/README.md
index 82781b540eca..377402467d4f 100644
--- a/rust/capture-apm-metrics/README.md
+++ b/rust/capture-apm-metrics/README.md
@@ -2,6 +2,8 @@
Receives OTLP metrics (`/i/v1/metrics`) and Prometheus remote-write (`/i/v1/prometheus/write`) and writes them to Kafka.
+The remote-write route accepts two body encodings. `Content-Encoding: snappy` (or no header) is the Prometheus remote-write v1 protocol. `Content-Encoding: zstd` is the VictoriaMetrics remote-write protocol, which `vmagent` sends by default. Both carry the same protobuf and produce the same rows.
+
This binary is the metrics half of [`capture-logs`](../capture-logs/README.md). It links the `capture-logs` library for parsing, authentication, and the Kafka sink, so metrics traffic can scale and deploy on its own. The base configuration, authentication, and response codes are the ones documented for `capture-logs`. The settings below are specific to this service.
## Configuration
diff --git a/rust/capture-apm-metrics/src/main.rs b/rust/capture-apm-metrics/src/main.rs
index e0a978d0ea3f..c0fe8f7dc9c5 100644
--- a/rust/capture-apm-metrics/src/main.rs
+++ b/rust/capture-apm-metrics/src/main.rs
@@ -262,10 +262,11 @@ async fn run(
.layer(RequestDecompressionLayer::new())
.layer(axum::middleware::from_fn(translate_compression_query_param));
- // Prometheus remote-write sends `Content-Encoding: snappy`, which
- // RequestDecompressionLayer rejects with 415 before the handler runs. This
- // route is deliberately kept off that layer (and the gzip query-param
- // shim); the handler snappy-decodes the body itself.
+ // Prometheus remote-write sends `Content-Encoding: snappy` and vmagent
+ // sends `Content-Encoding: zstd`, which RequestDecompressionLayer rejects
+ // with 415 before the handler runs. This route is deliberately kept off
+ // that layer (and the gzip query-param shim); the handler decodes the body
+ // itself.
let prometheus_router = Router::new()
.route(
"/i/v1/prometheus/write",
diff --git a/rust/capture-apm-metrics/src/prometheus.rs b/rust/capture-apm-metrics/src/prometheus.rs
index 1335a47d0fc5..0520921ca3ac 100644
--- a/rust/capture-apm-metrics/src/prometheus.rs
+++ b/rust/capture-apm-metrics/src/prometheus.rs
@@ -10,8 +10,9 @@ use axum::Json;
use bytes::Bytes;
use capture_logs::authorizer::Signal;
use capture_logs::endpoints::prometheus::{
- decode_write_request, estimate_expanded_bytes, write_request_to_kafka_rows,
+ decode_write_request, estimate_expanded_bytes, write_request_to_kafka_rows, RemoteWriteEncoding,
};
+use metrics::counter;
use serde::Deserialize;
use serde_json::json;
use tracing::{debug, error, instrument};
@@ -57,18 +58,23 @@ fn extract_token(
query_token.filter(|t| !t.is_empty()).map(str::to_string)
}
-/// Prometheus remote-write v1 ingestion endpoint.
+/// Prometheus remote-write v1 ingestion endpoint. Also accepts the
+/// VictoriaMetrics remote-write protocol (same protobuf, zstd body).
///
-/// Snappy-decodes the protobuf body, maps it to `KafkaMetricRow` records, and
+/// Decompresses the protobuf body, maps it to `KafkaMetricRow` records, and
/// produces them through the shared `KafkaSink` so the rest of the pipeline is
/// identical to OTLP ingestion. Response codes follow remote-write semantics:
-/// 204 on success, 400 on a permanent decode failure (sender drops the batch),
-/// 5xx on a transient produce failure (sender retries).
+/// 204 on success, 400 on a permanent decode failure (sender drops the batch;
+/// vmagent also falls back to snappy on 400), 5xx on a transient produce
+/// failure (sender retries).
#[instrument(skip_all, fields(
token = tracing::field::Empty,
user_agent = %headers.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or(""),
+ content_encoding = %headers.get("content-encoding")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or(""),
content_length = %headers.get("content-length")
.and_then(|v| v.to_str().ok())
.unwrap_or("")))
@@ -101,8 +107,15 @@ pub async fn export_prometheus_remote_write_http(
tracing::Span::current().record("token", &token);
+ let encoding = RemoteWriteEncoding::from_headers(&headers);
+ counter!(
+ "capture_metrics_remote_write_requests",
+ "encoding" => encoding.as_str()
+ )
+ .increment(1);
+
let (write_request, uncompressed_bytes) =
- match decode_write_request(&body, service.max_request_body_size_bytes) {
+ match decode_write_request(&body, encoding, service.max_request_body_size_bytes) {
Ok(decoded) => decoded,
Err(e) => {
error!("Failed to decode remote-write request: {e}");
diff --git a/rust/capture-logs/src/endpoints/prometheus.rs b/rust/capture-logs/src/endpoints/prometheus.rs
index 96f6e0885565..84ef84e8bf8b 100644
--- a/rust/capture-logs/src/endpoints/prometheus.rs
+++ b/rust/capture-logs/src/endpoints/prometheus.rs
@@ -38,16 +38,54 @@ const ROW_OVERHEAD_BYTES: u64 = 256;
/// below this; only expansion-bomb payloads exceed it.
const MAX_EXPANSION_FACTOR: u64 = 16;
-/// Decode a snappy-compressed Prometheus remote-write v1 payload, returning the
+/// Body compression of a remote-write request. Both protocols carry the same
+/// `WriteRequest` protobuf; only the compression differs.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RemoteWriteEncoding {
+ /// Prometheus remote-write v1: snappy block format.
+ Snappy,
+ /// VictoriaMetrics remote-write protocol, which vmagent tries first by
+ /// default: zstd frame, sent with `Content-Encoding: zstd` and
+ /// `X-VictoriaMetrics-Remote-Write-Version: 1`.
+ Zstd,
+}
+
+impl RemoteWriteEncoding {
+ /// `Content-Encoding: zstd` selects the VictoriaMetrics protocol. Every other
+ /// value, and a missing header, keeps the snappy default, because Prometheus
+ /// always sends snappy and some senders omit the header.
+ pub fn from_headers(headers: &HeaderMap) -> Self {
+ let is_zstd = headers
+ .get("content-encoding")
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.trim().eq_ignore_ascii_case("zstd"));
+ if is_zstd {
+ Self::Zstd
+ } else {
+ Self::Snappy
+ }
+ }
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Snappy => "snappy",
+ Self::Zstd => "zstd",
+ }
+ }
+}
+
+/// Decode a compressed Prometheus remote-write v1 payload, returning the
/// request and its decompressed size in bytes.
///
/// Prometheus sends `Content-Encoding: snappy` using the snappy *block* format
-/// (not the framed format), so we decode the raw body ourselves — the global
-/// `RequestDecompressionLayer` does not understand snappy.
+/// (not the framed format), and vmagent sends `Content-Encoding: zstd`. The
+/// global `RequestDecompressionLayer` understands neither, so we decode the
+/// raw body ourselves.
///
-/// The block format's length header is sender-controlled, so the claimed
-/// decompressed size is checked against `max_decompressed_bytes` before any
-/// allocation happens.
+/// Both formats let the sender claim the decompressed size (the snappy length
+/// header, the optional zstd frame content size), so the claim is checked
+/// against `max_decompressed_bytes` before any allocation happens. The zstd
+/// decoder is also capped while it streams, for frames without a claim.
///
/// The size is returned because this route bypasses `RequestDecompressionLayer`,
/// so the request body is still compressed when the handler sees it. The OTLP and
@@ -55,18 +93,27 @@ const MAX_EXPANSION_FACTOR: u64 = 16;
/// the same quota and rate-limiting counters, so the measure has to match.
pub fn decode_write_request(
body: &[u8],
+ encoding: RemoteWriteEncoding,
max_decompressed_bytes: usize,
) -> Result<(WriteRequest, u64)> {
- let claimed =
- snap::raw::decompress_len(body).map_err(|e| anyhow!("snappy decode failed: {e}"))?;
- if claimed > max_decompressed_bytes {
- return Err(anyhow!(
- "decompressed request body exceeds limit ({claimed} > {max_decompressed_bytes} bytes)"
- ));
- }
- let decompressed = snap::raw::Decoder::new()
- .decompress_vec(body)
- .map_err(|e| anyhow!("snappy decode failed: {e}"))?;
+ let decompressed = match encoding {
+ RemoteWriteEncoding::Snappy => {
+ let claimed = snap::raw::decompress_len(body)
+ .map_err(|e| anyhow!("snappy decode failed: {e}"))?;
+ if claimed > max_decompressed_bytes {
+ return Err(anyhow!(
+ "decompressed request body exceeds limit ({claimed} > {max_decompressed_bytes} bytes)"
+ ));
+ }
+ snap::raw::Decoder::new()
+ .decompress_vec(body)
+ .map_err(|e| anyhow!("snappy decode failed: {e}"))?
+ }
+ RemoteWriteEncoding::Zstd => {
+ common_compression::decompress_zstd_capped(body, max_decompressed_bytes)
+ .map_err(|e| anyhow!("zstd decode failed: {e}"))?
+ }
+ };
let uncompressed_bytes = decompressed.len() as u64;
let request = WriteRequest::decode(decompressed.as_slice())
.map_err(|e| anyhow!("remote-write protobuf decode failed: {e}"))?;
@@ -347,18 +394,23 @@ fn extract_token(
query_token.filter(|t| !t.is_empty()).map(str::to_string)
}
-/// Prometheus remote-write v1 ingestion endpoint.
+/// Prometheus remote-write v1 ingestion endpoint. Also accepts the
+/// VictoriaMetrics remote-write protocol (same protobuf, zstd body).
///
-/// Snappy-decodes the protobuf body, maps it to `KafkaMetricRow` records, and
+/// Decompresses the protobuf body, maps it to `KafkaMetricRow` records, and
/// produces them through the shared `KafkaSink` so the rest of the pipeline is
/// identical to OTLP ingestion. Response codes follow remote-write semantics:
-/// 204 on success, 400 on a permanent decode failure (sender drops the batch),
-/// 5xx on a transient produce failure (sender retries).
+/// 204 on success, 400 on a permanent decode failure (sender drops the batch;
+/// vmagent also falls back to snappy on 400), 5xx on a transient produce
+/// failure (sender retries).
#[instrument(skip_all, fields(
token = tracing::field::Empty,
user_agent = %headers.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or(""),
+ content_encoding = %headers.get("content-encoding")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or(""),
content_length = %headers.get("content-length")
.and_then(|v| v.to_str().ok())
.unwrap_or("")))
@@ -391,8 +443,15 @@ pub async fn export_prometheus_remote_write_http(
tracing::Span::current().record("token", &token);
+ let encoding = RemoteWriteEncoding::from_headers(&headers);
+ counter!(
+ "capture_metrics_remote_write_requests",
+ "encoding" => encoding.as_str()
+ )
+ .increment(1);
+
let (write_request, uncompressed_bytes) =
- match decode_write_request(&body, service.max_request_body_size_bytes) {
+ match decode_write_request(&body, encoding, service.max_request_body_size_bytes) {
Ok(decoded) => decoded,
Err(e) => {
error!("Failed to decode remote-write request: {e}");
diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rs
index 560df6904c89..8d85bc36ec85 100644
--- a/rust/capture-logs/src/main.rs
+++ b/rust/capture-logs/src/main.rs
@@ -187,10 +187,11 @@ async fn main() {
.layer(RequestDecompressionLayer::new())
.layer(axum::middleware::from_fn(translate_compression_query_param));
- // Prometheus remote-write sends `Content-Encoding: snappy`, which
- // RequestDecompressionLayer rejects with 415 before the handler runs. This
- // route is deliberately kept off that layer (and the gzip query-param
- // shim); the handler snappy-decodes the body itself.
+ // Prometheus remote-write sends `Content-Encoding: snappy` and vmagent
+ // sends `Content-Encoding: zstd`, which RequestDecompressionLayer rejects
+ // with 415 before the handler runs. This route is deliberately kept off
+ // that layer (and the gzip query-param shim); the handler decodes the body
+ // itself.
let prometheus_router = Router::new()
.route(
"/i/v1/prometheus/write",
diff --git a/rust/capture-logs/tests/prometheus_remote_write_test.rs b/rust/capture-logs/tests/prometheus_remote_write_test.rs
index 249c8ae21f5f..0e8d7c9e69bc 100644
--- a/rust/capture-logs/tests/prometheus_remote_write_test.rs
+++ b/rust/capture-logs/tests/prometheus_remote_write_test.rs
@@ -1,4 +1,6 @@
-use capture_logs::endpoints::prometheus::{decode_write_request, write_request_to_kafka_rows};
+use capture_logs::endpoints::prometheus::{
+ decode_write_request, write_request_to_kafka_rows, RemoteWriteEncoding,
+};
use chrono::{Duration, Utc};
use prometheus_rw_proto::prometheus::v1::{
metric_metadata::MetricType, Label, MetricMetadata, Sample, TimeSeries, WriteRequest,
@@ -273,7 +275,8 @@ fn snappy_round_trip_decodes_and_maps() {
let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();
let (decoded, _) =
- decode_write_request(&compressed, MAX_DECOMPRESSED).expect("snappy+protobuf decode");
+ decode_write_request(&compressed, RemoteWriteEncoding::Snappy, MAX_DECOMPRESSED)
+ .expect("snappy+protobuf decode");
let (rows, _) = write_request_to_kafka_rows(decoded);
assert_eq!(rows.len(), 1);
@@ -283,7 +286,12 @@ fn snappy_round_trip_decodes_and_maps() {
#[test]
fn rejects_non_snappy_garbage() {
- assert!(decode_write_request(b"not snappy at all", MAX_DECOMPRESSED).is_err());
+ assert!(decode_write_request(
+ b"not snappy at all",
+ RemoteWriteEncoding::Snappy,
+ MAX_DECOMPRESSED
+ )
+ .is_err());
}
/// The raw-snappy length header is sender-controlled: a tiny body can claim a
@@ -307,10 +315,89 @@ fn rejects_decompression_bomb_before_allocating() {
let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();
// A cap below the (legitimate) decompressed size must reject the payload.
- assert!(decode_write_request(&compressed, encoded.len() - 1).is_err());
+ assert!(
+ decode_write_request(&compressed, RemoteWriteEncoding::Snappy, encoded.len() - 1).is_err()
+ );
// The same payload passes with an adequate cap, so the rejection above is
// the cap and not a decode failure.
- assert!(decode_write_request(&compressed, encoded.len()).is_ok());
+ assert!(decode_write_request(&compressed, RemoteWriteEncoding::Snappy, encoded.len()).is_ok());
+}
+
+/// vmagent sends the same protobuf zstd-compressed (the VictoriaMetrics
+/// remote-write protocol). Before it was accepted, vmagent got a 400 on its
+/// first request and fell back to snappy, so a regression here is silent.
+#[test]
+fn zstd_round_trip_decodes_and_maps() {
+ let req = WriteRequest {
+ timeseries: vec![series(
+ vec![label("__name__", "up"), label("job", "vmagent")],
+ vec![Sample {
+ value: 1.0,
+ timestamp: now_ms(),
+ }],
+ )],
+ metadata: vec![],
+ };
+
+ let mut encoded = Vec::new();
+ req.encode(&mut encoded).unwrap();
+ let compressed = common_compression::compress_zstd(&encoded).unwrap();
+
+ let (decoded, uncompressed_bytes) =
+ decode_write_request(&compressed, RemoteWriteEncoding::Zstd, MAX_DECOMPRESSED)
+ .expect("zstd+protobuf decode");
+ let (rows, _) = write_request_to_kafka_rows(decoded);
+
+ assert_eq!(uncompressed_bytes, encoded.len() as u64);
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].metric_name, "up");
+ assert_eq!(rows[0].service_name, "vmagent");
+
+ // A snappy body labelled as zstd must fail, not be accepted by accident.
+ let snappy = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();
+ assert!(decode_write_request(&snappy, RemoteWriteEncoding::Zstd, MAX_DECOMPRESSED).is_err());
+}
+
+/// zstd compresses repetitive input past 1000:1, so the cap has to hold on the
+/// decompressed size and not on the body size.
+#[test]
+fn zstd_rejects_decompression_bomb() {
+ let bomb = vec![0u8; 4 * MAX_DECOMPRESSED];
+ let compressed = common_compression::compress_zstd(&bomb).unwrap();
+ assert!(compressed.len() < 4096, "bomb should compress small");
+
+ assert!(
+ decode_write_request(&compressed, RemoteWriteEncoding::Zstd, MAX_DECOMPRESSED).is_err()
+ );
+ // The same body under an adequate cap fails only on the protobuf decode, so
+ // the rejection above comes from the cap and not from the zstd decoder.
+ let err = decode_write_request(&compressed, RemoteWriteEncoding::Zstd, bomb.len())
+ .expect_err("zeros are not a WriteRequest");
+ assert!(err.to_string().contains("protobuf"), "{err}");
+}
+
+#[test]
+fn content_encoding_header_selects_encoding() {
+ use axum::http::HeaderMap;
+
+ let cases: [(Option<&str>, RemoteWriteEncoding); 5] = [
+ (None, RemoteWriteEncoding::Snappy),
+ (Some("snappy"), RemoteWriteEncoding::Snappy),
+ (Some("zstd"), RemoteWriteEncoding::Zstd),
+ (Some(" ZSTD "), RemoteWriteEncoding::Zstd),
+ (Some("gzip"), RemoteWriteEncoding::Snappy),
+ ];
+ for (value, expected) in cases {
+ let mut headers = HeaderMap::new();
+ if let Some(value) = value {
+ headers.insert("content-encoding", value.parse().unwrap());
+ }
+ assert_eq!(
+ RemoteWriteEncoding::from_headers(&headers),
+ expected,
+ "content-encoding {value:?}"
+ );
+ }
}
/// Quota and rate limiting charge the payload size the handler reports. This
@@ -336,7 +423,8 @@ fn reports_decompressed_payload_size() {
let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();
let (_, uncompressed_bytes) =
- decode_write_request(&compressed, MAX_DECOMPRESSED).expect("snappy+protobuf decode");
+ decode_write_request(&compressed, RemoteWriteEncoding::Snappy, MAX_DECOMPRESSED)
+ .expect("snappy+protobuf decode");
assert_eq!(uncompressed_bytes, encoded.len() as u64);
// Keeps the assertion above from passing vacuously: a payload that did not
diff --git a/rust/common/compression/src/lib.rs b/rust/common/compression/src/lib.rs
index 40ce13495ddb..c5e84887d76a 100644
--- a/rust/common/compression/src/lib.rs
+++ b/rust/common/compression/src/lib.rs
@@ -75,7 +75,10 @@ pub fn compress_gzip(data: &[u8]) -> Result<Vec<u8>, CompressionError> {
Ok(compressed)
}
-/// Zstd decompression (matching Django's ZstdCompressor)
+/// Zstd decompression (matching Django's ZstdCompressor) with **no output
+/// cap**. Safe only for trusted compressed bytes; for HTTP request bodies use
+/// [`decompress_zstd_capped`], because zstd reaches ratios well past 1000:1 on
+/// repetitive input.
pub fn decompress_zstd(bytes: &[u8]) -> Result<Vec<u8>, CompressionError> {
let mut decoder = Decoder::new(bytes)?;
let mut decompressed = Vec::new();
@@ -83,6 +86,38 @@ pub fn decompress_zstd(bytes: &[u8]) -> Result<Vec<u8>, CompressionError> {
Ok(decompressed)
}
+/// Zstd decompression with a hard output cap. Returns
+/// [`CompressionError::OutputTooLarge`] when the decompressed output would
+/// exceed `limit`.
+///
+/// A zstd frame may declare its content size in the header. When it does and
+/// the declared size is over the cap, the input is rejected before anything is
+/// allocated. The `take` cap on the streaming decoder covers frames without a
+/// declared size and frames whose header lies.
+pub fn decompress_zstd_capped(bytes: &[u8], limit: usize) -> Result<Vec<u8>, CompressionError> {
+ if let Ok(Some(declared)) = zstd::zstd_safe::get_frame_content_size(bytes) {
+ if declared > limit as u64 {
+ return Err(CompressionError::OutputTooLarge {
+ decompressed: usize::try_from(declared).unwrap_or(usize::MAX),
+ limit,
+ });
+ }
+ }
+
+ let mut buf = Vec::new();
+ Decoder::new(bytes)?
+ .take((limit as u64).saturating_add(1))
+ .read_to_end(&mut buf)?;
+
+ if buf.len() > limit {
+ return Err(CompressionError::OutputTooLarge {
+ decompressed: buf.len(),
+ limit,
+ });
+ }
+ Ok(buf)
+}
+
/// Zstd compression (matching Django's ZstdCompressor)
pub fn compress_zstd(data: &[u8]) -> Result<Vec<u8>, CompressionError> {
let mut encoder = Encoder::new(Vec::new(), 0)?; // Level 0 matches Django's zstd_preset = 0
@@ -307,6 +342,29 @@ mod tests {
}
}
+ #[test]
+ fn test_decompress_zstd_capped_at_and_over_limit() {
+ let original = vec![b'A'; 1025];
+ // The streaming encoder writes no content size in the frame header, so
+ // only the `take` cap can stop it. The bulk encoder declares the size,
+ // which exercises the early header check.
+ let streaming = compress_zstd(&original).unwrap();
+ let bulk = zstd::bulk::compress(&original, 0).unwrap();
+ assert!(matches!(
+ zstd::zstd_safe::get_frame_content_size(&bulk),
+ Ok(Some(1025))
+ ));
+
+ for compressed in [&streaming, &bulk] {
+ assert_eq!(decompress_zstd_capped(compressed, 1025).unwrap(), original);
+ assert!(matches!(
+ decompress_zstd_capped(compressed, 1024),
+ Err(CompressionError::OutputTooLarge { decompressed, limit })
+ if decompressed > 1024 && limit == 1024
+ ));
+ }
+ }
+
#[test]
fn test_decompress_gzip_capped_invalid_input() {
let result = decompress_gzip_capped(b"not gzip data", 1024);