REST API Specification for Hosted Documents
Medium · Software Engineering Fundamentals · Backend Engineer · Onsite
Prompt
Architect a production-ready HTTP API that allows client applications to create, retrieve, modify, and remove hosted text documents (for instance, Markdown operational runbooks inside a shared team workspace).
Treat this as an asynchronous backend design prompt where no live interviewer is available to answer clarifying questions mid-response. Begin by stating concrete product and system assumptions—covering payload format and size limits, multi-tenant access permissions, revision history and trash recovery, concurrent editing behavior across teammates, and whether external developer integrations consume the service alongside a first-party web client—and then specify the complete wire contract and production safeguards.
Scope & Expectations
- Explicit boundary assumptions: Upfront decisions on document representation, maximum inline payload size, tenant role hierarchy, historical snapshots, deletion recovery, concurrency semantics, and target API consumers.
- Resource schema and HTTP contract: Clear separation between caller-editable attributes and server-managed metadata, paired with versioned collection and item routes, request/response JSON shapes, partial-update semantics, and structured error status codes.
- Concurrency and retry safety: Mechanisms that prevent silent lost updates when two writers save against the same baseline revision and prevent duplicate creations when clients retry timed-out requests.
- Operational readiness: Scalable list pagination without row drift, tenant-safe authorization responses, soft-delete lifecycle management, rate limiting, and non-breaking API evolution.
Step-by-step walkthrough
Lock down scope with explicit assumptions
In an asynchronous API design exercise with no live Q&A, state concrete product assumptions up front—each choice directly shapes the wire contract:
- Payload format and size cap: A UTF-8
titleplus Markdowncontentup to1 MB, sent inline as JSON. Binary attachments (diagrams, PDFs) live under a separate/filesupload service, and multi-hundred-megabyte payloads are addressed in the follow-ups. - Tenancy and permissions: Every document belongs to a workspace. Workspace members hold one of three roles:
viewer(read only),editor(create, update, soft-delete), oradmin(also restore from trash and permanently purge). - Revision history and trash recovery: Every accepted edit writes an immutable historical snapshot. Deleting a document moves it to a 30-day trash (soft delete) so accidental removals can be undone before permanent purge.
- Concurrent editing model: Multiple teammates edit asynchronously rather than keystroke-by-keystroke in real time, so the server must reject saves built on outdated revisions instead of silently overwriting earlier work.
- API consumers: Both the first-party web application and external developer integrations (such as CI pipelines syncing runbooks from Git), requiring versioned URLs, scoped bearer tokens, rate limits, and structured error payloads.
- Payload format and size cap: A UTF-8
Define the document resource and storage schema
Draw a strict line between caller-editable attributes (
title,content) and system-managed metadata (id,workspace_id,version,size_bytes, timestamps, actor IDs,deleted_at). If a write payload supplies a system-managed or unknown key, reject it with400 Bad Requestso client bugs surface immediately instead of failing silently.{ "id": "doc_4d91e7a2c0b5", "workspace_id": "ws_904", "title": "Incident Response Playbook", "content": "# Incident Response\nPage the on-call engineer...", "version": 4, "size_bytes": 2410, "created_by": "usr_14", "created_at": "2026-11-18T09:15:00Z", "updated_by": "usr_29", "updated_at": "2026-11-25T14:22:08Z" }Four resource design choices prevent common production headaches:
- Opaque prefixed random IDs (
doc_4d91e7a2c0b5): Sequential integers (1, 2, 3) leak total document volume to outsiders and invite enumeration bugs when authorization checks slip; prefixes (doc_,ws_,usr_) make logs self-describing. - Omit
contentfrom collection list responses: Listing 50 runbooks should return lightweight metadata (~5 KB total), never up to 50 MB of Markdown bodies. Clients fetch fullcontentonly on single-item reads. - Monotonic integer
version: Starts at1on creation and increments by1on every accepted update, doubling as the HTTP ETag (entity tag—a revision identifier carried in HTTP headers). - UTC RFC 3339 timestamps (
YYYY-MM-DDTHH:MM:SSZexternally, persisted at microsecond precision internally).
In PostgreSQL, store live state in
documentsand append an immutable row todocument_versionsinside the same database transaction on every create or update:CREATE TABLE documents ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1, created_by TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_by TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL, deleted_at TIMESTAMPTZ -- NULL while active; timestamp when moved to trash ); -- Partial index accelerates listing active workspace documents in newest-edited order. CREATE INDEX documents_active_list_idx ON documents (workspace_id, updated_at DESC, id DESC) WHERE deleted_at IS NULL; CREATE TABLE document_versions ( document_id TEXT NOT NULL REFERENCES documents(id), version INTEGER NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, author_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (document_id, version) );- Opaque prefixed random IDs (
Specify REST routes, partial updates, and error codes
Scope collection creation and listing under
/v1/workspaces/{ws_id}/documents, while exposing single-resource routes at/v1/documents/{doc_id}becausedoc_idis globally unique:Method Path Purpose Success Status ------ -------------------------------------- -------------------------- ------------------------- POST /v1/workspaces/{ws_id}/documents Create document 201 Created + Location + ETag GET /v1/workspaces/{ws_id}/documents List metadata (no content) 200 OK GET /v1/documents/{doc_id} Read full document 200 OK + ETag (or 304) PATCH /v1/documents/{doc_id} Partial update 200 OK + new ETag DELETE /v1/documents/{doc_id} Move to 30-day trash 204 No Content POST /v1/documents/{doc_id}/restore Restore from trash 200 OK + ETag GET /v1/documents/{doc_id}/versions List revision snapshots 200 OK (paginated) GET /v1/documents/{doc_id}/versions/{ver} Read historical snapshot 200 OKUse JSON Merge Patch (
Content-Type: application/merge-patch+json, RFC 7396) onPATCH: omitted fields stay untouched and supplied fields replace existing values, so renaming a title sends ~45 bytes instead of re-uploading a 1 MB Markdown body (passing{"title": null}returns422becausetitleis non-nullable):POST /v1/workspaces/ws_904/documents Content-Type: application/json Idempotency-Key: 9c4e2a17-3b80-4f19-8d61-5e2a70c1b408 {"title": "Incident Response Playbook", "content": "# Incident Response\nPage the on-call engineer..."} --> 201 Created, Location: /v1/documents/doc_4d91e7a2c0b5, ETag: "1" PATCH /v1/documents/doc_4d91e7a2c0b5 Content-Type: application/merge-patch+json If-Match: "4" {"title": "Incident Response Playbook (Q4)"} --> 200 OK, ETag: "5"Return standard HTTP status codes paired with a single structured error schema (Problem Details, RFC 9457,
application/problem+json) so client SDKs need only one error parser:400 Bad Request(invalid JSON or unknown/server-managed field),401 Unauthorized(missing/expired token),403 Forbidden(insufficient role),404 Not Found(missing, trashed, or unauthorized workspace).409 Conflict(duplicateIdempotency-Keystill executing),412 Precondition Failed(outdatedIf-Matchversion),413 Content Too Large(> 1 MB),415 Unsupported Media Type,422 Unprocessable Content(empty title or reusedIdempotency-Keywith different payload),428 Precondition Required(missingIf-Match),429 Too Many Requests(withRetry-After).
{ "type": "https://api.example.com/errors/version-conflict", "title": "Document was modified by another writer", "status": 412, "detail": "Expected version 4 from If-Match header, but current version is 5.", "current_version": 5 }Prevent lost updates with ETags and optimistic concurrency
Suppose Maya and Priya both open revision
4of"Incident Response Playbook". Maya saves an updated pager escalation phone number; five seconds later Priya saves a new postmortem checklist. Without concurrency control, Priya's write overwrites Maya's update silently—a lost update.Solve this with optimistic concurrency control (letting readers work without locks and verifying at write time that nobody changed the revision they started from) using standard HTTP
ETagandIf-Matchheaders:Maya Document Service (v4) Priya |--- GET /documents/doc_4d ------->| | |<-- 200 OK, ETag: "4" ------------| | | |<--- GET /documents/doc_4d ----------| | |---- 200 OK, ETag: "4" ------------->| |--- PATCH (If-Match: "4") ------->| | |<-- 200 OK, ETag: "5" (v4 -> v5) -| | | |<--- PATCH (If-Match: "4") ----------| | |---- 412 Precondition Failed (v5) -->|Require
If-Matchon everyPATCHandDELETE(returning428 Precondition Requiredif omitted). Crucially, never checkversionin Python/Node memory and then issue an unconditionalUPDATE—a concurrent request can slip into the gap betweenSELECTandUPDATE. Execute the check and increment as a single atomic compare-and-set SQL statement:UPDATE documents SET title = $title, content = $content, version = version + 1, updated_by = $actor_id, updated_at = now() WHERE id = $doc_id AND version = $expected_version AND deleted_at IS NULL; -- 1 row updated -> insert version snapshot into document_versions in same tx, commit, return 200. -- 0 rows updated -> re-read row: missing or trashed -> 404; higher version exists -> 412.class VersionConflictError(Exception): """Raised when If-Match does not match the stored document version.""" def apply_patch_if_match(store: dict, doc_id: str, expected_version: int, patch: dict) -> int: """Model atomic compare-and-set update on a document's integer version.""" doc = store[doc_id] if doc["version"] != expected_version: raise VersionConflictError(f"expected v{expected_version}, found v{doc['version']}") doc.update(patch) doc["version"] += 1 return doc["version"] docs = {"doc_4d": {"title": "Incident Response Playbook", "version": 4}} print(apply_patch_if_match(docs, "doc_4d", 4, {"title": "Maya escalation fix"})) # 5 try: apply_patch_if_match(docs, "doc_4d", 4, {"title": "Priya outdated edit"}) except VersionConflictError as exc: print("412 Precondition Failed:", exc)Make network retries safe with idempotency keys
When a client sends
POST /v1/workspaces/ws_904/documentsand the network connection drops before the response arrives, the caller cannot tell whether the server persisted the row before the drop. Retrying a barePOSTcreates duplicate runbooks.Accept a caller-generated UUID in an
Idempotency-Keyheader onPOST(and optionallyPATCH) and store(caller_id, idempotency_key)with a 24-hour TTL:- Claim the key first: Insert
(caller_id, key, request_sha256, state='in_progress', expires_at)under aUNIQUE (caller_id, key)constraint and commit immediately. - Execute and record: Create the document and update the idempotency row to
state='done'with the serialized201status and response body in one transaction. - Handle retries deterministically:
- Same key + same body hash +
done-> replay the exact stored201 Createdanddoc_idwithout creating a second row. - Same key + different body hash ->
422 Unprocessable Content(catches accidental key reuse across unrelated calls). - Same key + still
in_progress(within a 60-second lease) ->409 Conflicttelling the caller the original attempt is still running.
- Same key + same body hash +
Make
DELETE /v1/documents/{doc_id}withIf-Match: "4"equally safe to retry: soft-deleting setsdeleted_atwithout incrementingversion. If the network drops the204response and the client retriesDELETEwithIf-Match: "4", the server sees the row is already in the trash atversion = 4and returns204again; whereas if Priya had edited the live runbook toversion = 5before Maya clicked Delete with outdatedIf-Match: "4",4 != 5returns412 Precondition Failedso Maya does not trash Priya's unseen edits.- Claim the key first: Insert
Paginate document lists with keyset cursors
GET /v1/workspaces/ws_904/documents?limit=2&cursor=...lists active documents ordered by(updated_at DESC, id DESC)(limitdefaults to50, capped at200).Avoid
?page=2&offset=50(offset pagination):OFFSET 100000forces PostgreSQL to scan and discard 100,000 index entries, and any concurrent edit or deletion shifts row offsets so clients skip or duplicate items. Instead, use keyset (cursor) pagination, encoding the last returned row's(updated_at, id)at full microsecond precision (rounding the cursor down to whole seconds would skip sibling rows edited later inside that same second!):Active rows in ws_904 (sorted by updated_at DESC, id DESC): Row 1: updated_at = 14:22:08.619402Z, id = doc_9 <-- Page 1 (limit=2) Row 2: updated_at = 14:22:08.619402Z, id = doc_5 <-- Page 1 ends here -> cursor = (14:22:08.619402Z, doc_5) Row 3: updated_at = 14:22:08.619402Z, id = doc_2 <-- Page 2 starts here! Same microsecond, but "doc_2" < "doc_5" Row 4: updated_at = 14:20:00.000000Z, id = doc_8In SQL, tuple comparison
(updated_at, id) < ($cursor_ts, $cursor_id)means "eitherupdated_at < $cursor_ts, orupdated_at = $cursor_tsandid < $cursor_id"—seeking directly intodocuments_active_list_idxinO(log N)time. Fetchlimit + 1rows; if rowlimit + 1exists, trim it and returnnext_cursorfrom rowlimit, otherwise returnnext_cursor: null:SELECT id, title, version, size_bytes, updated_by, updated_at FROM documents WHERE workspace_id = $ws_id AND deleted_at IS NULL AND (updated_at, id) < ($cursor_updated_at, $cursor_id) ORDER BY updated_at DESC, id DESC LIMIT 51;import base64 import json def encode_cursor(updated_at_us: str, doc_id: str) -> str: """Base64url-encode (updated_at, id) into an opaque URL-safe cursor token.""" payload = json.dumps({"u": updated_at_us, "id": doc_id}, separators=(",", ":")).encode("utf-8") return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") def decode_cursor(token: str) -> tuple[str, str]: """Decode an opaque cursor token back into (updated_at, id).""" padding = "=" * (-len(token) % 4) data = json.loads(base64.urlsafe_b64decode(token + padding)) return data["u"], data["id"] sample_cursor = encode_cursor("2026-11-25T14:22:08.619402Z", "doc_4d91e7") print(sample_cursor) print(decode_cursor(sample_cursor))Enforce authorization, soft deletion, rate limits, and API evolution
Finish the production contract with access control, lifecycle rules, abuse protection, and non-breaking evolution:
- Two-layer authorization (
404vs403): Authenticate callers via session cookies (first-party web) or scoped OAuth / API bearer tokens (documents:read,documents:write), then check workspace membership inside the SQLWHEREclause before pagination. Return404 Not Found(never403) when the caller does not belong to the document's workspace so outsiders cannot probe whether an ID exists; return403 Forbiddenonly when an authorizedviewerattempts a write (PATCH/DELETE). - Soft delete, restore, and purge:
DELETEsetsdeleted_at = now(), hiding the document from normal reads/lists while keeping it visible under?state=trashedso editors canPOST /v1/documents/{doc_id}/restorewithin 30 days. A nightly background job hard-deletes rows whosedeleted_at < now() - interval '30 days', and a dedicated admin/compliance endpoint supports immediate hard erasure for privacy requests. - Per-token rate limits and payload guards: Enforce
413above1 MBbodies,422on empty or> 200-char titles, and per-token rate limits (e.g.,120 requests/minreturning429 Too Many Requests+Retry-After) so one runaway script never starves other tenants. - URL path versioning (
/v1): Make only backward-compatible additive changes inside/v1(new optional response fields, new routes). Ship breaking schema changes under/v2alongside/v1, advertising deprecation timelines via standard HTTPSunsetheaders (RFC 8594).
Production HTTP API Checklist ----------------------------- Resource: caller edits {title, content}; server manages {id, workspace_id, version, timestamps} Concurrency: ETag + required If-Match -> atomic SQL WHERE version = $expected (428 / 412) Retries: Idempotency-Key on POST (201 replay, 409 in-flight, 422 payload mismatch) Pagination: base64url keyset cursor on microsecond (updated_at DESC, id DESC), no content in lists Security: token scopes + workspace RBAC in SQL WHERE; 404 across workspaces, 403 for viewer writes Lifecycle: 30-day soft-delete trash + /restore + background purge; /v1 path + Problem Details errors- Two-layer authorization (
Intuition & how it works
Think of a hosted document service like a shared engineering reference library where every binder has a revision number stamped on its spine (v1, v2, ...). Anyone with a team badge can skim a lightweight card catalog without photocopying every 50-page runbook; to file an updated edition, you must declare which revision you started from so you never accidentally paste over a teammate's newer fix; and when dispatching a brand-new binder over an unreliable courier, you attach a unique receipt ID so resending the courier never creates duplicate binders.
A textbook four-route CRUD (Create, Read, Update, Delete) API without these safeguards breaks immediately under production traffic. Retrying a timed-out POST creates duplicate runbooks, two engineers saving the same page silently overwrite each other's edits ("last write wins"), ?page=50 offset queries slow down and skip rows whenever items change, and returning full Markdown bodies inside list responses saturates network bandwidth.
Trace three operations on "Incident Response Playbook" inside workspace ws_904 to see how the contract works end to end:
1. Idempotent create: A client sends POST /v1/workspaces/ws_904/documents with Idempotency-Key: 9c4e... (a caller-generated unique token that lets the server replay a prior response safely on retry). The server persists doc_4d91e7a2c0b5 at version = 1 and returns 201 Created with ETag: "1" (an ETag is an HTTP header tagging the exact revision of a resource).
2. Accepted concurrent edit: Later at revision 4, Maya and Priya both GET the runbook (ETag: "4"). Maya sends PATCH with If-Match: "4" (telling the server "apply this change only if the stored revision is still 4"); PostgreSQL executes an atomic UPDATE ... WHERE id = ... AND version = 4, advances version to 5, writes an immutable row to document_versions, and returns 200 OK with ETag: "5".
3. Prevented lost update: Moments later, Priya sends PATCH with her outdated If-Match: "4". Zero rows match version = 4, so the server returns 412 Precondition Failed with "current_version": 5, prompting Priya's client to fetch revision 5 and merge cleanly instead of wiping out Maya's escalation fix.
Key points
- Strict attribute ownership: Callers write only
titleandcontent; the server manages opaque prefixed IDs (doc_...),workspace_id, integerversion, audit timestamps, anddeleted_at, rejecting writes to server-managed keys with400. Collection list endpoints omitcontentto keep responses compact. - RESTful routes and partial updates: Pair
/v1/workspaces/{ws_id}/documents(POST,GET) with/v1/documents/{doc_id}(GET,PATCH,DELETE,POST .../restore,GET .../versions). Use JSON Merge Patch (an HTTPPATCHformat where only modified fields are transmitted) and Problem Details (RFC 9457, a uniform JSON error envelope across all status codes). - Optimistic concurrency control: Expose integer
versionasETag, requireIf-MatchonPATCHandDELETE(428when omitted,412when outdated), and enforceWHERE id = $id AND version = $expectedatomically inside SQL. - Safe network retries: Support
Idempotency-KeyonPOST(201replay when complete,409while still executing,422if reused with a different request payload) and makeDELETEidempotent across network retries at the matching version. - Keyset cursor pagination: Page workspace collections using an opaque base64url keyset cursor (a token encoding the last row's microsecond
updated_atand tie-breakerid) soWHERE (updated_at, id) < (...)seeks into a B-tree index inO(log N)time without offset drift. - Defense-in-depth authorization & lifecycle: Enforce token scopes plus workspace role-based access control (
viewer,editor,admin) inside SQL queries, return404across workspace boundaries to prevent ID probing, use soft delete (deleted_attimestamp with 30-day restore before background purge), and ship breaking changes under/v2with HTTPSunsetheaders.
Common mistakes
- Putting RPC verbs in URL paths (
/createDocument,/deleteDocument) or returning200 OKwith{"success": false}instead of meaningful HTTP status codes (201,204,400,404,412,422,429). - Allowing "last write wins" without
If-Match, checkingversionin application memory withSELECTfollowed by an unconditionalUPDATE(which still loses updates under concurrent writes), or relying on wall-clockupdated_atinstead of an integerversion(two edits inside one clock tick collide). - Retrying timed-out
POSTrequests without anIdempotency-Key, creating duplicate documents whenever responses drop in transit. - Using
OFFSETpagination on mutable collections, omitting a maximumlimit, returning fullcontentinside list endpoints, or truncating cursor timestamps to whole seconds (which skips sibling documents updated in the same second). - Returning
403 Forbiddenfor document IDs belonging to another tenant's workspace (confirming that the secret ID exists), or filtering permissions in application code afterLIMIT 50(producing underfilled or empty pages). - Implementing soft delete (
deleted_at) inDELETEwhile forgettingWHERE deleted_at IS NULLin search, revision-history, or update queries.
Follow-up questions
- What architectural changes are needed when multiple authors type into the same page simultaneously in real time? Whole-document
PATCHwithIf-Matchfails with412on nearly every keystroke when multiple authors type simultaneously, so live editing moves onto a persistent per-document WebSocket session exchanging fine-grained character or block deltas while REST remains responsible for creation, listing, permissions, and historical snapshots. Concurrent edits merge automatically via CRDTs (Conflict-Free Replicated Data Types—structures like Yjs that mathematically converge to identical state regardless of arrival order) or Operational Transformation (OT) (server-sequenced index adjustments), while carrying ephemeral cursor presence alongside edits. Periodically (every few seconds or N operations), a background worker compacts the operation log into a new immutabledocument_versionssnapshot, and the WebSocket re-validates workspace membership on token refresh or role revocation so removed users disconnect immediately. - How should the upload and download flow evolve for multi-hundred-megabyte payloads that exceed single-request limits? Decouple metadata from blob bytes and use multipart presigned uploads directly to object storage (such as S3 or GCS) so multi-hundred-megabyte payloads never buffer in API server RAM. A client calls
POST /v1/documents/{id}/uploadsto obtain anupload_idand short-lived presigned part URLs, streams chunks (>= 5 MiBper part except the final chunk in S3) in parallel straight to object storage—retrying only failed chunks on network glitches—and finalizes viaPOST /v1/documents/{id}/uploads/{upload_id}/completewith part checksums, full-payload SHA-256, andIf-Match. The backend verifies checksums, atomically swaps the blob pointer while incrementingversion, and serves reads viaGET /v1/documents/{id}/contentsupporting HTTPRangerequests (206 Partial Content) or short-lived presigned download URLs. - How can an offline-capable client pull incremental updates since its previous checkpoint without missing deletions or out-of-order commits? Polling
?updated_after=<timestamp>silently drops updates because server clocks skew, slower database transactions can commit after transactions stamped with newer wall-clock times, and purged or trashed rows leave no trace. Instead, maintain a per-workspace monotonically increasing sequence number (change_seq) advanced inside every create, update, soft-delete, or restore transaction, appending tombstones (lightweight"op": "delete"entries) alongside upserts in aworkspace_changeslog table. Clients requestGET /v1/workspaces/{ws_id}/changes?since_seq=1042&limit=200to read ordered events plusnext_since_seq, and if a client stays offline past the log retention window (e.g., 30 days), the server returns410 Gonesignaling a clean full resync. - Where does HTTP or server-side caching make sense across these routes, and how do you prevent stale or leaked responses? On single-item reads (
GET /v1/documents/{id}), returnETag: "4"withCache-Control: private, no-cacheso browsers store the body locally, still contact the API on every read to verify workspace authorization, and receive a lightweight304 Not Modifiedwith an empty body whenever the revision matches—needing zero active cache invalidation. Historical revisions (GET /v1/documents/{id}/versions/{ver}) are immutable, makingCache-Control: private, max-age=31536000, immutablesafe (privateblocks shared CDN caches from leaking tenant content). Server-side, cache hot bodies in Redis under versioned keysdoc:{id}:v{version}after fetching(workspace_id, version, deleted_at)from PostgreSQL's narrow index: because each versioned key never mutates, race-condition cache corruption is impossible and superseded revisions age out naturally via LRU eviction, whereas rapidly changing workspace list endpoints skip caching and rely on partial B-tree indexes.
Follow-up questions
- What architectural changes are needed when multiple authors type into the same page simultaneously in real time?
- How should the upload and download flow evolve for multi-hundred-megabyte payloads that exceed single-request limits?
- How can an offline-capable client pull incremental updates since its previous checkpoint without missing deletions or out-of-order commits?
- Where does HTTP or server-side caching make sense across these routes, and how do you prevent stale or leaked responses?
Similar questions
- Translating a Static Mockup into an Accessible Card Component
- Evaluating and Deploying Database Indexes on High-Volume Tables
- Real-Time Collaborative Editor with Git Sync
- Senior Backend Manager Screen: Career Arc, Stack Flexibility, and Startup Fit
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target