Online
Local Layerv2.1.4
Uptime99.8%
Latency< 8ms
Services8 active

Core Infrastructure

RAFIQ Core Engine

The central orchestration layer running on Ubuntu Server. Manages all services, event loops, threading models, offline execution, and system lifecycle — independently of any cloud connectivity.

Host HardwareMiniPC · Ubuntu 22.04 LTS
PlatformMiniPC / RPi 5
OSUbuntu 22.04 LTS
RAM8 GB DDR4
Storage256 GB NVMe
CPU4–8 cores x86/ARM
RuntimePython 3.11
NetworkEthernet + WiFi
GPUCPU inference only

Core Services · 8 components

FastAPI Application Server

Uvicorn · ASGI · async/await

Main HTTP and WebSocket server. Handles REST API, WebSocket connections, and event broadcasting. Runs on asyncio event loop with worker threads for CPU-bound AI tasks.

Avg latency
<8ms
Workers
4
Port
8000
Python 3.11UvicornASGIasyncio

SQLite + WAL Engine

Write-Ahead Logging · Local-first

Primary local database with WAL mode for concurrent reads. Stores all patient data, events, AI logs, and sync queues. Zero network dependency for reads/writes.

WAL mode
ON
Max size
8GB
Checkpt
1000 pages
SQLite 3.44WALFTS5JSON1

MQTT Broker (Mosquitto)

Eclipse Mosquitto · QoS 0/1/2

Central message bus for all sensor data, device commands, and event notifications. Runs locally on port 1883, supports retained messages and last-will-testament.

Clients
3–8
QoS
0/1/2
Port
1883
Mosquitto 2.0TLSRetainedLWT

AI Decision Engine

Ollama · MedGemma · Rule Engine

Orchestrates AI inference requests across local LLMs. Applies health rules, generates interventions, classifies emergencies, and manages conversational memory.

Avg latency
160ms
Models
2 active
Queue
async
MedGemma:4bQwen2.5:3bGGUFllama.cpp

Emergency Engine

Real-time · Local-only · Fail-secure

Standalone safety processing loop that never depends on cloud or AI. Evaluates raw sensor thresholds, triggers valve shutdowns, activates sirens, and sends emergency SMS.

Response
<50ms
Mode
local-only
Priority
HIGHEST
fail-secureoffline-capableGPIOSMS

Sync Engine

SQLite ↔ Supabase · Retry Queue

Background service for bidirectional cloud synchronization. Maintains an offline queue when Supabase is unreachable, replays on reconnect with conflict resolution.

Interval
30s
Max retries
5
Strategy
LWW
Last-Write-Winsretry-queueexponential-backoff

Home Assistant Bridge

HA API · Automation · MQTT

Bidirectional bridge between RAFIQ core and Home Assistant. Subscribes to HA events via WebSocket API and publishes device commands through MQTT.

Automations
14
Devices
22
Protocol
WAMP
Home AssistantWAMPZigbee2MQTTREST

Local Cache Layer

In-memory · TTL · LRU

High-speed in-memory cache for frequently accessed data: recent wearable readings, AI responses, device states, and authentication tokens. Python dict + TTL expiry.

Max entries
10K
TTL
5–300s
Eviction
LRU
in-memoryTTLLRUthread-safe

Threading Model

Python asyncio event loop + OS threads for blocking operations

Thread / TaskTypeResponsibility
Main Event LoopasyncioHTTP, WebSocket, MQTT subscribe, coroutine scheduling
AI Worker PoolThreadPoolOllama inference calls (blocking I/O, CPU-bound)
Emergency WatchdogThreadSensor threshold polling — never blocked by async queue
Sync Background Taskasyncio TaskSupabase push/pull cycle every 30 seconds
MQTT PublisherasyncioOutbound MQTT messages to broker
STT/TTS PipelineThreadVoice stream processing (Whisper, Piper TTS)

Startup Sequence

core/main.py
python
# RAFIQ Core startup sequence
async def startup():
    # 1. Initialize SQLite with WAL mode
    await db.connect(pragmas={"journal_mode": "WAL", "cache_size": -65536})
    
    # 2. Run Alembic migrations
    await run_migrations()
    
    # 3. Connect to MQTT broker
    await mqtt_client.connect(host="localhost", port=1883)
    await mqtt_client.subscribe("rafiq/#", qos=1)
    
    # 4. Start background services
    asyncio.create_task(sync_engine.run())
    asyncio.create_task(emergency_engine.run())
    asyncio.create_task(ai_orchestrator.warmup())
    
    # 5. Initialize Home Assistant bridge
    await ha_bridge.connect(token=settings.HA_TOKEN)
    
    # 6. Ready signal
    logger.info("RAFIQ Core online — all services initialized")

Shutdown Lifecycle

core/main.py
python
# Graceful shutdown sequence
@app.on_event("shutdown")
async def shutdown():
    # 1. Stop accepting new requests
    # 2. Complete in-flight AI requests (max 5s timeout)
    await asyncio.wait_for(ai_orchestrator.drain(), timeout=5.0)
    
    # 3. Flush sync queue to disk
    await sync_engine.flush_to_disk()
    
    # 4. Close MQTT cleanly (send LWT disconnect)
    await mqtt_client.disconnect(reasoncode=0)
    
    # 5. Checkpoint SQLite WAL
    await db.execute("PRAGMA wal_checkpoint(FULL)")
    await db.disconnect()
    
    logger.info("RAFIQ Core shutdown complete")
Offline Operation ModelAlways-on · Cloud-optional

Local-first Storage

All writes go to SQLite first. Supabase sync is a background best-effort operation. No write is ever lost due to network failure.

Local AI Inference

Ollama runs entirely on-device. AI reasoning, health analysis, and emergency classification work without any internet connection.

Emergency Independence

Emergency engine operates on raw sensor data with zero AI/cloud dependency. Gas valve control, sirens, SMS — all fully local.

Failover State Machine

NORMAL
→ NET FAIL
OFFLINE MODE
→ AI FAIL
RULES ENGINE
→ EMERGENCY
SAFE SHUTDOWN