Design a Real-Time Collaborative Task List
System DesignModel answerLast updated
Architect a low-latency, real-time shared task list supporting concurrent edits, item reordering, explicit synchronous durability, and reconnection recovery.
Problem Context
Design the backend architecture for a real-time collaborative task list application (such as shared team checklists or joint planning boards). The system allows multiple users to view, add, modify, check off, delete, and reorder tasks within a list concurrently.
The application must ensure that local modifications are persisted durably and acknowledged directly to the author, while simultaneously broadcasting updates to other active collaborators on the same list with sub-second latency.
Requirements
Functional Requirements
- Shared Workspace: Users can create lists, manage access control, and receive live updates from active collaborators.
- Task Management: Support task creation, updating (title, status, assignee), deletion, and relative reordering.
- Real-Time Push: Active collaborators currently viewing a list must receive remote changes with minimal latency.
- Durable Acknowledgements: Modifications must be explicitly committed to persistent storage before returning a success acknowledgement to the authoring client.
- Conflict Handling: The backend must resolve concurrent mutations (e.g., simultaneous field edits or relative item positioning) deterministically without silent data loss.
- State Catch-up: Disconnected clients must seamlessly resynchronize missing updates upon reconnecting without needing to re-fetch full list state unless necessary.
Non-Functional Requirements & Scale
- Scale: 10 million Daily Active Users (DAU); 1 million peak concurrent active lists.
- Group Density: Typically 2–10 active collaborators per list; peak spikes up to 100 concurrent collaborators on a single list.
- Latency SLAs:
- Author write durability acknowledgement (p99) < 100ms.
- Broadcast fan-out latency to active collaborators (p99) < 250ms.
- Consistency: Strong consistency / linearizability per individual list. Global ordering across unrelated lists is not required.
Deliverables
Provide a complete architectural design covering:
- API & Data Representation: API specifications, schema design, task reordering strategy, and versioning primitives.
- System Architecture: High-level component diagram detailing the synchronous write durability path versus the asynchronous real-time fan-out tier.
- Concurrency Control: Mechanism for handling race conditions, concurrent field edits, and list reordering.
- Connection Management & Catch-up: Edge WebSocket routing, pub/sub integration, session state management, and reconnection protocol.
Hints
Hint 1
Differentiate the synchronous persistence path from the asynchronous broadcast path. Synchronous writes require disk flush before responding to the author, whereas client updates can be pushed via lightweight pub/sub.
Hint 2
For task reordering, avoid integer index shifts across the array. Consider string-based fractional indexing (e.g., LexoRank) to make reordering an isolated write.
Hint 3
Avoid putting a message queue like Kafka directly in the write confirmation loop. The author's HTTP/WebSocket ACK must wait on primary storage insertion, while CDC or transactional outbox handles the downstream publish.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Design a Real-Time Collaborative Task List
1. Capacity Estimations & System Constraints
To dimension the infrastructure correctly, we quantify the peak traffic, storage growth, and network requirements.
Workload & Throughput
- Peak Concurrent Active Lists: $1,000,000$
- Average Active Users per List: $4$
- Total Peak Concurrent Connections: $1,000,000 \text{ lists} \times 4 \text{ connections/list} = 4,000,000 \text{ active WebSockets}$.
- Write Operations: Assuming an active user mutates state once every $60\text{ seconds}$ on average: $$\text{Peak Write QPS} = \frac{4,000,000}{60} \approx 66,667 \text{ writes/sec} \quad (\text{Provision for } 150,000 \text{ peak QPS})$$
- Fan-Out Push Throughput: Each write is broadcast to 3 other collaborators on average: $$\text{Broadcast Pushes} = 66,667 \times 3 \approx 200,000 \text{ pushes/sec}$$
Storage Requirements
- Task Payload: $\sim 500 \text{ bytes}$ per task. Average list contains 50 tasks ($\sim 25 \text{ KB}$).
- Delta Event: $\sim 300 \text{ bytes}$ per change event.
- Event Log Volume: At $66,667 \text{ events/sec} \times 300 \text{ bytes} \approx 20 \text{ MB/sec} \approx 1.7 \text{ TB/day}$ of append-only log data before retention pruning or compaction.
2. Data Model & Ordering Strategy
We use a relational database sharded logically by list_id (e.g., CockroachDB, Vitess, or sharded PostgreSQL). Co-locating all tasks and events of a single list on the same physical shard ensures fast transactional boundaries and local linearizability.
+-----------------------+
| lists |
+-----------------------+
| list_id (PK, UUID) |
| title VARCHAR |
| head_seq BIGINT | <--- Per-list monotonic sequence
| snapshot_seq BIGINT |
+-----------------------+
|
| 1:N
v
+------------------------------------+
| tasks |
+------------------------------------+
| list_id (PK, UUID) |
| task_id (PK, UUID) |
| title VARCHAR |
| status VARCHAR |
| assignee_id UUID |
| rank VARCHAR | <--- LexoRank fractional index
| task_version INT | <--- Per-task Optimistic Version
| updated_seq BIGINT |
| is_deleted BOOLEAN |
+------------------------------------+
|
| 1:N
v
+------------------------------------+
| events |
+------------------------------------+
| list_id (PK, UUID) |
| seq BIGINT (PK, composite) |
| task_id UUID |
| client_op_id UUID | <--- Idempotency key
| op_type VARCHAR |
| payload JSONB |
| actor_id UUID |
| timestamp TIMESTAMPTZ |
+------------------------------------+
Fractional Indexing (LexoRank) for Item Reordering
Instead of using array indices (which require updating $N$ items when an item is moved to position 0), tasks are ordered lexicographically via a rank string:
- Inserting between rank
"a0"and"a1"assigns rank"a0M". - Moving a task requires modifying only one single database record.
- If rank length exceeds a set bound (e.g., 64 bytes due to repeated interspersing), an asynchronous background task rebalances the rank strings evenly across the entire list and records a single
LIST_REBALANCEDevent.
3. High-Level System Architecture
The architecture separates the synchronous write path (guaranteeing durability and ACID guarantees) from the asynchronous fan-out path (delivering low-latency pushes to active WebSocket nodes).
+--------------------------+
| Client Devices |
+--------------------------+
/ \
HTTP / WS Writes/ \ Persistent WS Connections
v v
+------------------+ +-------------------+
| Write API Tier | | WebSocket Tier |
| (Stateless) | | (Gateway Edge) |
+------------------+ +-------------------+
| ^
v | Local Pub/Sub
+------------------+ | Subscriptions
| Primary Sharded | +-------------------+
| Database Cluster| | Redis Enterprise / |
+------------------+ | Redpanda Pub/Sub |
| +-------------------+
| Commit Log ^
v |
+------------------+ |
| CDC / Outbox |------------------+
| Worker Service | Publish Event (by list_id)
+------------------+
Component Breakdown
- WebSocket Gateway Tier: Edge servers holding persistent TCP/WS links with clients. Maintains an in-memory map of
list_id -> Set<WebSocketSession>. - Write API Tier: Stateless microservices handling write operations over HTTP or WebSocket frames.
- Database Cluster: Authoritative data store. Writes execute within an explicit database transaction that updates task state, increments
lists.head_seq, and inserts aneventsrecord. - Change Data Capture (CDC) / Transactional Outbox: Tailer service that reads committed database events (or outbox table) and publishes them instantly to the message routing layer.
- Pub/Sub Layer: High-throughput message bus (Redis Pub/Sub or Kafka/Redpanda grouped by
list_id) routing updates to WebSocket gateway instances listening to active lists.
4. Workflows & Execution Paths
Synchronous Write Path (Durability Confirmation)
Client Write API Database Shard CDC / Outbox Pub/Sub Layer
| | | | |
|--- Mutate Task ---->| | | |
| (client_op_id, |--- Begin Txn ------>| | |
| base_version) | Lock list_id | | |
| | Update task | | |
| | Bump head_seq | | |
| | Insert event | | |
| |<-- Commit Success --| | |
|<-- ACK 200 OK ------| | | |
| (seq, task_version) | |-- Stream Commit Log -->| |
| | | |--- Publish Event ---->|
- Client Action: Client performs an optimistic local UI update and sends a mutation request containing
client_op_id,task_id,base_version, and field mutations. - Database Execution:
BEGIN; -- 1. Idempotency Check SELECT seq FROM events WHERE list_id = :list_id AND client_op_id = :client_op_id; -- If exists, return cached result immediately. -- 2. Lock List Header & Get Monotonic Sequence Number UPDATE lists SET head_seq = head_seq + 1 WHERE list_id = :list_id RETURNING head_seq; -- 3. Execute Mutation & Verify Task Version UPDATE tasks SET title = :title, status = :status, task_version = task_version + 1, updated_seq = :head_seq WHERE list_id = :list_id AND task_id = :task_id AND task_version = :base_version; -- 4. Log Immutable Event INSERT INTO events (list_id, seq, task_id, client_op_id, op_type, payload, actor_id) VALUES (:list_id, :head_seq, :task_id, :client_op_id, 'TASK_UPDATE', :payload_json, :actor_id); COMMIT; - Durability Response: API Tier responds to author with
200 OK+{seq: 1042, task_version: 4}once committed to DB storage engine. Target latency: < 50ms.
Asynchronous Fan-Out Path
- The CDC worker reads committed transaction logs and publishes
{list_id: "L-123", seq: 1042, payload: ...}to channellist:L-123. - Gateway instances holding active connections for
L-123receive the pub/sub event. - Gateway forwards the payload over active WebSockets to non-author clients viewing
L-123. Total p99 latency: < 150ms.
Crucial Architecture Note: Do not route the synchronous author ACK through Kafka or asynchronous worker queues. Placing a message queue prior to primary database storage delays durability acknowledgements and breaks write-retry semantics.
5. Concurrency Control & Conflict Resolution
Field-Level Optimistic Concurrency Control (OCC)
To prevent lost updates while avoiding disruptive user locks:
- Reads return
task_version. - Write requests pass
base_version. - If two users modify the same field concurrently, the second write fails with HTTP
409 Conflict. The client fetches the current state, rebases, and presents a merge conflict prompt or auto-retries if the modification is commutative (e.g., checking a box vs editing a string).
Intent-Based Commutation
Where possible, write APIs accept intent primitives rather than state replacement:
- Checkbox updates: Submit
{op: "SET_STATUS", value: "DONE"}instead of{op: "TOGGLE"}. - Task Movement: Submit
{op: "MOVE", target_id: "T-12", position: "AFTER", reference_id: "T-09"}. The backend calculates the newrankdynamically within the single database transaction.
6. Connection Lifecycle & Reconnect Protocol
Client Connection Logic
|
Connect / Reconnect WS
|
Send `subscribe` with
`last_known_seq`
|
v
+-----------------------------+
| Gateway fetches database |
| current `head_seq` for list |
+-----------------------------+
|
+--------------------+--------------------+
| |
(head_seq - last_known_seq) (head_seq - last_known_seq)
<= 500 > 500
| |
v v
+---------------------------+ +---------------------------+
| Stream Delta Events | | Send Full List Snapshot |
| SELECT * FROM events | | SELECT * FROM tasks |
| WHERE seq > last_known_seq| | WHERE is_deleted = false |
+---------------------------+ +---------------------------+
| |
+--------------------+--------------------+
|
v
Transition to Live Streaming
- Subscription: Upon establishing/re-establishing a WebSocket connection, the client sends:
{ "action": "subscribe", "list_id": "L-1029", "last_known_seq": 1018 } - Gateway Registration: Gateway registers local connection to internal subscriber list for
L-1029and subscribes to pub/sub topiclist:L-1029(if not already subscribed on behalf of another local client). - Catch-up Delta Strategy:
- If
head_seq - last_known_seq <= 500: Gateway executes a delta query against storage or Redis event buffer (SELECT * FROM events WHERE list_id = :list_id AND seq > 1018 ORDER BY seq ASC). - If
head_seq - last_known_seq > 500(or snapshot gap): Gateway returns a complete list snapshot frame to reset client state efficiently.
- If
- Buffering & Ordering: Events produced during the catch-up window are buffered at the gateway and flushed to the client after delta replay, guaranteeing monotonic
seqordering without missing frames.
7. Trade-offs & Failure Modes
| Alternative Architecture | Evaluated Choice | Trade-off Rationale |
|---|---|---|
| Operational Transformation (OT) / CRDTs | Server-Authoritative OCC + LexoRank | OT/CRDTs excel at long, offline collaborative plain-text editing (e.g., Google Docs). For structured task lists, server-authoritative OCC simplifies permission enforcement, database indexing, and linearizable event logs with significantly lower operational overhead. |
| In-Memory Cluster (e.g., Akka/Actors) | Stateless API + Sharded Relational DB | In-memory actor states require complex state hydration, cluster rebalancing, and split-brain resolution during node failure. DB-backed state isolates durability to standard transactional databases. |
| Global Sequence Numbers | Per-List Monotonic Sequences (head_seq) | Global auto-increment keys create severe database lock contention. Per-list sequencing bounds lock scope to an individual list record, scaling writes horizontally across shards. |
Operational Resilience & Edge Cases
- Duplicate Writes (Network Drops): If an ACK is lost on the return network link, the author retries with the same
client_op_id. The unique database constraint on(list_id, client_op_id)catches the duplicate and returns the previously processed result without side effects. - Hot Lists (High Contention): If a single list has 100+ active collaborators firing rapid mutations, list sequence lock wait times can increase. The system enforces write-throttling at the API Gateway level per
list_id(e.g., max 20 writes/sec per list) to prevent database row-lock starvation. - Pub/Sub Dropped Messages: Pub/sub delivery is treated as transient. Clients inspect event
seqnumbers; if a gap is detected (e.g., receivedseq: 1045afterseq: 1042), the client triggers an out-of-band delta fetch for sequence gap1043–1044.