Skip to content

About

A high-throughput, distributed streaming platform designed to monitor game server infrastructure, score match quality, profile player behavior, and detect anomalies (aimbots, smurfs) in real time using Apache Kafka, Apache Spark Structured Streaming, Go, and PySpark.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Real-Time Competitive Gaming Intelligence Platform

A high-throughput, distributed streaming platform designed to monitor game server infrastructure, score match quality, profile player behavior, and detect anomalies (aimbots, smurfs) in real time using Apache Kafka, Apache Spark Structured Streaming, Go, and PySpark.


Architecture

                              SIMULATOR (Go)
             ┌────────────────────────┼────────────────────────┐
      gameplay events           player events            server metrics
   (one SHOT per trigger     (login, matchmaking,       (cpu, ram, tick,
    pull, outcome inline)     purchases, reports)        loss, latency)
             └────────────────────────┼────────────────────────┘
                                      ▼
                               KAFKA (KRaft)
             gameplay_events · player_events · server_metrics · alerts
                                      │
                                      ▼
                  SPARK STRUCTURED STREAMING — 4 drivers
     server_health · match_quality · cheat_detection · advanced_analytics
                                        (smurf · behavior change · economy)
             │                        │                          │
             ▼                        ▼                          ▼
      Redis (live state)     Kafka `alerts` topic      Parquet archive (local
             │                        │                disk, ./data/parquet)
             │                        ▼                          │
             │                Alert Engine (Go)                  ▼
             │           dedup + per-entity rate limit   Historical batch
             │           → Postgres alert_history        (make spark-batch)
             │           → Redis pub/sub alerts:stream
             │           → optional webhook
             ▼                        │
     FastAPI REST + WebSockets ◄──────┘
     + Datastar dashboard (:8000)

Technology Stack

Layer Technology
Event Simulator Go 1.25 (kafka-go, concurrent goroutines, paced per-topic producers)
Ingestion Apache Kafka 3.7 (KRaft mode - no ZooKeeper)
Stream Processing Apache Spark 3.5 (PySpark Structured Streaming, Sliding/Tumbling/Session Windows)
Anomaly Model scikit-learn IsolationForest (trained offline, scored in foreachBatch)
Real-Time Storage Redis 7
Persistent Storage PostgreSQL 16 (alert history) + Parquet archive on local disk
Alert Engine Go 1.25 (kafka-go, go-redis, pgx)
Backend API Python FastAPI + WebSockets
Frontend Datastar v1.0.4 + Jinja2 SSR (SSE patches, zero build step)

Project Structure

gaming-intelligence-platform/
├── docker-compose.yml              # Kafka (+ topic init), Spark, Redis, Postgres, API, alert engine
├── Makefile                        # Automation shortcuts (`make help`)
├── README.md                       # Project overview and setup instructions
├── LICENSE                         # MIT
├── .gitignore                      # Git ignore rules
├── schemas/                        # Avro event contracts
│   ├── gameplay_event.avsc
│   ├── player_event.avsc
│   ├── server_metric.avsc
│   └── alert.avsc
├── simulator/                      # Go Game Event Simulator
│   ├── go.mod
│   ├── cmd/simulator/              # config · profiles · world · combat · engine · sink
│   └── profiles/                   # Statistical player archetypes (YAML)
│       ├── normal_bronze.yaml
│       ├── normal_gold.yaml
│       ├── normal_diamond.yaml
│       ├── cheater_aimbot.yaml
│       ├── cheater_wallhack.yaml
│       ├── smurf.yaml
│       └── toxic.yaml
├── streaming/                      # PySpark Streaming Pipelines
│   ├── Dockerfile                  # apache/spark:3.5.1 + pinned Python deps
│   ├── requirements.txt
│   ├── models/                     # IsolationForest artifact (make train-model)
│   ├── src/
│   │   ├── common/
│   │   │   ├── config.py
│   │   │   ├── schemas.py
│   │   │   ├── alerts.py           # Redis dedup + batched Kafka alert flush
│   │   │   ├── sinks.py            # Parquet archive sink
│   │   │   └── runtime.py
│   │   ├── jobs/                   # Streaming analytics jobs (4 submit targets)
│   │   ├── ml/                     # IsolationForest scoring + offline training
│   │   └── batch/                  # historical_analysis.py (make spark-batch)
│   └── tests/                      # PySpark unit tests (make test-streaming)
├── alert-engine/                   # Go alert engine: Kafka alerts → dedup → Postgres / Redis / webhook
│   ├── Dockerfile
│   ├── go.mod
│   └── *.go                        # config · alert · gate · handler · sinks · main (+ tests)
├── api/                            # FastAPI REST, WebSocket & Dashboard
│   ├── requirements.txt
│   ├── main.py                     # REST + WS endpoints
│   ├── state.py                    # Shared feed / sampler / PG pool
│   ├── dashboard.py                # SSR views + Datastar SSE streams
│   ├── templates/                  # Jinja2 (7 tabs + drill-downs)
│   └── static/                     # dashboard.css
├── benchmarks/                     # Phase 6: tiered load benchmark + collector
│   ├── run_benchmark.sh
│   ├── collect.py
│   └── plot_results.py
└── docs/
    └── screenshots/

