Hierarchical Learning Progress APIs and Data Model

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Design the authenticated HTTP API layer and relational persistence model for tracking learner progress across an online certification platform. Curriculum content follows a strict three-tier ordered hierarchy:

  • Course: Top-level program made up of an ordered sequence of Modules.
  • Module: Section inside a Course made up of an ordered sequence of Lessons.
  • Lesson: Smallest completable unit of instruction.

Your design should specify:

  1. REST Endpoint Contracts (HTTP method, URL route, request body/query parameters, status codes, and JSON response shapes) for three operations:
    • Complete a Lesson: Record that the authenticated caller finished a given lesson ID. Repeated or retried calls must be strictly idempotent—never inserting duplicate rows, overwriting the original completion timestamp, or returning server/conflict errors.
    • Fetch Single-Course Progress: Return the caller's overall completion percentage for one course, a per-module progress breakdown in display order, and the completion state of every lesson inside each module.
    • List Enrolled Courses: Return a paginated list of courses in which the caller is enrolled, including each course's high-level state (not_started, in_progress, or completed) and overall completion percentage.
  2. Identity Scoping & Hierarchy Validation:
    • Guarantee that callers can read or modify only their own progress, even if forged user identifiers are sent in path segments, query strings, headers, or JSON bodies.
    • Before recording a lesson completion, verify that the lesson is live and belongs to an active course in which the caller holds an active enrollment.
  3. Relational Schema, Concurrency, and Read Performance:
    • Define the tables, primary keys, foreign keys, uniqueness constraints, and indexes backing these access patterns.
    • Explain how concurrent completion requests for the same (user, lesson) pair avoid race conditions.
    • Show how nested course progress is assembled without N+1 database queries, and justify whether module and course percentages should be computed dynamically at read time or materialized/cached at write time.

Scope & Expectations

  • Provide concrete HTTP routes, status codes, and request/response schemas scoped strictly to the verified authentication token rather than client-supplied user IDs.
  • Enforce hierarchy integrity and race-free idempotency at the database constraint and SQL query level, not via fragile application-side check-then-insert logic.
  • Design targeted composite indexes, cursor pagination, and constant-query-count (O(1) round-trips) data fetching that eliminate N+1 bottlenecks.
  • Clearly weigh dynamic read-time aggregation against write-time counter materialization under curriculum edits and high concurrency.

