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): add LZ4 envelope compression for session replay Kafka … (#61077)

José Sequeirafdc731520882
diff --git a/nodejs/package.json b/nodejs/package.json
index 6d71ca79d210..9a95ed67b281 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -107,6 +107,7 @@
"libsodium-wrappers": "^0.7.15",
"liquidjs": "^10.27.0",
"lodash": "^4.18.1",
+ "lz4": "^0.6.5",
"lru-cache": "^11.0.0",
"luxon": "^3.4.4",
"node-fetch": "^2.6.1",
diff --git a/nodejs/src/ingestion/session_replay/parse-message-step.test.ts b/nodejs/src/ingestion/session_replay/parse-message-step.test.ts
index 218a98825965..02ff08b0e9e3 100644
--- a/nodejs/src/ingestion/session_replay/parse-message-step.test.ts
+++ b/nodejs/src/ingestion/session_replay/parse-message-step.test.ts
@@ -301,7 +301,7 @@ describe('createParseMessageStep', () => {
expect(result.type).toBe(PipelineResultType.DLQ)
if (result.type === PipelineResultType.DLQ) {
- expect(result.reason).toBe('invalid_gzip_data')
+ expect(result.reason).toBe('invalid_compressed_data')
}
})
diff --git a/nodejs/src/ingestion/session_replay/parse-message-step.ts b/nodejs/src/ingestion/session_replay/parse-message-step.ts
index 6c8e6d2b6a7c..6738c3a8f568 100644
--- a/nodejs/src/ingestion/session_replay/parse-message-step.ts
+++ b/nodejs/src/ingestion/session_replay/parse-message-step.ts
@@ -9,11 +9,14 @@ import {
SnapshotEvent,
SnapshotEventSchema,
} from '../../session-recording/kafka/types'
+import { SessionRecordingIngesterMetrics } from '../../session-recording/metrics'
import { parseJSON } from '../../utils/json-parse'
import { normalizeSessionId } from '../../utils/utils'
import { dlq, drop, ok } from '../pipelines/results'
import { ProcessingStep } from '../pipelines/steps'
+const lz4: { decodeBlock(input: Buffer, output: Buffer): number } = require('lz4')
+
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
const GZIP_HEADER = Uint8Array.from([0x1f, 0x8b, 0x08, 0x00])
@@ -26,7 +29,20 @@ export interface ParseMessageStepOutput {
}
function isGzipped(buffer: Buffer): boolean {
- return buffer.slice(0, GZIP_HEADER.length).equals(GZIP_HEADER)
+ return buffer.subarray(0, GZIP_HEADER.length).equals(GZIP_HEADER)
+}
+
+function getContentEncoding(headers: MessageHeader[] | undefined): string | null {
+ if (!headers) {
+ return null
+ }
+ for (const header of headers) {
+ const value = header['content-encoding']
+ if (value !== undefined) {
+ return typeof value === 'string' ? value : value.toString()
+ }
+ }
+ return null
}
function getValidEvents(events: unknown[]): {
@@ -89,13 +105,22 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proce
}
let messageUnzipped = message.value
+ const contentEncoding = getContentEncoding(message.headers)
try {
- if (isGzipped(message.value)) {
+ if (contentEncoding === 'lz4') {
+ const uncompressedSize = message.value.readUInt32LE(0)
+ const output = Buffer.allocUnsafe(uncompressedSize)
+ lz4.decodeBlock(message.value.subarray(4), output)
+ messageUnzipped = output
+ } else if (isGzipped(message.value)) {
messageUnzipped = gunzipSync(message.value)
}
} catch (error) {
- return dlq('invalid_gzip_data', error)
+ return dlq('invalid_compressed_data', error)
}
+ SessionRecordingIngesterMetrics.incrementMessagesByEncoding(
+ contentEncoding ?? (isGzipped(message.value) ? 'gzip' : 'none')
+ )
let rawPayload: unknown
try {
diff --git a/nodejs/src/session-recording/metrics.ts b/nodejs/src/session-recording/metrics.ts
index 1aa6f292f277..2743eadc8202 100644
--- a/nodejs/src/session-recording/metrics.ts
+++ b/nodejs/src/session-recording/metrics.ts
@@ -47,6 +47,12 @@ export class SessionRecordingIngesterMetrics {
help: 'The number of messages redirected to overflow due to event ingestion restrictions',
})
+ private static readonly messagesByEncoding = new Counter({
+ name: 'recording_blob_ingestion_v2_messages_by_encoding',
+ help: 'The number of messages received from Kafka broken down by envelope content-encoding',
+ labelNames: ['content_encoding'],
+ })
+
public static incrementMessageReceived(partition: number): void {
this.messageReceived.labels(partition.toString()).inc()
}
@@ -59,6 +65,10 @@ export class SessionRecordingIngesterMetrics {
this.messagesOverflowedByRestrictions.inc(count)
}
+ public static incrementMessagesByEncoding(encoding: string): void {
+ this.messagesByEncoding.labels(encoding).inc()
+ }
+
public static resetSessionsRevoked(): void {
this.sessionsRevoked.set(0)
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8afe6a949da0..e54dd780f217 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -439,7 +439,7 @@ importers:
'@storybook/react-webpack5':
specifier: ^8.6.14
'@storybook/test-runner':
specifier: ^0.19.1
@@ -493,7 +493,7 @@ importers:
version: 2.0.0([email protected])
webpack:
specifier: 5.88.2
webpack-cli:
specifier: ^5.1.4
version: 5.1.4([email protected])
@@ -1559,6 +1559,9 @@ importers:
luxon:
specifier: ^3.4.4
version: 3.5.0
+ lz4:
+ specifier: ^0.6.5
+ version: 0.6.5
node-fetch:
specifier: ^2.6.1
version: 2.6.9([email protected])
@@ -14070,6 +14073,9 @@ packages:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+ resolution: {integrity: sha512-d4ZVpCW31eWwCMe1YT3ur7mUDnTXbgwyzaL320DrcRT45rfjYxkt5QWLrmOJ+/UEAI2+fQgKe/fCjR8l4TpRgw==}
+
resolution: {integrity: sha512-CZa8pTkpEygxJRLH9aod/wfnSgK5z/0GJqG/NNehlwam+S8llqCWUXS3eCenvAiW5sTUpwTWE6bJaeeZ/b4pzA==}
peerDependencies:
@@ -17576,6 +17582,10 @@ packages:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
+ resolution: {integrity: sha512-KSZcJU49QZOlJSItaeIU3p8WoAvkTmD9fJqeahQXNu1iQ/kR0/mQLdbrK8JY9MY8f6AhJoMrihp1nu1xDbscSQ==}
+ engines: {node: '>= 0.10'}
+
resolution: {integrity: sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==}
engines: {node: '>=12'}
@@ -22701,6 +22711,9 @@ packages:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
+ resolution: {integrity: sha512-AkTuIuVTET12tpsVIQo+ZU6f/qDmKuRUcjaqR+OIvm+aCBsZ95i7UVY5WJ9TMsSaZ0DA2WxoZ4acu0sPH+OKAw==}
+
resolution: {integrity: sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==}
engines: {node: '>=16.0.0', npm: '>=8.0.0'}
@@ -31945,7 +31958,7 @@ snapshots:
ts-dedent: 2.2.0
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
'@types/semver': 7.7.1
@@ -31963,12 +31976,12 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
style-loader: 3.3.3([email protected])
+ terser-webpack-plugin: 5.6.0([email protected])([email protected])
ts-dedent: 2.2.0
url: 0.11.1
util: 0.12.5
util-deprecate: 1.0.2
webpack-dev-middleware: 6.1.3([email protected])
webpack-hot-middleware: 2.25.4
webpack-virtual-modules: 0.6.2
@@ -32062,7 +32075,7 @@ snapshots:
dependencies:
storybook: 8.6.18([email protected])
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
@@ -32077,7 +32090,7 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
tsconfig-paths: 4.2.0
optionalDependencies:
typescript: 6.0.3
transitivePeerDependencies:
@@ -32111,7 +32124,7 @@ snapshots:
react-docgen-typescript: 2.2.2([email protected])
tslib: 2.8.1
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -32149,10 +32162,10 @@ snapshots:
- supports-color
- typescript
dependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
@@ -34504,17 +34517,17 @@ snapshots:
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
'@xmldom/[email protected]': {}
@@ -35083,7 +35096,7 @@ snapshots:
loader-utils: 2.0.4
make-dir: 3.1.0
schema-utils: 2.7.1
dependencies:
@@ -36032,7 +36045,7 @@ snapshots:
dependencies:
buildcheck: 0.0.6
- nan: 2.24.0
+ nan: 2.27.0
optional: true
@@ -36188,7 +36201,7 @@ snapshots:
postcss-value-parser: 4.2.0
schema-utils: 2.7.1
semver: 6.3.1
dependencies:
@@ -36200,7 +36213,7 @@ snapshots:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
semver: 7.8.0
dependencies:
@@ -36302,6 +36315,8 @@ snapshots:
+
dependencies:
clsx: 2.1.1
@@ -37782,7 +37797,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
@@ -37901,7 +37916,7 @@ snapshots:
semver: 7.8.0
tapable: 2.3.0
typescript: 6.0.3
dependencies:
@@ -38564,7 +38579,7 @@ snapshots:
dependencies:
html-webpack-plugin: 5.5.3([email protected])
dependencies:
@@ -38573,7 +38588,7 @@ snapshots:
lodash: 4.18.1
pretty-error: 4.0.0
tapable: 2.2.1
dependencies:
@@ -40818,7 +40833,7 @@ snapshots:
less: 4.2.2
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -41182,6 +41197,13 @@ snapshots:
+ dependencies:
+ buffer: 5.7.1
+ cuint: 0.2.2
+ nan: 2.27.0
+ xxhashjs: 0.2.2
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -43129,7 +43151,7 @@ snapshots:
postcss: 8.5.15
schema-utils: 3.3.0
semver: 7.7.0
dependencies:
@@ -43921,7 +43943,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -44985,7 +45007,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
semver: 7.7.0
optionalDependencies:
sass: 1.56.0
@@ -45404,7 +45426,7 @@ snapshots:
bcrypt-pbkdf: 1.0.2
optionalDependencies:
cpu-features: 0.0.10
- nan: 2.24.0
+ nan: 2.27.0
@@ -45649,11 +45671,11 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -46018,28 +46040,26 @@ snapshots:
ansi-escapes: 4.3.2
supports-hyperlinks: 2.3.0
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
'@swc/core': 1.15.18
- esbuild: 0.25.12
+ esbuild: 0.27.7
postcss: 8.5.15
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
- '@swc/core': 1.15.18
- esbuild: 0.27.7
postcss: 8.5.15
@@ -47233,7 +47253,7 @@ snapshots:
import-local: 3.1.0
interpret: 3.1.1
rechoir: 0.8.0
webpack-merge: 5.8.0
@@ -47244,7 +47264,7 @@ snapshots:
range-parser: 1.2.1
schema-utils: 4.3.3
optionalDependencies:
dependencies:
@@ -47304,7 +47324,7 @@ snapshots:
- postcss
- uglify-js
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.8
@@ -47327,7 +47347,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
tapable: 2.3.0
+ terser-webpack-plugin: 5.6.0([email protected])([email protected])
watchpack: 2.5.1
webpack-sources: 3.3.4
optionalDependencies:
@@ -47590,6 +47610,10 @@ snapshots:
+ dependencies:
+ cuint: 0.2.2
+
dependencies:
lib0: 0.2.117
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 700380679995..df7c476afd77 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1745,6 +1745,7 @@ dependencies = [
"lifecycle",
"limiters",
"lz-str",
+ "lz4",
"metrics",
"metrics-exporter-prometheus",
"metrics-util",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 0667eaeff245..0fe47f3e75a7 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -185,6 +185,7 @@ redis = { version = "0.32.7", features = [
regex = "1.11.1"
fancy-regex = "0.17"
lz-str = "0.2.1"
+lz4 = "1.28"
opentelemetry-proto = { version = "0.29.0", features = ["with-serde"] }
tonic = { version = "0.12.3", features = ["zstd"] }
tonic-build = "0.12"
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.toml
index af87ad305ae6..7bae3ec1bcd3 100644
--- a/rust/capture/Cargo.toml
+++ b/rust/capture/Cargo.toml
@@ -56,6 +56,7 @@ aws-config = { workspace = true }
aws-sdk-s3 = { workspace = true }
chrono = { workspace = true }
lz-str = { workspace = true }
+lz4 = { workspace = true }
multer = "3.0"
futures = { workspace = true }
sha2 = { workspace = true }
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 315664514fb1..accec17075ba 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -34,6 +34,28 @@ impl std::str::FromStr for CaptureMode {
}
}
+/// Compression algorithm applied at the Kafka message payload (envelope) level,
+/// independent of the broker-level `compression.codec` setting.
+/// Enables Warpstream billing reduction by storing compressed bytes.
+#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
+pub enum EnvelopeCompression {
+ #[default]
+ None,
+ Lz4,
+}
+
+impl std::str::FromStr for EnvelopeCompression {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_ref() {
+ "none" => Ok(EnvelopeCompression::None),
+ "lz4" => Ok(EnvelopeCompression::Lz4),
+ _ => Err(format!("Unknown EnvelopeCompression: {s}")),
+ }
+ }
+}
+
#[derive(Envconfig, Clone)]
pub struct Config {
#[envconfig(default = "false")]
@@ -254,6 +276,11 @@ pub struct KafkaConfig {
pub kafka_producer_message_max_bytes: u32, // message.max.bytes - max kafka message size we will produce
#[envconfig(default = "none")]
pub kafka_compression_codec: String, // none, gzip, snappy, lz4, zstd
+ /// Application-level compression for session replay (snapshot) Kafka payloads.
+ /// Independent of broker-level compression; consumers must detect and decompress.
+ /// Set to "lz4" to enable. Default "none" for safe rollout and rollback.
+ #[envconfig(default = "none")]
+ pub kafka_replay_envelope_compression: EnvelopeCompression,
pub kafka_hosts: String,
#[envconfig(default = "events_plugin_ingestion")]
pub kafka_topic: String,
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 6cac9ee1a9a6..00c8a295c1f4 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -2210,7 +2210,7 @@ mod tests {
);
let original_captured: CapturedEvent =
- serde_json::from_str(&original.payload).expect("payload should be a CapturedEvent");
+ serde_json::from_slice(&original.payload).expect("payload should be a CapturedEvent");
let original_raw: RawEvent = serde_json::from_str(&original_captured.data)
.expect("data field should be a serialized RawEvent");
assert!(
@@ -2245,7 +2245,7 @@ mod tests {
);
let redirect_captured: CapturedEvent =
- serde_json::from_str(&redirect.payload).expect("payload should be a CapturedEvent");
+ serde_json::from_slice(&redirect.payload).expect("payload should be a CapturedEvent");
assert_eq!(redirect_captured.event, "$$heatmap");
let redirect_raw: RawEvent = serde_json::from_str(&redirect_captured.data)
.expect("data field should be a serialized RawEvent");
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 9306b71896d7..b32e4ed44ae7 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -18,7 +18,7 @@
//! cost in the scatter-gather batch path at two `Arc::clone` calls (producer
//! + topics) rather than deep copies of limiter state.
use crate::api::CaptureError;
-use crate::config::KafkaConfig;
+use crate::config::{EnvelopeCompression, KafkaConfig};
use crate::sinks::producer::{KafkaProducer, ProduceRecord};
use crate::sinks::Event;
use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
@@ -195,15 +195,17 @@ impl From<&KafkaConfig> for KafkaTopicConfig {
/// Generic Kafka sink that can use any producer implementation.
///
-/// Holds only the producer handle and the topic config. No limiter state —
-/// overflow and replay-overflow routing decisions are stamped upstream in the
-/// pipeline onto `ProcessedEventMetadata::overflow_reason` and read here.
-/// Both fields are `Arc` so `clone()` is two atomic ref-count increments,
+/// Holds only the producer handle, the topic config, and the replay envelope
+/// compression setting. No limiter state — overflow and replay-overflow routing
+/// decisions are stamped upstream in the pipeline onto
+/// `ProcessedEventMetadata::overflow_reason` and read here.
+/// Both Arc fields are cheap to clone (two atomic ref-count increments),
/// which matters under the scatter-gather batch produce path where the sink
/// is cloned once per spawned prep task.
pub struct KafkaSinkBase<P: KafkaProducer> {
producer: Arc<P>,
topics: Arc<KafkaTopicConfig>,
+ replay_envelope_compression: EnvelopeCompression,
}
impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
@@ -211,6 +213,7 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
Self {
producer: Arc::clone(&self.producer),
topics: Arc::clone(&self.topics),
+ replay_envelope_compression: self.replay_envelope_compression,
}
}
}
@@ -344,6 +347,7 @@ impl KafkaSink {
Ok(KafkaSinkBase {
producer: Arc::new(rd_producer),
topics,
+ replay_envelope_compression: config.kafka_replay_envelope_compression,
})
}
}
@@ -356,6 +360,20 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
Self {
producer: Arc::new(producer),
topics: Arc::new(topics),
+ replay_envelope_compression: EnvelopeCompression::None,
+ }
+ }
+
+ /// Same as `with_producer` but with envelope compression enabled. Used in tests.
+ pub fn with_producer_and_compression(
+ producer: P,
+ topics: KafkaTopicConfig,
+ replay_envelope_compression: EnvelopeCompression,
+ ) -> Self {
+ Self {
+ producer: Arc::new(producer),
+ topics: Arc::new(topics),
+ replay_envelope_compression,
}
}
@@ -376,11 +394,33 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
fn prepare_record(&self, event: ProcessedEvent) -> Result<ProduceRecord, CaptureError> {
let (event, metadata) = (event.event, event.metadata);
- let payload = serde_json::to_string(&event).map_err(|e| {
+ let json = serde_json::to_string(&event).map_err(|e| {
error!("failed to serialize event: {e:#}");
CaptureError::NonRetryableSinkError
})?;
+ // Apply envelope-level compression for session replay when configured.
+ // Block format is used with a 4-byte LE uncompressed-size prefix so
+ // consumers can decompress without needing to inspect magic bytes —
+ // the `content-encoding` Kafka header signals that decompression is
+ // required. This allows compressed and uncompressed messages to coexist
+ // during rollout and rollback.
+ let payload = match (metadata.data_type, self.replay_envelope_compression) {
+ (DataType::SnapshotMain, EnvelopeCompression::Lz4) => {
+ let json_bytes = json.as_bytes();
+ let compressed = lz4::block::compress(json_bytes, None, false).map_err(|e| {
+ error!("failed to LZ4-compress payload: {e:#}");
+ CaptureError::NonRetryableSinkError
+ })?;
+ let uncompressed_len = json_bytes.len() as u32;
+ let mut payload = Vec::with_capacity(4 + compressed.len());
+ payload.extend_from_slice(&uncompressed_len.to_le_bytes());
+ payload.extend_from_slice(&compressed);
+ payload
+ }
+ _ => json.into_bytes(),
+ };
+
let data_type = metadata.data_type;
let event_key = event.key();
let session_id = metadata.session_id.clone();
@@ -507,6 +547,12 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
}
};
+ if matches!(self.replay_envelope_compression, EnvelopeCompression::Lz4)
+ && matches!(data_type, DataType::SnapshotMain)
+ {
+ headers.set_content_encoding("lz4".to_string());
+ }
+
Ok(ProduceRecord {
topic: topic.to_string(),
key: partition_key.map(|s| s.to_string()),
@@ -745,7 +791,7 @@ pub(crate) fn test_topics() -> KafkaTopicConfig {
#[cfg(test)]
mod tests {
use crate::api::CaptureError;
- use crate::config;
+ use crate::config::{self, EnvelopeCompression};
use crate::sinks::kafka::KafkaSink;
use crate::sinks::Event;
use crate::utils::uuid_v7;
@@ -834,6 +880,7 @@ mod tests {
kafka_metrics_producer_max_retries: None,
kafka_metrics_topic_metadata_refresh_interval_ms: None,
kafka_metrics_metadata_max_age_ms: None,
+ kafka_replay_envelope_compression: EnvelopeCompression::None,
};
let sink = KafkaSink::new(config, handle)
.await
@@ -1025,6 +1072,7 @@ mod tests {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
};
let owned_headers: OwnedHeaders = headers_historical.into();
@@ -1046,6 +1094,7 @@ mod tests {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
};
let owned_headers: OwnedHeaders = headers_main.into();
@@ -1075,6 +1124,7 @@ mod tests {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
};
// Convert to owned headers and back
@@ -1109,6 +1159,7 @@ mod tests {
dlq_reason: Some("test reason".to_string()),
dlq_step: Some("test step".to_string()),
dlq_timestamp: Some(dlq_timestamp.clone()),
+ content_encoding: None,
};
// Convert to owned headers and back
@@ -2247,7 +2298,7 @@ mod tests {
.iter()
.map(|r| {
let v: serde_json::Value =
- serde_json::from_str(&r.payload).expect("payload is valid json");
+ serde_json::from_slice(&r.payload).expect("payload is valid json");
v.get("uuid")
.and_then(|u| u.as_str())
.expect("uuid field present")
@@ -2373,7 +2424,7 @@ mod tests {
.iter()
.map(|r| {
let v: serde_json::Value =
- serde_json::from_str(&r.payload).expect("payload is valid json");
+ serde_json::from_slice(&r.payload).expect("payload is valid json");
v.get("distinct_id")
.and_then(|u| u.as_str())
.expect("distinct_id field present")
@@ -2423,7 +2474,7 @@ mod tests {
.iter()
.map(|r| {
let v: serde_json::Value =
- serde_json::from_str(&r.payload).expect("payload is valid json");
+ serde_json::from_slice(&r.payload).expect("payload is valid json");
v["distinct_id"].as_str().unwrap().to_string()
})
.collect();
@@ -2454,7 +2505,7 @@ mod tests {
.iter()
.map(|r| {
let v: serde_json::Value =
- serde_json::from_str(&r.payload).expect("payload is valid json");
+ serde_json::from_slice(&r.payload).expect("payload is valid json");
v["distinct_id"].as_str().unwrap().to_string()
})
.collect();
@@ -2539,5 +2590,82 @@ mod tests {
// 10 events >= SCATTER_GATHER_MIN_BATCH => scatter-gather path.
mixed_datatypes_routing_for_batch(10).await;
}
+
+ // ==================== Envelope compression ====================
+
+ #[tokio::test]
+ async fn snapshot_payload_uncompressed_by_default() {
+ let producer = MockKafkaProducer::new();
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+
+ let event = create_test_event(&EventInput {
+ data_type: DataType::SnapshotMain,
+ ..Default::default()
+ });
+ sink.kafka_send(event).unwrap().await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ // Payload must be valid UTF-8 JSON when compression is off.
+ let v: serde_json::Value = serde_json::from_slice(&records[0].payload)
+ .expect("uncompressed payload is valid json");
+ assert!(v.get("distinct_id").is_some());
+ }
+
+ #[tokio::test]
+ async fn snapshot_payload_lz4_compressed_when_enabled() {
+ let producer = MockKafkaProducer::new();
+ let sink = KafkaSinkBase::with_producer_and_compression(
+ producer.clone(),
+ test_topics(),
+ EnvelopeCompression::Lz4,
+ );
+
+ let event = create_test_event(&EventInput {
+ data_type: DataType::SnapshotMain,
+ ..Default::default()
+ });
+ sink.kafka_send(event).unwrap().await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ // `content-encoding: lz4` header must be present.
+ assert_eq!(
+ records[0].headers.content_encoding.as_deref(),
+ Some("lz4"),
+ "expected content-encoding: lz4 header"
+ );
+ // Payload = 4-byte LE uncompressed size + LZ4 block data. Decompress and verify.
+ let payload = &records[0].payload;
+ let uncompressed_len = u32::from_le_bytes(payload[..4].try_into().unwrap()) as usize;
+ let decompressed = lz4::block::decompress(&payload[4..], Some(uncompressed_len as i32))
+ .expect("failed to decompress");
+ let v: serde_json::Value =
+ serde_json::from_slice(&decompressed).expect("decompressed payload is valid json");
+ assert!(v.get("distinct_id").is_some());
+ }
+
+ #[tokio::test]
+ async fn non_snapshot_payload_not_compressed_when_lz4_enabled() {
+ let producer = MockKafkaProducer::new();
+ let sink = KafkaSinkBase::with_producer_and_compression(
+ producer.clone(),
+ test_topics(),
+ EnvelopeCompression::Lz4,
+ );
+
+ let event = create_test_event(&EventInput {
+ data_type: DataType::AnalyticsMain,
+ ..Default::default()
+ });
+ sink.kafka_send(event).unwrap().await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ // Non-snapshot payloads must stay uncompressed regardless of the flag.
+ let v: serde_json::Value =
+ serde_json::from_slice(&records[0].payload).expect("payload must be plain json");
+ assert!(v.get("distinct_id").is_some());
+ }
}
}
diff --git a/rust/capture/src/sinks/producer.rs b/rust/capture/src/sinks/producer.rs
index 929916be1f90..228fcefae7e1 100644
--- a/rust/capture/src/sinks/producer.rs
+++ b/rust/capture/src/sinks/producer.rs
@@ -16,7 +16,7 @@ use crate::prometheus::report_dropped_events;
pub struct ProduceRecord {
pub topic: String,
pub key: Option<String>,
- pub payload: String,
+ pub payload: Vec<u8>,
pub headers: CapturedEventHeaders,
}
@@ -137,7 +137,7 @@ impl<C: rdkafka::ClientContext + Send + Sync + 'static> KafkaProducer for RdKafk
match self.producer.send_result(FutureRecord {
topic: &record.topic,
- payload: Some(&record.payload),
+ payload: Some(record.payload.as_slice()),
partition: None,
key: record.key.as_deref(),
timestamp: None,
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index 44b52e558442..00cc894a8bdf 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -173,6 +173,7 @@ impl SinkEvent for WrappedEvent {
dlq_reason,
dlq_step,
dlq_timestamp,
+ content_encoding: None,
}
}
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index b686e2cd8f2a..88869f10ad53 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -104,6 +104,8 @@ mod tests {
use tracing::Level;
use uuid::Uuid;
+ use crate::config::EnvelopeCompression;
+
use crate::config::{CaptureMode, Config, KafkaConfig};
use crate::v1::analytics::types::{Event, Options};
@@ -205,6 +207,7 @@ mod tests {
kafka_metrics_producer_max_retries: None,
kafka_metrics_topic_metadata_refresh_interval_ms: None,
kafka_metrics_metadata_max_age_ms: None,
+ kafka_replay_envelope_compression: EnvelopeCompression::None,
},
otel_url: None,
otel_sampling_rate: 0.0,
diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
index df4a2b8cb011..62058eb07c73 100644
--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs
+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
@@ -37,6 +37,7 @@ fn empty_captured_headers() -> CapturedEventHeaders {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
}
}
diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rs
index b441b6cb3fbb..b76f09ef5b3e 100644
--- a/rust/capture/src/v1/sinks/router.rs
+++ b/rust/capture/src/v1/sinks/router.rs
@@ -176,6 +176,7 @@ mod tests {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
}
}
fn partition_key(&self, _ctx: &Context, buf: &mut String) {
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index ed6aeaaba45f..18e73a80babc 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -26,7 +26,7 @@ use tokio::net::TcpListener;
use tokio::time::timeout;
use tracing::{info, warn, Level};
-use capture::config::{CaptureMode, Config, KafkaConfig};
+use capture::config::{CaptureMode, Config, EnvelopeCompression, KafkaConfig};
use capture::server::serve;
use capture::setup;
use common_continuous_profiling::ContinuousProfilingConfig;
@@ -129,6 +129,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
kafka_metrics_producer_max_retries: None,
kafka_metrics_topic_metadata_refresh_interval_ms: None,
kafka_metrics_metadata_max_age_ms: None,
+ kafka_replay_envelope_compression: EnvelopeCompression::None,
},
otel_url: None,
otel_sampling_rate: 0.0,
diff --git a/rust/common/types/src/event.rs b/rust/common/types/src/event.rs
index 097cff126f96..8abb868029ac 100644
--- a/rust/common/types/src/event.rs
+++ b/rust/common/types/src/event.rs
@@ -123,6 +123,7 @@ pub struct CapturedEventHeaders {
pub dlq_reason: Option<String>,
pub dlq_step: Option<String>,
pub dlq_timestamp: Option<String>,
+ pub content_encoding: Option<String>,
}
impl CapturedEventHeaders {
@@ -145,6 +146,10 @@ impl CapturedEventHeaders {
pub fn set_dlq_timestamp(&mut self, value: String) {
self.dlq_timestamp = Some(value);
}
+
+ pub fn set_content_encoding(&mut self, value: String) {
+ self.content_encoding = Some(value);
+ }
}
impl From<CapturedEventHeaders> for OwnedHeaders {
@@ -217,6 +222,12 @@ impl From<CapturedEventHeaders> for OwnedHeaders {
value: Some(timestamp.as_str()),
});
}
+ if let Some(ref encoding) = headers.content_encoding {
+ owned = owned.insert(Header {
+ key: "content-encoding",
+ value: Some(encoding.as_str()),
+ });
+ }
owned
}
@@ -253,6 +264,7 @@ impl From<OwnedHeaders> for CapturedEventHeaders {
dlq_reason: headers_map.get("dlq_reason").cloned(),
dlq_step: headers_map.get("dlq_step").cloned(),
dlq_timestamp: headers_map.get("dlq_timestamp").cloned(),
+ content_encoding: headers_map.get("content-encoding").cloned(),
}
}
}
@@ -313,6 +325,7 @@ impl CapturedEvent {
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
+ content_encoding: None,
}
}