Stream-ML: Stream-Based Continual Learning
Goal
A production-oriented streaming system on Apache Flink that continuously updates an SGDClassifier on streaming data under configurable labeling budgets, with online model updates broadcast back to inference via BroadcastStream and a thread-safe relay queue.
The Problem
Traditional ML models are static artifacts—once trained, they remain frozen, unable to adapt to distribution shifts in streaming data. Yet in real-world applications like fraud detection, recommendation systems, or IoT sensor monitoring, data distributions evolve continuously. Retraining from scratch is prohibitively expensive, and labeling every incoming sample is impractical due to budget constraints.
We needed a system that could:
- Learn continuously from streaming data without full retraining
- Operate under labeling budgets (e.g., only 1 in 10 samples can be labeled)
- Adapt to concept drift while maintaining low-latency inference
- Provide observability into model performance, latency, and resource usage
- Be deployable with production-grade state management and fault tolerance
Methodology
We broke down the project into four stages, each addressing a core challenge of streaming continual learning:
1. Data Simulation with Concept Drift
Challenge: Need a controlled environment to test model adaptation to distribution shifts.
Approach: Loaded the MNIST dataset (70,000 handwritten digits) and simulated concept drift by reordering class distributions mid-stream:
- Pre-drift (first 50% of records): Only digits 0-4 appear
- Post-drift (remaining records): Only digits 5-9 appear
This creates a sudden distribution shift at a configurable point, forcing the model to adapt or fail. The dataset is cached locally as a pickle file to avoid repeated downloads across experiments.
2. Real-Time Inference with Active Learning
Challenge: Run low-latency predictions while intelligently selecting which samples to label under budget constraints.
Approach: Implemented a KeyedBroadcastProcessFunction (Flink's stateful stream processing primitive) that handles two data streams simultaneously.
For each incoming record:
- Runs inference using an SGDClassifier
- Calculates uncertainty score using modAL's uncertainty sampling (1 - max probability)
- Tracks end-to-end latency for performance monitoring
Token bucket labeling budget (implemented with Flink ValueState):
- Maintains two counters: tokens remaining and window progress
- Replenishes K tokens every N arrivals (e.g., 1 label per 10 records)
- Only labels samples where: uncertainty > threshold AND tokens available
- Routes labeled samples to a side output (Flink's multi-output pattern)
- Cold start handling: Before any model is trained, labels all samples to bootstrap the training operator
Result: Inference latency under 100ms (p99) with intelligent sample selection that prioritizes uncertain predictions.
3. Continual Learning with Replay Buffer
Challenge: Train on streaming data without forgetting past patterns, while respecting memory limits.
Approach: Designed a stateful training operator with three key components:
- Replay Buffer (Flink ListState):
- Stores labeled samples in a bounded buffer (configurable: 250-500 samples)
- Implements pluggable eviction policies:
- FIFO: Remove oldest sample when full (sliding window of recent data)
- Reservoir Sampling: Maintains uniform random sample of entire stream history (Algorithm R)
- Timer-Triggered Training (ProcessingTimeTimer):
- Fires at configurable intervals (3-10 seconds)
- Draws mini-batch (64 samples) from replay buffer
- Calls
partial_fit()on SGDClassifier (online learning) - Clears buffer after training (each sample used once)
- MLflow Integration:
- Logs per-training-step metrics: accuracy, buffer size, training duration
- Tracks system metrics: memory usage (RSS), labeling throughput
Result: Model continuously updates without catastrophic forgetting, with reservoir sampling maintaining 4-7% higher accuracy under tight budgets.
4. Model Feedback Loop (The Innovation)
Challenge: Flink execution graphs must be DAGs (Directed Acyclic Graphs), but this system logically requires training to feed back to inference—a cycle.
Approach: Broke the cycle with a thread-safe relay queue:
- Training → Queue: After each
partial_fit(), training operator serializes the model and puts it intomodel_relay.put(update) - Queue → Broadcast: A polling source reads from the queue every 50ms and emits updates as a Flink stream
- Broadcast → Inference: Updates are broadcast to all inference operator instances via Flink's
broadcast()primitive - Bootstrap: Null model seeds the broadcast so inference has something to read before first real update
Result: Continuous model improvement loop within Flink's DAG constraints—a production-ready pattern that could scale to Kafka in deployment.
Results
- Eviction Policy Comparison: Reservoir sampling held accuracy 4-7% higher across concept drift than FIFO, particularly under tight budgets (1/20), by preserving a more representative history.
- Budget-Accuracy Trade-off: Tighter budgets traded a small accuracy drop (2-3%) for noticeably lower CPU and memory usage.
- Training Interval: The 3,000ms training interval maximized post-drift accuracy at a modest p99 latency cost (<10ms increase).
- Inference Latency: Achieved p50 < 30ms and p99 < 100ms across all configurations.
- Throughput: Processed 500+ records/second on a local Flink MiniCluster.
- Memory Stability: Maintained stable RSS memory footprint under 200MB with bounded ListState and eviction policies.
- Concept Drift Recovery: Accuracy recovered from pre-drift levels (0-4 digits) to post-drift performance (5-9 digits) within 2-3 training cycles (10-15 seconds), demonstrating effective continual learning.