Design a Collaborative LLM Prompt Workbench with Live Streaming
System DesignModel answerLast updated
Design a multi-tenant web tool where teams author prompts, run them on external LLMs with streamed output, version and compare results, and track cost, latency, and safety.
You are asked to design an LLM prompt workbench: a web product where developers and prompt engineers compose prompts, pick model parameters, execute them against hosted language models, and watch the output arrive token by token. Teams save prompt revisions, put outputs side by side, share work with colleagues, and examine the cost, latency, and safety outcome of each execution.
This is an open-ended design discussion. Work through it as you would in a real session: clarify requirements, estimate scale, draw a high-level architecture, then dive into the hardest areas. Write down every assumption you make.
Scale assumptions
Use these figures unless you explicitly state others:
- 100,000 monthly active users
- 1 million prompt executions per day
- A portion of executions stream tokens to the browser live
- Users are grouped into workspaces or organizations (multi-tenant)
- Prompts and outputs may contain sensitive data
Third-party model providers are a network dependency. Every call costs money per token, latency varies, requests may be throttled or fail temporarily, and the provider may decline to answer.
What to cover
- Requirements and user flows. Functional and non-functional requirements tied to this product, an explicit out-of-scope list, and the end-to-end journey: write, run, stream, save a version, compare, review history.
- APIs and data model. Core entities and an API surface. Make runs reproducible and decide where large or sensitive bodies are stored.
- High-level architecture. Components and the request path, with one clear structural decision at the center.
- Execution, streaming, retries, cancellation. The run lifecycle, how tokens reach the browser, which failures you retry, how you avoid double charges, and how a cancel actually stops spend.
- Versioning, collaboration, history. How edits become versions, how comments and sharing work, and how history is stored and queried at 1M runs/day.
- Security, privacy, abuse. Tenant isolation, encryption, secrets, rate limits versus spend quotas, retention and deletion, abuse detection.
- Observability, cost, tradeoffs. What you measure, how authoritative cost is computed and stored, and the main tradeoffs you are choosing.
Good clarifying questions to raise: read/write mix, average output length and streaming share, internal vs external models and fallbacks, time-to-first-token target, what happens to a run if the browser disconnects, strictness of isolation and retention, and whether live co-editing is in scope.
Hints
Hint 1
Convert the numbers first: 1M runs/day is about 12 runs/s on average, maybe 50 to 100/s at peak. With runs lasting 10 to 30 seconds, that implies thousands of concurrent streams. Use these figures to size the streaming tier and the provider rate budget.
Hint 2
Split the system into an authoring/collaboration plane (CRUD, versions, comments, history) and an execution plane (queue, workers, model gateway, streaming). Make the execution side survive a closed browser tab by writing tokens to a stream buffer that clients can reattach to.
Hint 3
For cost, think about three things together: an idempotency key on run creation, cancellation that aborts the upstream provider request, and token cost computed at run time with the price snapshot stored on the run record rather than recomputed from current prices later.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions and sizing
- 1M runs/day is roughly 12 runs/s average; assume a 5 to 8x peak, so about 60 to 100 runs/s.
- Average run lasts about 15 s, and 60% stream. Peak concurrent streams are roughly 100 x 15 x 0.6, so about 1,000 to 2,000 (provision for 5k).
- Average run: 1.5k input tokens and 600 output tokens. Prompt plus output is about 10 KB, so about 10 GB/day of bodies, or 3.5 TB/year. That belongs in object storage, not in the primary database.
- Provider spend is the real risk: 1M runs at even $0.01 each is $10k/day, so quotas and idempotency matter as much as uptime.
Requirements
Functional: edit prompts with variables, choose model and parameters, run, stream, cancel, save immutable versions, compare runs side by side, comment and share, browse history, view usage and cost.
Non-functional: low time-to-first-token (added overhead under 300 ms), in-flight runs survive browser disconnects, strict tenant isolation, bounded spend, and an authoritative audit trail.
Out of scope: fine-tuning, payments and invoicing, cursor-level co-editing, and building our own models.
Data model
workspace,membership(role),prompt(id, workspace_id, head_version_id)prompt_version: immutable, holding template, model, and params.run:version_id, effective config snapshot, variable values, status, tokens in/out,cost_usd, price snapshot, latency fields, refusal flag,idempotency_key,body_ref.run_outputand large prompt bodies: object storage, encrypted, referenced by key.comment(separate from versions),quota,audit_event.
Storage split: metadata is small, queried by workspace, prompt, and time, so it goes in a relational database (Postgres, partitioned by month). Bodies are large and read by ID, so they go in object storage. Reproducibility means pinning the version and snapshotting the effective config and inputs. Note that at temperature > 0 outputs are not deterministic; "rerun" is not "replay".
API sketch
POST /prompts,POST /prompts/{id}/versionsPOST /runs(requiresIdempotency-Key) returnsrun_idGET /runs/{id}/stream(SSE withLast-Event-IDresume)POST /runs/{id}/cancelGET /runs?prompt_id=&cursor=,POST /compare,GET /usage
Architecture
The central decision is separating the authoring plane (low-volume CRUD, strongly consistent) from the execution plane (bursty, long-lived, cost-bearing). They scale, fail, and degrade independently.
Flow: client, then API gateway (auth, workspace resolution, rate limit), then run orchestrator (validates, checks quota, writes run as queued, enqueues), then a queue partitioned by workspace for fairness, then workers, then the model gateway, then providers.
The model gateway owns provider SDKs, keys, request format translation, retries, per-provider concurrency limits, circuit breakers, fallback models, and token accounting. Everything else stays provider-agnostic.
A separate streaming tier terminates SSE/WebSocket connections. Workers publish token chunks to a per-run stream (Redis Streams or similar, short TTL) with sequence numbers, and the streaming tier fans out to clients. This decouples the run from the browser.
Run lifecycle
queued → running → succeeded | failed | canceled
- The client calls
POST /runswith an idempotency key. A unique constraint on(workspace_id, key)makes retries return the same run, which prevents double charging. - A worker claims the run with a lease and heartbeats. If it dies, the run is requeued only if no tokens were emitted, or marked failed with a partial output otherwise (never silently re-bill).
- Tokens are appended to the stream buffer. On completion the worker writes the full body to object storage and finalizes the DB row in one transition.
- If the browser drops, the run continues. The client reconnects with
Last-Event-IDand replays from the buffer, or reads the final result.
Retries: retry timeouts, 429 (with Retry-After and jitter), and 5xx, with a capped count and total deadline. Do not retry validation errors, context-length errors, or content refusals. A refusal is a valid terminal result recorded as such. Fall back to a secondary model only if the user allows it, and record it on the run.
Cancellation: POST /cancel sets a cancel_requested flag and publishes to a per-run control channel. The worker subscribes, and on receipt aborts the upstream HTTP request (closing the connection), which is what stops provider generation and billing. Race: the final transition is a compare-and-set on status. If completion wins, cancel is a no-op returning succeeded. If cancel wins, we record tokens consumed so far and bill only those.
Versioning and collaboration
Editing a draft is last-write-wins with autosave. "Save version" creates an immutable prompt_version and moves the head pointer. Comments attach to a version and never mutate it. For v1 I would not build OT/CRDT: the usage pattern is mostly one author at a time with review by others, so drafts with version history and a soft "someone else is editing" indicator suffice. Revisit if live multiplayer becomes core.
History at scale: 1M rows/day is about 365M/year. Partition by month, index on (workspace_id, created_at), retain hot data for 90 days, and archive or drop per workspace policy. Run dashboards and usage aggregations come from a read replica or an OLAP store (ClickHouse or a warehouse) fed by an event stream, not from the primary.
Security and abuse
workspace_idcomes from the authenticated session, never the request body, and is applied on every query (optionally enforced by row-level security). Roles: viewer, editor, admin.- TLS in transit, encryption at rest, optionally per-workspace keys (KMS) for enterprise tenants.
- Provider keys live only in the gateway's secret manager. Logs and traces store IDs, sizes, and hashes, never prompt or output text.
- Rate limits (token bucket per user and workspace at the gateway) protect the system. Spend quotas (daily or monthly dollar and token budgets, reserved at enqueue using estimated max cost and reconciled afterward) protect the budget. They are different controls at different layers.
- Configurable retention, hard-delete jobs that purge object storage and metadata, and audit events for access.
- Abuse detection: anomaly alerts on spend spikes, many new accounts from one source, and input and output moderation hooks.
Observability and cost
- Metrics: queue wait, time-to-first-token, tokens/s, end-to-end latency (p50/p95/p99), error, refusal, timeout, and cancel rates, and cost per workspace, model, and provider. One trace ID spans gateway, queue, worker, and provider call.
- Authoritative cost is computed when the run finishes, from actual provider-reported usage times the price at that time, and stored on the run with the price snapshot. Recomputing from a current price constant at read time is a trap, because price changes rewrite history and break invoices and audits.
Tradeoffs
- Async queue vs synchronous call: adds a hop (tens of ms) but gives durability, fairness, backpressure, and survival of disconnects.
- Storage split: more moving parts, but cheap, scalable bodies and a lean, fast metadata DB.
- Output caching: only for identical, deterministic (
temperature = 0) requests within a workspace, because cross-tenant caching risks leaks and caching stochastic outputs misleads users. - Graceful degradation: under provider trouble, shed lowest-priority runs, show queue position, switch to fallback models, and keep authoring and history fully available since they are on a separate plane.
Common mistakes
- Streaming directly from the worker to the browser, so a dropped tab kills the run.
- Retrying refusals or non-idempotent creates, double-billing users.
- Cancel that only closes the browser stream while the provider keeps generating.
- Trusting a client-supplied workspace ID.
- Logging raw prompts.