Design a Shared SQL Canvas with Immutable Releases and Async Runs
System DesignModel answerLast updated
Design a collaborative SQL editor featuring real-time document sync, frozen releases, and async execution tracking with strict input-output lineage.
You are tasked with designing a shared SQL Canvas for an enterprise analytics platform. The platform enables data engineers and analysts to collaborate on SQL queries, create immutable snapshots (releases), and execute queries against external cloud warehouses asynchronously while retaining total traceability of inputs and results.
Core Functional Requirements
- Real-time Collaboration: Workspace users can concurrently edit shared SQL drafts. Editors must see live presence indicators and cursor positions of active collaborators.
- Frozen Snapshots: Any editor can lock the current draft state into an immutable, versioned snapshot containing the exact SQL script, parameter definitions, default values, and target warehouse settings (such as target cluster, timeout, and row limits).
- Async Execution Engine: Authorized users can trigger execution of a specific snapshot by providing runtime parameter values. Queries run asynchronously (taking anywhere from a few seconds up to 45 minutes) and must support background execution without requiring an open browser session.
- Result Traceability and Side-by-Side Comparison: Each run records terminal state, execution duration, total row counts, error logs, a truncated result preview (up to 10,000 rows), and a link to a full export artifact. Users can view any two historical runs side-by-side with complete lineage of SQL code, parameters, settings, and output differences.
- Role-Based Access Control (RBAC): Workspace roles are categorized as Viewer (read-only access to drafts, snapshots, and results), Editor (can modify drafts and freeze snapshots), and Runner (Editor permissions plus the ability to submit query runs). Database credentials must be handled strictly server-side and never exposed to client applications.
Non-Functional & Scale Requirements
- Usage: 25,000 active workspaces, 200,000 Monthly Active Users (MAU), and up to 5,000 concurrent active editors at peak.
- Run Volume: 500,000 execution requests per day, peaking at 40 runs/second.
- Latency & Reliability: Document edits must propagate to concurrent collaborators in under 250ms (p95). Zero lost edits after client acknowledgement. Guaranteed at-most-once execution side-effects on the warehouse under client retries or network failures.
- Immutability Guarantee: Query parameters, environment settings, and code bound to a specific execution run must be completely unmodifiable once submitted.
Clarifying Questions to Address
- How should concurrent edit conflicts be resolved? Is CRDT/OT required or structured pessimistic/optimistic locking?
- How are unexpected worker failures or lost warehouse connections handled mid-run?
- How are query cancellations managed, and what is the retention model for preview data vs full exports?
Deliverables
- Data Model: Schema design supporting collaborative state, version snapshots, execution runs, and output artifacts.
- Real-time Synchronization Architecture: Protocol and handling logic for editing, presence, and reconnection semantics.
- Run Execution Lifecycle: End-to-end design covering API contracts, queueing, worker scheduling, idempotency, cancellation, and recovery from indeterminate states.
- System Architecture & Key Trade-offs: Architecture diagram, scaling strategies, and detailed evaluation of system trade-offs.
Hints
Hint 1
Decouple the mutable collaboration domain (high write frequency, ephemeral) from the execution domain (immutable records, low write frequency).
Hint 2
Use client-side operation deduplication and a deterministic warehouse-side execution ID (e.g., query query_id/run_id labels) to prevent duplicate runs upon worker recovery.
Hint 3
Leverage consistent hashing or sticky sessions for routing collaboration web sockets to keep document state in-memory before persisting compaction frames.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architectural Approach
A robust collaborative SQL platform must separate mutable, fast-moving collaborative editing from immutable, audit-safe execution lineages.
+-------------------+
| Web Clients |
+---------+---------+
|
+-------------------+-------------------+
| (WebSocket / WSS) | (HTTPS REST)
v v
+-------------------------+ +-------------------------+
| Collaboration Gateway | | Execution API Gateway |
| (Node.js / Go Stateful) | | (Stateless REST) |
+------------+------------+ +------------+------------+
| |
+-----------+-----------+ +-----------+-----------+
| | | |
v v v v
+--------------+ +----------------+ +-----------+ +--------------+
| Redis PubSub | | Primary DB | | SQS/Kafka | | Secrets Manager|
| (Presence) | | (PostgreSQL) | | Queue | | (Credentials)|
+--------------+ +----------------+ +-----+-----+ +--------------+
|
v
+------------------+
| Execution Worker |
| Fleet |
+--------+---------+
|
+----------+----------+
| |
v v
+-------------------+ +-------------------+
| External Data | | Object Storage |
| Warehouse (Snow- | | (S3 / GCS for |
| flake/BigQuery) | | Previews/Exports) |
+-------------------+ +-------------------+
1. Data Model
The data layer separates mutable draft logs, frozen releases, and execution runs into clear operational boundaries.
-- Workspaces & RBAC
CREATE TABLE workspaces (
id UUID PRIMARY KEY,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE workspace_members (
workspace_id UUID REFERENCES workspaces(id),
user_id UUID NOT NULL,
role VARCHAR(32) NOT NULL CHECK (role IN ('VIEWER', 'EDITOR', 'RUNNER')),
PRIMARY KEY (workspace_id, user_id)
);
-- Documents & Real-time Edits
CREATE TABLE sql_documents (
id UUID PRIMARY KEY,
workspace_id UUID REFERENCES workspaces(id),
title VARCHAR(255) NOT NULL,
created_by UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Compaction checkpoints for fast document restoration
CREATE TABLE document_checkpoints (
document_id UUID REFERENCES sql_documents(id),
seq_number BIGINT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (document_id, seq_number)
);
-- Append-only operation log for conflict resolution
CREATE TABLE document_operations (
document_id UUID REFERENCES sql_documents(id),
seq_number BIGINT NOT NULL,
client_id VARCHAR(64) NOT NULL,
client_op_id BIGINT NOT NULL,
op_payload JSONB NOT NULL,
user_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (document_id, seq_number)
);
-- Immutable Frozen Snapshots
CREATE TABLE snapshots (
id UUID PRIMARY KEY,
document_id UUID REFERENCES sql_documents(id),
snapshot_number INT NOT NULL,
sql_text TEXT NOT NULL,
param_schema JSONB NOT NULL, -- e.g. {"date_range": {"type": "DATE", "required": true}}
default_params JSONB NOT NULL,
settings JSONB NOT NULL, -- e.g. {"warehouse_cluster": "MEDIUM_WH", "timeout_sec": 1800}
content_hash VARCHAR(64) NOT NULL, -- SHA-256 over SQL + schema + settings
created_by UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (document_id, snapshot_number)
);
-- Execution Runs
CREATE TABLE execution_runs (
id UUID PRIMARY KEY,
snapshot_id UUID REFERENCES snapshots(id),
requested_by UUID NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
status VARCHAR(32) NOT NULL CHECK (status IN ('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCEL_REQUESTED', 'CANCELLED', 'UNKNOWN')),
submitted_params JSONB NOT NULL,
runtime_settings JSONB NOT NULL,
attempt_count INT NOT NULL DEFAULT 0,
warehouse_job_id VARCHAR(255),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
error_message TEXT,
row_count BIGINT,
UNIQUE (requested_by, idempotency_key)
);
-- Execution Results & Artifact Metadata
CREATE TABLE execution_results (
run_id UUID PRIMARY KEY REFERENCES execution_runs(id),
preview_s3_uri VARCHAR(512) NOT NULL,
export_s3_uri VARCHAR(512) NOT NULL,
result_schema JSONB NOT NULL,
byte_size BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
2. Real-Time Collaboration & Synchronization Engine
Editing Protocol
To handle concurrent text edits across 5,000 active users with low latency, we use a Conflict-free Replicated Data Type (CRDT) (such as Yjs or Automerge) over persistent WebSockets.
-
Routing & Session State:
- WebSockets connect to a cluster of Collaboration Gateway Servers.
- Sockets are sticky per
document_idvia a consistent hash ring on gateway nodes. - When an active editor updates code, delta operations are published to local memory and immediately broadcasted to other clients connected to that document session via Redis Pub/Sub channels.
-
Persistence & Compaction Log:
- Incoming ops are stamped with a monotonic server sequence number
seq_number. - Ops are batch-inserted into
document_operations. - Every 500 operations or every 5 minutes, a background thread compiles the state vector into a snapshot row in
document_checkpoints(content) and truncates older operation logs beyond the compaction point.
- Incoming ops are stamped with a monotonic server sequence number
-
Presence & Cursors:
- Cursor positions, current selection ranges, and active user metadata are sent as ephemeral binary frames over WebSockets.
- Presence is cached exclusively in Redis with a 5-second TTL per active client session and is never written to relational storage.
-
Reconnection Logic:
- Upon network reconnect, the client submits its last acknowledged
seq_numberor CRDT state vector. - If the server's minimum retained
seq_numberis $\le$ client sequence number, the server streams the missing delta operations. - If the gap extends past the current compaction threshold, the server sends the latest full
document_checkpointspayload, after which the client re-applies local unacknowledged changes.
- Upon network reconnect, the client submits its last acknowledged
3. Asynchronous Execution Engine & Lifecycle
Run Execution Flow
Client (Runner) API Gateway Queue (SQS/Kafka) Worker Fleet Warehouse
| | | | |
|-- 1. POST /runs ----->| | | |
| (Params, Key) |-- 2. Lock & Insert ---->| | |
| | (Status=QUEUED) | | |
| |-- 3. Publish Message -->| | |
|<-- 4. 202 Accepted ---| | | |
| | |-- 5. Poll Job ------>| |
| | | |-- 6. Claim Job --->|
| | | | (Set RUNNING) |
| | | |-- 7. Execute SQL ->|
| | | | (Label=run_id) |
| | | |<-- 8. Stream Results|
| | | |-- 9. Store Output -> S3
| | | |-- 10. Finalize ---> DB
Steps in Execution
-
Submission:
- Client submits
POST /api/v1/snapshots/{id}/runswith parameters and a unique client-generatedidempotency_key. - API verifies user's
RUNNERpermission for the workspace and validates inputs againstsnapshots.param_schema. - Database creates an
execution_runsrow withstatus='QUEUED'. If(requested_by, idempotency_key)exists, it returns the existing run object without re-queuing. - Event is pushed to an SQS queue (partitioned by
workspace_idto prevent single-tenant starvation).
- Client submits
-
Processing:
- A worker fetches the message, obtains short-lived database credentials from AWS Secrets Manager/Vault (the client never sees these), and atomically updates the run state:
UPDATE execution_runs SET status = 'RUNNING', attempt_count = attempt_count + 1, started_at = NOW() WHERE id = :run_id AND status = 'QUEUED'; - Worker launches the execution against the data warehouse, attaching a custom query tag:
client_run_id = :run_id.
- A worker fetches the message, obtains short-lived database credentials from AWS Secrets Manager/Vault (the client never sees these), and atomically updates the run state:
-
Handling Failures, Retries, and Idempotency:
- Worker Crash / Network Disconnection: Workers send a periodic heart-beat to Redis (
SET run:lease:<run_id> EX 30). If a heartbeat expires, a Reconciliation Watchdog process searches the data warehouse for queries tagged withclient_run_id = :run_id.- If the warehouse query is still executing, the watchdog re-binds tracking to a new worker.
- If completed, the worker writes the output to S3 and updates status to
SUCCEEDED. - If the query was never received by the warehouse, the status reverts to
QUEUEDfor retry. - If the connection state remains indeterminate, status moves to
UNKNOWN, prompting manual or system-reconciled intervention without blindly executing duplicate queries.
- Worker Crash / Network Disconnection: Workers send a periodic heart-beat to Redis (
-
Cancellation:
- When
POST /api/v1/runs/{id}/cancelis invoked, DB status becomesCANCEL_REQUESTED. - The executing worker observes the cancellation flag (or receives a pub/sub signal), issues a
KILL QUERY <warehouse_job_id>command to the target warehouse, updates status toCANCELLED, and terminates execution.
- When
-
Result Storage and Retention:
- Up to 10,000 rows are parsed into JSON format and saved directly to Amazon S3 as
s3://workbench-artifacts/previews/{run_id}.json. - Full datasets are saved as Parquet/CSV artifacts in
s3://workbench-artifacts/exports/{run_id}.csv.gz. - Lifecycle policies automatically transition preview files to S3 Glacier after 30 days and delete unreferenced raw exports after 90 days.
- Up to 10,000 rows are parsed into JSON format and saved directly to Amazon S3 as
4. Side-by-Side Comparison Engine
Since every execution_runs entry links directly to an immutable snapshot_id, comparing two historical runs (run_id_A vs run_id_B) involves deterministic read operations:
- Code & Setting Delta: Retrieve
sql_text,param_schema, andsettingsfromsnapshotsfor both runs and compute diffs on client or server. - Runtime Delta: Compute exact differences across execution profiles (e.g., duration, row counts, memory/bytes scanned, and submitted runtime params).
- Output Delta: Fetch preview JSON structures from S3 for both runs to display side-by-side data grids highlighting altered values, structural schema changes, or row count variances.
5. Scale & Storage Estimates
- Write Operations (Drafting): 5,000 active users typing at peak generate ~10 keystrokes/second, batched every 50ms = 2,000 messages/second across the Collaboration Gateway. Easily handled by a 4-node cluster using Go/NodeJS.
- Run Submissions: Peak 40 runs/sec is well within standard relational database write capacities (~100–150 Postgres TPS required for metadata logging).
- Result Storage: 500,000 runs/day $\times$ ~2 MB average preview size = ~1 TB/day uncompressed storage. S3 handling with gzip/parquet compression reduces this to ~150–200 GB/day (~6 TB monthly).
6. Key System Trade-offs
| Decision | Selected Design | Alternative Design | Key Trade-off Analysis |
|---|---|---|---|
| Synchronization | CRDT (e.g., Yjs) over WebSockets | Optimistic Locking (Save/Conflict) | CRDT offers seamless real-time multi-user UX and elegant offline editing merges, but increases client memory overhead and gateway architectural complexity compared to HTTP POST locks. |
| Warehouse Interactivity | Asynchronous Queue + Polling/Sockets | Synchronous HTTP Keep-Alive | Async worker architecture handles long queries (up to 45 mins) smoothly across browser disconnects, whereas synchronous connections break under load or network timeouts. |
| Result Traceability | Immutable Snapshots + Cached S3 Previews | Re-running Queries On-Demand | Preserving previews in object storage guarantees reproducible historical auditing regardless of underlying database mutations, at the cost of continuous S3 storage expenditure. |