Syncing
Sync Layerv2.0
Interval30s
Max Retries5
StrategyLWW + VC

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.

Sync State MachineOnline ↔ Offline lifecycle
ONLINE
→
SYNCING
→
NET FAIL
→
QUEUED
→
RECONNECT
→
DRAINING
→
ONLINE

Table Sync Configuration

Priority 1 = first to sync after reconnect

TableDirectionPriorityConflict StrategySync Interval
emergency_states↑↓1 — CriticalVector ClockImmediate
alerts↑↓2 — CriticalVector ClockImmediate
patients↑↓3 — HighLWW30 seconds
reminders↑↓4 — HighLWW30 seconds
ai_memory↑↓5 — HighLWW30 seconds
automation_rules↑↓6 — HighLWW30 seconds
wearable_metrics↑7 — MediumAppend-only30 seconds
ai_logs↑8 — MediumAppend-only30 seconds
device_status↑9 — MediumLWW30 seconds
sync_queue—— SystemLocal-onlyN/A

Push Cycle Implementation

sync/push_engine.py
python
# 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}")
Live Sync QueueReal-time queue state
alertsINSERT152Bretry 1done
ai_logsDELETE583Bretry 0done
wearable_metricsUPDATE489Bretry 0done
system_eventsUPDATE326Bretry 1syncing
remindersINSERT420Bretry 1pending
alertsINSERT339Bretry 1pending