Build a Multi-User Prompt Editor with Versioning and Execution
System DesignModel answerLast updated
Design a system where teams edit prompts collaboratively, snapshot immutable versions, run them against LLMs, and trace results back to exact inputs.
You're building a platform where teams craft and test LLM prompts together. Multiple users work on a shared draft, create frozen snapshots, send those snapshots to a language model, and review outputs while preserving full traceability to the configuration that produced them.
Requirements
Collaborative editing: Several authenticated project members may edit the same prompt draft at once. The system must handle concurrent modifications and client reconnections without data loss or silent overwrites.
Immutable versions: Users snapshot the draft into numbered versions. A version captures prompt text, any template variables, model settings, and tool definitions. Once created, a version never changes.
Execution: A user selects a version, supplies input variables, and submits a run. The system calls the LLM provider, stores the response, and links it permanently to the version and inputs that produced it.
Traceability: Anyone inspecting a result must see exactly which version, input values, model name, temperature, and other settings were used—even if the draft or project configuration has since changed.
Scope and Assumptions
- Users belong to a project and are already authenticated; focus on the editor, version, and execution subsystems.
- You may choose any collaboration strategy (operational transforms, CRDTs, last-write-wins with conflict detection, etc.)—justify your choice.
- Model calls are expensive, slow (multi-second), and may time out or return errors; treat them as asynchronous external requests.
- A lost client connection or retry must not create duplicate runs or lose in-flight results.
What to Address
- Data model: Define the draft, version, and run entities and their relationships.
- Concurrent editing: Explain your conflict resolution approach and when users see each other's changes.
- Version immutability: How do you prevent accidental mutation of a version already referenced by past runs?
- Asynchronous execution: Describe the lifecycle of a run request, from submission through provider call to result storage, including retries and failures.
- Access control: Who can edit, create versions, execute runs, or view results?
- Scalability sketch: Identify bottlenecks and suggest how you'd scale collaboration traffic separately from execution.
Provide a high-level architecture, justify key trade-offs, and call out common pitfalls.
Hints
Hint 1
Separate the hot collaboration path from the cold execution and storage path—real-time edits shouldn't block model calls.
Hint 2
Assign each run a unique idempotency key so retries don't spawn duplicate requests or charge twice.
Hint 3
Store the full version snapshot with every run record; never rely on a mutable draft or configuration reference.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
This system splits into three layers: a collaboration service for real-time draft editing, a version store for immutable snapshots, and an execution engine that calls LLM providers and records results. The key insight is to keep fast, frequent draft updates separate from slow, expensive model invocations, and to bind every result to a complete, frozen configuration.
Data Model
Project: A workspace containing drafts, versions, and runs. Members have roles (editor, viewer, admin).
Draft: The live, mutable working copy. Fields:
project_id,content(prompt text),template_vars(JSON schema for inputs),model_config(model name, temperature, max tokens, tools),updated_at,updated_by.
Version: An immutable snapshot. Fields:
version_id(UUID),project_id,version_number(auto-increment per project),content,template_vars,model_config,created_at,created_by.- Stored as a frozen JSON blob or normalized table; either way, it never changes after creation.
Run: A single execution. Fields:
run_id(UUID),version_id,input_values(JSON),model_config_snapshot(denormalized copy from version),status(pending, running, succeeded, failed, canceled),output,error,tokens_used,latency_ms,created_at,completed_at,idempotency_key.
Rationale: Denormalizing the configuration into the run record ensures traceability even if the version or project is deleted. The idempotency key prevents duplicate submissions.
Concurrent Editing
Strategy: Operational Transformation (OT) or CRDT for character-level merging if real-time co-editing is required; optimistic locking with conflict detection if users save periodically.
For a prompt playground, optimistic locking is often sufficient:
- Client fetches draft with
version(timestamp or integer). - User edits locally.
- On save, client sends
{ content, previous_version }. - Server checks current
updated_atagainstprevious_version. If they match, apply the update and increment version. If not, return HTTP 409 Conflict with the current draft; client merges or overwrites.
Presence and cursors: Broadcast lightweight cursor positions and active users via WebSocket or SSE, but don't persist them. They're ephemeral UI state, not document data.
Reconnection: Client re-fetches the latest draft on reconnect. If local unsaved changes exist, diff and prompt the user to merge or discard.
Trade-off: OT/CRDT gives seamless Google-Docs-style merging but adds complexity. Optimistic locking is simpler, fits prompt editing (less frequent saves than prose), and surfaces conflicts explicitly—acceptable when edits are coarse-grained.
Version Immutability
When a user clicks "Create Version," the server:
- Copies
draft.content,template_vars, andmodel_configinto a newVersionrow. - Assigns
version_number = MAX(version_number) + 1for that project. - Returns
version_idand number.
Enforcement: The Version table has no UPDATE path. Application code only INSERTs. Database constraints (immutable columns, append-only audit log) provide defense in depth.
Why it matters: If a version's prompt could change after a run completes, result comparisons become meaningless. Immutability guarantees that run.version_id = 42 always references the same text and settings.
Asynchronous Execution
Submission
- User selects version, fills template variables (if any), and submits.
- API generates
run_idandidempotency_key = hash(project_id, version_id, input_values, user_id, timestamp)(or client provides a UUID). - Server checks for an existing run with that key. If found, return it (idempotent).
- Otherwise, insert
Runwithstatus = pending, enqueue a job{ run_id, version_id, input_values, model_config }to a task queue (SQS, Redis, RabbitMQ), and returnrun_idimmediately.
Execution Worker
- Dequeue job, update
status = running. - Call LLM provider API (OpenAI, Anthropic, Vertex, etc.) with prompt rendered from
version.content+input_values, passingmodel_config. - On success: store
output,tokens_used,latency_ms, setstatus = succeeded. - On error: store
errormessage, setstatus = failed. - On timeout or provider 503: retry with exponential backoff (up to 3 attempts), then mark
failedif exhausted. - Publish result via WebSocket or polling endpoint so UI updates.
Idempotency and Retries
- If client retries the submission (network blip), the idempotency key ensures no duplicate run or double charge.
- If the worker crashes mid-execution, the job reappears in the queue (visibility timeout). The worker checks
Run.status; if alreadysucceededorfailed, skip. Otherwise, retry the provider call. - Provider-side idempotency (if supported) adds another layer: pass
run_idas the provider's idempotency token.
Result Delivery
- Client polls
GET /runs/{run_id}or subscribes via WebSocket. - When status transitions to terminal (
succeeded,failed,canceled), UI displays output or error.
Trade-off: Async execution decouples UI responsiveness from model latency. The cost is complexity in job queuing, retry logic, and status tracking.
Access Control
Project roles:
- Viewer: read draft, versions, runs.
- Editor: all viewer permissions, plus edit draft, create versions, submit runs.
- Admin: all editor permissions, plus manage members, delete project.
Credential isolation: Model API keys are stored at the project or organization level, encrypted at rest, and never exposed to clients. Workers fetch them from a secret store (AWS Secrets Manager, Vault) per run.
Run visibility: All project members see all runs by default. For sensitive workloads, add a created_by filter or run-level ACLs.
Architecture Sketch
┌─────────────┐ WebSocket/HTTP ┌──────────────────┐
│ Browser │ ←─────────────────────────→ │ Collaboration │
│ (React) │ draft edits, presence │ Service (Node) │
└─────────────┘ └──────────────────┘
↓
┌──────────────────┐
│ PostgreSQL │
│ (drafts, │
│ versions) │
└──────────────────┘
┌─────────────┐ REST: submit run ┌──────────────────┐
│ Browser │ ──────────────────────────→ │ API Server │
└─────────────┘ │ (Python/Go) │
↑ └──────────────────┘
│ ↓
│ enqueue job
│ ↓
│ ┌──────────────────┐
│ │ Task Queue │
│ │ (Redis/SQS) │
│ └──────────────────┘
│ ↓
│ ┌──────────────────┐
│ │ Execution │
│ │ Workers (pool) │
│ └──────────────────┘
│ ↓
│ LLM Provider API
│ ↓
└──────────── result notification ───────────┘
(WebSocket or polling)
Separation of concerns:
- Collaboration service handles high-frequency, low-latency draft updates; horizontally scalable stateless nodes with sticky sessions or shared state in Redis.
- Execution workers are isolated, auto-scale based on queue depth, and hold provider credentials.
Scalability and Bottlenecks
Collaboration: If thousands of users edit simultaneously, shard drafts by project_id and use Redis pub/sub for presence. For very large documents, switch to a CRDT library (Yjs, Automerge).
Execution: Model calls are the bottleneck. Rate-limit submissions per user/project, queue jobs, and scale worker pool. Cache results for identical (version_id, input_values) if deterministic.
Storage: Runs accumulate quickly. Partition Run table by created_at, archive old runs to S3/GCS, and keep recent runs in hot storage.
Cost: Each run costs API tokens. Enforce quotas, show token estimates before submission, and alert on anomalies.
Common Pitfalls
- Losing provenance: Storing only a
version_idreference in the run; if the version is deleted or migrations alter the schema, results become orphaned. Mitigation: Denormalize the full config into each run. - Race conditions on version creation: Two users click "Create Version" simultaneously, both get number 5. Mitigation: Use database-generated sequence or SELECT FOR UPDATE.
- Duplicate runs on retry: User clicks "Run" twice, gets charged twice. Mitigation: Idempotency keys.
- Silent edit conflicts: Last write wins without notification; one user's work is lost. Mitigation: Optimistic locking with explicit conflict UI.
- Stale credentials: API key rotates, all runs fail. Mitigation: Centralized secret management, periodic validation, clear error messages.
Summary
This design separates collaboration (frequent, cheap) from execution (infrequent, expensive), uses immutable versions to preserve history, and binds every result to its complete input and configuration. Optimistic locking balances simplicity and conflict awareness, while async execution with idempotency handles retries and provider flakiness gracefully. The architecture scales horizontally and keeps credentials isolated from client code.