LIVING SPECIFICATION / MOCK 04

Realtime Collaborative SDLC

Design structured Requirements and Blueprint documents where humans and agents coedit, comment, suggest, publish versions, and survive offline races without losing intent.

30 MINUTES16 INTERVIEWER TURNSFULL Q & AINTERACTIVE LAB

The problem on the whiteboard

Read this once, then begin aloud. Spend the first two minutes establishing contract, actors, risk and what must remain authoritative.

Design LivingSpec, a multi-tenant collaborative editor for structured Requirements and Blueprints. Humans and AI agents edit concurrently; documents contain typed requirement blocks, acceptance criteria, architecture components and references. Users need presence, comments, suggestions, offline edits, version history, approval, diff and a stable published revision for downstream work orders.
Central design thesis

Use convergent draft operations for availability, but make schema-valid publication a server-authoritative transaction. Draft collaboration and approved truth have intentionally different consistency models.

Scope before components

These are supplied mock numbers for sizing and follow-ups. Say your assumptions before using them.

Workspace10,000 organizations · 1M documents · 40M structured blocks
ConcurrencyUp to 150 live editors/agents on one document; 8,000 ops/s global peak
LatencyLocal echo < 30 ms; remote op p95 < 250 ms; reconnect < 5 s for normal docs
HistorySeven years of approved revisions; 90 days granular draft ops
TrustNo lost accepted edit; published revision schema-valid and immutable

Actors

  • Product manager editing requirements
  • Architect maintaining blueprints
  • Reviewer approving or rejecting suggestions
  • AI agent drafting or proposing a patch
  • Commenter and mentioned teammate
  • Org admin or auditor

Functional scope

  • Structured block editing with real-time presence
  • Comments, anchored threads and suggestions
  • Offline operation and agent patch rebasing
  • Immutable published revisions, diff and approval
  • References and validation across documents

Explicitly out

  • Full source-code editor
  • Video calling
  • Arbitrary pixel-perfect pages
  • Autonomous agent publication
  • Cross-organization public documents

A traceable end-to-end path

Name the authoritative state, derived projections, asynchronous boundaries and the exact point where a business decision becomes durable.

Realtime Collaborative SDLC reference architectureSix stage architecture from Client replica through Published truth.Client replicaoptimistic echoRealtime edgeauth + roomsOp logordered per docMaterializersnapshotsValidatorschema + refsPublished truthimmutable revisionaudit · policy · metrics · lineage
01Client replicaoptimistic echo
02Realtime edgeauth + rooms
03Op logordered per doc
04Materializersnapshots
05Validatorschema + refs
06Published truthimmutable revision

Keys that preserve history

The table is logical, not a mandate for one database. Choose physical stores after access patterns, transactions, retention and rebuildability are clear.

EntityPrimary / unique keyImportant fields and purpose
Document(tenant_id, document_id)type, title, draft_epoch, published_revision, acl_epoch
Block(document_id, block_id)kind, parent_id, rank, attributes, tombstone
Operation(document_id, draft_epoch, actor_id, op_seq)client_op_id, causal_clock, payload, received_at
Snapshot(document_id, draft_epoch, snapshot_seq)state_blob_hash, vector_clock, schema_version
Suggestion(document_id, suggestion_id)base_clock, patch, author, state, decision_version
CommentThread(document_id, thread_id)anchor_block, relative_range, context_hash, state
PublishedRevision(document_id, revision)content_hash, approval_set, source_clock, immutable_body
ReferenceEdge(from_revision, from_block, to_document, to_block)edge_type, resolution_state
WS /v1/docs/{id}/sessions

Join with draft epoch, auth token and last vector clock

snapshot + missing ops
POST /v1/docs/{id}/operations

Batch offline ops; clientOpId dedupe

accepted clock / rejected epoch
POST /v1/docs/{id}/suggestions

Patch against base clock with intent summary

201 {suggestionId,rebaseStatus}
POST /v1/suggestions/{id}/decision

Accept/reject with expected decisionVersion

200 / 409
POST /v1/docs/{id}/publish

Expected draft clock + approvals + idempotency key

201 {revision,contentHash}
GET /v1/docs/{id}/diff?from=&to=

Semantic block diff between immutable revisions

200 {changes}

The complete mock interview

Answers are written in a speakable first-person style. Turn on Practice Mode to hide them, answer aloud, then reveal one at a time.

INTERVIEWER

Design the collaborative product.

CANDIDATE

I will separate two user promises. Drafting should feel local-first and converge under concurrent human and agent edits. Publishing should create one immutable, schema-valid revision that downstream systems can trust. So I use a CRDT-like operation model for drafts, server validation plus compare-and-swap for publication, and explicit suggestions for agent work. Before choosing algorithms I would ask whether arbitrary rich text or structured domain blocks dominate.

