Sync Layer
Sync Engine
Bidirectional synchronization between the local SQLite database and Supabase cloud. Operates as a background service with priority-ordered push, Realtime subscription pull, exponential-backoff retry, and conflict resolution.
Push Engine
Local → Supabase
Reads sync_queue and batch-upserts to Supabase in priority order. Up to 50 items per cycle.
Pull Subscriber
Supabase Realtime → Local
Subscribes to Supabase Realtime events for bidirectional tables. Applies remote changes to local SQLite on receive.
Retry Queue
Exponential backoff
Failed items retry at 30s, 60s, 120s, 300s. After 5 retries: dead-letter to error log for manual inspection.
Priority Scheduler
Critical → Low ordering
Emergency states and alerts always pushed first. Wearable metrics and AI logs go last. Configurable priority table.
Table Sync Configuration
Priority 1 = first to sync after reconnect
| Table | Direction | Priority | Conflict Strategy | Sync Interval |
|---|---|---|---|---|
| emergency_states | ↑↓ | 1 — Critical | Vector Clock | Immediate |
| alerts | ↑↓ | 2 — Critical | Vector Clock | Immediate |
| patients | ↑↓ | 3 — High | LWW | 30 seconds |
| reminders | ↑↓ | 4 — High | LWW | 30 seconds |
| ai_memory | ↑↓ | 5 — High | LWW | 30 seconds |
| automation_rules | ↑↓ | 6 — High | LWW | 30 seconds |
| wearable_metrics | ↑ | 7 — Medium | Append-only | 30 seconds |
| ai_logs | ↑ | 8 — Medium | Append-only | 30 seconds |
| device_status | ↑ | 9 — Medium | LWW | 30 seconds |
| sync_queue | — | — System | Local-only | N/A |
Push Cycle Implementation
# Sync engine push cycle (Python)
async def push_cycle():
# 1. Read pending items from sync_queue, ordered by priority
items = await db.fetch_all("""
SELECT sq.*, pt.priority_rank
FROM sync_queue sq
JOIN table_priorities pt ON sq.table_name = pt.table_name
WHERE sq.status = 'pending' AND sq.retries < 5
ORDER BY pt.priority_rank ASC, sq.created_at ASC
LIMIT 50
""")
if not items:
return # Nothing to push
# 2. Batch by table for efficient upsert
for table_name, batch in groupby(items, key=lambda x: x['table_name']):
rows = [json.loads(item['payload']) for item in batch]
try:
# 3. Upsert to Supabase
await supabase.table(table_name).upsert(rows).execute()
# 4. Mark as done
ids = [item['id'] for item in batch]
await db.execute("UPDATE sync_queue SET status='done' WHERE id = ANY(?)", ids)
except Exception as e:
# 5. Exponential backoff on failure
for item in batch:
backoff = min(30 * (2 ** item['retries']), 300)
await db.execute(
"UPDATE sync_queue SET status='pending', retries=retries+1 WHERE id=?",
item['id']
)
logger.warning(f"Sync push failed for {table_name}: {e}")