A distributed task queue with AI-powered scheduling, failure analysis, and real-time observability β built with FastAPI, Redis, and React.
- Overview
- Architecture
- Features
- Installation
- Quick Start
- API Reference
- CLI Usage
- AI Features
- Load Testing
- Configuration
- Roadmap
- Testing
- License
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.
| 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 |
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
| 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 |
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
PENDING βββ RUNNING βββ COMPLETED
β
ββββ PENDING (retry with backoff)
β
ββββ FAILED (max retries exceeded β DLQ)
- Priority-based scheduling β Tasks routed across high / medium / low priority queues
- Automatic retries β Exponential backoff (
2^nseconds) with configurable max attempts - Dead Letter Queue β Permanently failed tasks stored with metadata; inspectable and manually retryable
- Stale task recovery β Scheduler detects orphaned
RUNNINGtasks and requeues them - Worker pool β Horizontally scalable via
docker compose up --scale worker=N - Optimistic locking β Redis
WATCH/MULTIprevents race conditions on concurrent state mutations
- 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
- 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
- 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
- Python 3.12+
- Redis 7+
- Node.js 20+ (frontend only)
- Docker & Docker Compose (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/healthgit 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.maincd frontend
npm install
npm run dev
# http://localhost:5173curl -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"
}curl http://localhost:8000/tasks/task_abc123curl http://localhost:8000/tasks/task_abc123/resultcurl http://localhost:8000/metrics# 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_abc123curl http://localhost:8000/metrics
curl http://localhost:8000/metrics/queues
curl http://localhost:8000/metrics/workers
curl http://localhost:8000/health# 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/aicurl 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 DLQpip install -e .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_abc123taskflow 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 10taskflow status task_abc123
taskflow metrics
taskflow metrics queues
taskflow metrics workers
taskflow workers
taskflow healthtaskflow dlq
taskflow dlq show task_abc123
taskflow dlq retry task_abc123
taskflow dlq clearβββββββββββββββββββββββββββββββββββββββββββ
β 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 β
βββββββββββββββββββββββββββββββββββββββββββ
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"
}
}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"
}
}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 |
| 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 |
docker compose up -d --scale worker=5The 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
# 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 -vMIT β see LICENSE.
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