INTERVIEWER

Clarify scope and semantics.

CANDIDATE

The first release supports typed requirement, acceptance-criterion, component, API and decision blocks; reorder and nesting; inline text; comments; suggestions; presence; offline edits; immutable publication and revision diff. An accepted suggestion is a new operation batch, not a hidden overwrite. Agents cannot publish. Cross-document references may be temporarily unresolved in a draft but must satisfy policy at publish. Presence is ephemeral. I exclude source-code editing, video, public sharing and autonomous approval.

  • Draft guarantee: eventually convergent, with visible conflicts when intent cannot be merged safely.
  • Publish guarantee: one schema-valid immutable content hash.
  • Downstream consumers pin revision numbers, never “latest draft”.
INTERVIEWER

Estimate load and storage.

CANDIDATE

The mock peak is 8,000 operations/s. If a compressed operation averages 350 bytes including metadata, raw ingress is 2.8 MB/s or about 242 GB/day before replication. Keeping every granular operation for seven years would be wasteful, so retain 90 days of ops, compact snapshots, and preserve approved revisions permanently. At 1M documents, an average 40 blocks gives 40M blocks. Hot-room fan-out is the harder problem: 150 participants receiving 20 ops/s means 3,000 deliveries/s for one active document.

8,000 ops/s × 350 B ≈ 2.8 MB/s
Per day ≈ 242 GB raw
Hot room: 20 ops/s × 150 peers = 3,000 deliveries/s
INTERVIEWER

Model the data.

CANDIDATE

Document holds identity, type and current draft epoch. Blocks have stable UUIDs, kind, parent and a fractional rank so moves do not renumber siblings. Operations are append-only and deduped by actor/clientOpId within an epoch. Snapshots record state plus causal clock. Suggestions preserve their base clock and patch. Comments anchor to block ID plus a relative text position and context hash. PublishedRevision stores immutable canonical content, source clock, approvers and content hash. ReferenceEdge is generated from the published revision for impact analysis.

  • Deleting a block creates a tombstone until compaction, preserving concurrent references.
  • Human identity and agent identity are distinct actors with delegation metadata.
  • Published revision is content-addressed and never edited in place.
INTERVIEWER

Why a CRDT, and where would you not use it?

CANDIDATE

A CRDT gives offline availability and convergence without a single low-latency primary for every keystroke. I would use a sequence CRDT inside rich-text fields and stable block IDs with conflict-free order for the tree. But convergence is not semantic validity: two edits can each be valid and jointly violate “unique requirement ID” or create a reference cycle. Therefore draft replicas converge first, a deterministic validator annotates invariant conflicts, and publish rejects unresolved blocking issues. Approval, role changes, suggestion decisions and publication stay serialized transactions.

INTERVIEWER

Walk the architecture.

CANDIDATE

The client applies an operation locally, assigns actor sequence and causal context, persists it in an offline queue, then sends to the nearest realtime edge. The edge authenticates tenant/document permission and ACL epoch, dedupes clientOpId, and appends to a document-partitioned durable log. Room fan-out sends the accepted op immediately. Materializers consume in document order, build snapshots, update search and run incremental schema checks. Presence uses an expiring in-memory channel and is not logged as truth. Publish goes to the owning document transaction service, verifies expected draft clock and approvals, canonicalizes content, validates cross-document policy, writes PublishedRevision and an outbox event atomically.

  • Partition durable operations by document ID.
  • Route a hot document across fan-out nodes while keeping one logical operation order.
  • Derived notifications, search and reference graphs consume the outbox.
INTERVIEWER

Deep dive: structured documents create harder conflicts than text. Solve that.

CANDIDATE

Each operation names a stable block and a typed intent: insert block, move block, set scalar, splice text, add reference, tombstone. Syntactic merge is deterministic. Semantic validators then evaluate unique IDs, allowed parents, required fields, contract compatibility and cycles. Nonblocking violations appear inline. Blocking violations prevent publication. For fields where last-writer-wins would erase intent—such as an API method or data classification—I use a multi-value conflict register that shows both proposals and requires resolution. Schema migrations are versioned transforms over snapshots, tested for determinism and reversible before rollout.

  • Stable identity survives move and rename.
  • Canonical serializer makes equal logical state hash identically.
  • Validation result pins schema and policy bundle versions.
INTERVIEWER

Deep dive: comments and suggestions must survive edits.

CANDIDATE

