Pipelines Live
Edge → Local → Cloudv2.1.0
End-to-End~250ms
Emergency Path<5ms local
Uptime99.7%

Infrastructure · Pipeline

Data Flow Architecture

End-to-end data pipelines from physical sensors through edge computing, MQTT messaging, local AI inference, and cloud synchronization. Every hop is designed for offline-first reliability with deterministic latency bounds.

Active Pipelines
Health Monitoring Pipeline10 steps
Emergency Response Pipeline9 steps

Pipeline 01 · Health Monitoring

🔵 Monitoring Path

Health Monitoring Pipeline

Continuous biometric data flow from wearable sensor through local AI analysis to cloud sync

10 nodes
01
Wearable Device

ESP32 + MAX30102

Sensor
02
BLE Transport

2.4GHz · GATT Profile

BLE
10–50ms
03
ESP32 Gateway

BLE→WiFi Bridge

Bridge
2–8ms
04
MQTT Broker

Mosquitto v2 · QoS 1

MQTT
5–20ms
05
Core Engine

FastAPI · Python 3.12

Async
1–5ms
↩ continues
06
SQLite Write

WAL · In-process DB

WAL
1–5ms
07
AI Analysis

MedGemma 4B · Ollama

llama.cpp
140–200ms
08
Decision Engine

Rule evaluation · CEP

Internal
1–3ms
09
Supabase Sync

PostgreSQL · REST API

HTTPS
200–2000ms
10
Mobile App

Flutter · Push Notify

Push
async

Pipeline 02 · Emergency Response

🔴 Emergency Path

Emergency Response Pipeline

Life-critical gas detection with local-first hardware failsafe and multi-channel alerting

9 nodes
01
Raqeeb Gas Sensor

MQ-2 · MQ-7 · MQ-135

ADC
02
ESP32 Emergency MCU

Dedicated safety MCU

GPIO
<1ms
03
Local Threshold Check

No cloud dependency

Local
0.1ms
04
Valve Shutdown

GPIO · Relay control

GPIO
<5ms
05
MQTT Alert

QoS 2 · Retained

MQTT
5–20ms
↩ continues
06
AI Classification

Emergency type ID

Ollama
140–200ms
07
SMS Gateway

Twilio · Fallback SIM

SMS
1–5s
08
App Push Notification

FCM · Critical alert

FCM
200–500ms
09
HA Automation

Home Assistant · YAML

MQTT→HA
50–200ms
Async vs Sync Execution ModelHow RAFIQ handles blocking vs non-blocking operations
Synchronous Path
  • ›Sensor → BLE → MQTT: sequential, blocking per packet
  • ›GPIO relay control: hardware interrupt, <1ms guaranteed
  • ›SQLite WAL write: synchronous before ACK
  • ›Local threshold evaluation: immediate decision, no network
  • ›Emergency MQTT publish QoS 2: requires broker confirmation
Asynchronous Path
  • ›AI inference via asyncio.create_task() — never blocks main loop
  • ›Supabase sync runs in background queue with exponential retry
  • ›Push notifications dispatched post-decision asynchronously
  • ›SMS gateway call fire-and-forget with separate delivery tracking
  • ›HA automations triggered via MQTT retain — eventual consistency

Execution Timeline (example: wearable HR packet)

BLE receive
0ms
MQTT publish
15ms
SQLite write
19ms
AI inference
180ms ↗
Decision eval
62ms
Supabase sync
~500ms ↗↗

↗ = async dispatch (does not block main pipeline) · Timeline not to scale

Latency Class Reference

Per-hop timing characteristics across the data pipeline

ComponentProtocol/ModeTypical LatencyMax LatencyAsync?
BLE TransportBluetooth 5.010ms50msNo
WiFi (ESP32→Router)802.11n 2.4GHz2ms15msNo
MQTT PublishMQTT v3.1.15ms20msNo (QoS 1)
SQLite WAL WriteWAL Journal1ms5msNo
Core Engine Dispatchasyncio0.5ms3msYes
MedGemma Inferencellama.cpp/Ollama160ms300msYes
Decision EngineInternal Python1ms5msNo
Supabase REST SyncHTTPS/REST250ms2000msYes (queue)
SMS GatewayTwilio API1.5s5sYes
FCM PushFirebase FCM300ms1000msYes
GPIO RelayESP32 GPIO0.1ms1msNo (hardware)
HA AutomationMQTT→HA WS80ms250msYes
Retry & Queue MechanicsDurable message delivery and conflict resolution
Offline Queue (SQLite-backed)
  • ·All outbound records written to sync_queue table before cloud push attempt
  • ·Queue is durable — persists across process restarts and power cycles
  • ·Each entry: table, operation (INSERT/UPDATE/DELETE), payload_json, retries, status
  • ·Worker polls queue every 30s; on cloud availability, drains in FIFO order
