Skip to main content
Spacedrive synchronizes library metadata across all your devices using a leaderless peer-to-peer model. Every device is equal. No central server, no single point of failure.

How Sync Works

Sync uses two protocols based on data ownership: Device-owned data (locations, files): The owning device broadcasts changes in real-time and responds to pull requests for historical data. No conflicts possible since only the owner can modify. Shared resources (tags, collections): Any device can modify. Changes are ordered using Hybrid Logical Clocks (HLC) to ensure consistency across all devices.
Library Sync handles metadata synchronization. For file content synchronization between storage locations, see File Sync.

Quick Reference

Data Ownership

Spacedrive recognizes that some data naturally belongs to specific devices.

Device-Owned Data

Only the device with physical access can modify:
  • Locations: Filesystem paths like /Users/alice/Photos
  • Entries: Files and folders within those locations
  • Volumes: Physical drives and mount points

Shared Resources

Any device can create or modify:
  • Devices: Library membership - all devices automatically discover each other
  • Tags: Labels applied to files, with hierarchy support
  • Collections: Groups of files
  • User Metadata: Notes, ratings, custom fields
  • Content Identities: Content-hash-based file identification
  • Spaces: User-defined workspace containers
  • Media Metadata: Video, audio, and image metadata
  • Sidecars: Generated files like thumbnails and previews
  • Audit Logs: Action history for compliance
  • Extension Data: Custom models from extensions
This ownership model eliminates most conflicts and simplifies synchronization.

Sync State Machine

The sync service runs as a background process with well-defined state transitions.

States

Transitions

Buffer Queue

During backfill, incoming real-time updates are buffered to prevent data loss:
  • Max capacity: 100,000 updates
  • Ordering: Priority queue sorted by timestamp/HLC
  • Overflow handling: Drops oldest updates to prevent OOM
  • Processing: Drained in order during CatchingUp phase

Catch-Up Escalation

If incremental catch-up fails repeatedly, the system uses exponential backoff before escalating to a full backfill. This prevents permanent sync failures from transient network issues.

Sync Protocols

State-Based Sync (Device-Owned)

See core/tests/sync_backfill_test.rs and core/tests/sync_realtime_test.rs for sync protocol tests.
State-based sync uses two mechanisms depending on the scenario: Real-time broadcast: When Device A creates or modifies a location, it sends a StateChange message via unidirectional stream to all connected peers. Peers apply the update immediately. Pull-based backfill: When Device B is new or reconnecting after being offline, it sends a StateRequest to Device A. Device A responds with a StateResponse containing records in configurable batches. This request/response pattern uses bidirectional streams. For large datasets, pagination automatically handles multiple batches using cursor-based checkpoints. The StateRequest includes both watermark and cursor:
No version tracking needed. The owner’s state is always authoritative.

Log-Based Sync (Shared Resources)

See core/tests/sync_realtime_test.rs for shared resource sync tests.
Shared resources sync through an ordered log. When you create a tag, the device inserts it locally, generates an HLC timestamp, appends to the sync log, and broadcasts a SharedChange message. Receiving devices apply changes in HLC order, then acknowledge receipt. Once all peers acknowledge, the entry is pruned from the log. Batch operations work the same way but send a single SharedChangeBatch message containing multiple entries. This reduces network overhead during bulk imports while preserving HLC ordering for each individual record. For large datasets, the system uses HLC-based pagination. Each request includes the last seen HLC, and the peer responds with the next batch. This scales to millions of shared resources.

Hybrid Logical Clocks

HLC conflict resolution is covered in core/tests/sync_realtime_test.rs.
HLCs provide global ordering without synchronized clocks:
The HLC string format for storage and comparison is {timestamp:016x}-{counter:016x}-{device_id}, which is lexicographically sortable. Properties:
  • Events maintain causal ordering
  • Any two HLCs can be compared
  • No clock synchronization required

HLC Update Algorithm

When generating or receiving an HLC, the system maintains causality:
This ensures:
  • Local events always have increasing HLCs
  • Received events update local clock to maintain causality
  • Clock drift is bounded by the max of all observed timestamps

Conflict Resolution

Each shared model implements its own apply_shared_change() method, allowing per-model conflict resolution strategies. The Syncable trait provides this flexibility. Default behavior (most models): Last Write Wins based on HLC ordering. When two devices concurrently modify the same record, the change with the higher HLC is applied:
Creation conflicts: When two devices create resources with the same logical identity (e.g., same tag name) but different UUIDs, both resources coexist. This is an implicit union merge - no data is lost.
Custom strategies: Models can override apply_shared_change() to implement:
  • Field-level merging (merge specific fields from both versions)
  • CRDT-style merging (for sets, counters, etc.)
  • Domain-specific rules (e.g., always prefer longer descriptions)
The sync system checks the peer log before applying changes to ensure only newer updates are applied.

Database Architecture

Main Database (database.db)

Contains all library data from all devices:
Ownership flows through volumes: Device → Volume → Location/Entry. This indirection enables portable storage to transfer between devices with a single volume update.

Sync Database (sync.db)

Contains pending changes for shared resources and sync coordination data:
The sync database stays small (under 1MB) due to aggressive pruning after acknowledgments.

Using the Sync API

The sync API handles all complexity internally. Three methods cover all use cases:
The API automatically:
  • Detects ownership type (device-owned vs shared)
  • Manages HLC timestamps for shared resources
  • Converts between local IDs and UUIDs for foreign keys
  • Uses batch FK lookups to reduce queries
  • Batches network broadcasts (single message for many items)
  • Creates tombstones for deletions (device-owned models)
  • Manages the sync log and pruning

Implementing Syncable Models

To make a model syncable, implement the Syncable trait and register it with a macro:
The with_rebuild flag triggers post_backfill_rebuild() after backfill completes, which rebuilds derived tables like entry_closure or tag_closure from the synced base data. The registration macros use the inventory crate for automatic discovery at startup - no manual registry initialization needed.

Custom Conflict Resolution

Shared models can implement custom conflict resolution by overriding apply_shared_change():
Currently, all models use the default LWW strategy. Custom strategies can be added per-model as needed without changes to the sync infrastructure.

Dependency Resolution Algorithm

To prevent foreign key violations, the sync system must process models in a specific order (e.g., Device records must exist before the Location records that depend on them). Spacedrive determines this order automatically at startup using a deterministic algorithm. The process works as follows:
  1. Dependency Declaration: Each syncable model declares its parent models using the sync_depends_on() function. This creates a dependency graph where an edge from Entry to Volume means Entry depends on Volume.
  2. Topological Sort: The SyncRegistry takes the full list of models and their dependencies and performs a topological sort using Kahn’s algorithm. This algorithm produces a linear ordering of the models where every parent model comes before its children. It also detects circular dependencies (e.g., A depends on B, and B depends on A).
  3. Ordered Execution: The BackfillManager receives this ordered list (e.g., ["device", "volume", "tag", "location", "entry"]) and uses it to sync data in the correct sequence, guaranteeing that no foreign key violations can occur.

Dependency Management

The sync system respects model dependencies and enforces ordering: Shared resources sync first because entries reference content identities via foreign key. This prevents NULL foreign key references during backfill.

Foreign Key Translation

The sync system must ensure that relationships between models are preserved across devices. Since each device uses local, auto-incrementing integer IDs for performance, these IDs cannot be used for cross-device references. This is where foreign key translation comes in, a process orchestrated by the foreign_key_mappings() function on the Syncable trait. The Process:
  1. Outgoing: When a record is being prepared for sync, the system uses the foreign_key_mappings() definition to find all integer foreign key fields (e.g., parent_id: 42). It looks up the corresponding UUID for each of these IDs in the local database and sends the UUIDs over the network (e.g., parent_uuid: "abc-123...").
  2. Incoming: When a device receives a record, it does the reverse. It uses foreign_key_mappings() to identify the incoming UUID foreign keys, looks up the corresponding local integer ID for each UUID, and replaces them before inserting the record into its own database (e.g., parent_uuid: "abc-123..."parent_id: 15).
This entire translation process is automatic and transparent. Batch FK Optimization: For bulk operations (backfill, batch sync), the system uses batch_map_sync_json_to_local() which reduces database queries from N×M (N records × M FKs) to just M (one query per FK type). For 1000 records with 3 FK fields each, this is a 365x reduction in queries.
Separation of Concerns: sync_depends_on() determines the order of model synchronization at a high level. foreign_key_mappings() handles the translation of specific foreign key fields within a model during the actual data transfer.

Dependency Tracking

During backfill, records may arrive before their FK dependencies (e.g., an entry before its parent folder). The DependencyTracker handles this efficiently:
This provides O(n) targeted retry instead of O(n²) “retry entire buffer” approaches: The tracker maintains a map of missing_uuid → Vec<waiting_updates>. When a record is successfully applied, its UUID is checked against the tracker to resolve any waiting dependents.

Sync Flows

See core/tests/sync_backfill_test.rs and core/tests/sync_realtime_test.rs for sync flow tests.

Creating a Location

Location and entry sync is tested in test_initial_backfill_alice_indexes_first in core/tests/sync_backfill_test.rs.
1

Device A Creates Location

User adds /Users/alice/Documents:
  • Insert into local database
  • Call library.sync_model(&location)
  • Send StateChange message to connected peers via unidirectional stream
2

Device B Receives Update

Receives StateChange message: - Map device UUID to local ID - Insert location (read-only view) - Update UI instantly
3

Complete

No conflicts possible (ownership is exclusive)

Creating a Tag

1

Device A Creates Tag

User creates “Important” tag:
  • Insert into local database
  • Generate HLC timestamp
  • Append to sync log
  • Broadcast to peers
2

Device B Applies Change

Receives tag creation: - Update local HLC - Apply change in order - Send acknowledgment
3

Log Cleanup

After all acknowledgments:
  • Remove from sync log
  • Log stays small

New Device Joins

1

Pull Shared Resources First

New device sends SharedChangeRequest:
  • Peer responds with recent changes from sync log
  • If log was pruned, includes current state snapshot
  • For larger datasets, paginate using HLC cursors
  • Apply tags, collections, content identities in HLC order
  • Shared resources sync first to satisfy foreign key dependencies (entries reference content identities)
2

Pull Device-Owned Data

New device sends StateRequest to each peer: - Request locations, entries, volumes owned by peer - Peer responds with StateResponse containing records in batches - For large datasets, automatically paginates using timestamp|uuid cursors - Apply in dependency order (devices, then locations, then entries)
3

Catch Up and Go Live

Process any changes that occurred during backfill from the buffer queue. Transition to Ready state. Begin receiving real-time broadcasts.

Advanced Features

Transitive Sync

See core/tests/sync_backfill_test.rs for backfill scenarios.
Spacedrive does not require a direct connection between all devices to keep them in sync. Changes can propagate transitively through intermediaries, ensuring the entire library eventually reaches a consistent state. This is made possible by two core architectural principles:
  1. Complete State Replication: Every device maintains a full and independent copy of the entire library’s shared state (like tags, collections, etc.). When Device A syncs a new tag to Device B, that tag becomes a permanent part of Device B’s database, not just a temporary message.
  2. State-Based Backfill: When a new or offline device (Device C) connects to any peer in the library (Device B), it initiates a backfill process. As part of this process, Device C requests the complete current state of all shared resources from Device B.
How it Works in Practice:
1

1. Device A syncs to B

Device A creates a new tag. It connects to Device B and syncs the tag. The tag is now stored in the database on both A and B. Device A then goes offline.
2

2. Device C connects to B

Device C comes online and connects only to Device B. It has never communicated with Device A.
3

3. Device C Backfills from B

Device C requests the complete state of all shared resources from Device B. Since Device B has a full copy of the library state (including the tag from Device A), it sends that tag to Device C.
4

4. Library is Consistent

Device C now has the tag created by Device A, even though they never connected directly. The change has propagated transitively.
This architecture provides significant redundancy and resilience, as the library can stay in sync as long as there is any path of connectivity between peers.