A comment anchor includes block ID, CRDT-relative start/end positions and a small context hash. Text operations transform the relative positions. If the block is deleted, the thread becomes orphaned but remains visible in document history with surrounding context. A suggestion is not a private fork of the whole document; it is a typed operation patch against a base clock. The server previews the rebased patch. Accept performs a compare-and-swap on suggestion decision version, translates the patch onto current state, reruns validation, and appends the resulting operation batch attributed to the reviewer and original author.

  • Two reviewers cannot both accept the same suggestion.
  • Partially conflicting suggestions require an explicit revised patch.
  • Mentions are derived notifications, not authorization grants.
INTERVIEWER

How do consistency and idempotency work?

CANDIDATE

Draft operation delivery is at least once and eventual; actor sequence plus clientOpId makes replays harmless. The append log gives an accepted operation durable order per document, while replicas may display causally ready ops early. Strong transactions protect ACL changes, publish, approval, suggestion decision and billing. Publish includes expected draft vector/hash and idempotency key; a duplicate returns the same revision. If new operations landed, it returns 409 with the new clock rather than silently publishing a different document.

INTERVIEWER

Failure injection: an agent works offline for 20 minutes while humans restructure the document.

CANDIDATE

The agent returns a patch based on an old clock, never raw “replace document” content. Stable block IDs let the rebaser apply independent edits. Operations against moved blocks follow identity; edits against deleted or type-changed blocks become conflicts. The system produces a preview classified as clean, auto-rebased with warnings, or needs-human-resolution. It does not let a stale agent publish or overwrite. For very old epochs after compaction or schema migration, the agent must retrieve the current snapshot and regenerate its proposal, while its original response remains auditable.

INTERVIEWER

What about hot rooms and reconnect storms?

CANDIDATE

Realtime edges maintain room membership, but durable ops stay in the partitioned log. Fan-out uses coalesced operation frames and bounded per-client buffers; a slow client receives a catch-up cursor rather than unbounded memory. During reconnect, clients send last clock and pending client IDs. The server returns a compact snapshot plus only missing ops. Add jitter, admission control and a per-tenant reconnect budget. Presence degrades first. Editing remains locally available; publication may be briefly unavailable if the owning transaction shard is recovering.

  • Snapshot every N ops or bytes, tuned by replay budget.
  • Hot-doc detection adds fan-out replicas but does not split document truth.
  • Backpressure tells clients to batch cursor/presence noise.
INTERVIEWER

Failure injection: two humans approve while an agent changes a required block.

CANDIDATE

Approval is bound to a content hash and policy bundle, not a floating document. The agent edit advances the draft clock and invalidates approvals whose policy says the changed block matters. The first publish transaction checks expected content hash and approval set; it either publishes exactly that reviewed state or returns stale. The second publish with the same idempotency key returns the existing revision; a different key receives a conflict. The UI shows “approval expired by blocks X and Y” so users understand why.

INTERVIEWER

Security and tenant isolation?

CANDIDATE

Authorization is enforced on session join, every reconnect, publish, export and notification. ACL epochs fence long-lived sockets; permission changes force re-auth. Document and operation keys include tenant ID, and storage/search partitions carry tenant labels. Agent tokens are scoped to tenant, project, document, action and expiry; delegated identity records the human or service that invoked them. Encrypt approved revisions with tenant keys, sanitize rich content, scan uploads, and treat agent-authored links/instructions as untrusted. Audit reads of sensitive documents, approval, export and permission changes.

  • A WebSocket is not permanently authorized because it was valid at connect time.
  • Mention does not grant access.
  • Cross-document reference resolution cannot reveal a forbidden title.
INTERVIEWER

How do you observe and evaluate it?

CANDIDATE

Measure local-to-ack and accepted-to-peer latency, op-log lag, reconnect duration, snapshot replay bytes, dedupe rate, validation latency, publish conflicts, lost-anchor rate and hot-room buffer drops. Correctness uses deterministic convergence tests: shuffle, duplicate and delay operations across replicas and assert identical canonical hash. Fuzz tree moves, deletes and schema migrations. Product quality includes suggestion acceptance, manual-conflict rate, time from draft to approval and approval invalidation frequency. Audit jobs verify every published hash can be reconstructed.

  • SLO: no acknowledged operation lost.
  • Invariant dashboard: duplicate requirement IDs and dangling published references target zero.
  • Canary schema migrations on cloned snapshots.
INTERVIEWER

Rollout, trade-offs and traps?

CANDIDATE

Ship single-user structured editing and immutable versions first, then multi-user online collaboration, then offline, comments, suggestions and agents. Run a shadow canonicalizer before trusting hash reconstruction. CRDT complexity is justified by offline and concurrency needs; if those disappear, a simpler server-ordered OT design may win. Traps are using last-write-wins for meaningful fields, treating presence as durable, anchoring comments only by character offsets, allowing agents to replace documents, and binding approvals to “latest.”