Exponential Backoff
  • ·First retry: 30s · Second: 2min · Third: 10min · Fourth+: 1 hour cap
  • ·Jitter factor ±20% added to prevent synchronized thundering herd
  • ·Failed entries after 5 retries → moved to dead_letter_queue table
  • ·Dead letter queue is manually reviewed via admin API: GET /api/sync/dead-letter
Conflict Resolution
  • ·Last-write-wins strategy using updated_at UTC timestamps
  • ·Wearable metrics never conflict (append-only by device_id + timestamp)
  • ·User settings: server wins unless local version has unseen field changes
  • ·Emergency events: always preserved, never overwritten by cloud version
Guaranteed Delivery (Emergency)
  • ·Emergency alerts use MQTT QoS 2 (exactly-once delivery guarantee)
  • ·SMS via Twilio with delivery receipt polling — retries until confirmed
  • ·Critical events stored locally with status=unconfirmed until acked by server
  • ·Separate emergency sync channel runs independently of normal sync pipeline

MQTT Subscriber Pattern

rafiq/core/mqtt_subscriber.py
python
import asyncio
import json
import logging
from datetime import datetime

import aiomqtt
from sqlalchemy.ext.asyncio import AsyncSession

from rafiq.core.db import get_session
from rafiq.ai.orchestrator import AIOrchestrator
from rafiq.decision.engine import DecisionEngine

logger = logging.getLogger("mqtt-subscriber")

BROKER_HOST = "localhost"
BROKER_PORT = 1883
SUBSCRIPTIONS = [
    ("rafiq/wearable/#", 1),   # Biometrics — QoS 1
    ("rafiq/emergency/#", 2),  # Emergency alerts — QoS 2
    ("rafiq/home/#", 1),       # Home events — QoS 1
    ("rafiq/ai/#", 0),         # AI responses — QoS 0
]

async def handle_wearable(topic: str, payload: dict, session: AsyncSession) -> None:
    """Process incoming wearable sensor readings."""
    metric_type = topic.split("/")[-1]  # heartrate | spo2 | steps
    
    # 1. Persist to SQLite immediately (WAL mode, <5ms)
    await session.execute(
        "INSERT INTO wearable_metrics (type, value, ts) VALUES (:t, :v, :ts)",
        {"t": metric_type, "v": payload.get("value"), "ts": datetime.utcnow()},
    )
    await session.commit()
    
    # 2. Dispatch to AI asynchronously (non-blocking)
    asyncio.create_task(
        AIOrchestrator.analyze_health(metric_type, payload)
    )

async def handle_emergency(topic: str, payload: dict) -> None:
    """Handle emergency events — priority path, no async delay."""
    event_type = payload.get("type", "unknown")
    severity   = payload.get("severity", "medium")
    
    logger.critical(f"[EMERGENCY] {event_type} @ severity={severity}")
    
    # Decision engine runs synchronously for emergencies
    decision = await DecisionEngine.evaluate_emergency(event_type, severity)
    await decision.execute()  # Triggers GPIO, SMS, push

async def mqtt_subscriber_loop() -> None:
    """Main MQTT subscriber coroutine with auto-reconnect."""
    async with aiomqtt.Client(BROKER_HOST, BROKER_PORT) as client:
        # Subscribe to all topic patterns
        for topic, qos in SUBSCRIPTIONS:
            await client.subscribe(topic, qos=qos)
            logger.info(f"Subscribed: {topic} (QoS {qos})")
        
        async with client.messages() as messages:
            async for message in messages:
                topic   = str(message.topic)
                payload = json.loads(message.payload.decode())
                
                try:
                    async with get_session() as session:
                        if topic.startswith("rafiq/wearable/"):
                            await handle_wearable(topic, payload, session)
                        elif topic.startswith("rafiq/emergency/"):
                            await handle_emergency(topic, payload)
                except Exception as exc:
                    logger.error(f"Subscriber error [{topic}]: {exc}")

if __name__ == "__main__":
    asyncio.run(mqtt_subscriber_loop())
Design Principles

Local First

Every critical operation (emergency response, health writes, AI inference) runs without cloud. Cloud sync is additive, never critical path.

Deterministic Emergency

Gas sensor → valve shutdown path is hardware-guaranteed at <5ms using GPIO. AI classification follows asynchronously.

Bounded Latency

AI inference is capped at 300ms by llama.cpp timeout. All UI interactions stay responsive via async task dispatch.