Peer Selection

When starting a backfill, the system scores available peers to select the best source:
Peers are sorted by score (highest first). The best peer is selected for backfill. If that peer disconnects, the checkpoint is saved and a new peer is selected.

Deterministic UUIDs

System-provided resources use deterministic UUIDs (v5 namespace hashing) so they’re identical across all devices:
Use deterministic UUIDs for:
  • System tags (system, screenshot, download, document, image, video, audio, hidden, archive, favorite)
  • Built-in collections
  • Library defaults
Use random UUIDs for:
  • User-created tags (supports duplicate names in different contexts)
  • User-created collections
  • All user content
This prevents creation conflicts for system resources while allowing polymorphic naming for user content.

Delete Handling

See core/tests/sync_realtime_test.rs for deletion sync tests.
Device-owned deletions use tombstones that sync via StateResponse. When you delete a location or folder with thousands of files, only the root UUID is tombstoned. Receiving devices cascade the deletion through their local tree automatically. Shared resource deletions use HLC-ordered log entries with ChangeType::Delete. All devices process deletions in the same order for consistency. Pruning: Both deletion mechanisms use acknowledgment-based pruning. Tombstones and peer log entries are removed after all devices have synced past them. A 7-day safety limit prevents offline devices from blocking pruning indefinitely. The system tracks deletions in a device_state_tombstones table. Each tombstone contains just the root UUID of what was deleted. When syncing entries for a device, the StateResponse includes both updated records and a list of deleted UUIDs since your last sync.
Receiving devices look up each deleted UUID and call the same deletion logic used locally. For entries, this triggers delete_subtree() which removes all descendants via the entry_closure table. A folder with thousands of files requires only one tombstone and one network message. Race condition protection: Models check tombstones before applying state changes during backfill. If a deletion arrives before the record itself, the system skips creating it. For entries, the system also checks if the parent is tombstoned to prevent orphaned children.

Pre-Sync Data

Pre-sync data backfill is tested in core/tests/sync_backfill_test.rs.
Data created before enabling sync is included during backfill. When the peer log has been pruned or contains fewer items than expected, the response includes a current state snapshot:
The receiving device applies both the incremental changes and the current state snapshot, ensuring all shared resources sync correctly even if created before sync was enabled.

Watermark-Based Incremental Sync

See core/tests/sync_backfill_test.rs for incremental sync tests.
When devices reconnect after being offline, they use watermarks to avoid full re-sync. Per-Resource Watermarks: Each resource type (location, entry, volume) tracks its own timestamp watermark per peer device. This prevents watermark advancement in one resource from filtering out records in another resource with earlier timestamps. The device_resource_watermarks table in sync.db tracks:
  • Which peer device the watermark is for
  • Which resource type (model) the watermark covers
  • The last successfully synced timestamp
This allows independent sync progress: if entries sync to timestamp T1 but locations only sync to T0, each resource type resumes from its own watermark rather than a global one. Watermark Advancement: Watermarks only advance when data is actually received. This invariant prevents a subtle data loss bug: if a catch-up request returns empty (peer has no new data), advancing the watermark anyway would permanently filter out any records that should have been returned. The system tracks the maximum timestamp from received records and uses that for the watermark update. Shared Watermark: HLC of the last shared resource change seen. Used for incremental sync of tags, collections, and other shared resources. Stale Watermark Handling: If a watermark is older than force_full_sync_threshold_days (default 25 days), the system forces a full sync instead of incremental catch-up. This ensures consistency when tombstones for deletions may have been pruned. During catch-up, the device sends a StateRequest with the since parameter set to its watermark. The peer responds with only records modified after that timestamp. This is a pull request, not a broadcast. Example flow when Device B reconnects:
This syncs only changed records instead of re-syncing the entire dataset.

Pagination for Large Datasets

Pagination ensures backfill works reliably for libraries with millions of records.
Both device-owned and shared resources use cursor-based pagination for large datasets. Batch size is configurable via SyncConfig. Device-owned pagination uses a timestamp|uuid cursor format:
Query logic handles identical timestamps from batch inserts:
Shared resource pagination uses HLC cursors:
The peer log query returns the next batch starting after the provided HLC, maintaining total ordering. Both pagination strategies ensure all records are fetched exactly once, no records are skipped even with identical timestamps, and backfill is resumable from checkpoint if interrupted.

Protocol Messages

The sync protocol uses JSON-serialized messages over Iroh/QUIC streams:

Message Types

Message Structures

Serialization

  • Format: JSON via serde
  • Bidirectional streams: 4-byte length prefix (big-endian) + JSON bytes
  • Unidirectional streams: Direct JSON bytes
  • Timeout: 30s for messages, 60s for backfill requests

Connection State Tracking

See core/tests/sync_realtime_test.rs for connection handling tests.
The sync system uses the Iroh networking layer as the source of truth for device connectivity. When checking if a peer is online, the system queries Iroh’s active connections directly rather than relying on cached state. A background monitor updates the devices table at configured intervals for UI purposes:
All sync decisions use real-time Iroh connectivity checks, ensuring messages only send to reachable peers.

Derived Tables

Some data is computed locally and never syncs:
  • directory_paths: A lookup table for the full paths of directories.
  • entry_closure: Parent-child relationships
  • tag_closure: Tag hierarchies
These rebuild automatically from synced base data.

Retry Queue

Failed sync messages are automatically retried with exponential backoff:

Retry Behavior

How It Works

Queue Management

  • Atomic processing: Messages removed before retry to prevent duplicates
  • Ordered by next_retry: Earliest messages processed first
  • No persistence: Queue lost on restart (messages will re-sync via watermarks)
  • Metrics: retry_queue_depth tracks current queue size
The retry queue handles transient network failures without blocking real-time sync. Permanent failures eventually resolve via watermark-based catch-up when the peer reconnects.

Portable Volumes & Ownership Changes

A key feature of Spacedrive is the ability to move external drives between devices without losing track of the data. This is handled through a special sync process that allows the “ownership” of a Location to change.

Changing Device Ownership

When you move a volume from one device to another, the Location associated with that volume must be assigned a new owner. This process is designed to be extremely efficient, avoiding the need for costly re-indexing or bulk data updates. It is handled using a Hybrid Ownership Sync model:
1

Ownership Change is Requested

When a device detects a known volume that it does not own, it broadcasts a special RequestLocationOwnership event. Unlike normal device-owned data, this event is sent to the HLC-ordered log, treating it like a shared resource update.
2

Peers Process the Change

Every device in the library processes this event in the same, deterministic order. Upon processing, each peer performs a single, atomic update on its local database: UPDATE locations SET device_id = 'new_owner_id' WHERE uuid = 'location_uuid'
3

Ownership is Transferred Instantly

This single-row update is all that is required. Because an Entry’s ownership is inherited from its parent Location at runtime, this change instantly transfers ownership of millions of files. No bulk updates are needed on the entries or directory_paths tables. The new owner then takes over state-based sync for that Location.

Handling Mount Point Changes

A simpler scenario is when a volume’s mount point changes on the same device (e.g., from D:\ to E:\ on Windows).
  1. Location Update: The owning device updates the path field on its Location record.
  2. Path Table Migration: This change requires a bulk update on the directory_paths table to replace the old path prefix with the new one (e.g., REPLACE(path, 'D:\', 'E:\')).
  3. No Entry Update: Crucially, the main entries table, which is the largest, is completely untouched. This makes the operation much faster than a full re-index.

Performance

Sync Characteristics

Optimizations

Batching: The sync system batches both device-owned and shared resource operations. Batch sizes are configurable via SyncConfig. Device-owned data syncs in batches during file indexing. One StateBatch message replaces many individual StateChange messages, providing significant performance improvement. Shared resources send batch messages instead of individual changes. For example, linking thousands of files to content identities during indexing sends a small number of network messages instead of one per file, providing substantial reduction in network traffic. Both batch types still write individual entries to the sync log for proper HLC ordering and conflict resolution. The optimization is purely in network broadcast efficiency. Pruning: The sync log automatically removes entries after all peers acknowledge receipt, keeping the sync database under 1MB. Compression: Network messages use compression to reduce bandwidth usage. Caching: Backfill responses cache for 15 minutes to improve performance when multiple devices join simultaneously.

Troubleshooting

Changes Not Syncing

Check:
  1. Devices are paired and online
  2. Both devices joined the library
  3. Network connectivity between devices
  4. Sync service is running
Debug commands:

Common Issues

Large sync.db: Peers not acknowledging. Check network connectivity. Missing data: Verify dependency order. Parents must sync before children. Conflicts: Check HLC implementation maintains ordering.

Error Types

The sync system defines specific error types for different failure modes:

Infrastructure Errors

Registry Errors

Dependency Errors

Transaction Errors

All errors implement std::error::Error and include context for debugging.

Metrics & Observability

The sync system collects metrics for monitoring and debugging.

Metric Categories

State Metrics:
  • current_state - Current sync state (Uninitialized, Backfilling, etc.)
  • state_entered_at - When current state started
  • state_history - Recent state transitions (ring buffer)
  • total_time_in_state - Cumulative time per state
  • transition_count - Number of state transitions
Operation Metrics:
  • broadcasts_sent - Total broadcast messages sent
  • state_changes_broadcast - Device-owned changes broadcast
  • shared_changes_broadcast - Shared resource changes broadcast
  • changes_received - Updates received from peers
  • changes_applied - Successfully applied updates
  • changes_rejected - Updates rejected (conflict, error)
  • active_backfill_sessions - Concurrent backfills in progress
  • retry_queue_depth - Messages waiting for retry
Data Volume Metrics:
  • entries_synced - Records synced per model type
  • entries_by_device - Records synced per peer device
  • bytes_sent / bytes_received - Network bandwidth
  • last_sync_per_peer - Last sync timestamp per device
  • last_sync_per_model - Last sync timestamp per model
Performance Metrics:
  • broadcast_latency - Time to broadcast to all peers (histogram)
  • apply_latency - Time to apply received changes (histogram)
  • backfill_request_latency - Backfill round-trip time (histogram)
  • peer_rtt_ms - Per-peer round-trip time
  • watermark_lag_ms - How far behind each peer is
  • hlc_physical_drift_ms - Clock drift detected via HLC
  • hlc_counter_max - Highest logical counter seen
Error Metrics:
  • total_errors - Total error count
  • network_errors - Connection/timeout failures
  • database_errors - DB operation failures
  • apply_errors - Change application failures
  • validation_errors - Invalid data received
  • recent_errors - Last N errors with details
  • conflicts_detected - Concurrent modification conflicts
  • conflicts_resolved_by_hlc - Conflicts resolved via HLC

Histogram Metrics

Performance metrics use histograms with atomic min/max/avg tracking:

Snapshots

Metrics can be captured as point-in-time snapshots:

History

A ring buffer stores recent snapshots for time-series analysis:

Persistence

Metrics are persisted to the database every 5 minutes (configurable via metrics_log_interval_secs). This enables post-mortem analysis of sync issues.

Sync Event Bus

The sync system uses a dedicated event bus separate from the general application event bus:

Why Separate?

The general EventBus handles high-volume events (filesystem changes, job progress, UI updates). During heavy indexing, thousands of events per second can queue up. The SyncEventBus is isolated to prevent sync events from being starved:
  • Capacity: 10,000 events (vs 1,000 for general bus)
  • Priority: Sync-critical events processed first
  • Droppable: Metrics events can be dropped under load

Event Types

Event Criticality

Critical events trigger warnings if the bus lags. Non-critical events are silently dropped under load.

Real-Time Batching

The event listener batches events before broadcasting:
This reduces network overhead during rapid operations (e.g., bulk tagging).

Implementation Status

See core/tests/sync_backfill_test.rs, core/tests/sync_realtime_test.rs, and core/tests/sync_metrics_test.rs for the test suite.

Production Ready

  • One-line sync API (sync_model, sync_model_with_db, sync_models_batch)
  • HLC implementation (thread-safe, lexicographically sortable)
  • Syncable trait infrastructure with inventory-based registration
  • Foreign key mapping with batch optimization (365x query reduction)
  • Dependency ordering via topological sort (Kahn’s algorithm)
  • Network transport (Iroh/QUIC with bidirectional streams)
  • Backfill orchestration with resumable checkpoints
  • State snapshots for pre-sync data
  • HLC conflict resolution (last write wins)
  • Per-resource watermark tracking for incremental sync
  • Connection state tracking via Iroh
  • Transitive sync through intermediary devices
  • Cascading tombstones for device-owned deletions
  • Unified acknowledgment-based pruning
  • Post-backfill rebuild for closure tables
  • Metrics collection for observability

Currently Syncing

Device-Owned Models (3): Shared Models (16):

Excluded Fields

Each model excludes certain fields from sync (local-only data): All models sync automatically during creation, updates, and deletions. File indexing uses batch sync for both device-owned entries (StateBatch) and shared content identities (SharedChangeBatch) to reduce network overhead. Deletion sync: Device-owned models (locations, entries, volumes) use cascading tombstones. The device_state_tombstones table tracks root UUIDs of deleted trees. Shared models use standard ChangeType::Delete in the peer log. Both mechanisms prune automatically once all devices have synced.

Extension Sync

Extension sync framework is ready. SDK integration pending.
Extensions can define syncable models using the same infrastructure as core models. The registry pattern automatically handles new model types without code changes to the sync system. Extensions will declare models with sync metadata:
The sync system will detect and register extension models at runtime, applying the same HLC-based conflict resolution and dependency ordering used for core models.

Configuration

Sync behavior is controlled through a unified configuration system. All timing, batching, and retention parameters are configurable per library.

Default Configuration

The system uses sensible defaults tuned for typical usage across LAN and internet connections:
Batching controls how many records are processed at once. Larger batches improve throughput but increase memory usage. Real-time batching collects changes for a short interval before flushing to reduce network overhead during rapid operations. Retention controls how long sync coordination data is kept. The acknowledgment-based strategy prunes tombstones and peer log entries as soon as all devices have synced past them. A 7-day safety limit prevents offline devices from blocking pruning indefinitely. Network controls timeouts and polling intervals. Shorter intervals provide faster sync but increase network traffic and CPU usage. Monitoring controls metrics collection and sync database maintenance. Metrics track operations, latency, and data volumes for debugging and observability.

Presets

Aggressive is optimized for fast local networks with always-online devices. Small batches and frequent pruning minimize storage and latency. Conservative handles unreliable networks and frequently offline devices. Large batches improve efficiency, and extended retention accommodates longer offline periods. Mobile optimizes for battery life and bandwidth. Less frequent sync checks and longer retention reduce power consumption.

Configuring Sync

Configuration can also be set via environment variables or a TOML file. The loading priority is: environment variables, config file, database, then defaults.

Summary

Library Sync is not traditional multi-leader replication. While multi-leader systems treat all nodes as equal for all data, Spacedrive recognizes a fundamental truth: /Users/alice/Photos can only be modified by Alice’s laptop. This ownership model eliminates the entire class of filesystem conflicts that plague distributed systems. Hybrid ownership splits the problem in two. Device-owned data (files, folders, volumes) uses single-leader-per-resource semantics. No CRDTs, no version vectors, no conflict resolution needed. The owner’s state is authoritative. Shared resources (tags, collections) use multi-leader semantics with HLC-based ordering. Only this small subset of data requires conflict resolution, and last-write-wins is sufficient. State-based sync handles device-owned data. Changes propagate via real-time broadcasts to connected peers. Historical data transfers via pull requests when devices join or reconnect. Log-based sync handles shared resources. Hybrid Logical Clocks maintain causal ordering without clock synchronization. All devices converge to the same state regardless of network topology. Automatic recovery handles offline periods through watermark-based incremental sync. Reconnecting devices receive only changes since their last sync, typically a small delta rather than the full dataset. The system is production-ready with all core models syncing automatically. Extensions can use the same infrastructure to sync custom models.