INTERVIEWER

Give me your spoken recap.

CANDIDATE

LivingSpec keeps a highly available convergent draft and a strongly controlled published truth. Clients optimistically apply typed CRDT operations; a document-partitioned log durably orders accepted ops, materializers snapshot and validate them, and ephemeral presence stays outside truth. Stable block IDs preserve moves, comments use relative anchors, and agents submit reviewable patches against base clocks. Publication validates schema, references, approvals and expected content in one transaction, producing an immutable hash. Epoch fencing, dedupe, convergence fuzzing and gradual rollout make human-plus-agent collaboration trustworthy.

Two places to earn the strong hire

These mechanisms are the interview’s differentiators. Be able to redraw each from memory and defend its failure behavior.

01

Deep dive A · Two consistency planes

Draft collaboration optimizes availability and convergence. Publication optimizes reviewability, invariants and stable downstream references.

  1. Optimistic local draft operations
  2. Durable per-document op order
  3. Incremental semantic validation
  4. Content-bound approvals
  5. Serializable immutable publish
02

Deep dive B · Durable anchors

Identity and relative positions survive routine editing; explicit orphan states preserve context when their target disappears.

  1. Stable UUID for every block
  2. CRDT-relative text positions
  3. Context hash for recovery
  4. Orphaned thread history
  5. Suggestion patch rebased as typed intent

Revise, do not hand-wave

When the interviewer injects a fault, restate the violated assumption, change state or protocol, and name the new invariant.

InjectionRecovery mechanismTempting wrong answer
01Duplicate/offline opsactor sequence + clientOpId dedupeDouble insert
02Slow clientBound buffer; send catch-up cursorRoom memory blow-up
03Hot documentScale fan-out; preserve one logical op orderSplit brain
04Stale agent patchRebase preview or explicit conflictWhole-doc overwrite
05Approval raceBind approval to content hash; serializable publishUnreviewed content ships
06ACL revokedEpoch-fence socket and cachesStale connection reads

Calculate before you provision

Use orders of magnitude to expose the bottleneck. State what this simple model omits.

Collaboration storage lab

Tune mock peak operation rate, size and granular retention. The result is a deliberately conservative peak-sustained bound; approved revisions are separate.

Peak-sustained raw operation volumeChange an input to recalculate.
Ops
Snapshots
Published
Indexes

Prove quality in production

A system is incomplete without observable user outcomes, staged deployment, rollback and an answer to “how will we know?”

Scoreboard

  • Operation ack and peer latency
  • Acknowledged-op loss (target zero)
  • Convergence hash mismatch
  • Reconnect bytes and duration
  • Publish conflict/validation rate
  • Comment anchor orphan rate

Rollout ladder

  1. 01Single-user blocks + versioning
  2. 02Online coediting
  3. 03Snapshots and reconnect
  4. 04Comments + stable anchors
  5. 05Suggestions + agent patches
  6. 06Offline mode and org-scale hardening

Corrections worth memorizing

Use these as flash cards. The right column is the compact sentence you want available under pressure.

TrapBetter move
CRDT = semantic correctnessValidate domain invariants separately.
Character-offset commentsUse stable block + relative text anchors.
Approval of “latest”Bind it to immutable content hash.
Agent replaces whole docRequire typed patch with base clock.
Presence in the audit logKeep it ephemeral and expiring.
Socket authorized foreverFence sessions with ACL epochs.

Vocabulary without fog

Define the term, then connect it to a concrete invariant in this design. Avoid dropping vocabulary as a substitute for reasoning.

CRDT
Data type whose concurrent operations converge without central conflict resolution.
Causal clock
Metadata describing which operations an edit has observed.
Tombstone
Deletion marker retained long enough for concurrent references to converge.
Canonicalization
Deterministic serialization so equal logical content has the same hash.
Materializer
Consumer that turns an operation log into queryable current state.
Optimistic concurrency
Mutation succeeds only when the caller’s expected version is current.
Relative anchor
Position tied to collaborative text identity rather than fragile integer offset.
Outbox
Rows written with a transaction and later delivered as reliable events.

Close with a decision, not a component list

LivingSpec keeps a highly available convergent draft and a strongly controlled published truth. Clients optimistically apply typed CRDT operations; a document-partitioned log durably orders accepted ops, materializers snapshot and validate them, and ephemeral presence stays outside truth. Stable block IDs preserve moves, comments use relative anchors, and agents submit reviewable patches against base clocks. Publication validates schema, references, approvals and expected content in one transaction, producing an immutable hash. Epoch fencing, dedupe, convergence fuzzing and gradual rollout make human-plus-agent collaboration trustworthy.

Rehearse again