Skip to content

Latest commit

Β 

History

19 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ Kyronix Flow

A distributed task queue with AI-powered scheduling, failure analysis, and real-time observability β€” built with FastAPI, Redis, and React.

CI Python FastAPI Redis React Docker License: MIT


πŸ“‹ Table of Contents


πŸ” Overview

Kyronix Flow is a project demonstrating distributed systems engineering end-to-end. It implements a background task processing pipeline with priority queues, automatic retries, dead letter queues, stale task recovery, and an AI layer for natural language task creation and failure analysis β€” all served through a REST API, a React dashboard, and a CLI.

Note: This project demonstrates distributed systems concepts, reliability patterns, and AI integration depth. While it implements several production patterns, it is not hardened for production use in its current form. A path to production readiness is outlined in the Roadmap.

What it demonstrates

Concept Implementation
Message queue Redis lists as priority queues, BRPOP for blocking dequeue
State machine PENDING β†’ RUNNING β†’ COMPLETED / FAILED with retry transitions
Exponential backoff 2^n second delays via Redis sorted set scheduling
Dead Letter Queue Permanent failure storage with metadata and manual retry
Stale task recovery Scheduler detects and requeues orphaned RUNNING tasks
Worker pool ThreadPoolExecutor with heartbeat and TTL-based eviction
Optimistic locking Redis WATCH/MULTI for concurrent state mutations
AI reliability layer Prompt injection defense, hallucination guard, cost tracking, fallback heuristics

πŸ—οΈ Architecture

System Diagram

graph TB
    subgraph Clients["πŸ‘₯ Clients"]
        CLI[CLI]
        FE[React Dashboard]
    end

    subgraph Proxy["πŸ”’ Proxy"]
        NGINX[Nginx<br/>Rate Limit + Security]
    end

    subgraph Services["πŸ”§ Services"]
        FastAPI[FastAPI<br/>REST Endpoints]
        AI_SVC[AI Service<br/>OpenAI-compatible API]
    end

    subgraph Workers["βš™οΈ Workers"]
        CPU[CpuWorker]
        API_W[ApiWorker]
        FILE[FileWorker]
        ML[MlWorker]
    end

    subgraph Scheduler["⏱️ Scheduler"]
        RETRY[Retry Scheduler]
    end

    subgraph Data["πŸ’Ύ Data"]
        REDIS[(Redis 7)]
    end

    CLI -->|HTTP| FastAPI
    FE --> NGINX --> FastAPI
    FastAPI --> REDIS
    CPU --> REDIS
    API_W --> REDIS
    FILE --> REDIS
    ML --> REDIS
    RETRY --> REDIS
    FastAPI --> AI_SVC
Loading

Tech Stack

Layer Technology Purpose
API FastAPI, Python 3.12 REST endpoints, async request handling
Data Redis 7 Task state, priority queues, retry sorted set, metrics
Workers Python, ThreadPoolExecutor Parallel task execution with heartbeat monitoring
AI OpenAI-compatible API (GPT-4o-mini, OpenRouter, etc.) NL parsing, failure analysis, optimization suggestions
Frontend React 19, Vite, TypeScript, TanStack Query, Recharts, TailwindCSS Real-time dashboard
Proxy Nginx 1.27 Rate limiting, gzip, security headers
CLI Click, Rich Formatted command-line interface
Infra Docker, Docker Compose, GitHub Actions Containerization, CI/CD

Redis Key Schema

taskflow:task:{id}               # Task state hash
taskflow:result:{id}             # Task result hash
taskflow:queue:{high|medium|low} # Priority queues (lists)
taskflow:retry_queue             # Retry sorted set (score = unix timestamp)
taskflow:dlq                     # Dead letter queue (list)
taskflow:dlq:{id}                # DLQ entry metadata (hash)
taskflow:metrics                 # Global metrics (hash)
taskflow:metrics:workers         # Worker registry (hash)
taskflow:metrics:workers:alive   # Worker heartbeat sorted set

Task State Machine

PENDING ──→ RUNNING ──→ COMPLETED
               β”‚
               β”œβ”€β”€β†’ PENDING (retry with backoff)
               β”‚
               └──→ FAILED (max retries exceeded β†’ DLQ)

✨ Features

Core Task Processing

  • Priority-based scheduling β€” Tasks routed across high / medium / low priority queues
  • Automatic retries β€” Exponential backoff (2^n seconds) with configurable max attempts
  • Dead Letter Queue β€” Permanently failed tasks stored with metadata; inspectable and manually retryable
  • Stale task recovery β€” Scheduler detects orphaned RUNNING tasks and requeues them
  • Worker pool β€” Horizontally scalable via docker compose up --scale worker=N
  • Optimistic locking β€” Redis WATCH/MULTI prevents race conditions on concurrent state mutations

AI Layer

  • Natural language task creation β€” Plain-English prompts parsed into structured tasks via OpenAI-compatible API
  • Failure analysis β€” Root cause categorization (timeout, network, validation, etc.) with confidence scores
  • Retry recommendations β€” AI-suggested retry strategy and optimal delay
  • Task optimization β€” Batching, chunking, and caching suggestions
  • Prompt injection defense β€” Rejects suspicious patterns before they reach the model
  • Hallucination guard β€” Validates AI output against allowed values before acting on it
  • Cost tracking β€” Token usage and estimated cost logged per request
  • Graceful fallback β€” Heuristic defaults when the OpenAI API is unavailable

Observability

  • Real-time dashboard β€” React frontend polling task counts, queue depths, worker health, and success rates
  • REST metrics endpoints β€” /metrics, /metrics/queues, /metrics/workers
  • Worker heartbeat β€” TTL-based eviction removes stale workers from the registry automatically

Infrastructure

  • Docker Compose β€” Dev and production configurations, single command startup
  • Nginx reverse proxy β€” Rate limiting, gzip compression, security headers
  • GitHub Actions CI β€” Lint, type check (mypy), tests, and Docker build verification on every push
  • CLI β€” Rich-formatted task management and monitoring from the terminal

πŸš€ Installation

Prerequisites

  • Python 3.12+
  • Redis 7+
  • Node.js 20+ (frontend only)
  • Docker & Docker Compose (recommended)

Option 1: Docker (Recommended)

git clone https://github.com/sumitchintanwar/kyronix-flow.git
cd kyronix-flow/taskflow
cp .env.example .env
# Edit .env and set OPENAI_API_KEY + OPENAI_BASE_URL for AI features (optional)

docker compose up -d

# Verify
curl http://localhost:8000/health

Option 2: Manual

git clone https://github.com/sumitchintanwar/kyronix-flow.git
cd kyronix-flow/taskflow
cp .env.example .env
# Edit .env and set OPENAI_API_KEY + OPENAI_BASE_URL for AI features (optional)

python -m venv venv
source venv/bin/activate       # Linux/macOS
# venv\Scripts\activate        # Windows

pip install -e .

# Start Redis
redis-server

# Start API (terminal 1)
uvicorn api.main:app --reload --port 8000

# Start a worker (terminal 2)
python -m workers.main

Option 3: Frontend Only

cd frontend
npm install
npm run dev
# http://localhost:5173

⚑ Quick Start

1. Submit a task

curl -X POST http://localhost:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{
    "type": "cpu",
    "payload": {"action": "fibonacci", "n": 30},
    "priority": "medium",
    "max_retries": 3
  }'
{
  "task_id": "task_abc123",
  "status": "pending"
}

2. Check status

curl http://localhost:8000/tasks/task_abc123

3. Get result

curl http://localhost:8000/tasks/task_abc123/result

4. View metrics

curl http://localhost:8000/metrics

πŸ“‘ API Reference

Tasks

# Create a CPU task
curl -X POST http://localhost:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"type": "cpu", "payload": {"action": "is_prime", "n": 97}, "priority": "high"}'

# Create a file processing task
curl -X POST http://localhost:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"type": "file", "payload": {"action": "csv_parse", "file_path": "/data/input.csv"}}'

# Create an API call task
curl -X POST http://localhost:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"type": "api", "payload": {"method": "GET", "url": "https://api.example.com/data"}}'

# List tasks
curl "http://localhost:8000/tasks?limit=10"

# Delete a task
curl -X DELETE http://localhost:8000/tasks/task_abc123

Metrics & Health

curl http://localhost:8000/metrics
curl http://localhost:8000/metrics/queues
curl http://localhost:8000/metrics/workers
curl http://localhost:8000/health

AI Endpoints

# Natural language task creation
curl -X POST http://localhost:8000/tasks/natural-language \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Calculate the first 50 prime numbers and sort them"}'

# Failure analysis + retry recommendation for a task
curl http://localhost:8000/tasks/task_abc123/insights

# AI usage metrics
curl http://localhost:8000/metrics/ai

Dead Letter Queue

curl http://localhost:8000/tasks/dead                          # List DLQ entries
curl -X POST http://localhost:8000/dlq/task_abc123/retry       # Retry a failed task
curl -X DELETE http://localhost:8000/dlq                       # Clear the DLQ

πŸ–₯️ CLI Usage

pip install -e .

Task Management

taskflow task create --type cpu --payload '{"operation": "fibonacci", "n": 30}' --priority high
taskflow task list --limit 10
taskflow task get task_abc123
taskflow task result task_abc123
taskflow task delete task_abc123

Quick Submit

taskflow submit cpu fibonacci --n 30
taskflow submit ml sentiment --text "This is amazing!"
taskflow submit api webhook --url https://example.com
taskflow submit file csv-parse --rows 500 --columns 10

Monitoring

taskflow status task_abc123
taskflow metrics
taskflow metrics queues
taskflow metrics workers
taskflow workers
taskflow health

Dead Letter Queue

taskflow dlq
taskflow dlq show task_abc123
taskflow dlq retry task_abc123
taskflow dlq clear

Example Output

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚         Task Status: task_abc123        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Status      β”‚ completed                 β”‚
β”‚ Type        β”‚ cpu                       β”‚
β”‚ Priority    β”‚ high                      β”‚
β”‚ Retries     β”‚ 0/3                       β”‚
β”‚ Created     β”‚ 2026-01-15 10:30:00 UTC   β”‚
β”‚ Updated     β”‚ 2026-01-15 10:30:02 UTC   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Task Result                β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ operation     β”‚ fibonacci               β”‚
β”‚ n             β”‚ 30                      β”‚
β”‚ result        β”‚ 832040                  β”‚
β”‚ execution_ms  β”‚ 1247                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ€– AI Features

Natural Language Task Creation

curl -X POST http://localhost:8000/tasks/natural-language \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Urgently calculate the first 100 prime numbers"}'
{
  "task_id": "task_xyz789",
  "parsed_task": {
    "task_type": "cpu",
    "priority": "high",
    "payload": {"operation": "prime", "n": 100},
    "confidence": 0.95,
    "reasoning": "User requested prime calculation with urgency keyword"
  }
}

Failure Analysis

curl http://localhost:8000/tasks/task_abc123/insights
{
  "task_id": "task_abc123",
  "failure_analysis": {
    "root_cause": "Task exceeded 30s timeout due to large input size",
    "category": "timeout",
    "confidence": 0.92,
    "recommendation": "Increase timeout or split into smaller chunks",
    "prevention_strategy": "Add input size validation before processing"
  },
  "retry_recommendation": {
    "should_retry": true,
    "suggested_delay": 5.0,
    "reasoning": "Timeout failures are transient; retry with increased timeout"
  },
  "optimization": {
    "recommendations": ["Batch input into chunks of 1000"],
    "estimated_improvement": "50% faster execution",
    "risk_notes": "Chunking may increase memory usage"
  }
}

πŸ“Š Load Testing

cd taskflow/load_tests
pip install -r requirements.txt

# Run all scenarios
./run_load_tests.sh all

# Run a specific scenario
./run_load_tests.sh task_creation
./run_load_tests.sh task_polling
./run_load_tests.sh metrics_requests
./run_load_tests.sh ai_requests
./run_load_tests.sh combined

# Analyze results
python3 analyze_results.py ./results
Scenario Description Users
task_creation POST /tasks write throughput 10-100
task_polling Create β†’ poll β†’ completion latency 10-50
metrics_requests Dashboard polling simulation 10-100
ai_requests Natural language + insights endpoints 5-20
combined Mixed realistic workload 20-100

πŸ”§ Configuration

Environment Variables

Variable Default Description
REDIS_HOST localhost Redis host
REDIS_PORT 6379 Redis port
OPENAI_API_KEY β€” Required for AI features
OPENAI_BASE_URL β€” Custom OpenAI-compatible API base URL (e.g. https://openrouter.ai/api/v1)
OPENAI_MODEL gpt-4o-mini Model to use
WORKER_CONCURRENCY 4 Worker thread pool size

Scaling Workers

docker compose up -d --scale worker=5

πŸ—ΊοΈ Roadmap

The following tracks what would be needed to move this toward production readiness:

Near-term

  • WebSocket support for real-time push (replacing polling)
  • Task dependencies and DAG-based execution ordering
  • Persistent task history backed by PostgreSQL

AI improvements

  • Multi-model support (Claude, Gemini, local models)
  • Predictive failure detection based on historical patterns
  • Batch task optimization suggestions

Production hardening

  • Role-based access control (RBAC)
  • Audit logging
  • SLA monitoring and alerting
  • Kubernetes deployment manifests
  • Prometheus metrics export
  • Distributed tracing via OpenTelemetry
  • Multi-tenant support

πŸ§ͺ Testing

# Run all tests
pytest

# With coverage report
pytest --cov=api --cov=ai --cov=workers

# Specific modules
pytest tests/test_api_endpoints.py -v
pytest tests/test_integration.py -v

πŸ“„ License

MIT β€” see LICENSE.


πŸ™ Acknowledgments

FastAPI Β· Redis Β· OpenAI Β· Rich Β· Docker


Built to demonstrate distributed systems engineering end-to-end

Tested with: cohere/north-mini-code:free via OpenRouter

Report a Bug Β· Wiki

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages