# zihad18/streaming-continual-learning-for-multi-vector-ddos-detection architecture

> Architecture diagram of the GitHub repository zihad18/streaming-continual-learning-for-multi-vector-ddos-detection, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection
- Repository: https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection

## Overview

1. **Overall shape**
   - This repo is a **streaming ML system** with a clear split between **offline initialization/training** and **online inference/adaptation**.
   - The runtime loop is: **generate stream data → publish to Kafka → consume in Spark → score with online ensemble → adapt models when drift is detected**.

2. **Offline training and data preparation boundary (`train_models.py`)**
   - This script is the setup phase.
   - It prepares the KDD Cup ’99 dataset, fits a preprocessing pipeline with scikit-learn, trains an initial ensemble of **river `ARFClassifier`** models, and saves model artifacts under `MODEL_DIR`.
   - It also creates a **drift-heavy evaluation stream** with block-wise distribution shifts that later feeds the producer.

3. **Streaming data source boundary (`kdd_producer.py`)**
   - This component is a **Kafka producer**.
   - It reads the generated evaluation dataset and emits records into the Kafka topic named by `KAFKA_TOPIC`.
   - It can optionally include labels or simulate a label-free production stream via `SEND_LABEL`.

4. **Stream processing and model-serving boundary (`spark_consumer.py`)**
   - This is the core online engine.
   - It uses **PySpark Structured Streaming** to consume Kafka micro-batches, then performs ensemble inference and model updates inside `foreachBatch`.
   - It is designed to run locally (`LOCAL_MODE=true`) or in a distributed Spark environment.

5. **Data flow through the system**
   - The input records originate from the generated KDD stream file, are published to Kafka, then consumed by Spark.
   - Within the consumer, each record is passed through the saved preprocessing/model state, scored by the ensemble, and optionally used for incremental learning.
   - The persistent handoff points are the **Kafka topic** and the **model artifact directory**.

6. **Modeling strategy**
   - The online models are **incremental tree-based learners** from the `river` library.
   - The ensemble uses **majority voting** for predictions, which makes the consumer a lightweight streaming inference service rather than a batch retrainer.
   - The system is explicitly built for **continual learning** instead of periodic offline retraining.

7. **Drift detection mechanism**
   - `spark_consumer.py` contains a custom **RealTimeOAW** state machine.
   - It does not rely on ground-truth labels in real time; instead, it monitors a **confidence-derived anomaly signal** as a proxy for error likelihood.
   - The detector moves through **Normal → Alert → Drift** states based on recent anomaly ratios.

8. **Adaptation behavior**
   - When a model enters **Drift**, it retrains incrementally using a recent adaptive window.
   - The model backfills that window with **pseudo-labels from its own predictions**, which is the key self-correction mechanism in this repo.
   - This creates a closed-loop adaptation path entirely inside the streaming consumer.

9. **Metrics and observability**
   - If labels are available (`SEND_LABEL=true`), the consumer can compute standard supervised metrics such as **accuracy, precision, recall, F1, and confusion matrix**.
   - It also reports per-tree state transitions and summary metrics periodically, roughly every 500 records.
   - If labels are absent, the system still functions using the label-free drift signal.

10. **Infrastructure and deployment boundary**
   - The architecture depends on **Kafka**, **Spark**, **Python 3.8+**, **JDK 8/11**, and the Python ML stack (`pyspark`, `river`, `scikit-learn`, `kafka-python`, etc.).
   - `docker-compose.yml` likely supports local infrastructure orchestration, while the README also notes compatibility with cloud Spark environments such as **Dataproc**.
   - Environment variables control the main deployment seams: Kafka endpoint, topic, model storage location, local-vs-cluster Spark mode, and drift threshold.

Main entry points: [`train_models.py`](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/train_models.py) (Train models), [`kdd_producer.py`](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/kdd_producer.py) (Kafka producer), [`spark_consumer.py`](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/spark_consumer.py) (Spark consumer), [`docker-compose.yml`](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/docker-compose.yml) (Docker Compose)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_offline["Offline setup"]
  node_train["Train models<br/>offline training pipeline<br/>[train_models.py]"]
  node_prep["Data prep<br/>dataset prep"]
  node_preproc["Preprocess<br/>sklearn pipeline"]
  node_initial["Seed ensemble<br/>river ARF"]
  node_evalstream["Eval stream<br/>drifted stream"]
end

subgraph group_streaming["Streaming path"]
  node_producer["Kafka producer<br/>stream publisher<br/>[kdd_producer.py]"]
  node_topic["Kafka topic<br/>message bus"]
  node_consumer["Spark consumer<br/>stream processor<br/>[spark_consumer.py]"]
  node_foreach["Batch loop<br/>foreachBatch engine"]
  node_ensemble["Online ensemble<br/>river ensemble"]
  node_vote(("Majority vote<br/>prediction rule"))
  node_oaw{{"RealTimeOAW<br/>drift detector"}}
  node_adapt["Adaptive window<br/>online retraining"]
  node_pseudo["Pseudo-labels<br/>self-labeling"]
  node_metrics["Metrics<br/>observability"]
end

subgraph group_ops["Deployment"]
  node_compose["Docker Compose<br/>local infra<br/>[docker-compose.yml]"]
  node_env["Runtime config<br/>environment variables"]
end

node_train -->|"loads"| node_prep
node_train -->|"fits"| node_preproc
node_train -->|"trains"| node_initial
node_train -->|"generates"| node_evalstream
node_evalstream -->|"input"| node_producer
node_producer -->|"publishes"| node_topic
node_topic -->|"consumes"| node_consumer
node_consumer -->|"executes"| node_foreach
node_foreach -->|"applies"| node_preproc
node_foreach -->|"scores"| node_ensemble
node_ensemble -->|"aggregates"| node_vote
node_foreach -->|"monitors"| node_oaw
node_oaw -->|"drift"| node_adapt
node_adapt -->|"fills"| node_pseudo
node_pseudo -->|"updates"| node_ensemble
node_foreach -->|"reports"| node_metrics
node_compose -.->|"supports"| node_producer
node_compose -.->|"supports"| node_consumer
node_env -.->|"configures"| node_train
node_env -.->|"configures"| node_producer
node_env -.->|"configures"| node_consumer
node_env -.->|"names"| node_topic

click node_train "https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/train_models.py"
click node_producer "https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/kdd_producer.py"
click node_consumer "https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/spark_consumer.py"
click node_compose "https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/docker-compose.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_train,node_prep,node_preproc,node_initial,node_evalstream toneBlue
class node_producer,node_topic,node_consumer,node_foreach,node_ensemble,node_vote,node_oaw,node_adapt,node_pseudo,node_metrics toneAmber
class node_compose,node_env toneMint
```

## Components

### Offline setup

Dataset preparation, preprocessing, and initial model training.

- [Train models](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/train_models.py): offline training pipeline · Prepares KDD data, fits preprocessing, trains initial river ensemble, and writes artifacts. · `train_models.py`
- **Data prep**: dataset prep · Loads and shapes the KDD Cup '99 data used for training and stream generation.
- **Preprocess**: sklearn pipeline · Feature transformation pipeline saved with the model artifacts.
- **Seed ensemble**: river ARF · Initial incremental tree ensemble used as the starting online model state.
- **Eval stream**: drifted stream · Block-wise shifted evaluation stream used to drive the producer and stress drift handling.

### Streaming path

Kafka-based production and online processing loop.

- [Kafka producer](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/kdd_producer.py): stream publisher · Reads the generated evaluation stream and publishes records to Kafka. · `kdd_producer.py`
- **Kafka topic**: message bus · Persistent handoff between producer and Spark consumer.
- [Spark consumer](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/spark_consumer.py): stream processor · Consumes Kafka micro-batches and runs online inference and adaptation. · `spark_consumer.py`
- **Batch loop**: foreachBatch engine · Micro-batch execution boundary where scoring and model updates happen.
- **Online ensemble**: river ensemble · Incremental tree-based model state used for majority-vote prediction.
- **Majority vote**: prediction rule · Combines tree outputs into the final class prediction.
- **RealTimeOAW**: drift detector · State machine that tracks confidence-derived anomaly ratios and transitions through normal, alert, and drift.
- **Adaptive window**: online retraining · Recent window used to incrementally refresh the ensemble after drift is detected.
- **Pseudo-labels**: self-labeling · Model-generated labels used to backfill the adaptive window during drift recovery.
- **Metrics**: observability · Optional supervised metrics and periodic state summaries when labels are available.

### Deployment

Local orchestration and environment boundaries.

- [Docker Compose](https://github.com/zihad18/streaming-continual-learning-for-multi-vector-ddos-detection/blob/main/docker-compose.yml): local infra · Local orchestration for Kafka and related services. · `docker-compose.yml`
- **Runtime config**: environment variables · Controls Kafka endpoint, topic, model directory, Spark mode, label handling, and drift threshold.

## Connections

- Train models → Data prep: loads · Training begins by preparing the KDD dataset.
- Train models → Preprocess: fits · Builds the preprocessing pipeline.
- Train models → Seed ensemble: trains · Creates the seed online ensemble.
- Train models → Eval stream: generates · Produces the drift-heavy evaluation stream.
- Eval stream → Kafka producer: input · Producer reads the prepared stream file.
- Kafka producer → Kafka topic: publishes · Sends records to Kafka.
- Kafka topic → Spark consumer: consumes · Spark reads Kafka micro-batches.
- Spark consumer → Batch loop: executes · Streaming logic runs per micro-batch.
- Batch loop → Preprocess: applies · Uses saved preprocessing during scoring.
- Batch loop → Online ensemble: scores · Runs online inference with the ensemble.
- Online ensemble → Majority vote: aggregates · Tree predictions are combined by majority vote.
- Batch loop → RealTimeOAW: monitors · Confidence signal feeds drift detection.
- RealTimeOAW → Adaptive window: drift · Drift state triggers adaptive retraining.
- Adaptive window → Pseudo-labels: fills · Recent records are backfilled with self-generated labels.
- Pseudo-labels → Online ensemble: updates · Incremental learning refreshes the ensemble state.
- Batch loop → Metrics: reports · Produces supervised and summary metrics when labels exist.
- Docker Compose → Kafka producer: supports · Local infrastructure helps run the producer stack.
- Docker Compose → Spark consumer: supports · Local infrastructure helps run Spark locally.
- Runtime config → Train models: configures · Controls model paths and training behavior.
- Runtime config → Kafka producer: configures · Controls Kafka topic and label emission.
- Runtime config → Spark consumer: configures · Controls Spark mode, drift threshold, and model location.
- Runtime config → Kafka topic: names · Defines the Kafka topic boundary.
