Architecting a Public and Token-Shared Prompt Library
System DesignModel answerLast updated
Design a scalable prompt-sharing platform supporting public, private, and secret-link access with instant token revocation and high-throughput read caching.
Create the technical architecture for a web application where creators can manage, store, and distribute AI prompts. The platform must accommodate public discovery, strict private ownership, and secure, revokable token-based sharing.
Core Requirements
- Content Management: Users can create, view, modify, and soft-delete prompts.
- Access Control: Prompts can be marked as
Public(globally indexed) orPrivate(restricted to owner). - Link Sharing: Private items can be shared using randomly generated secret URLs. Anyone with a valid link can view the prompt.
- Forking: Registered users can duplicate any accessible prompt (public or shared link) into their own personal space.
System Performance & SLA Constraints
- High read-to-write ratio (~100:1).
- Near-instant (sub-second) revocation when a shared link is disabled by the owner.
- Search queries over public prompts must be fast and responsive, never exposing private or newly-revoked items.
- The platform must handle traffic spikes when individual prompts go viral.
Deliverables
- Scale & Capacity Estimation: Rough estimates for bandwidth, storage, and throughput.
- Data Model: Storage paradigm selection, schema details, and authorization design.
- API Interfaces: Primary endpoints for prompt lifecycle, sharing, and search.
- Architecture & Caching Strategy: System flow, multi-layer caching, and instantaneous access revocation.
- Hot-Key Mitigation: Engineering solutions for handling viral public content.
Hints
Hint 1
Decouple prompt identity from access tokens so link revocation doesn't modify prompt IDs.
Hint 2
Distinguish public content caching rules (CDN-friendly) from link-shared content caching rules (never cache at CDN layer).
Hint 3
Hash secret share tokens before storing them in the database to prevent token leakage.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture & Engineering Approach
A robust solution for a prompt-sharing platform requires balancing aggressive caching for viral public content with strict, zero-trust authorization checks and sub-second revocation for shared links.
1. Scale & Capacity Estimation
Assuming a system with 10 million registered accounts and 1 million Daily Active Users (DAU):
- Volume: 50 million total prompts.
- Data Size: Average prompt payload is ~4 KB (text + system parameters). Max payload limit is 100 KB.
- Base Storage: $50\text{M} \times 4\text{ KB} = 200\text{ GB}$.
- Including 5 historical revisions per prompt: $\sim 1\text{ TB}$ total content payload storage.
- Traffic Profile:
- Read-to-Write Ratio: 100:1.
- Average Read Throughput: 20,000 QPS.
- Average Write Throughput: 200 QPS.
- Peak Viral Read Load: 100,000+ QPS on a single hot prompt.
- SLAs:
- Link Revocation: Access denied within <1 second globally.
- Search Visibility Lag: Newly made public prompts searchable within <5 seconds.
2. Data Model & Storage Paradigm
We utilize a hybrid data layer: PostgreSQL for relational metadata, ACLs, and transaction integrity, alongside S3-compatible Object Storage for storing large immutable prompt version payloads.
+-------------------------------------------------------+
| users |
+-------------------------------------------------------+
| id (UUID, PK) |
| handle (VARCHAR, UNIQUE) |
| email (VARCHAR, UNIQUE) |
| created_at (TIMESTAMP) |
+-------------------------------------------------------+
+-------------------------------------------------------+
| prompts |
+-------------------------------------------------------+
| id (UUID, PK) |
| owner_id (UUID, FK -> users.id) |
| title (VARCHAR) |
| description (TEXT) |
| visibility (ENUM: 'public', 'private') |
| active_version_id (UUID) |
| forked_from_version_id (UUID, NULL) |
| fork_count (BIGINT, DEFAULT 0) |
| view_count (BIGINT, DEFAULT 0) |
| created_at (TIMESTAMP) |
| updated_at (TIMESTAMP) |
| deleted_at (TIMESTAMP, NULL) |
+-------------------------------------------------------+
Indexes:
- (owner_id, updated_at)
- (visibility, updated_at) WHERE deleted_at IS NULL
+-------------------------------------------------------+
| prompt_versions |
+-------------------------------------------------------+
| id (UUID, PK) |
| prompt_id (UUID, FK -> prompts.id) |
| version_number (INT) |
| content_hash (VARCHAR) -- SHA-256 for dedup |
| payload_location (VARCHAR) -- S3 URI or inline text |
| created_at (TIMESTAMP) |
+-------------------------------------------------------+
Indexes:
- UNIQUE(prompt_id, version_number)
+-------------------------------------------------------+
| share_links |
+-------------------------------------------------------+
| id (UUID, PK) |
| prompt_id (UUID, FK -> prompts.id) |
| token_hash (VARCHAR(64), UNIQUE) -- SHA-256 of token |
| allow_fork (BOOLEAN, DEFAULT TRUE) |
| expires_at (TIMESTAMP, NULL) |
| revoked_at (TIMESTAMP, NULL) |
| created_at (TIMESTAMP) |
+-------------------------------------------------------+
Indexes:
- (token_hash)
- (prompt_id)
+-------------------------------------------------------+
| prompt_tags |
+-------------------------------------------------------+
| prompt_id (UUID, FK -> prompts.id) |
| tag (VARCHAR) |
+-------------------------------------------------------+
Indexes:
- PK (prompt_id, tag)
- (tag)
Key Data Modeling Decisions:
- Opaque Identifiers: All prompt IDs use ULIDs or UUIDv4 to prevent ID enumeration.
- Hashed Tokens: Raw shared-link secret tokens are never stored in plain text. Store only
SHA-256(raw_token)in the database. If the database leaks, existing secret share links are not compromised. - Payload Optimization: Prompt payloads $\le 8\text{ KB}$ can sit inline within
prompt_versions. Larger payloads are written to Object Storage (S3) using content-addressable hashes (s3://prompts-bucket/{content_hash}). This keeps PostgreSQL table rows lean and memory-dense. - Copy-on-Write Forking: Forking duplicates references to the existing
content_hashwithout physically copying large text blobs.
3. API Specification
POST /api/v1/prompts
Request: { title: str, description: str, body: str, visibility: "public"|"private", tags: string[] }
Response: 201 Created { id: UUID, active_version_id: UUID }
GET /api/v1/prompts/{id}
Headers: Authorization: Bearer <JWT> (Optional)
Response: 200 OK { id, title, body, visibility, owner_handle, ... }
PATCH /api/v1/prompts/{id}
Headers: If-Match: <version_etag>
Request: { title?, body?, visibility?, tags? }
Response: 200 OK
DELETE /api/v1/prompts/{id}
Response: 204 No Content
POST /api/v1/prompts/{id}/shares
Request: { expires_in_seconds?: int, allow_fork?: bool }
Response: 201 Created { share_url: "https://promptlib.io/s/{raw_token}", expires_at: timestamp }
DELETE /api/v1/prompts/{id}/shares/{share_id}
Response: 204 No Content
GET /api/v1/s/{raw_token}
Response: 200 OK { prompt_id, title, body, owner_handle, allow_fork }
POST /api/v1/prompts/{id}/fork
Request: { share_token?: str }
Response: 201 Created { new_prompt_id: UUID }
GET /api/v1/search
Params: q=text&tags=tag1,tag2&limit=20&cursor=string
Response: 200 OK { items: [...], next_cursor: string }
4. System Architecture & Caching Strategy
+--------------------+
| Edge CDN / WAF |
+---------+----------+
|
v
+--------------------+
| API Gateway |
+---------+----------+
|
+------------------------+------------------------+
| |
v v
+--------------------+ +--------------------+
| Prompt Service | | Search Service |
+--+--------------+--+ +---------+----------+
| | |
| +---------------+ |
v v v
+---------------+ +---------------+ +------------------+
| Redis Cluster | | Primary DB | | Search Engine |
| (Cache/Token) | | (PostgreSQL) | | (OpenSearch) |
+---------------+ +-------+-------+ +------------------+
|
v
+---------------+
| CDC / Kafka |
+---------------+
Dual Caching Strategy for Security & Scale
-
Public Prompts Layer:
- Cache at the Edge CDN.
- Header:
Cache-Control: public, max-age=60, stale-while-revalidate=300. - CDN absorbs massive surges for viral public prompts.
-
Secret Share Links Layer:
- Never cache secret-link responses at the CDN level (
Cache-Control: no-store, private). - The token authorization resolution path uses Redis Key-Value storage at the application layer:
- Redis Key:
token_cache:{SHA256(token)}-> Values:{ prompt_id, status: active|revoked, allow_fork, expires_at }. - Key TTL: 30 seconds (short-lived safety window).
- Redis Key:
- Never cache secret-link responses at the CDN level (
Instant Revocation Strategy
When a user revokes a share link:
- PostgreSQL updates
revoked_at = NOW()inside an explicit transaction. - The application service issuing the update executes a synchronous eviction of
token_cache:{SHA256(token)}in Redis. - An invalidation message is broadcast via Redis Pub/Sub to clear any local in-memory LRU caches across running API instances.
- Subsequent requests with the token hit Redis (or fall back to SQL), observe
revoked_at IS NOT NULL, and return404 Not Foundor410 Gonein < 50 milliseconds.
Search Engine Ingestion
- Database updates emit Transaction Log Change Data Capture (CDC via Debezium/Kafka).
- An asynchronous indexing worker reads CDC logs and pushes public documents to OpenSearch.
- If visibility flips from
publictoprivate, or a record is soft-deleted, the pipeline immediately issues a delete document command to the OpenSearch index. - Search API gateways perform a fast secondary check against the Redis metadata cache prior to returning search results to guarantee private content is never returned during indexing lag.
5. Managing High Load and Viral Prompts
When a prompt goes viral (e.g., featured on social media, generating >100,000 QPS):
Single Flight Gatekeeper
Request 1 --------+
Request 2 --------| +------------------+ +------------------+
Request 3 --------+------> | Single-Flight | -----> | Database Fetch |
... | | Mutex Aggregator | | (Executes Once) |
Request 1000 ------+ +------------------+ +------------------+
-
Request Coalescing (Single-Flight Pattern):
- When a cache key expires under heavy load, thousands of concurrent requests might simultaneously hit the database (Thundering Herd Problem).
- We implement in-memory single-flight locking (e.g., Go's
singleflightpackage or Redis lock locks per key). Only one upstream database fetch is dispatched; all other concurrent requests wait for the result of that single execution.
-
Multi-Tiered Local Cache (L1 Application In-Memory):
- Add a fast, memory-bounded L1 LRU cache (e.g., Ristretto/Guava) directly inside API nodes.
- Hot keys are stored locally for 2–5 seconds, short-circuiting Redis lookups entirely during massive traffic spikes.
-
Asynchronous Metrics Aggregation:
view_countandfork_countincrements are never written directly to PostgreSQL synchronously per request.- Counters are pushed to Kafka or incremented via
HINCRBYin Redis, then periodically flushed to PostgreSQL in background batch jobs (e.g., every 60 seconds).
Summary Matrix of Access Behaviors
| Access Type | Public Discovery | CDN Caching | Redis Strategy | Target Latency |
|---|---|---|---|---|
| Public | Indexed in Search | Allowed (s-maxage=60) | 1-Hour Cache | < 20 ms |
| Private | Hidden | Disabled (no-store) | Authorizer check only | < 30 ms |
| Shared Link | Hidden | Disabled (no-store) | 30s TTL + Sync Evict | < 30 ms (Revocation < 50ms) |
| Fork Request | Supported | Disabled | Invalidates owner stats | < 100 ms |