Step-by-step walkthrough

  1. Separate curriculum catalog from per-learner progress

    Split the domain cleanly into two kinds of data with very different read/write patterns:

    Curriculum catalog (shared across all learners, edited rarely by authors):
      Course (1) ----< Module (1..*, ordered) ----< Lesson (1..*, ordered)
    
    Learner state (scoped to one authenticated user, written frequently):
      Enrollment (user_id, course_id)          LessonCompletion (user_id, lesson_id)
    

    State three foundational rules upfront so all endpoints agree: - Facts vs. derived metrics: The database stores atomic facts (Enrollment and LessonCompletion with its original completed_at timestamp). Module percentages, course percentages, and statuses (not_started, in_progress, completed) are derived from those facts — never trusted from client payloads. - Lesson-weighted course progress: A course with 10 live lessons where the learner completed 5 is at 50.0%, regardless of how those 10 lessons are grouped across modules. - Soft deletion (archived_at): Removing outdated content sets archived_at on the lesson instead of deleting historical completion rows, keeping audit history intact while excluding archived lessons from active progress totals.

  2. Design the relational schema and integrity constraints

    Using PostgreSQL (any relational database with composite keys and atomic conflict handling works identically):

    CREATE TABLE courses (
      id          BIGINT PRIMARY KEY,
      title       TEXT NOT NULL,
      status      TEXT NOT NULL CHECK (status IN ('draft', 'active', 'archived'))
    );
    
    CREATE TABLE modules (
      id          BIGINT PRIMARY KEY,
      course_id   BIGINT NOT NULL REFERENCES courses (id),
      position    INT    NOT NULL,
      title       TEXT   NOT NULL,
      -- DEFERRABLE allows swapping two module positions inside a single transaction.
      UNIQUE (course_id, position) DEFERRABLE INITIALLY DEFERRED,
      -- Required target for the composite foreign key on lessons below.
      UNIQUE (id, course_id)
    );
    
    CREATE TABLE lessons (
      id          BIGINT PRIMARY KEY,
      module_id   BIGINT NOT NULL,
      -- Denormalized copy of course_id so course-level queries avoid joining through modules.
      course_id   BIGINT NOT NULL,
      position    INT    NOT NULL,
      title       TEXT   NOT NULL,
      archived_at TIMESTAMPTZ,
      -- Guarantees lesson.course_id always matches its parent module.course_id.
      FOREIGN KEY (module_id, course_id) REFERENCES modules (id, course_id),
      UNIQUE (module_id, position) DEFERRABLE INITIALLY DEFERRED,
      UNIQUE (id, course_id)
    );
    
    CREATE TABLE enrollments (
      user_id     BIGINT NOT NULL REFERENCES users (id),
      course_id   BIGINT NOT NULL REFERENCES courses (id),
      status      TEXT   NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'revoked')),
      enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
      PRIMARY KEY (user_id, course_id)
    );
    
    CREATE TABLE lesson_completions (
      user_id      BIGINT NOT NULL REFERENCES users (id),
      lesson_id    BIGINT NOT NULL,
      course_id    BIGINT NOT NULL,
      completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
      -- Enforces at most one completion record per (user, lesson) at the storage level.
      PRIMARY KEY (user_id, lesson_id),
      -- Guarantees completion.course_id matches the lesson's actual course_id.
      FOREIGN KEY (lesson_id, course_id) REFERENCES lessons (id, course_id)
    );
    

    Notice why denormalizing course_id (copying course_id onto lessons and lesson_completions) is safe here: the composite foreign keys (module_id, course_id) and (lesson_id, course_id) make it mathematically impossible to insert a completion whose course_id disagrees with its lesson's parent course, while letting us fetch all completions for (user_id, course_id) in a single index scan.

  3. Add targeted indexes for every access pattern

    Design indexes directly from the exact WHERE and ORDER BY clauses of our three endpoints:

    Access pattern                                      Supporting index
    --------------------------------------------------  ------------------------------------------------------------------
    Check / insert one lesson completion (idempotency)  lesson_completions PRIMARY KEY (user_id, lesson_id)
    Fetch user's completions in one or more courses     lesson_completions (user_id, course_id) INCLUDE (lesson_id, completed_at)
    Verify active enrollment in a course                enrollments PRIMARY KEY (user_id, course_id)
    Paginate user's enrolled courses newest-first       enrollments (user_id, enrolled_at DESC, course_id DESC)
    Load a course's modules and lessons in order        modules UNIQUE (course_id, position), lessons UNIQUE (module_id, position)
    Count live (non-archived) lessons per course        lessons (course_id) WHERE archived_at IS NULL   (partial index)
    

    Every learner-facing query begins with user_id = $1, so index lookups touch only that single learner's rows (typically a handful of courses and a few hundred lessons) whether the platform has 1,000 or 10,000,000 total users.

  4. Enforce token-scoped authorization and hierarchy validation

    1. Never trust client-supplied user identifiers: Authentication middleware verifies the cryptographic signature and expiration of the caller's session cookie or JWT (JSON Web Token — a signed credential issued by the auth server) and attaches the verified auth_user_id to the server-side request context. - Learner endpoints live under /v1/me/... and accept no user_id path, query, header, or body field. Even if a malicious client appends ?user_id=999 or X-User-Id: 999, the handler ignores unparsed parameters (or rejects unknown fields with 400 Bad Request) and binds $1 = context.auth_user_id in every SQL query. - Separate admin/support endpoints (/v1/admin/users/{user_id}/...) require an explicit admin role permission check.

    2. Validate the full curriculum hierarchy before writing: Before recording a completion for lesson_id, verify in a single join that the lesson exists, is not archived, belongs to an 'active' course, and that auth_user_id holds an 'active' enrollment in that course:

    -- $1 = verified auth_user_id from token, $2 = lesson_id from URL path
    SELECT l.id AS lesson_id, l.module_id, l.course_id
    FROM lessons l
    JOIN courses c     ON c.id = l.course_id
    JOIN enrollments e ON e.course_id = l.course_id AND e.user_id = $1
    WHERE l.id = $2
      AND l.archived_at IS NULL
      AND c.status = 'active'
      AND e.status = 'active';
    

    If this query returns zero rows, distinguish the error cleanly: return 404 Not Found if the lesson does not exist or is archived, or 403 Forbidden (not_enrolled / course_inactive) if the user lacks an active enrollment (or return 404 uniformly if private course existence must not be leaked).

  5. Endpoint 1: Mark Lesson Complete with race-free idempotency

    An operation is idempotent if calling it once or ten times produces the exact same stored state and response shape. Using PUT on the singleton sub-resource "my completion of lesson {lesson_id}" expresses this naturally:

    Request:
      PUT /v1/me/lessons/{lesson_id}/completion
      Authorization: Bearer <jwt>
      (empty body)
    
    Responses:
      200 OK
      {
        "lesson_id": "103",
        "module_id": "12",
        "course_id": "7",
        "completed": true,
        "completed_at": "2026-03-04T15:20:11Z"
      }
    
      401 Unauthorized   -- missing or expired token
      403 Forbidden      -- learner not actively enrolled or course inactive
      404 Not Found      -- unknown or archived lesson_id
    

    Handling retries and concurrent double-clicks without race conditions: Never write application-side SELECT followed by INSERT ("check-then-act") — two simultaneous requests will both see no row, both run INSERT, and crash one request with a 23505 unique_violation (500 Internal Server Error). Also avoid ON CONFLICT DO UPDATE SET completed_at = now(), which corrupts the historical completed_at timestamp on retries!

    Instead, rely on the database's PRIMARY KEY (user_id, lesson_id) with an atomic upsert-ignore (INSERT ... ON CONFLICT DO NOTHING):

    -- Attempt atomic insert; returns completed_at only if THIS call created the row.
    INSERT INTO lesson_completions (user_id, lesson_id, course_id)
    VALUES ($1, $2, $3)
    ON CONFLICT (user_id, lesson_id) DO NOTHING
    RETURNING completed_at;
    
    -- If RETURNING yielded 0 rows, the completion already existed; read its original timestamp.
    SELECT completed_at
    FROM lesson_completions
    WHERE user_id = $1 AND lesson_id = $2;
    

    Trace what happens when two concurrent requests Req A and Req B race on (user 42, lesson 103):

    Time   Req A (double-click 1)                        Req B (double-click 2)
    ----   --------------------------------------------  ----------------------------------------------------
    t1     Hierarchy check passes (course_id = 7)        Hierarchy check passes (course_id = 7)
    t2     INSERT (42, 103, 7) acquires key lock         INSERT (42, 103, 7) blocks waiting on key (42, 103)
    t3     COMMIT -> returns completed_at = 15:20:11Z    Unblocks -> sees committed conflict -> DO NOTHING!
    t4     Responds 200 OK (15:20:11Z)                   Fallback SELECT reads 15:20:11Z (READ COMMITTED)
    t5                                                   Responds 200 OK (15:20:11Z)
    

    (Note: To prevent an edge case where an admin revokes the enrollment between t1 and t2, wrap the hierarchy check and INSERT in one transaction and append FOR SHARE OF e to the hierarchy check.)

  6. Endpoint 2: Get Course Progress without N+1 queries

    Request:
      GET /v1/me/courses/{course_id}/progress
      Authorization: Bearer <jwt>
    
    Response: 200 OK
    {
      "course_id": "7",
      "status": "in_progress",
      "completed_lessons": 5,
      "total_lessons": 10,
      "percent_complete": 50.0,
      "modules": [
        {
          "module_id": "11",
          "title": "API Foundations",
          "status": "completed",
          "completed_lessons": 4,
          "total_lessons": 4,
          "percent_complete": 100.0,
          "lessons": [
            {"lesson_id": "101", "title": "HTTP Essentials", "completed": true, "completed_at": "2026-03-01T10:00:00Z"}
          ]
        }
      ]
    }
    

    Avoiding the N+1 query bottleneck: A naive ORM loop runs 1 query for the course, M queries to load lessons for each of the M modules, and L queries to check completion for each lesson (1 + 10 + 150 = 161 database round-trips!). Instead, execute exactly 3 fast queries regardless of curriculum size, then stitch the tree together in O(M + L) memory:

    -- Query 1: Verify active enrollment in an active course (else 403 / 404).
    SELECT 1
    FROM enrollments e
    JOIN courses c ON c.id = e.course_id
    WHERE e.user_id = $1 AND e.course_id = $2
      AND e.status = 'active' AND c.status = 'active';
    
    -- Query 2: Fetch all modules and live lessons in display order (LEFT JOIN preserves empty modules).
    SELECT m.id AS module_id, m.title AS module_title,
           l.id AS lesson_id, l.title AS lesson_title
    FROM modules m
    LEFT JOIN lessons l ON l.module_id = m.id AND l.archived_at IS NULL
    WHERE m.course_id = $2
    ORDER BY m.position ASC, l.position ASC;
    
    -- Query 3: Fetch all completed lesson timestamps for this user in this course via covering index.
    SELECT lesson_id, completed_at
    FROM lesson_completions
    WHERE user_id = $1 AND course_id = $2;
    

    In-memory assembly in Python:

    def compute_percent(done: int, total: int) -> float:
        if total == 0:
            return 0.0
        return round(100.0 * done / total, 1)
    
    
    def compute_status(done: int, total: int) -> str:
        # Check done == 0 first so an empty module (0/0) reports "not_started", not "completed".
        if done == 0:
            return "not_started"
        if done >= total:
            return "completed"
        return "in_progress"
    
    
    def assemble_course_progress(course_id, tree_rows, completed_map):
        """Join ordered (module, lesson) rows with {lesson_id: completed_at} in O(lessons) time."""
        modules = []
        module_by_id = {}
    
        for module_id, module_title, lesson_id, lesson_title in tree_rows:
            if module_id not in module_by_id:
                module_by_id[module_id] = {
                    "module_id": str(module_id),
                    "title": module_title,
                    "completed_lessons": 0,
                    "lessons": [],
                }
                modules.append(module_by_id[module_id])
    
            # LEFT JOIN produces lesson_id = None when a module currently has 0 live lessons.
            if lesson_id is None:
                continue
    
            completed_at = completed_map.get(lesson_id)
            is_done = completed_at is not None
            module_by_id[module_id]["lessons"].append({
                "lesson_id": str(lesson_id),
                "title": lesson_title,
                "completed": is_done,
                "completed_at": completed_at,
            })
            if is_done:
                module_by_id[module_id]["completed_lessons"] += 1
    
        course_done = 0
        course_total = 0
        for mod in modules:
            mod_done = mod["completed_lessons"]
            mod_total = len(mod["lessons"])
            mod["total_lessons"] = mod_total
            mod["percent_complete"] = compute_percent(mod_done, mod_total)
            mod["status"] = compute_status(mod_done, mod_total)
            course_done += mod_done
            course_total += mod_total
    
        return {
            "course_id": str(course_id),
            "status": compute_status(course_done, course_total),
            "completed_lessons": course_done,
            "total_lessons": course_total,
            "percent_complete": compute_percent(course_done, course_total),
            "modules": modules,
        }
    

    Worked numeric check: Suppose a course has 3 modules of sizes 4, 3, and 3 (10 live lessons total), and the learner completed 4, 1, and 0. Module percentages are 100.0%, 33.3%, and 0.0%, while overall course progress is (4 + 1 + 0) / 10 = 50.0% (whereas naively averaging the three module percentages would give (100 + 33.3 + 0) / 3 = 44.4%!). Also notice that any historical completion of an archived lesson in completed_map is automatically ignored because Query 2 filters l.archived_at IS NULL.

  7. Endpoint 3: List User Courses and compute-on-read vs. materialization

    Request:
      GET /v1/me/courses?limit=20&cursor=eyJlIjoiMjAyNi0wMi0wMVQwOTowMDowMFoiLCJjIjo3fQ
      Authorization: Bearer <jwt>
    
    Response: 200 OK
    {
      "items": [
        {
          "course_id": "7",
          "title": "Backend Systems 101",
          "status": "in_progress",
          "completed_lessons": 5,
          "total_lessons": 10,
          "percent_complete": 50.0,
          "enrolled_at": "2026-02-01T09:00:00Z"
        }
      ],
      "next_cursor": null
    }
    

    Use keyset (cursor) pagination encoding the last item's (enrolled_at, course_id) tuple rather than OFFSET: OFFSET 5000 forces the database to scan and discard 5,000 index entries and duplicates/skips rows when a new enrollment is inserted, whereas WHERE (enrolled_at, course_id) < ($2, $3) jumps straight to the next page in O(limit) index reads. Fetch limit + 1 rows (e.g., 21 for limit = 20) to know whether another page exists, and batch-load counts for the page's course_ids ($4) in two aggregate queries:

    -- Query 1: Fetch one page of active enrollments in active courses (limit + 1 rows).
    SELECT e.course_id, e.enrolled_at, c.title
    FROM enrollments e
    JOIN courses c ON c.id = e.course_id
    WHERE e.user_id = $1
      AND e.status = 'active'
      AND c.status = 'active'
      AND (e.enrolled_at, e.course_id) < ($2, $3)   -- omitted on first page (cursor is absent)
    ORDER BY e.enrolled_at DESC, e.course_id DESC
    LIMIT 21;
    
    -- Query 2: Live lesson totals for the page's course IDs ($4 =bigint[]). Easily cached!
    SELECT course_id, COUNT(*) AS total_lessons
    FROM lessons
    WHERE course_id = ANY($4) AND archived_at IS NULL
    GROUP BY course_id;
    
    -- Query 3: Completed live lessons for this user across the page's course IDs.
    SELECT lc.course_id, COUNT(*) AS completed_lessons
    FROM lesson_completions lc
    JOIN lessons l ON l.id = lc.lesson_id AND l.archived_at IS NULL
    WHERE lc.user_id = $1 AND lc.course_id = ANY($4)
    GROUP BY lc.course_id;
    

    Dynamic calculation on read vs. materializing on write: - Default recommendation — compute dynamically on read: 1. Zero cache/counter drift: Adding or archiving a lesson updates percentages across every learner immediately without background backfills across millions of enrollments. 2. Fast bounded reads: A single course has ~20–200 lessons and one page lists ~20 courses; indexed by user_id, all three queries finish in single-digit milliseconds. 3. Contention-free writes: PUT .../completion touches only lesson_completions, avoiding write-lock contention on enrollments rows when a learner completes several short lessons rapidly. - When to materialize: Only if product requirements add server-side filtering/sorting by progress (GET /v1/me/courses?status=completed) or extreme scale demands shaving the join in Query 3. Even then, materialize integer counters (enrollments.completed_lessons), never percentages — increment completed_lessons inside the same transaction only when INSERT ... ON CONFLICT DO NOTHING RETURNING 1 actually inserted a new row, and still divide by the cached live total_lessons at read time.

Intuition & how it works

Think of this progress service like a coffee-shop stamp card stapled to an official menu:

  1. You only stamp your own card (token-scoped identity): The barista checks your verified photo ID (JWT / session token — a cryptographically signed credential issued at login) rather than letting you shout someone else's account number across the counter.
  2. Each drink slot can only be stamped once (database-enforced idempotency): Stamping slot #103 twice because the mobile app lost Wi-Fi and retried leaves the exact same single stamp and original timestamp, never two stamps or an error.
  3. Count stamps against today's live menu at read time (dynamic progress + bulk queries): Instead of asking the database 150 separate questions ("Did they finish Lesson 1? Lesson 2? ..."), you grab the whole menu for Course 7 in one query, grab all of the learner's stamps for Course 7 in a second query, and match them up in memory in microseconds.

Why do obvious approaches fail? First, designing URLs like GET /users/{user_id}/courses and reading user_id from the path or request body creates a Broken Object Level Authorization (BOLA / IDOR) vulnerability where changing 42 to 43 leaks another learner's training records. Second, implementing idempotency in Python with if not exists(): insert() fails under double-click concurrency when two requests pass exists() simultaneously and collide on INSERT. Third, pre-saving percent_complete = 50.0 on the enrollment row goes stale the instant a course author publishes or archives a lesson.

Walk through a concrete 3-step trace for learner user_id = 42 enrolled in Course 7 (Module 11 with 2 lessons 101, 102, and Module 12 with 2 lessons 103, 104): 1. Double-clicked completion: The browser sends two concurrent PUT /v1/me/lessons/103/completion requests. Both verify (lesson 103 is live, course 7 is active, user 42 is enrolled) and run INSERT INTO lesson_completions ... ON CONFLICT (user_id, lesson_id) DO NOTHING RETURNING completed_at. Request 1 inserts the row (15:20:11Z); Request 2 hits the primary-key conflict, does nothing, runs a fallback SELECT, and also returns 200 OK with 15:20:11Z. 2. Course progress load: GET /v1/me/courses/7/progress runs 3 queries: (1) check enrollment, (2) fetch the 4 ordered (module, lesson) rows, and (3) fetch completed lessons {101, 102, 103} for (user 42, course 7). 3. In-memory assembly: Python marks Module 11 at 2 / 2 = 100.0% (completed), Module 12 at 1 / 2 = 50.0% (in_progress), and Course 7 overall at 3 / 4 = 75.0% (in_progress).

Key points

  • Token-derived scoping (/v1/me/...): Extract user_id exclusively from the verified auth token middleware, omit user_id from learner request paths/payloads, and require user_id in every data-access method signature.
  • Hierarchy validation before writes: Verify in a single join that the target lesson is unarchived (archived_at IS NULL), its parent course has status = 'active', and the caller's enrollment has status = 'active'.
  • Database-level idempotency: Enforce PRIMARY KEY (user_id, lesson_id) on lesson_completions and write via upsert-ignore (INSERT ... ON CONFLICT DO NOTHING RETURNING completed_at plus fallback SELECT), returning 200 OK with the original completed_at on every retry.
  • Safe denormalization via composite foreign keys: Copy course_id onto lessons and lesson_completions and enforce FOREIGN KEY (lesson_id, course_id) REFERENCES lessons (id, course_id) so course-level completion lookups scan a single index (user_id, course_id) without risking inconsistent parent IDs.
  • Eliminate N+1 queries (the anti-pattern of issuing one database query per child item in a loop): Both Get Course Progress and List User Courses use 3 fixed bulk queries joined in application memory.
  • Keyset (cursor) pagination: Paginate GET /v1/me/courses using an opaque cursor over (enrolled_at DESC, course_id DESC) so page 100 is just as fast as page 1 (O(limit) index scan rather than O(offset + limit)).
  • Compute percentages on read: Derive percentages dynamically from live lesson counts so curriculum edits take effect instantaneously; only materialize an integer completed_lessons counter if filtering/sorting by progress becomes required.

Common mistakes

  • Trusting user_id from path, query, or JSON body: Exposes every learner's progress to trivial parameter tampering unless strictly cross-checked or replaced by /v1/me/... token scoping.
  • Application-level check-then-insert (SELECT then INSERT): Under concurrent retries or double clicks, both transactions read 0 rows and one crashes with a unique-constraint error (500).
  • Overwriting completed_at on conflict (DO UPDATE SET completed_at = now()): Destroys the audit timestamp of when the learner actually finished the lesson, or returning 409 Conflict on retries, breaking HTTP PUT idempotency.
  • Checking only lesson_id existence on completion: Allows an authenticated user to record completions on draft courses, archived lessons, or courses they never enrolled in.
  • Averaging module percentages instead of weighting by lessons: If Module 1 has 9 lessons (9/9 = 100%) and Module 2 has 1 lesson (0/1 = 0%), the learner finished 9 / 10 = 90.0% of the course, not (100% + 0%) / 2 = 50.0%.
  • Counting archived completions in the numerator: If a completed lesson is later archived and you count raw lesson_completions without filtering l.archived_at IS NULL, completed_lessons can exceed total_lessons (110% complete!).

Follow-up questions

  • Suppose a content author publishes an additional lesson inside a course or module that learners have already finished. How should progress percentages and earned completions behave? With dynamic calculation on read, adding an 11th lesson immediately shifts a 10 / 10 learner to 10 / 11 = 90.9% (in_progress) with zero database backfill. However, silently revoking a learner's earned badge or certificate is poor UX, so separate live curriculum progress from earned credentials: the first time a learner hits 100%, insert an immutable record into course_certificates (user_id, course_id, awarded_at, curriculum_version). The UI can then keep their certificate active while displaying "Completed (1 new optional lesson available)" — or, for mandatory compliance updates, bump curriculum_version and notify certified learners of a renewal deadline.
  • Once the platform scales to millions of enrolled learners, how would you keep the enrolled-courses listing endpoint consistently under 50 ms latency? Because every query is leading-key indexed on user_id, scanning 20 enrollments for one learner already touches only 20 index entries regardless of total user count, so the main work is eliminating per-page aggregation joins and primary-DB load. First, cache total_lessons and title per (course_id, curriculum_version) in Redis or local server memory (since course structure changes rarely, removing Query 2 completely). Second, materialize completed_lessons on enrollments (updated transactionally only when INSERT ... ON CONFLICT DO NOTHING inserts a new row, reconciled on lesson archive), collapsing List Enrolled Courses into a single index scan on enrollments (user_id, enrolled_at DESC, course_id DESC). Third, serve GET requests from read replicas (routing a user to the primary for a few seconds right after a PUT write so they see read-your-writes consistency) and hash-partition enrollments and lesson_completions by user_id once single-node storage becomes a bottleneck.
  • How would your API contracts and schema evolve if lessons needed granular progress state—such as seconds of video watched or quiz attempt scores—rather than binary completion? Replace lesson_completions with lesson_progress (user_id, lesson_id, course_id, max_watched_seconds INT, best_quiz_score NUMERIC, completed_at TIMESTAMPTZ NULL, updated_at TIMESTAMPTZ, PRIMARY KEY (user_id, lesson_id)). Expose PUT /v1/me/lessons/{lesson_id}/video-progress accepting {"watched_seconds": 540} (comparing against server-stored lessons.duration_seconds — never trusting a client-supplied percentage or duration!) and POST /v1/me/lessons/{lesson_id}/quiz-submissions where the server grades submitted answers. Merge updates with monotonic SQL functions so out-of-order network heartbeats and retries can never move progress backward or overwrite the first completion timestamp: max_watched_seconds = GREATEST(old, LEAST(new, duration)), best_quiz_score = GREATEST(old, new), and completed_at = COALESCE(old, CASE WHEN criteria_met THEN now() END).

Follow-up questions

Similar questions

More Fora Travel interview questions

All 7 Fora Travel questions →