Build a Sync Engine for Multi-Scope IDE Configuration
System DesignModel answerLast updated
Design a configuration service that merges settings from org, team, workspace, user, and local scopes, syncs across devices, and handles offline edits with conflict resolution.
Context
You're architecting a configuration synchronization service for a cloud-connected development environment. Developers define preferences—keyboard shortcuts, editor behavior, extensions, linter rules—at multiple levels of granularity. An engineer might inherit their company's Python formatting standard, overlay their team's shared keybindings, then add personal customizations that follow them across every machine they use.
Your system must store, version, and merge these layered configurations while supporting offline work and ensuring every client converges to the same resolved state.
Requirements
Functional
Layered precedence with overrides
Configuration sources form a hierarchy: default → organization → team → repository → user account → local device. Each layer can override keys from lower layers, or an administrative layer can lock specific keys to prevent user modification.
Offline-first operation with merge on reconnect
Engineers edit settings without network access. When connectivity returns, local changes must reconcile with remote updates without data loss. Conflicts between concurrent edits need deterministic resolution.
Immutable history and point-in-time recovery
Every configuration layer maintains an audit trail. Administrators roll back to earlier revisions, compare snapshots across time, and understand who changed what.
Permission enforcement
Only authorized users modify team or organization settings. Membership updates—adding someone to a team or changing their role—immediately affect which configurations they inherit.
Schema compatibility across client versions
Not every user upgrades simultaneously. The backend gracefully handles clients that send deprecated keys, renamed fields, or type mismatches, migrating data transparently.
Non-Functional
Sub-50 ms resolution on startup
The editor computes the final merged configuration fast enough that it never blocks the application launch, even on slower hardware.
Near-real-time propagation
When an admin publishes a new organization policy, all connected clients receive a notification and refresh within two seconds.
Graceful degradation
If the sync service is unreachable, the client continues using its last-known state. No connectivity failures prevent the editor from opening or functioning.
Scale Expectations
- 5 million daily active users, each running the editor on two devices on average
- 500,000 teams and organizations
- Each configuration scope is roughly 50 KB of JSON
- Peak read load: 15,000 queries per second (read-heavy, cacheable)
- Peak write load: 200 updates per second
What to Cover
-
Schema and storage model: How you represent scopes, revisions, locks, and membership. What goes in a relational store versus a blob store, and how you handle immutability.
-
Synchronization mechanics: Client-server protocol for fetching deltas, submitting changes, and detecting conflicts. How offline edits reconcile when multiple devices modify the same key.
-
Merge and evaluation logic: Where hierarchical resolution happens (client, server, or both) and how you implement deterministic precedence with locking.
-
Failure and edge-case handling: Strategies for partition tolerance, disaster recovery, duplicate event delivery, and schema validation breakage.
Provide concrete architectural choices, data flow diagrams where helpful, and reasoning about trade-offs.
Hints
Hint 1
The 50 ms startup constraint means hierarchical resolution must happen fully offline from cached state.
Hint 2
Storing full snapshots for every revision wastes space; key-level deltas and content-addressed blobs deduplicate effectively.
Hint 3
A monotonic revision number per scope is simpler than vector clocks when the server serializes all writes to that scope.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Start by identifying the hardest constraints. The 50 ms startup requirement rules out any network dependency during launch—resolution must run entirely from local cache. The offline editing requirement means the client needs an optimistic write log that replays on reconnect. The read-heavy traffic pattern (15K QPS reads vs. 200 QPS writes at a 75:1 ratio) makes aggressive caching essential, especially for hot organization and team configurations shared by thousands of users.
High-Level Architecture
Client agent
Embedded in the IDE, it maintains a local SQLite or file-based cache holding the latest snapshot of each relevant scope (org, team, workspace, user) tagged with its revision number. On startup, it loads and merges these snapshots locally in a few milliseconds. A background task polls or subscribes to push notifications, fetching deltas when remote revisions advance. Offline writes accumulate in an operation log with base revision markers.
API gateway and settings service
Stateless application tier handling authentication, authorization, schema validation, and three-way merge logic. Every modification runs a compare-and-swap on the scope's head revision to serialize concurrent updates.
Metadata database
Sharded relational store (Postgres, Spanner) keyed by scope_id. Each scope has a home shard providing a single serialization point. Tables:
- scope:
scope_id,type,owner_id,head_revision,head_snapshot_hash - revision:
scope_id,revision(monotonic int),parent_revision,author_id,timestamp,client_operation_id,operations[],snapshot_hash— append-only log - lock:
scope_id,key_path,mode(advisory or enforced),value - membership:
user_id,team_id,org_id,role,membership_epoch
Blob store
Content-addressed object storage (S3, GCS) holding:
- snapshots: hash → map of
{key_path → value_hash} - values: hash → typed JSON value
Deduplication is automatic: unchanged keys share the same value hash across revisions, and identical snapshots reuse the same blob.
Cache layer
Redis or CDN caching (scope_id, revision) → snapshot. Because the cache key includes the revision, entries are immutable and never need invalidation. Organization and team scopes, each read by thousands of users, achieve hit rates above 99%.
Event pipeline
Write commits publish to an outbox table, then stream through Kafka to a WebSocket/SSE gateway. Events carry only (scope_id, new_revision) as hints—clients fetch deltas separately. Fan-out logic maps scope changes to affected user subscriptions. At ~100K connections per gateway node, 50 nodes handle 5M concurrent clients.
Data Flow
Startup and sync
- Client reads cached snapshots from disk (org, team, workspace, user).
- Merges them locally in precedence order: default → org → team → workspace → user → local.
- Applies lock policies (enforced locks override lower layers).
- Renders the resolved configuration to the editor, all within 5–10 ms.
- In the background, sends
GET /syncwith a revision vector{org:847, team:62, workspace:15, user:9302}. - Server responds with deltas for any scope whose head exceeds the client's known revision.
- Client updates cache and re-evaluates if any scope changed.
Write path
- User modifies a setting (e.g., changes font size in their user scope).
- Client records operation
{key: "editor.fontSize", op: "set", value: 14, base_revision: 9302}with a uniqueclient_operation_id. - If online, immediately posts to
POST /scopes/{user_scope_id}/changes. - Server checks authorization, compares
base_revisionwithhead_revision. - If equal, applies operation and increments revision to 9303.
- If not equal (concurrent edit), runs three-way merge per key.
- On success, writes a new revision row, updates
head_revisionvia CAS, and publishes event. - All other devices subscribed to that user's scope receive the notification and fetch the delta.
Offline reconciliation
- While offline, client queues operations locally.
- On reconnect, batches them and sends with their
base_revision. - Server compares base against current head. If diverged:
- No conflict: key changed on only one side → auto-merge.
- Same value on both sides: no-op.
- Different values:
- User scope: last-write-wins by hybrid logical clock; losing value preserved in history with "overwritten by device X" annotation.
- Team/org scope: return 409 Conflict with both versions; client prompts for manual resolution or discards local edit.
Synchronization Protocol Details
Revision numbering
Each scope uses a server-assigned monotonic integer. No need for vector clocks because the database's compare-and-swap serializes all updates to a given scope. The client only tracks the latest known revision per scope.
Delta encoding
Instead of transmitting full 50 KB snapshots, the server computes a diff between the client's known revision and head. Most syncs transfer only a few changed keys (hundreds of bytes). For large gaps (e.g., first sync or long offline period), the server may send a full snapshot if the delta exceeds a threshold.
Idempotent event handling
Notifications are unreliable hints. Clients ignore events for revisions they already possess. Duplicate events do nothing. Out-of-order delivery is harmless because the client requests deltas from its known revision, which linearizes history. A background 5-minute poll ensures missed events eventually sync.
Merge and Evaluation Logic
Resolution runs on both sides
Server-side resolution powers admin dashboards showing "effective configuration" and enforces security policies. Client-side resolution delivers sub-50 ms startup. Both implementations share a canonical specification with identical test cases to guarantee deterministic output.
Per-key merge strategies
The schema registry defines how each key combines across layers:
replace: scalars (font size, theme) take the highest-precedence value.append-unique: arrays (linter rules, plugin IDs) concatenate, removing duplicates.deep-merge: nested objects (keybindings map) merge recursively.
Lock enforcement
If any scope applies an "enforce" lock to a key, the highest-authority lock wins (org beats team beats user). All lower-precedence layers for that key are ignored. Advisory locks show a warning but allow overrides.
Scalability and Performance
Storage
Current state: ~10M scopes × 50 KB ≈ 500 GB raw, but content addressing and key-level deltas reduce actual storage significantly. History at 200 writes/sec × 1 KB delta × 86400 sec ≈ 17 GB/day. Partitioning by scope_id shards naturally, and each scope's working set is small.
Read path
Cache hit rates above 95% for org/team scopes drop database load to ~750 QPS. Conditional requests (If-None-Match by revision) return 304 Not Modified when the client is current, eliminating payload transfer.
Write path
200 writes/sec spread across shards. Each write is a single-row insert to the append-only revision table and a CAS update to the head pointer. The outbox table enables reliable event publishing without blocking the write transaction.
Failure Modes and Mitigations
Network partition
Client continues operating from cache. Offline operation log grows until reconnect. Periodic cache expiration (e.g., 7 days) for team/org scopes prompts manual refresh if extremely stale.
Database unavailability
Read cache serves stale data. Write buffer backs up; clients retry with exponential backoff and surface "sync pending" status to users.
Duplicate or reordered events
Revision-based change detection makes the system idempotent. Clients fetch only deltas they haven't seen, regardless of event order.
Schema evolution
The service stores a version tag with each write. Reads translate deprecated keys via migration rules defined in the schema registry. For example, renaming tabs.size to editor.tabSize maps old keys transparently. Clients on older versions continue writing the old key; the server writes both until all clients upgrade.
Conflict storms
Rapid concurrent writes to a shared team scope can cause repeated CAS failures. Introduce jittered retry and potentially a short-lived distributed lock for high-contention scopes.
Complexity
Time
- Client resolution: O(L × K) where L is the number of layers (typically 5–6) and K is the number of keys (~500). In practice, ~2 ms.
- Sync check: O(S) where S is the number of scopes a user subscribes to (~4–5). Single round-trip, <20 ms.
- Three-way merge: O(K_changed), typically <10 keys per conflict.
Space
- Client cache: 50 KB × 5 scopes ≈ 250 KB per user.
- Server per-scope overhead: revision log grows with history. Archive revisions older than 90 days to cold storage; recent working set remains small.
Common Mistakes
- Resolving settings on the server at startup: The round-trip alone exceeds 50 ms. Always cache and resolve locally.
- Storing full snapshots for every revision: Wastes storage and bandwidth. Use key-level deltas and content addressing.
- Silently discarding offline edits on conflict: Breaks user trust. Preserve conflicting values in history and notify the user.
- Invalidating cache on every write: Immutable cache keys (scope + revision) eliminate invalidation complexity.
- Not testing schema migration paths: Deploy a test matrix covering N–1, N, and N+1 client versions against the live schema registry.
Code Sketch: Client Resolution
def resolve_settings(layers: dict[str, Snapshot], locks: dict[str, Lock],
schema: SchemaRegistry) -> dict:
"""
layers: {"org": snapshot, "team": snapshot, "user": snapshot, "local": snapshot}
locks: {key_path: Lock(scope, mode, value)}
"""
result = {}
precedence = ["default", "org", "team", "workspace", "user", "local"]
all_keys = set()
for snap in layers.values():
all_keys.update(snap.keys())
for key in all_keys:
# Collect values from each layer
values = [(layer, layers[layer].get(key))
for layer in precedence if layer in layers and key in layers[layer]]
# Check for enforced lock
if key in locks and locks[key].mode == "enforce":
result[key] = locks[key].value
continue
# Apply merge strategy from schema
strategy = schema.get_merge_strategy(key)
if strategy == "replace":
result[key] = values[-1][1] # highest precedence
elif strategy == "append-unique":
result[key] = list(dict.fromkeys(
item for _, val in values for item in val
))
elif strategy == "deep-merge":
merged = {}
for _, val in values:
deep_merge_into(merged, val)
result[key] = merged
return result
This architecture delivers deterministic, low-latency configuration management that scales to millions of users while gracefully handling the messy realities of distributed, offline-capable systems.