Online
Data Layerv3.0
Tables12
StrategyLWW
ModeOffline-first

Data Layer

Database Architecture

RAFIQ uses a dual-database architecture: SQLite as the always-available local store and Supabase as the cloud replica. All writes succeed locally first. Cloud sync is a background best-effort operation — never a blocker.

SQLite

WAL · FTS5 · JSON1

Primary local store. Always writable. WAL mode for concurrent reads.

SQLite 3.44WALin-process

Supabase

PostgreSQL · RLS · Realtime

Cloud replica. Receives sync pushes. Provides multi-device access.

PostgreSQL 15RLSRealtime

Sync Engine

30s cycle · Retry queue

Background service. Reads sync_queue, pushes to Supabase, pulls remote changes.

asyncexponential-backoff

Conflict Resolver

LWW · Vector clocks

Last-Write-Wins by updated_at. Vector clocks for emergency_states.

LWWVector Clockidempotent
Offline-First Sync FlowAll writes local → background push
App Write
any service
→
SQLite
instant, offline-safe
→
Trigger → sync_queue
auto-enqueued
→
Sync Engine
30s cycle
→
Supabase
if online

Table Schema · 12 tables

SQLite primary · Supabase replica · sync_queue-driven push

TableKey ColumnsSync DirectionPriority
patientsid, name, dob, conditions[], medications[]↑↓ BidirectionalCritical
wearable_metricsid, patient_id, bpm, spo2, steps, ts↑ Push-onlyHigh
alertsid, type, severity, source, status, ts↑↓ BidirectionalCritical
remindersid, patient_id, type, scheduled_at, done↑↓ BidirectionalHigh
ai_logsid, model, input, output, latency_ms, ts↑ Push-onlyMedium
ai_memoryid, patient_id, context_json, updated_at↑↓ BidirectionalHigh
sync_queueid, table_name, op, payload, status, retries⊘ Local-onlySystem
mqtt_logsid, topic, payload, qos, ts⊘ Local-onlyLow
system_eventsid, service, event, data, ts⊘ Local-onlyLow
emergency_statesid, type, severity, active, resolved_at↑↓ BidirectionalCritical
automation_rulesid, trigger_json, action_json, enabled↑↓ BidirectionalHigh
device_statusid, device_id, room, state, last_seen↑ Push-onlyMedium

Service Read/Write Access Matrix

Servicepatientswearablealertsai_logssync_queueemergency
Core EngineR/WR/WR/WRR/WR/W
AI OrchestratorRRRR/W—R
Sync EngineRRRRR/WR
Emergency EngineRRR/W——R/W
HA Bridge——R——R
FastAPI (REST)R/WRR/WRRR

Database Mission Control

Structured SQL infrastructure · ownership · sync topology · entity relationships

LOCAL (SQLite)
CLOUD (Supabase)
SYNC (Both)
PK
FK
System Status
LIVE
LOCAL DB
SQLite
WAL mode
CLOUD DB
Supabase
PostgreSQL 15
SYNC
Bidir · LWW
30s cycle
CONFLICT
LWW + Vector
updated_at wins
10TABLES
7FK LINKS
3FLOWS
Data Flow
Patient Createddata path
1
App
user action
2
FastAPI
POST /patients
3
SQLite
instant write
4
sync_queue
trigger enqueued
5
Sync Engine
30s cycle
6
Supabase
cloud replica
SQL Tables · Tap to Inspect
Core Entity
patientsSYNC
Related Tables
alertsSYNC
devicesSYNC
locationsSYNC
remindersSYNC
emergency_contactsSYNC
Local Storage
wearable_metricsLOCAL
sync_queueLOCAL
ai_logsLOCAL
Cloud Only
profile_validationCLOUD

SQLite Init + Sync Queue

db/init.sql
sql
-- SQLite initialization with WAL mode
PRAGMA journal_mode = WAL;        -- Write-Ahead Logging
PRAGMA synchronous = NORMAL;      -- fsync on WAL checkpoints
PRAGMA cache_size = -65536;       -- 64MB page cache
PRAGMA foreign_keys = ON;         -- Referential integrity
PRAGMA auto_vacuum = INCREMENTAL; -- Reclaim space incrementally
PRAGMA wal_autocheckpoint = 1000; -- Checkpoint every 1000 pages

-- Sync queue table (core of offline-first architecture)
CREATE TABLE IF NOT EXISTS sync_queue (
  id          TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
  table_name  TEXT NOT NULL,
  operation   TEXT NOT NULL CHECK (operation IN ('INSERT','UPDATE','DELETE')),
  row_id      TEXT NOT NULL,
  payload     JSON NOT NULL,
  status      TEXT NOT NULL DEFAULT 'pending',
  retries     INTEGER NOT NULL DEFAULT 0,
  created_at  TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
  updated_at  TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);

Auto-Queue Trigger

db/triggers.sql
sql
-- Auto-queue writes for sync (example: wearable_metrics)
CREATE TRIGGER wearable_metrics_sync_insert
AFTER INSERT ON wearable_metrics
BEGIN
  INSERT INTO sync_queue (table_name, operation, row_id, payload)
  VALUES (
    'wearable_metrics', 'INSERT', NEW.id,
    json_object('id', NEW.id, 'patient_id', NEW.patient_id,
                'bpm', NEW.bpm, 'spo2', NEW.spo2, 'ts', NEW.ts)
  );
END;
Conflict Resolution Strategy

Last-Write-Wins (default)

Applied to all non-critical tables. The row with the highest updated_at timestamp wins. Simple, predictable, and fast to resolve. Works well for wearable metrics, device states, and AI logs.

Vector Clocks (emergency data)

Applied to emergency_states and alerts. Tracks causality — if an emergency was resolved locally but the cloud still shows active, the resolution wins. Prevents false-clear scenarios.