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(property-vals-rs): LZ4 envelope compression for intermediate topic (#61548)

José Sequeirabc64245a4cb6
diff --git a/rust/common/kafka/src/kafka_consumer.rs b/rust/common/kafka/src/kafka_consumer.rs
index 70248803b8fd..0e632e4c3403 100644
--- a/rust/common/kafka/src/kafka_consumer.rs
+++ b/rust/common/kafka/src/kafka_consumer.rs
@@ -17,7 +17,7 @@ use tracing::warn;
use crate::config::{ConsumerConfig, KafkaConfig};
-const LZ4_FRAME_MAGIC: &[u8; 4] = &[0x04, 0x22, 0x4d, 0x18];
+pub(crate) const LZ4_FRAME_MAGIC: &[u8; 4] = &[0x04, 0x22, 0x4d, 0x18];
const MAX_DECOMPRESSED_KAFKA_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
const KAFKA_LZ4_PAYLOADS_TOTAL: &str = "common_kafka_lz4_payloads_total";
const KAFKA_LZ4_COMPRESSED_BYTES: &str = "common_kafka_lz4_compressed_bytes";
diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rs
index 1b15180923ed..d9557ab490e6 100644
--- a/rust/common/kafka/src/kafka_producer.rs
+++ b/rust/common/kafka/src/kafka_producer.rs
@@ -1,14 +1,46 @@
+use std::io::Write;
use std::sync::Arc;
use crate::config::KafkaConfig;
use common_liveness::SyncLivenessReporter;
+use lz4::EncoderBuilder;
use rdkafka::error::KafkaError;
use rdkafka::producer::{FutureProducer, FutureRecord, Producer};
use rdkafka::{ClientConfig, ClientContext};
use serde::Serialize;
use serde_json::error::Error as SerdeError;
use thiserror::Error;
-use tracing::{debug, error, info};
+use tracing::{debug, error, info, warn};
+
+const KAFKA_LZ4_COMPRESS_TOTAL: &str = "common_kafka_lz4_compress_total";
+const KAFKA_LZ4_COMPRESS_UNCOMPRESSED_BYTES: &str = "common_kafka_lz4_compress_uncompressed_bytes";
+const KAFKA_LZ4_COMPRESS_COMPRESSED_BYTES: &str = "common_kafka_lz4_compress_compressed_bytes";
+
+/// Envelope-level encoding applied to the serialized message value before it is
+/// produced, independent of the broker-level `compression.codec`. `Lz4` emits
+/// the LZ4 *frame* format, whose magic bytes let `SingleTopicConsumer`
+/// decompress transparently — so encoded and plain messages can coexist on a
+/// topic during rollout. Use `Lz4` only for topics consumed by
+/// `SingleTopicConsumer`, never for ones read by a ClickHouse Kafka engine
+/// table, which expects raw rows.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum EnvelopeEncoding {
+ #[default]
+ None,
+ Lz4,
+}
+
+impl std::str::FromStr for EnvelopeEncoding {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_ref() {
+ "none" => Ok(EnvelopeEncoding::None),
+ "lz4" => Ok(EnvelopeEncoding::Lz4),
+ _ => Err(format!("Unknown EnvelopeEncoding: {s}")),
+ }
+ }
+}
pub struct KafkaContext {
liveness: Arc<dyn SyncLivenessReporter>,
@@ -154,6 +186,31 @@ where
.await
}
+/// Like `send_keyed_iter_to_kafka`, but applies the given envelope encoding to
+/// each serialized payload before producing. With `EnvelopeEncoding::Lz4` the
+/// frame magic bytes let `SingleTopicConsumer` decompress transparently, so
+/// encoded and plain messages can coexist on a topic during rollout.
+pub async fn send_keyed_iter_to_kafka_with_encoding<T, C: ClientContext>(
+ kafka_producer: &FutureProducer<C>,
+ topic: &str,
+ key_extractor: impl Fn(&T) -> Option<String>,
+ encoding: EnvelopeEncoding,
+ iter: impl IntoIterator<Item = T>,
+) -> Vec<Result<(), KafkaProduceError>>
+where
+ T: Serialize,
+{
+ send_keyed_iter_to_kafka_inner(
+ kafka_producer,
+ topic,
+ key_extractor,
+ |_| None,
+ iter,
+ encoding,
+ )
+ .await
+}
+
pub async fn send_keyed_iter_to_kafka_with_headers<T, C: ClientContext>(
kafka_producer: &FutureProducer<C>,
topic: &str,
@@ -161,6 +218,28 @@ pub async fn send_keyed_iter_to_kafka_with_headers<T, C: ClientContext>(
headers_extractor: impl Fn(&T) -> Option<rdkafka::message::OwnedHeaders>,
iter: impl IntoIterator<Item = T>,
) -> Vec<Result<(), KafkaProduceError>>
+where
+ T: Serialize,
+{
+ send_keyed_iter_to_kafka_inner(
+ kafka_producer,
+ topic,
+ key_extractor,
+ headers_extractor,
+ iter,
+ EnvelopeEncoding::None,
+ )
+ .await
+}
+
+async fn send_keyed_iter_to_kafka_inner<T, C: ClientContext>(
+ kafka_producer: &FutureProducer<C>,
+ topic: &str,
+ key_extractor: impl Fn(&T) -> Option<String>,
+ headers_extractor: impl Fn(&T) -> Option<rdkafka::message::OwnedHeaders>,
+ iter: impl IntoIterator<Item = T>,
+ encoding: EnvelopeEncoding,
+) -> Vec<Result<(), KafkaProduceError>>
where
T: Serialize,
{
@@ -170,7 +249,7 @@ where
for (index, item) in iter.into_iter().enumerate() {
let key = key_extractor(&item);
let headers = headers_extractor(&item);
- let payload = match serde_json::to_string(&item)
+ let json = match serde_json::to_vec(&item)
.map_err(|e| KafkaProduceError::SerializationError { error: e })
{
Ok(p) => p,
@@ -180,6 +259,13 @@ where
}
};
+ // On compression failure we fall back to the raw JSON: the consumer
+ // handles both, so failing open keeps the topic flowing.
+ let payload = match encoding {
+ EnvelopeEncoding::None => json,
+ EnvelopeEncoding::Lz4 => maybe_compress_lz4_frame(json, topic),
+ };
+
let record = FutureRecord {
topic,
key: key.as_deref(),
@@ -220,3 +306,92 @@ where
results.into_iter().map(|(_, r)| r).collect()
}
+
+/// LZ4-frame-compress `payload`, falling back to the original bytes if the
+/// encoder errors (extremely unlikely with an in-memory writer). The frame
+/// magic bytes are what the consumer keys off to decompress transparently.
+fn maybe_compress_lz4_frame(payload: Vec<u8>, topic: &str) -> Vec<u8> {
+ match compress_lz4_frame(&payload) {
+ Ok(compressed) => {
+ metrics::counter!(
+ KAFKA_LZ4_COMPRESS_TOTAL,
+ "topic" => topic.to_string(),
+ "result" => "success",
+ )
+ .increment(1);
+ metrics::histogram!(KAFKA_LZ4_COMPRESS_UNCOMPRESSED_BYTES, "topic" => topic.to_string())
+ .record(payload.len() as f64);
+ metrics::histogram!(KAFKA_LZ4_COMPRESS_COMPRESSED_BYTES, "topic" => topic.to_string())
+ .record(compressed.len() as f64);
+ compressed
+ }
+ Err(e) => {
+ metrics::counter!(
+ KAFKA_LZ4_COMPRESS_TOTAL,
+ "topic" => topic.to_string(),
+ "result" => "failure",
+ )
+ .increment(1);
+ warn!(error = %e, topic, "failed to LZ4-compress Kafka payload, producing raw JSON");
+ payload
+ }
+ }
+}
+
+fn compress_lz4_frame(payload: &[u8]) -> std::io::Result<Vec<u8>> {
+ let mut encoder = EncoderBuilder::new().build(Vec::with_capacity(payload.len()))?;
+ encoder.write_all(payload)?;
+ let (compressed, result) = encoder.finish();
+ result?;
+ Ok(compressed)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Read;
+
+ use lz4::Decoder;
+
+ use super::{compress_lz4_frame, maybe_compress_lz4_frame, EnvelopeEncoding};
+ use crate::kafka_consumer::LZ4_FRAME_MAGIC;
+
+ #[test]
+ fn lz4_frame_starts_with_magic_and_round_trips() {
+ let original = br#"{"team_id":1,"property_key":"$browser","property_value":"Chrome"}"#;
+
+ let compressed = compress_lz4_frame(original).unwrap();
+
+ assert!(
+ compressed.starts_with(LZ4_FRAME_MAGIC),
+ "compressed payload must carry the LZ4 frame magic so the consumer detects it"
+ );
+
+ let mut decoder = Decoder::new(compressed.as_slice()).unwrap();
+ let mut decompressed = Vec::new();
+ decoder.read_to_end(&mut decompressed).unwrap();
+ assert_eq!(decompressed, original);
+ }
+
+ #[test]
+ fn maybe_compress_round_trips_for_lz4() {
+ let original = br#"{"team_id":42,"property_value":"x"}"#.to_vec();
+
+ let payload = maybe_compress_lz4_frame(original.clone(), "test-topic");
+
+ let mut decoder = Decoder::new(payload.as_slice()).unwrap();
+ let mut decompressed = Vec::new();
+ decoder.read_to_end(&mut decompressed).unwrap();
+ assert_eq!(decompressed, original);
+ }
+
+ #[test]
+ fn envelope_encoding_parses_from_str() {
+ assert_eq!(
+ "none".parse::<EnvelopeEncoding>(),
+ Ok(EnvelopeEncoding::None)
+ );
+ assert_eq!("LZ4".parse::<EnvelopeEncoding>(), Ok(EnvelopeEncoding::Lz4));
+ assert!(" lz4 ".parse::<EnvelopeEncoding>().is_ok());
+ assert!("gzip".parse::<EnvelopeEncoding>().is_err());
+ }
+}
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index 91d17104c11d..9981fab420f1 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -6,6 +6,7 @@ use std::{num::ParseIntError, str::FromStr};
use common_continuous_profiling::ContinuousProfilingConfig;
use common_kafka::config::{ConsumerConfig, KafkaConfig};
+use common_kafka::kafka_producer::EnvelopeEncoding;
use envconfig::Envconfig;
use siphasher::sip::SipHasher13;
@@ -26,6 +27,12 @@ pub struct Config {
#[envconfig(default = "property_vals_intermediate")]
pub intermediate_topic: String,
+ // Envelope encoding for payloads produced to the intermediate topic. The
+ // merger consumer decodes transparently, so `lz4` can roll out
+ // incrementally. `none` by default.
+ #[envconfig(default = "none")]
+ pub intermediate_topic_encoding: EnvelopeEncoding,
+
#[envconfig(default = "clickhouse-property-vals-rs-merger")]
pub merger_consumer_group: String,
diff --git a/rust/property-vals-rs/src/main.rs b/rust/property-vals-rs/src/main.rs
index 878f55d0f31f..c9154c65e7b1 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -3,6 +3,7 @@ use std::time::Duration;
use axum::{response::IntoResponse, routing::get, Router};
use common_kafka::kafka_consumer::SingleTopicConsumer;
+use common_kafka::kafka_producer::EnvelopeEncoding;
use lifecycle::{ComponentOptions, Manager};
use property_vals_rs::{
config::Config,
@@ -86,6 +87,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
groups_topic = %config.groups_kafka_consumer_topic,
groups_consumer_group = %config.groups_kafka_consumer_group,
intermediate_topic = %config.intermediate_topic,
+ intermediate_topic_encoding = ?config.intermediate_topic_encoding,
merger_consumer_group = %config.merger_consumer_group,
output_topic = %config.output_topic,
flush_interval_secs = config.flush_interval_secs,
@@ -101,6 +103,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.intermediate_topic.clone(),
produce_timeout,
true,
+ config.intermediate_topic_encoding,
)
.await?;
@@ -114,6 +117,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.intermediate_topic.clone(),
produce_timeout,
true,
+ config.intermediate_topic_encoding,
)
.await?;
@@ -121,12 +125,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
merger_consumer_config.kafka_consumer_topic = config.intermediate_topic.clone();
merger_consumer_config.kafka_consumer_group = config.merger_consumer_group.clone();
let merger_consumer = SingleTopicConsumer::new(config.kafka.clone(), merger_consumer_config)?;
+ // Output topic is read by ClickHouse, which expects raw rows — never encode.
let merger_producer = AggregatedProducer::new(
&config.kafka,
merger_handle.clone(),
config.output_topic.clone(),
produce_timeout,
config.emit_event_name,
+ EnvelopeEncoding::None,
)
.await?;
diff --git a/rust/property-vals-rs/src/producer.rs b/rust/property-vals-rs/src/producer.rs
index d1523ea79c26..41a3d4909f24 100644
--- a/rust/property-vals-rs/src/producer.rs
+++ b/rust/property-vals-rs/src/producer.rs
@@ -3,7 +3,8 @@ use std::time::Duration;
use async_trait::async_trait;
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::{
- create_kafka_producer, send_keyed_iter_to_kafka, KafkaContext, KafkaProduceError,
+ create_kafka_producer, send_keyed_iter_to_kafka_with_encoding, EnvelopeEncoding, KafkaContext,
+ KafkaProduceError,
};
use rdkafka::error::KafkaError;
use rdkafka::producer::FutureProducer;
@@ -54,6 +55,10 @@ pub struct AggregatedProducer {
output_topic: String,
produce_timeout: Duration,
serialize_event_name: bool,
+ // Envelope encoding for the produced payloads. Only `Lz4`-safe for the
+ // intermediate topic, which the merger consumes; the output topic is read
+ // by ClickHouse and must stay `None`.
+ encoding: EnvelopeEncoding,
}
impl AggregatedProducer {
@@ -63,6 +68,7 @@ impl AggregatedProducer {
output_topic: String,
produce_timeout: Duration,
serialize_event_name: bool,
+ encoding: EnvelopeEncoding,
) -> Result<Self, KafkaError>
where
L: common_liveness::SyncLivenessReporter + Clone + 'static,
@@ -73,6 +79,7 @@ impl AggregatedProducer {
output_topic,
produce_timeout,
serialize_event_name,
+ encoding,
})
}
}
@@ -105,7 +112,7 @@ impl Producer for AggregatedProducer {
// from any pod always lands on the same partition, so the merger on
// the consuming side can merge the per-pod duplicates that the
// events/groups workers emit across replicas.
- let send_fut = send_keyed_iter_to_kafka(
+ let send_fut = send_keyed_iter_to_kafka_with_encoding(
&self.inner,
&self.output_topic,
|m| {
@@ -117,6 +124,7 @@ impl Producer for AggregatedProducer {
m.property_value,
))
},
+ self.encoding,
messages,
);