Design a Structured Learning Content Service
System DesignModel answerLast updated
Design a data model, API, reordering mechanism, and publishing/caching strategy for a fixed 3-tier learning content management system.
Problem Context
You are tasked with designing the core backend service for an enterprise learning platform. Content is organized in a fixed 3-level hierarchy:
- Course Track (e.g., "Senior Sales Executive Training")
- Learning Module (e.g., "Negotiation Strategies")
- Lesson (e.g., "Handling Price Resistance")
Learners consume published content frequently through web and mobile clients, while curriculum managers continuously create, edit, reorder, move, and publish updates.
Core Requirements
Functional Requirements
- Hierarchy Read Capabilities: Clients must be able to load a complete course track with all child modules and lessons in a single call, or retrieve individual items with parent context (breadcrumbs).
- Content Operations: Support creating, updating, archiving, and reordering items (e.g., repositioning a lesson within its module or moving a lesson to another module entirely).
- Deterministic Ordering: Items within a parent container must maintain consistent, explicit ordering despite simultaneous edits.
- Publishing & Caching Workflow: Content creators work on draft states. Publishing must be atomic—learners should only see fully published releases, and updates must invalidate caches instantly.
Non-Functional Requirements
- Low Read Latency: Read requests for published track structures must return within p95 < 30 ms.
- Data Integrity: Operations like item moves and structural reordering must be transactional—no item can be lost, duplicated, or orphaned mid-operation.
- Fixed Depth: The hierarchy is strictly 3 tiers deep. General tree traversal routines for arbitrary depths are unnecessary.
Scale & Traffic Profile
- Volume: 1,000 active tracks, 10,000 modules, 100,000 lessons.
- Learner Traffic: 50,000 daily active users, producing 500 read requests/sec at peak.
- Authoring Activity: ~50 content managers performing ~1,000 draft modifications/day (99.9% read-heavy workload).
System Design Deliverables
- Data Schema: A relational data model showing tables, primary/foreign keys, indexing, and position ordering fields.
- REST API Specifications: Resource endpoints for structure retrieval, content mutation, and item repositioning.
- Ordering & Concurrency Strategy: A scalable method for dynamic reordering without expensive index shifts or race conditions.
- Publishing & Cache Lifecycle: A snapshot and cache invalidation architecture ensuring zero partial reads for end users.
Hints
Hint 1
Exploit the fixed 3-tier depth—you do not need graph algorithms, closure tables, or arbitrary tree recursion.
Hint 2
For item reordering, consider fractional indexing (lexicographical string keys) to avoid shifting all sibling positions on every edit.
Hint 3
Decouple authoring (drafts) from reader traffic (published state) via snapshot-based versioning to guarantee zero partial-state reads.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture & System Design Strategy
When designing a hierarchical content platform with a fixed depth, the primary design principles are simplicity and isolation between reader and author workloads. With 100,000 total lessons and 500 RPS peak, the workload is overwhelmingly read-heavy and relatively modest in absolute data volume.
1. Data Model & Schema Design
Because the domain strictly enforces a 3-tier hierarchy (Tracks $\rightarrow$ Modules $\rightarrow$ Lessons), standard third-normal-form (3NF) tables with single parent foreign keys are simple, robust, and performant.
PostgreSQL Relational Schema
CREATE TABLE tracks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
draft_revision BIGINT NOT NULL DEFAULT 1,
published_version BIGINT DEFAULT NULL,
archived_at TIMESTAMPTZ DEFAULT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE modules (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
track_id UUID NOT NULL REFERENCES tracks(id) ON DELETE RESTRICT,
position TEXT NOT NULL COLLATE "C",
title TEXT NOT NULL,
archived_at TIMESTAMPTZ DEFAULT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_module_position UNIQUE (track_id, position)
);
CREATE TABLE lessons (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
module_id UUID NOT NULL REFERENCES modules(id) ON DELETE RESTRICT,
position TEXT NOT NULL COLLATE "C",
title TEXT NOT NULL,
draft_body_key TEXT, -- Pointer to Object Store (S3) or draft rich text
archived_at TIMESTAMPTZ DEFAULT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_lesson_position UNIQUE (module_id, position)
);
-- Immutable Snapshots for Publishing
CREATE TABLE track_versions (
track_id UUID NOT NULL REFERENCES tracks(id),
version BIGINT NOT NULL,
published_tree JSONB NOT NULL, -- Pre-assembled tree structure
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_by UUID NOT NULL,
PRIMARY KEY (track_id, version)
);
CREATE TABLE lesson_versions (
lesson_id UUID NOT NULL REFERENCES lessons(id),
version BIGINT NOT NULL,
body_content TEXT NOT NULL,
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (lesson_id, version)
);
Key Schema Decisions
- Single Foreign Key Parentage: Direct child-to-parent pointers (
lessons.module_id,modules.track_id) prevent structural corruption. An item cannot accidentally belong to multiple parents. - Fractional Indexing Keys (
position TEXT NOT NULL COLLATE "C"): Position values are stored as lexicographically sortable strings. Utilizing PostgreSQL's byte-value collation (COLLATE "C") ensures exact binary string ordering across database drivers. - Composite Unique Constraints: Constraints on
(track_id, position)and(module_id, position)act as a fail-safe against concurrent order collisions. - Draft vs. Published Decoupling: Live operational tables reflect draft edits. The
track_versionstable stores immutable, fully assembledJSONBtrees representing exact published snapshots.
2. Dynamic Ordering Strategy (Fractional Indexing)
The Anti-Pattern: Integer Positions
Using integer positions (1, 2, 3...) requires an $O(N)$ update operation to shift all higher siblings whenever an item is inserted or moved. Under concurrent edits, integer updates create massive lock contention and risk duplicate index ranks.
The Solution: Lexicographical String Keys
By assigning string positions, a new key can always be generated between any two existing string keys without modifying sibling records.
Initial state:
Lesson A: "a0"
Lesson B: "a1"
Insert Lesson C between A and B:
Lesson C: "a0V" (Since "a0" < "a0V" < "a1")
- Single-Row Mutation: Inserting or reordering requires updating exactly one row.
- Server-Calculated Placement: The client sends intent (
after_id,before_id), and the application server computes the mid-point string using a standard mid-string generation library (e.g., base-62 lexicographical bisect). - Rebalancing: If repeated insertions at the same spot cause string lengths to grow excessively (e.g., > 100 characters), a background task rebalances string ranks evenly across siblings for that container.
3. REST API Specification
Reader Endpoints (Learners)
Learners interact strictly with published releases.
GET /v1/tracks/{trackId}
Description: Fetch published structure tree (modules + lessons metadata).
Headers:
If-None-Match: "v3"
Response (200 OK):
{
"trackId": "c39e...",
"version": 3,
"title": "Senior Sales Executive Training",
"modules": [
{
"moduleId": "m1",
"title": "Negotiation Strategies",
"lessons": [
{ "lessonId": "l1", "title": "Handling Price Resistance" }
]
}
]
}
GET /v1/lessons/{lessonId}
Description: Fetch published lesson body content along with breadcrumbs.
Response (200 OK):
{
"lessonId": "l1",
"version": 3,
"title": "Handling Price Resistance",
"body": "...",
"breadcrumbs": {
"track": { "id": "c39e...", "title": "Senior Sales Executive Training" },
"module": { "id": "m1", "title": "Negotiation Strategies" }
}
}
Authoring & Reordering Endpoints (Curriculum Managers)
GET /v1/tracks/{trackId}/draft
Description: Retrieve complete draft hierarchy (editor mode).
POST /v1/lessons/{lessonId}/move
Headers:
If-Match: "rev_42" # Optimistic concurrency check on draft_revision
Request Payload:
{
"targetModuleId": "m2",
"afterLessonId": "l5",
"beforeLessonId": "l6"
}
Response (200 OK):
{ "status": "moved", "newPosition": "a0V", "draftRevision": 43 }
POST /v1/tracks/{trackId}/publish
Description: Atomically capture draft snapshot, create new track version, and update point pointer.
Response (200 OK):
{ "publishedVersion": 4, "publishedAt": "2026-03-30T10:00:00Z" }
4. Transactional Edits & Concurrency Control
To prevent race conditions when two managers reorder items simultaneously, structural changes use optimistic lock verification tied to explicit row-level locks on parent containers.
Transaction: Moving a Lesson Across Modules
BEGIN;
-- 1. Lock the parent track to serialize concurrent structural modifications for this curriculum
SELECT draft_revision FROM tracks WHERE id = :track_id FOR UPDATE;
-- 2. Verify Optimistic Lock Header (If-Match)
-- If current draft_revision != expected_revision, ROLLBACK and return HTTP 412 Precondition Failed.
-- 3. Retrieve sibling position strings to calculate the intermediate string position
SELECT position FROM lessons
WHERE id IN (:after_id, :before_id) AND module_id = :target_module_id;
-- (Application logic generates :new_position)
-- 4. Update item location in a single atomic SQL statement
UPDATE lessons
SET module_id = :target_module_id,
position = :new_position,
updated_at = NOW()
WHERE id = :lesson_id;
-- 5. Increment draft revision counter
UPDATE tracks
SET draft_revision = draft_revision + 1
WHERE id = :track_id;
COMMIT;
If two transactions attempt cross-track modifications, resources must be locked in a deterministic order (e.g., sorting UUIDs lexicographically prior to SELECT FOR UPDATE) to avoid database deadlocks.
5. Publishing Architecture & Caching Strategy
Because reader latency must remain strictly below 30 ms (p95), public read paths bypass hierarchy construction completely by relying on pre-assembled snapshots in cache and key-value datastructures.
[ Learner Requests ]
│
▼
[ API Gateway / Edge ]
│
▼
┌──────────────────────────┐
│ Redis Cache Layer │ ── (Hit: < 5 ms) ──► Return JSONB
└──────────────────────────┘
│
(Cache Miss)
│
▼
┌──────────────────────────┐
│ PostgreSQL Read Replica │ ── Query `track_versions` table
└──────────────────────────┘
The Invalidation Lifecycle
- Publish Execution: When an author triggers
/publish, the server queries the active draft modules and lessons in binary position order, constructs a complete JSON document, writes an entry intotrack_versions, and updatestracks.published_versionwithin a single SQL transaction. - Transactional Outbox Event: Simultaneously, an event payload is written to an
outboxtable. An asynchronous relay publisher pushes an invalidation event to Redis / NGINX local cache layers:{ "event": "TRACK_PUBLISHED", "trackId": "c39e...", "newVersion": 4 } - Redis Write Through: The cache worker fetches the newly published tree JSON from
track_versionsand populates Redis:- Key:
cache:track:c39e... - Value:
{ ...tree payload... }
- Key:
- Cache Revalidation: Subsequent learner calls hit Redis directly. In-flight reads during a publish event either finish reading the old version pointer or receive the new pointer seamlessly—eliminating partial reads or broken structural references.
Performance & Scalability Summary
| Metric / Scenario | Strategy / Design Target |
|---|---|
| Track Read p95 | < 10 ms via Redis string cache; < 25 ms DB query fallback on JSONB pre-built tree column. |
| Sibling Reordering | $O(1)$ single-row update via fractional indexing string mid-point. |
| Structural Integrity | Guaranteed via PostgreSQL composite unique keys (parent_id, position) and FK cascade restrictions. |
| Publishing Atomicity | Single SQL transaction inserting immutable snapshot into track_versions table. |