Screenshots

Overview — live KPIs, event stream, alerts, flagged players:

Overview dashboard

Server health map — live health bars and status chips (server-02 is the simulator's deliberately-degraded node):

Server health

Match quality — distribution histogram with per-match drill-down:

Match quality

Anti-cheat — flagged players ranked by effective suspicion (base score + behavior boost + IsolationForest):

Anti-cheat

Alerts — live feed pushed by the Go alert engine, plus the filterable PostgreSQL alert_history:

Alerts


Quick Start

1. Launch the Infrastructure

make up

This starts:

  • Kafka broker, reachable from the host at localhost:9094 (containers use kafka:9092); a one-shot kafka-init container creates the four topics (broker auto-creation is off)
  • Spark Master Web UI at http://localhost:8080
  • 2 Spark Workers (2 cores, 2GB memory each) with the Python ML packages installed
  • Redis on port 6379
  • PostgreSQL on host port 5433 (container port 5432)
  • FastAPI backend + dashboard on port 8000 (starts after kafka-init has created the topics)
  • Go alert engine (consumes the alerts topic; same start condition)

2. Verify Kafka Topics

make kafka-topics

3. Train the Anomaly Model

make train-model

Fits the IsolationForest on simulated normal play and writes streaming/models/anti_cheat_isolation_forest.joblib. cheat_detection loads it at start-up, so train before submitting the jobs (without it the job runs on the heuristic score alone).

4. Submit the PySpark Streaming Jobs

There are four drivers. Submit them one at a time, waiting until each app shows up as running in the Spark UI before the next — concurrent cold submits race on the shared Ivy cache that --packages downloads into:

make spark-submit JOB=server_health
make spark-submit JOB=match_quality
make spark-submit JOB=cheat_detection
make spark-submit JOB=advanced_analytics   # smurf + behavior change + economy

Each driver is capped at 1 core, so the four exactly fill the 4-core cluster. make spark-submit stays attached to the driver; run each in its own terminal.

Recovery and checkpoint migration

  • Stop the existing drivers before deploying these changes. Cheat detection uses the new cheat_detection_v3 checkpoint because it finalizes event-time windows before advancing persistence. Finalized behavior steps use behavior_change_steps_v2; the separate raw-shot archive retains the original behavior_change checkpoint. Do not delete existing checkpoints. New queries read retained Kafka history; their first catch-up can be large.
  • Behavior state is rebuilt once when migrating from the old partial-window detector to state version 2. It must complete its warm-up again. Steps are 5-second event-time windows finalized with a 30-second watermark. Very late data can be dropped; when input stops, the trailing windows remain open until event time advances. Source-offset drain is not proof of window finalization.
  • Redis/Kafka transient failures use bounded retries, then fail the query; restart the affected driver after recovery. Serving-state updates and alert intents commit together in Redis. alerts:outbox retains intents until Kafka acknowledges them; replay may deliver duplicates with the same alert ID. Do not expire or manually clear the outbox. Cheat verdicts for the outstanding batch are retained in Redis so archive retries do not recompute decisions.
  • Compose enables Redis AOF with appendfsync always to persist acknowledged state/outbox writes. This favors durability over peak write throughput and requires recreating the Redis service to apply to an existing stack; retain its volume. This is not protection against volume loss or disk failure.
  • Parquet failures now fail the batch. Archives publish complete files using atomic rename and keep generation/batch receipts across compaction, preventing replay duplicates. This requires local storage or HDFS, not object-store rename semantics. Compaction must still run only while writers are stopped.
  • Historical cheat analysis reports recorded, judged online decisions separately from raw heuristic sweeps. Legacy/missing decisions are reported as unknown, not fabricated clean verdicts. Source bounds exclude mixed/previous-run windows; legacy boundary windows without bounds are excluded conservatively.

5. Run Event Simulator

Run against local Kafka:

make simulator-run

Or test locally without Kafka running (dry-run mode):

make simulator-dry-run

6. Open the API and Dashboard

The API is already running from make up. Interactive Swagger docs are at http://localhost:8000/docs.

The live dashboard is served from the same server at http://localhost:8000/ — server-rendered HTML with Datastar SSE patches (no build step, no separate frontend container). After changing anything under api/, rebuild and restart it with make api-up.

7. Batch Analysis and Benchmark

make spark-batch JOB=all     # or skill, weapon, cheat, quality, servers, peak
make benchmark               # tiered load test, 1k → 20k events/s (RATES=, DURATION=)
make benchmark-plot          # newest run → docs/benchmarks.png

spark-batch runs in local[1] mode on the master on purpose: the streaming jobs hold every cluster core. It reads the Parquet archive the jobs write to ./data/parquet.


Configuration

Alert engine (environment variables)

Variable Default Notes
KAFKA_BOOTSTRAP_SERVERS localhost:9092 compose sets kafka:9092; from the host use localhost:9094
ALERTS_TOPIC alerts
ALERT_ENGINE_GROUP alert-engine Kafka consumer group (at-least-once: offsets commit after the Postgres insert)
REDIS_HOST / REDIS_PORT localhost / 6379 Redis ≥ 7 supported deployment (atomic Lua gates; persistent streaming outbox)
POSTGRES_URL — full DSN; overrides the POSTGRES_* parts below
POSTGRES_HOST / POSTGRES_PORT localhost / 5432 from the host the published port is 5433
POSTGRES_USER / POSTGRES_PASSWORD / POSTGRES_DB gaming / gaming_dev / gaming_platform
ALERT_DEDUP_TTL 5m Go duration; window in which a repeated alert (same type + entity) is dropped
ALERT_RATE_LIMIT_TTL 5m Go duration; at most one alert per entity per window
ALERT_WEBHOOK_URL empty (disabled) optional http(s) URL; each accepted alert is POSTed as Discord/Slack-style JSON

The engine validates the whole configuration at start-up and exits with every problem listed. Accepted alerts land in Postgres alert_history and are published on the Redis channel alerts:stream. Compose passes ALERT_WEBHOOK_URL, ALERT_DEDUP_TTL and ALERT_RATE_LIMIT_TTL through from your shell or .env (empty = default):

ALERT_DEDUP_TTL=2m ALERT_WEBHOOK_URL=https://hooks.example.com/abc make up

Observability & Telemetry (Grafana, Prometheus, Jaeger)

The platform provides end-to-end metrics and distributed tracing across both Python (FastAPI, Redis, Kafka sampler) and Go (Alert Engine):

Service Host URL Description
Grafana http://localhost:3000 (admin / admin) Pre-provisioned dashboards for cheaters flagged, smurfs detected, behavior anomalies, server health, match quality, throughput, and alert lifecycle.
Prometheus http://localhost:9090 Scrapes /metrics from FastAPI (:8000) and the Go Alert Engine (:9095).
Jaeger UI http://localhost:16686 Distributed trace explorer showing end-to-end spans (gate.admit, postgres.store, redis.publish, webhook.notify, HTTP endpoints).

Simulator flags

Run simulator/bin/simulator --help for the full list. The main ones:

Flag Default Meaning
--events-per-sec 1000 target SHOT events per second on gameplay_events (player events and server metrics come on top)
--duration 5m total run time
--kafka-brokers localhost:9094 comma-separated bootstrap brokers
--players / --matches-concurrent 0 0 = size the player pool and match count from --events-per-sec
--cheater-ratio / --smurf-ratio / --toxic-ratio 0.05 each share of accounts per archetype
--behavior-shift 0.05 share of players whose accuracy jumps at the run midpoint
--late-event-ratio 0.05 share of shots emitted with a delayed event time
--degraded-servers server-02 servers that report degraded health
--seed 0 fixed seed for a reproducible run (0 = random)
--dry-run off generate events without connecting to Kafka

All flags are validated up front. The simulator prints a per-topic summary (published / delivered / failed / unconfirmed) and exits 0 on success, 1 on a delivery failure, 2 on a usage error.


License

Released under the MIT License — see LICENSE for the full text.

Copyright (c) 2026 Karthik Das P

About

A high-throughput, distributed streaming platform designed to monitor game server infrastructure, score match quality, profile player behavior, and detect anomalies (aimbots, smurfs) in real time using Apache Kafka, Apache Spark Structured Streaming, Go, and PySpark.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages