Building Real-Time Streaming Analytics with Quix and Polars
Traditional Python streaming pipelines face an uncomfortable architectural compromise: either write row-by-row event handlers that choke under high message throughput, or deploy heavy JVM clusters (Apache Flink / Spark Structured Streaming) that introduce operational complexity and serialization overhead for Python data science teams.
Pairing Quix Streams with Polars eliminates both bottlenecks. Quix Streams provides a pure-Python, Kafka-native stream processing runtime with RocksDB-backed state stores and exactly-once semantics, while Polars executes Rust-powered, SIMD-vectorized transformations and rolling aggregations over buffered micro-batches at native C/Rust speeds.
Why Combine Quix Streams with Polars?
Quix handles distributed Kafka partition management, consumer offsets, and fault-tolerant window state, while Polars processes tabular feature engineering inside each window or micro-batch without Python for-loop overhead:
| Streaming Architecture | Runtime Stack | Stateful Windowing | Tabular Feature Throughput | Operational Complexity |
|---|---|---|---|---|
Raw kafka-python + Pandas | Pure Python | Manual in-memory dicts (lost on crash) | Low (row-oriented overhead) | Low, but fragile state |
| PySpark Structured Streaming | JVM + Py4J Serialization | Built-in | High (after JVM warmup) | Heavy cluster orchestration |
| Quix Streams + Polars | Python + Rust (librdkafka + Arrow) | RocksDB-backed fault-tolerant state | Very High (SIMD columnar execution) | Lightweight Docker / Kubernetes pods |
Pipeline Architecture
In this project, we build an Industrial IoT Telemetry & Anomaly Alerting Pipeline that ingests high-frequency turbine sensor readings (temperature, vibration_rms, rpm, power_kw), aggregates 10-second tumbling windows, computes vectorized z-score anomaly features in Polars, and publishes structured alerts to downstream topics:
[Sensor Producer] ──▶ Kafka Topic: `turbine-telemetry`
│
▼
[Quix Streams Application]
├── 10s Tumbling Window (RocksDB State)
├── Polars Vectorized Feature Engine (P95, Z-Score, EWMA)
└── Conditional Alert Router
├──▶ Kafka Topic: `turbine-metrics-10s`
└──▶ Kafka Topic: `turbine-alerts`
Project Structure & Dependencies
Organize the streaming application into modular producer, transformation, and pipeline entrypoint files:
quix-polars-telemetry/
├── docker-compose.yml # Local Redpanda (Kafka-compatible) broker
├── src/
│ ├── producer.py # Synthetic IoT telemetry stream generator
│ ├── analytics.py # Vectorized Polars window feature computations
│ └── pipeline.py # Quix Streams stateful window & routing topology
└── requirements.txt
Install Quix Streams and Polars:
pip install quixstreams polars numpy
Spin up a lightweight local Kafka-compatible broker using Redpanda (docker-compose.yml):
services:
redpanda:
image: redpandadata/redpanda:latest
command:
- redpanda start
- --smp 1
- --overprovisioned
- --kafka-addr internal://0.0.0.0:9092,external://0.0.0.0:19092
- --advertise-kafka-addr internal://redpanda:9092,external://localhost:19092
ports:
- "19092:19092"
Start the broker:
docker compose up -d
Step 1: Streaming Telemetry Producer (src/producer.py)
This producer simulates a fleet of wind turbines emitting JSON telemetry events keyed by turbine_id (ensuring all messages for a given turbine route to the same Kafka partition) with occasional vibration spikes:
import json
import random
import time
from datetime import datetime, timezone
from quixstreams import Application
BROKER_ADDRESS = "localhost:19092"
INPUT_TOPIC = "turbine-telemetry"
TURBINE_IDS = ["TRB-01", "TRB-02", "TRB-03", "TRB-04"]
def generate_telemetry_event(turbine_id: str) -> dict:
"""Simulate realistic sensor readings with occasional mechanical vibration anomalies."""
is_spike = random.random() < 0.04
base_vibration = random.gauss(2.1, 0.25)
vibration = base_vibration + (random.uniform(3.5, 6.0) if is_spike else 0.0)
return {
"turbine_id": turbine_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
"rpm": round(random.gauss(14.5, 0.6), 2),
"temperature_c": round(random.gauss(64.0, 2.2) + (6.5 if is_spike else 0.0), 2),
"vibration_rms": round(vibration, 3),
"power_kw": round(random.gauss(2450.0, 110.0), 1),
}
def run_producer() -> None:
app = Application(broker_address=BROKER_ADDRESS)
topic = app.topic(INPUT_TOPIC, value_serializer="json")
print(f"Streaming telemetry to '{INPUT_TOPIC}' on {BROKER_ADDRESS}...")
with app.get_producer() as producer:
while True:
for turbine_id in TURBINE_IDS:
event = generate_telemetry_event(turbine_id)
producer.produce(
topic=topic.name,
key=turbine_id,
value=json.dumps(event).encode("utf-8"),
)
time.sleep(0.1) # 40 events/sec across 4 turbines
if __name__ == "__main__":
run_producer()
Step 2: Vectorized Window Analytics with Polars (src/analytics.py)
Inside each closed tumbling window, Quix hands our reducer a list of buffered sensor dictionaries. Converting that window buffer into a Polars DataFrame lets us compute multi-column quantiles, dynamic z-scores, power efficiency ratios, and anomaly flags in a single lazy expression graph:
import polars as pl
def compute_window_metrics(
turbine_id: str,
window_start_ms: int,
window_end_ms: int,
events: list[dict],
) -> dict:
"""
Aggregate a buffered tumbling window of sensor events using Polars expressions.
"""
df = pl.DataFrame(events)
# Vectorized feature engineering & summary statistics in Polars
summary = (
df.lazy()
.with_columns(
[
(pl.col("power_kw") / pl.col("rpm").clip(lower_bound=0.1)).alias(
"kw_per_rpm"
),
(
(pl.col("vibration_rms") - pl.col("vibration_rms").mean())
/ pl.col("vibration_rms").std().fill_null(1.0).clip(lower_bound=1e-4)
).alias("vibration_zscore"),
]
)
.select(
[
pl.len().alias("sample_count"),
pl.col("temperature_c").mean().round(2).alias("avg_temp_c"),
pl.col("temperature_c").max().round(2).alias("max_temp_c"),
pl.col("vibration_rms").mean().round(3).alias("avg_vibration"),
pl.col("vibration_rms").quantile(0.95).round(3).alias("p95_vibration"),
pl.col("vibration_zscore").max().round(2).alias("max_vibration_zscore"),
pl.col("power_kw").mean().round(1).alias("avg_power_kw"),
pl.col("kw_per_rpm").mean().round(2).alias("avg_efficiency_ratio"),
]
)
.collect()
.to_dicts()[0]
)
is_anomalous = (
summary["p95_vibration"] > 4.5
or summary["max_temp_c"] > 72.0
or summary["max_vibration_zscore"] > 2.6
)
return {
"turbine_id": turbine_id,
"window_start_ms": window_start_ms,
"window_end_ms": window_end_ms,
"is_anomalous": is_anomalous,
**summary,
}
Step 3: Stateful Quix Streams Topology (src/pipeline.py)
Now we wire up the StreamingDataFrame in Quix Streams. Using tumbling_window(duration_ms=10_000) with a custom reduce + initializer, Quix buffers incoming messages per turbine_id in local RocksDB state, invokes compute_window_metrics once each 10-second window closes (.final()), and branches anomalous windows to a dedicated alerting topic:
from datetime import timedelta
from quixstreams import Application
from analytics import compute_window_metrics
BROKER_ADDRESS = "localhost:19092"
INPUT_TOPIC = "turbine-telemetry"
METRICS_TOPIC = "turbine-metrics-10s"
ALERTS_TOPIC = "turbine-alerts"
def init_window_buffer(first_event: dict) -> list[dict]:
"""Initialize RocksDB state buffer with the first event in the window."""
return [first_event]
def append_event_to_buffer(buffer: list[dict], event: dict) -> list[dict]:
"""Accumulate incoming events into the partition's window buffer."""
buffer.append(event)
return buffer
def build_and_run_pipeline() -> None:
app = Application(
broker_address=BROKER_ADDRESS,
consumer_group="turbine-analytics-v1",
auto_offset_reset="latest",
state_dir="state/rocksdb",
)
input_topic = app.topic(INPUT_TOPIC, value_deserializer="json")
metrics_topic = app.topic(METRICS_TOPIC, value_serializer="json")
alerts_topic = app.topic(ALERTS_TOPIC, value_serializer="json")
sdf = app.dataframe(input_topic)
# 1. Group events into 10-second tumbling windows with 1-second grace period
windowed_sdf = (
sdf.tumbling_window(
duration_ms=timedelta(seconds=10),
grace_ms=timedelta(seconds=1),
)
.reduce(reducer=append_event_to_buffer, initializer=init_window_buffer)
.final()
)
# 2. Run vectorized Polars analytics over each completed window
enriched_sdf = windowed_sdf.apply(
lambda row: compute_window_metrics(
turbine_id=row["value"][0]["turbine_id"],
window_start_ms=row["start"],
window_end_ms=row["end"],
events=row["value"],
)
)
# 3. Publish all aggregated metrics to the primary analytics topic
enriched_sdf.to_topic(metrics_topic)
# 4. Filter and route high-severity anomalies to the alerting topic
alerts_sdf = enriched_sdf.filter(lambda metrics: metrics["is_anomalous"])
alerts_sdf.update(
lambda alert: print(
f"[ALERT] {alert['turbine_id']} | P95 Vib: {alert['p95_vibration']} | "
f"Max Temp: {alert['max_temp_c']}C | Z-Score: {alert['max_vibration_zscore']}"
)
)
alerts_sdf.to_topic(alerts_topic)
print("Starting Quix + Polars streaming analytics pipeline...")
app.run(sdf)
if __name__ == "__main__":
build_and_run_pipeline()
Run the pipeline and producer in separate terminals:
# Terminal 1: Start stream processor
python src/pipeline.py
# Terminal 2: Start synthetic sensor stream
python src/producer.py
Scaling & Fault Tolerance Under Production Load
When deploying this architecture to production Kubernetes clusters, Quix and Polars scale horizontally without code changes:
- Partition-Aligned Horizontal Scaling: If
turbine-telemetryhas 12 Kafka partitions, deploying 4 replicas ofpipeline.pywith the sameconsumer_groupautomatically assigns 3 partitions and 3 isolated RocksDB state directories per pod. - Persistent Volume Claims (PVCs) for RocksDB State: Mount persistent block storage to
state_dirin Kubernetes so pod restarts recover local window state from disk rather than replaying Kafka changelog topics from scratch. - Zero-Copy Arrow Sinks: For cold analytics storage, add a sink worker that collects 5,000-row Polars DataFrames and writes partitioned Parquet files directly to S3 or Iceberg using
df.write_parquet().
Best Practices for Quix + Polars Streaming Pipelines
- Construct Polars DataFrames once per window or micro-batch: Never instantiate
pl.DataFrame([single_row])per individual message; batch 50+ events via tumbling windows or micro-batches so Polars' Arrow memory allocation overhead is amortized across hundreds of rows. - Extract event timestamps from payload fields (
timestamp_extractor): Configureapp.topic(..., timestamp_extractor=...)to use event-time timestamps rather than Kafka broker ingestion time so network jitter does not distort tumbling window boundaries. - Use Polars
LazyFramequery optimization: Chaining expressions inside.lazy() ... .collect()enables predicate pushdown and common subexpression elimination across complex rolling features. - Set explicit
grace_msfor out-of-order IoT packets: Cellular and edge gateways routinely deliver delayed packets; a1s–5sgrace period prevents late readings from being dropped silently.
Common Mistakes
- Creating a Polars DataFrame inside a per-message
.apply()step: Instantiating a DataFrame for every single Kafka message adds ~150 microseconds of overhead per row, reducing throughput by 20x compared to window-level aggregation. - Forgetting message keys on the producer: Producing events with
key=Noneround-robins messages across partitions, scattering a single device's telemetry across multiple consumer workers and breaking per-device window aggregations. - Storing unbounded lists in RocksDB without window expiration: Always use
.tumbling_window()or.hopping_window()with.final()rather than appending indefinitely tostate.get()keys, which causes unbounded disk growth.
Summary
Combining Quix Streams and Polars gives Python data engineering and ML teams a high-throughput, fault-tolerant streaming analytics stack without JVM overhead. Quix handles Kafka partitioning, event-time windowing, and RocksDB state recovery, while Polars executes vectorized feature engineering and anomaly detection at Rust speed.