LLM System Design ยท Chapter 4 ยท Case study

Designing an Adaptive Learning App

A language-learning app like Duolingo that uses LLMs to create lessons and personalise them for every learner

SA
Shivank AgarwalFuture with Shivank

Imagine a tutor who knows exactly what you've mastered, what you keep getting wrong, and what question to ask you next, for 50 million learners at the same time. In this chapter we design that system step by step, like a real interview: requirements โ†’ numbers โ†’ APIs โ†’ blueprint โ†’ database โ†’ deep dives โ†’ testing โ†’ monitoring.

This chapter stands on its own. Start with the starter kit if any term is new.

๐Ÿง  Think of it likeโ€ฆ an everyday analogy
๐ŸŒ Real-world example where you have seen this
๐Ÿ” Worked example step by step, with real values
โš ๏ธ Watch out a common mistake
๐ŸŽฏ Interview tip a line you can say in an interview
๐Ÿš€ Going deeper optional, for the curious
๐ŸŽฌ Sequence diagrams press โ–ถ Play to animate them

๐ŸŽ’ Starter kit: 16 ideas you need for this chapter

1. LLM & prompt
An LLM (Large Language Model) is a big AI model like GPT, Claude or Gemini that reads and writes text. The instruction you give it is the prompt. LLM calls are slow (seconds) and cost money.
๐Ÿง  A brilliant friend who charges a fee per question and takes a moment to think.
2. Hallucination
LLMs sometimes state wrong things confidently. In a learning app, teaching wrong grammar destroys trust, which is why human experts review content in this design.
๐Ÿง  The uncle who says "go straight" even when he doesn't know the way.
3. DAU, RPS, P99
DAU = daily active users. RPS = requests per second. P99 < 500 ms = 99 of every 100 requests finish within half a second. Servers are sized for peak RPS.
๐Ÿง  Railways plan counters for the festival rush, not a quiet day.
4. API gateway
The front door for every request: checks identity and permissions, then routes it to the right service.
๐Ÿง  Your society's security guard.
5. Sync vs async, "202 Accepted"
Sync: the user waits for the answer. Async: work happens in the background; the server instantly replies 202 Accepted with a job_id, and the user checks status later (polling).
๐Ÿง  Chai stall (sync) vs dry cleaner's token slip (async).
6. Message queue & workers
A queue (SQS, Kafka) is a line of jobs. Producers add jobs; workers pick them up at their own pace. In a spike, the line grows but nothing crashes (backpressure).
๐Ÿง  A bank's token system: counters call the next token when ready.
7. Cache & Redis
Redis is a super-fast in-memory store (milliseconds). Keep ready-made results there. Hit = found; miss = fetch from the source. TTL = expiry.
๐Ÿง  Daily tea leaves on the kitchen shelf, not in the storeroom.
8. Redis list & LPOP
A Redis list is an ordered line of items. LPOP takes the first item out and removes it in one atomic step, so no one else can grab the same item at the same moment.
๐Ÿง  A candy dispenser: the top candy comes out, and it can't come out twice. ๐Ÿฌ
9. SQL (PostgreSQL) vs NoSQL (DynamoDB / Cassandra)
PostgreSQL: tables, relationships, flexible queries; scale reads with read replicas. DynamoDB / Cassandra: built for huge numbers of writes per second and scale out horizontally.
๐Ÿง  A well-organised office register (SQL) vs a station with hundreds of ticket counters (NoSQL).
10. Partition key & sort key
In DynamoDB, the partition key (e.g. user_id) decides which "cupboard" the data goes into; the sort key orders items inside that cupboard (e.g. by session).
๐Ÿง  One cupboard per person; files inside sorted by date.
11. Embedding & pgvector
An embedding is the meaning of text as a list of numbers (e.g. 768). Similar meanings โ†’ nearby vectors. pgvector is a PostgreSQL add-on that stores them and finds "similar" items.
๐Ÿง  A GPS address for the meaning of each question.
12. Retry, backoff, circuit breaker
Retry with exponential backoff: on failure, wait and retry, waiting longer each time. Circuit breaker: if a provider keeps failing, stop calling it for a while (open), try one test request later (half-open), go back to normal if it works (closed).
๐Ÿง  The MCB switch at home. โšก
13. Human-in-the-loop (HITL)
Before AI-made content goes live, a human expert checks it: accept, edit or reject.
๐Ÿง  A reporter writes; the editor approves before printing. ๐Ÿ“ฐ
14. Cron job / nightly job
A task that runs automatically at a fixed time, e.g. every night at 2 am.
๐Ÿง  The milkman who arrives at 5 am every day without being called. ๐Ÿฅ›
15. Data lake, Parquet, streams
A data lake is cheap cloud storage (like Amazon S3) holding all historical data for analysis. Parquet is a compressed file format that's fast to analyse. DynamoDB Streams is a live feed of every change in a table.
๐Ÿง  Old belongings go to the storeroom: not used daily, but not thrown away.
16. Function calling, CEFR levels, distractors
Function calling: instead of judging itself, the LLM asks a tool (like an answer checker) for an exact result. CEFR A1โ€“C2 are standard language levels (A1 = beginner โ€ฆ C2 = near-native). Distractors are the wrong-but-believable options in a multiple-choice question.
๐Ÿง  A teacher grades with the answer key, not by mood.

Chapter 4 ยท Case Study: Designing an Adaptive Learning AppLLM-generated lessons + personalised curation for every learner

4.1 Introduction: the future of learning is personal

A great learning app moves at each learner's own pace. It spends less time on what you already know and more on lessons that are challenging but not discouraging, which is the sweet spot for staying motivated. It also needs fresh lessons regularly, as it learns from usage and feedback what works.

LLMs can transform this in two ways:

๐Ÿญ 1. Creating new exercises
Generate thousands of new practice questions quickly, across many languages and levels.
๐ŸŽฏ 2. Personalising the path
Pick the perfect next question for each learner, based on their history.

We'll design the core AI features of a Duolingo-style app: personalised lesson progression and interactive exercises. Out of scope: detailed scoring systems (XP, leagues). They matter for the product, but we'll keep our focus on the AI architecture.

What the learner experiences
๐Ÿ“ฑ Learner's phone
Home screen๐Ÿ”ฅ Streak: 12 days
๐ŸŽฏ Next: Unit 3, Travel
tap Start
Interactive lesson๐Ÿค– Personalised question:
"Translate: the cat"
learner types an answer
Check the answer
correct
Positive feedbackโœ… "el gato"
+10 XP
wrong
Helpful correctionโŒ "gato" is masculine,
so it's "el", not "la"
Next personalised question
One small loop: question โ†’ answer โ†’ feedback โ†’ the next question chosen for this learner.
๐Ÿง  Think of it likeโ€ฆA great tuition teacher ๐Ÿ‘ฉโ€๐Ÿซ doesn't repeat what you already know. She gives you more practice exactly where you struggle: never so hard that you give up, never so easy that you get bored. This app is that teacher, for crores of students at once.

Roadmap: functional requirements โ†’ non-functional requirements โ†’ scale โ†’ API design โ†’ blueprint โ†’ databases โ†’ deep dives โ†’ testing โ†’ monitoring.

4.2 Functional requirements: what must it DO?

๐Ÿญ Lesson generation
Create complete exercises and lessons for every language and level, so there's always a fresh, relevant stream of content.
๐ŸŽฏ Adaptive curation
Look at a learner's past answers and pick the perfect next question: not too hard, not too easy.

4.3 Non-functional requirements: how WELL must it work?

RequirementTarget / meaning
โšก Low latencyFrom submitting an answer to seeing feedback or the next question: P99 under 500 ms.
๐ŸŽฏ High accuracyA matter of trust: no wrong answers, no confusing explanations.
๐Ÿ›ก High availabilityAn LLM provider outage must not take the whole app down.
๐Ÿ‘ค PersonalisedLessons fit the learner: not too hard, not too easy.
๐Ÿ’ธ Cost-effectiveLLM calls are expensive, so we need a clear strategy for when and where to use them.
๐Ÿ“ˆ ScalableHandle peaks when busy hours in different time zones overlap.
๐ŸŽฏ Interview tip"The central tension: personalisation needs an LLM, but a 500 ms P99 and cost limits mean we cannot call an LLM on every request. So I'll push the LLM work offline and into the background, and serve the live path from pre-computed caches."

4.4 Back-of-envelope numbers

Assume 50 million daily active users. The app teaches 50 languages; the most popular have about 250 lessons each, less common ones up to 70. Each lesson has up to 10 questions.

๐Ÿ” Worked example: from users to requests per second
  1. Questions served per day: 50M users ร— 3 lessons ร— 10 questions = 1.5 billion questions/day.
  2. Per second: 1.5 billion รท 86,400 seconds in a day โ‰ˆ 17,400 questions per second.
  3. API calls per question: at least 3: GET the question, POST the answer, GET the feedback. So 17,400 ร— 3 โ‰ˆ 52,000 RPS on average.
  4. Peak (ร—5): traffic isn't flat; evenings and overlapping time zones bring spikes. 52K ร— 5 โ‰ˆ 260,000 RPS.
  5. Extra features: conversation practice (+20%) and real-time analytics (+15%): 260K ร— 1.35 โ‰ˆ ~350,000 RPS at peak.
  6. How many are writes? Roughly 1 in 3 calls (submitting answers, saving progress) writes data: 260K รท 3 โ‰ˆ ~90,000 writes per second at peak. This number will drive our database choice.
๐ŸŽฎ Try it: change the assumptions
Questions / second
Average API RPS
Peak RPS
Total peak (with extras)

Peak writes โ‰ˆ one third of the peak API RPS (before extras):

๐Ÿš€ Going deeper: why the LLM can't sit on the live pathIf every question needed an LLM call, that's 17,000+ LLM calls per second, each taking 1โ€“5 seconds: tens of thousands of calls in flight at any moment and an enormous bill. But if one LLM call picks a playlist of 20โ€“30 questions, we need 20โ€“30ร— fewer calls, and they can happen in the background. That single idea shapes this entire design.

4.5 API design

Two groups of APIs: admin APIs for language experts who create and review content, and a learner API that serves personalised lessons. Every question moves through these statuses:

A question's life
NEWthe LLM just made it
IN_REVIEWwaiting for an expert
expert says no
REJECTEDnever goes live
expert says yes
ACCEPTEDapproved
nightly job
LIVEin the question bank

๐Ÿ›  Admin APIs (for content experts)

All admin APIs require an admin login token in the header: Authorization: Bearer <admin_token>.

1. Generate a few questions right now (sync): POST /api/v1/admin/questions

Why: for small batches (5 or fewer), for quick testing. The admin waits a few seconds and gets the questions directly, with no queue.

// Request
{ "format": "FILL_IN_THE_BLANK",
  "count": 2,
  "level": "A2",
  "language": "Spanish",
  "topic": "prepositions" }
// Response
{ "count_generated": 2, "status": "IN_REVIEW",
  "questions": [
   { "id": "q_137293",
     "text": "El libro estรก ___ la mesa.",
     "choices": ["en","sobre","hacia","entre"] },
   { "id": "q_137294",
     "text": "Caminamos ___ el parque.",
     "choices": ["por","sobre","hacia","entre"] } ] }

(For English readers: "El libro estรก ___ la mesa" = "The book is ___ the table"; the answer is sobre, "on". "Caminamos ___ el parque" = "We walk ___ the park"; the answer is por, "through".)

format
Type of exercise: FILL_IN_THE_BLANK, MULTIPLE_CHOICE, TRANSLATIONโ€ฆ
level
CEFR level (A1 beginner โ€ฆ C2 near-native).
topic
The grammar or vocabulary focus.
status
New questions always start in review: nothing goes live without a human.

2. Start a big generation job (async): POST /api/v1/admin/question-generation-jobs

Why: generating 100+ questions takes minutes. The request is queued and the admin's screen stays usable.

// Request
{ "format": "FILL_IN_THE_BLANK", "count": 100,
  "level": "A2", "language": "Spanish",
  "topic": "prepositions" }
// Response: 202 Accepted (immediately)
{ "job_id": "job_d9e8f7a6", "status": "PENDING",
  "status_url":
   "/api/v1/admin/question-generation-jobs/job_d9e8f7a6" }

3. Check job status: GET /api/v1/admin/question-generation-jobs/{job_id}

Why: the dashboard polls this to show "Processingโ€ฆ" and then "Done".

// While running
{ "job_id": "job_d9e8f7a6", "status": "PROCESSING",
  "progress": "6 of 10 batches done" }
// When finished
{ "job_id": "job_d9e8f7a6", "status": "COMPLETED",
  "message": "Generated 100 questions.",
  "results_url": "/api/v1/admin/questions?job_id=job_d9e8f7a6" }

4. Get a job's questions: GET /api/v1/admin/questions?job_id=job_d9e8f7a6

[ { "id": "q_201", "text": "Vivo ___ Madrid.", "type": "FILL_IN_THE_BLANK",
    "language": "Spanish", "level": "A2", "status": "IN_REVIEW" },
  { "id": "q_202", "text": "El gato duerme ___ la cama.", ... }
  // ... 100 questions in total (paginated)
]

5. Review one question in detail: GET /api/v1/admin/questions/{question_id}

{ "id": "q_137293", "text": "El libro estรก ___ la mesa.",
  "type": "FILL_IN_THE_BLANK", "choices": ["en","sobre","hacia","entre"],
  "answer": "sobre", "explanation": "'sobre' = on top of",
  "status": "IN_REVIEW", "language": "Spanish", "level": "A2", "topic": "prepositions" }

The answer is visible here because only experts see this API.

6. Approve or reject many at once: POST /api/v1/admin/questions:batchUpdateStatus

// Request
{ "question_ids": ["q_201", "q_202", "q_207"],
  "status": "ACCEPTED" }
// Response
{ "updated": 3, "status": "ACCEPTED" }

7. Fix a question: PATCH /api/v1/admin/questions/{question_id}

Why: the AI got something slightly wrong; the expert corrects the text, options or difficulty before approving. PATCH means "change only these fields".

// Request
{ "text": "El libro estรก ___ la mesa. (on top of)",
  "choices": ["en", "sobre", "bajo"] }
// Response: the updated question
{ "id": "q_137293",
  "text": "El libro estรก ___ la mesa. (on top of)",
  "choices": ["en", "sobre", "bajo"],
  "status": "IN_REVIEW" }

๐ŸŽฏ Learner API: start a personalised lesson: POST /api/v1/lesson-sessions

Why: builds a full lesson (10โ€“20 questions) for this learner, based on their current level and history. When: the learner taps "Start".

// Request
{ "skill_id": "skill_past_tense_verbs",
  "type": "PRACTICE",   // or TEST, REVIEW
  "preferred_question_count": 10 }
// Response
{ "lesson_session_id": "session_a4b1c2d3",
  "estimated_duration_seconds": 300,
  "questions": [
    { "question_id": "q_12483240", "type": "MULTIPLE_CHOICE",
      "prompt": "She ___ to the store yesterday.",
      "options": [ {"id":"opt_1","text":"go"},
                   {"id":"opt_2","text":"went"},
                   {"id":"opt_3","text":"gone"} ] },
    { "question_id": "q_43854", "type": "FILL_IN_THE_BLANK",
      "prompt": "We ___ the movie last night." } ] }
โš ๏ธ Notice what's missingThe learner's response contains no answers. If it did, anyone could open the browser's developer tools and see them. Answers are checked on the server when the learner submits.
Walk a question through its life
๐ŸŽฎ Try it: use the buttons in a sensible order (and in a silly order, to see the rules)
๐Ÿ†• NEW๐Ÿ” IN_REVIEWโœ… ACCEPTEDโŒ REJECTED๐Ÿฆ LIVE in question bank
๐Ÿง  Think of it likeโ€ฆThe sync API is buying "two jalebis, please" at a sweet shop: you get them on the spot. The async API is ordering "500 laddoos for a wedding": you get a receipt (job_id), call to check progress (polling), and collect when ready (results_url). ๐Ÿฌ

4.6 The blueprint: two systems, not one

In education, safety and quality are non-negotiable. Letting an LLM create lessons on the fly, live, for each learner is risky: errors, inconsistencies, even inappropriate content could reach a child's screen. So the core design idea is to separate quality from speed:

Two separate systems
๐Ÿญ System I: offline content factory
LLM createsat scale
Experts reviewhuman-in-the-loop
Quality checks
Question bank

Can be slow. Quality comes first.

โšก System II: online tutor
Question bank
select
Personalised lesson
๐Ÿ‘ค Learner

Only picks from already-approved questions: fast and safe.

The best of both: AI's scale and creativity + human quality control.
๐Ÿง  Think of it likeโ€ฆA restaurant's central kitchen (System I) prepares gravies and bases in the morning, and the head chef tastes and approves them. At the serving counter (System II), an order is assembled in two minutes. Nobody starts the gravy from scratch for every order! ๐Ÿ›

๐Ÿญ System I: the offline content factory

Its only job: fill one central question bank with lots of high-quality, approved content. It runs offline, so it never affects live learners.

The offline pipeline
Content team
Admin portalReview portal
โ†“ POST generation jobโ†‘ 202 Accepted + job_id
Async generation pipeline
Lesson generation service
publish job(s)
Generation job queue
worker takes a job
Orchestrator workers
call โ‡„ result
LLM
publish result
Results queue
DB worker takes it
Staging DBquestions waiting for review
โ‡… review portal loads, edits, accepts, rejects
Going live
Nightly job
reads ACCEPTED questions
Automatic checks
insert
Main question bank
๐ŸŒฑ Requesting content
Language experts use internal tools to call the admin API and ask for a batch of questions, choosing the language, level, topic and format.
๐Ÿšช API gateway
Checks the admin's identity and permissions, then forwards the request to the lesson generation service.
๐Ÿ— Lesson generation service
Manages the whole lifecycle: sends generation requests to the orchestrator, stores results in the staging area, supports many rounds of review until each question is right, and marks good ones as accepted. A scheduled job then moves accepted questions into the live bank.

๐Ÿง  The orchestrator

Depending on the request (a simple check, bulk generation, a complex conversation), the orchestrator picks the best model, builds the full prompt, adds resilience (retries, fallbacks), and validates the reply.

Inside the orchestrator
LLM orchestrator
Request in
Model routerrules: cost ยท speed ยท complexity
chosen model
Prompt layerbuilds the full prompt
Resilience layer
Automatic retries
Circuit breaker
Reroute / fallback
External LLM providers
Safety & validation layerchecks format and content
Response out
๐Ÿ” Worked example: generating questions with a clear prompt

A good generation prompt is precise about the count, the level, the theme, the answer format and the output shape:

Create 10 fill-in-the-blank questions for Spanish learners at level A2 to practise the simple future tense. Theme: food. For each question give exactly one correct answer and three believable wrong options (distractors). Tag each question with its grammar point. Return only a JSON object: {"questions": [...]}
from pydantic import BaseModel

class Question(BaseModel):          # the exact shape of one question
    sentence: str
    answer: str
    distractors: list[str]
    grammar_tag: str
    level: str
    topic: str

class QuestionSet(BaseModel):
    questions: list[Question]

r = client.chat.completions.parse(
    model="gpt-6.1-terra",
    response_format=QuestionSet,          # Structured Outputs: every question has exactly these fields
    messages=[{"role": "system", "content": "You are an expert Spanish teacher writing exercises."},
              {"role": "user", "content": prompt}])
questions = r.choices[0].message.parsed.questions     # already Python objects, no json.loads
print(questions[0].model_dump())

Output (first question):

{"sentence": "Maรฑana yo ___ paella con mi familia.",
 "answer": "comerรฉ",
 "distractors": ["comรญ", "como", "comรญa"],
 "grammar_tag": "future_simple", "level": "A2", "topic": "food"}

("Tomorrow I ___ paella with my family." The answer, comerรฉ, means "I will eat"; the distractors are past and present forms.)

โš ๏ธ Watch out: say exactly what you meanIf a prompt says "create 10 lessons" when you want 10 questions, the model may produce 10 full lessons. Use precise words and give the exact JSON shape you expect.
๐Ÿ™‹ Human review
Experts check every question: grammar, difficulty, format and platform standards. They fix small issues and then accept or reject.
๐Ÿฆ Going live (ingestion)
A scheduled nightly job picks up newly accepted questions, runs automatic checks (valid JSON, answer is among the options, no duplicatesโ€ฆ), and inserts them into the main question bank. The bank is the single source of truth for all approved, live content in every language.

โšก System II: the online tutor

1. Request & gateway
The learner's app asks for a lesson (POST /api/v1/lesson-sessions). The gateway checks identity and routes it to the lesson curator service.
2. Lesson curator service
The real-time brain: fetches the learner's next lesson from the approved bank, based on their level, understanding and progress, and keeps adapting as they improve.
3. Learner context
A user context service keeps each learner's progress: completed lessons, scores per skill, known vocabulary, strengths and recent mistakes.
4. Prepare in advance
We cannot run a slow, expensive LLM call for every learner in real time. So the online path uses proactive curation: the next lessons are chosen before the learner asks.

Why prepare in advance? If we waited until a learner finished a question and only then asked an LLM "what's the best next question?", they would stare at a spinner for seconds every time. Instead, we do that thinking ahead of time, in the background, in batches, and keep the results ready in a fast cache. That gives us two paths: warm (results ready) and cold (nothing ready yet).

๐Ÿ”ฅ The warm path: instant lessons for active learners

Serving a lesson
Learner's app
1. request a lesson
API gateway
Lesson curator service
2. check the cache
Playlist ready in the cache?
yes ยท warm path
3a. Fetch full contentfrom the question bank
4a. serve the lesson
โ†’ Learner
no ยท cold path
3b. Rule-based lessonquick query on the bank
4b. serve it
โ†’ Learner
5b. refill later
Background refill job

The warm path in one line: when a learner requests a lesson, the curator takes the next lesson's question IDs from that learner's ready-made playlist in Redis (precomputed_lesson_playlists) using LPOP, fetches the questions, and serves them instantly.

How the playlist gets refilled in the background
Triggerlesson completed, or a cache miss
Refill-check queue
Personalisation job
Curation worker
get learner context
Progress DB
get candidates
Question bank
publish job
Personalisation queue
Orchestrator worker
"sequence these" โ‡„
LLM
ordered question IDs
Redis playlist
โšก Event trigger
When a learner completes a lesson (or does anything that shows they're active), a tiny message such as {"userId": "user_123"} is put on a dedicated low-priority queue called refill_check_queue.
๐Ÿงฎ Buffer check
A background worker reads the queue and checks how many lessons are left in that learner's Redis playlist. If it's running low (say fewer than 5), it starts a refill.
๐Ÿ“ฆ Gather context
The worker collects the learner's recent progress, the history of their last 50 lessons, and a pool of a few hundred unseen questions from the bank at the right level, bundles it all into one message, and puts it on an SQS queue.
๐Ÿง  LLM sequencing
Orchestrator workers take these jobs at a controlled pace (so neither the LLM nor our services are overwhelmed). Prompt: "Based on this learner's history, choose and order the best 20โ€“30 questions from this candidate pool." The resulting question IDs are pushed onto the learner's Redis playlist.
๐Ÿ” Worked example: the playlist in Redis, command by command

Each element of the list is one lesson: a group of question IDs.

# the background job adds 3 lessons to the end of user_123's playlist
> RPUSH playlist:user_123 "q_88,q_91,q_17,q_42,q_63" "q_12,q_19,q_77,q_80,q_05" "q_31,q_33,q_09,q_51,q_70"
(integer) 3

# learner taps Start โ†’ take the FIRST lesson and remove it, in one atomic step
> LPOP playlist:user_123
"q_88,q_91,q_17,q_42,q_63"

> LLEN playlist:user_123          # how many lessons are left?
(integer) 2

# ...two more lessons later...
> LPOP playlist:user_123
(nil)                             # empty โ†’ this is the cold path

Why LPOP and not "read, then delete"? Because LPOP does both in one atomic step. If the learner opens the app on their phone and tablet at the same moment, each device gets a different lesson; the same lesson can never be served twice. The small buffer of ready lessons also hides any short delays in the background refill.

๐ŸŽฌ The full curation flow (press Play)
Two triggers, one purposeRefills are started by events (a lesson completed โ†’ refill immediately) and also by a safety scan every 5 minutes that catches any learner whose event was missed. The new plan is saved twice: in the database (durable, survives crashes) and in Redis (fast to serve).

๐ŸงŠ The cold path: new and returning learners

This path is for learners who have no ready playlist: brand-new users, or people returning after weeks away whose playlist has expired.

Cold path
Learner
1. request a lesson
Cold-path logic
Curation service
2. check the cache
Cache empty?
yes
3. Quick rule-based queryno LLM involved
Question bank
4. one lesson
5. Serve + start a refill
6a. serve now
โ†’ Learner
6b. refill in background
Async refill
1. Cache miss
The learner asks for a lesson; Redis LPOP returns nil (nothing there).
2. Synchronous fallback
Don't make them wait for the background job. Build just this one lesson right now with a fast rule-based query that skips the LLM: match the learner's language and level, and exclude questions they've seen recently. Not perfectly personalised, but fast and reliable.
3. Serve and trigger
Send that first lesson immediately, and at the same time start the async refill, so every following request takes the warm path.
๐Ÿ” Worked example: the rule-based query
-- One lesson for a Spanish A2 learner, skipping recently seen questions
SELECT id FROM question_bank
WHERE language = 'Spanish'
  AND difficulty_level = 'A2'
  AND id NOT IN (:recently_seen_ids)     -- from the learner's last 20 lessons
ORDER BY random()
LIMIT 10;

Output: 10 question IDs, returned in a few milliseconds. No LLM, no waiting.

โœ… Why this design works
  1. Decoupling: the personalisation engine is separated from what learners click, so the LLM sees steady, predictable load instead of sudden bursts.
  2. Buffering: keeping 20โ€“30 lessons ready means short hiccups in the background pipeline are invisible to learners.
  3. Graceful degradation: if the LLM providers are down or slow, don't send work to the orchestrator; use the rule-based selection (same level, not seen in the last 20 lessons). Lessons keep flowing, just a little less personalised.
๐ŸŽฎ Try it: warm and cold paths for one learner's playlist

Start lessons and watch the playlist drain and refill. Then take the LLM down, or crash Redis, and see what happens.

playlist:user_123

Demo rules: refill when fewer than 5 lessons remain; a refill adds 20 lessons and takes ~1.5 s. Each green box is one lesson.

๐Ÿง  Think of it likeโ€ฆWarm path = tiffins packed the night before and kept in the fridge: grab one and go (LPOP). Cold path = unexpected guests and no tiffin ready: make quick Maggi now (rule-based), and start cooking a proper meal for tomorrow (async refill). If the gas runs out (LLM down), serve whatever's ready at home (graceful degradation). ๐Ÿฑ
๐Ÿš€ Going deeper

๐Ÿง  The orchestrator, up close

The orchestrator builds detailed prompts, decides which LLM should serve each request (based on availability, response time and whether the use case needs accuracy or speed), and runs a safety and validation check on every reply before passing it back to the calling service.

๐Ÿ”€ The model router: rules for reliability and cost
RuleConditionRoute to
Rule 1: simple taskA simple grammar check?A small, fast model hosted in-house (e.g. Llama 3.1 8B)
Rule 2: complex taskPart of a complex conversation practice?A strong mid-tier model (e.g. Claude Sonnet 5.5 or gpt-6.1-terra)
Rule 3: premium featureA premium learner asking for a deep explanation?A top-tier model (e.g. gpt-6-astra)
โœ๏ธ The prompt layer

Builds the prompt for the chosen model and the learner's context: instructions, guardrails ("never use slang with A1 learners"), the expected output format, and a few examples so the reply comes back in the right shape.

๐Ÿ›ก The resilience layer

The orchestrator depends on outside APIs, which can fail in four typical ways:

๐Ÿ“ถ Network blips
Brief glitches, failed secure handshakes, momentary packet loss.
๐Ÿšฆ Rate limits (429)
The provider is busy, or we've used our quota.
๐Ÿ’ฅ Outages (5xx)
Major failure at the provider: errors or full downtime.
๐Ÿข Timeouts
The model takes longer than we can wait.
๐Ÿ” Automatic retries
On a temporary error (like 429 or 503), retry automatically.
Purpose: fix short glitches without a human or a model switch.
Exponential backoff: wait longer between each attempt, so we don't pile more load onto a struggling provider (a "retry storm").
Limit: usually 3 attempts. If all fail, the problem isn't temporary, and the circuit breaker takes over.
โšก Circuit breaker
Stops sending requests to a provider that is clearly and repeatedly failing.
โ†ช๏ธ Rerouting
When: the breaker is open, or the primary still times out after retries.
What: switch to a backup provider (e.g. primary OpenAI โ†’ backup Anthropic or Google).
Tiered fallback: first a strong backup, then a cheaper, simpler one (graceful degradation).
Keep the context: translate the prompt, context and history correctly into the backup provider's API format.
Breaker stateWhenWhat the orchestrator does
๐ŸŸข Closed (normal)Everything is healthyAll requests go to the primary provider
๐Ÿ”ด Open (failing)A failure threshold is crossed (e.g. 5 server errors in a row, or a 20% error rate within 60 seconds)Stop sending traffic immediately; fail fast or reroute. No time or tokens wasted on doomed requests, and the failing provider gets breathing room.
๐ŸŸก Half-open (testing)After a cooldown (e.g. 30 seconds)Send one test request. Success โ†’ closed. Failure โ†’ open again.
๐ŸŽฎ Try it: the circuit breaker (trips after 5 failures in a row)
๐Ÿง  Think of it likeโ€ฆRetry = a call doesn't connect, so you wait a bit and redial (waiting longer each time). Circuit breaker = after hearing "the number you are calling is switched off" 5 times, you stop trying for 30 seconds and call a different friend instead (backup provider). ๐Ÿ“ž

โœ… The safety & validation layer ยท ๐Ÿ—„ the data lake

โœ… Safety & validation
Every LLM reply is checked for structure (is it valid JSON with the right fields?), parsing and content (is it appropriate and within guidelines?). Bad replies are discarded and logged, and the results feed a feedback loop to improve prompts.
๐Ÿ—„ Data lake for learning
To keep improving, every service sends events (lesson started, answer submitted, mistake made) to a central event streaming platform, which lands them in a data lake on cloud object storage, in a modern open table format so big analysis jobs run reliably. Analysts and models learn from this to improve content and personalisation.
๐Ÿ” Worked example: validating the LLM's playlist
def validate_playlist(reply_text, candidate_ids):
    data = json.loads(reply_text)                      # 1. must be valid JSON (else retry/reroute)
    ids = data["question_ids"]
    assert 20 <= len(ids) <= 30                       # 2. right size
    assert set(ids) <= set(candidate_ids)             # 3. NO invented IDs allowed!
    assert len(ids) == len(set(ids))                  # 4. no duplicates
    return ids

validate_playlist('{"question_ids": ["q_88", "q_999999", ...]}', candidates)

Output:

AssertionError  (q_999999 was never in the candidate pool โ†’ the LLM made it up โ†’ rejected)

The most dangerous hallucination here is the LLM returning a question ID that doesn't exist. This check is cheap, exact and catches it every time.

4.7 Databases and data modelling

Different kinds of data have very different needs, so we use different databases for each, choosing the best fit for performance, scale and reliability.

How the data relates
QUESTIONS_STAGING
uuididPK
uuidjob_idFK
textstatus
jsonbcontent
STAGING โ”€โ”€promoted toโ”€โ”€โ–ถ QUESTION_BANK
PLAYLIST (Redis)
textuser_idkey
listlessons (question IDs)
PLAYLIST โ”€โ”€points toโ”€โ”€โ–ถ QUESTION_BANK
QUESTION_BANK
uuididPK
vectorembeddingindex
jsonbcontent
textlanguage
textdifficulty_level
SKILL_STRENGTH
uuiduser_idPK
textskill_idSK
intstrength_percent
LESSON_HISTORY โ”€โ”€used to calculateโ”€โ”€โ–ถ SKILL_STRENGTH
LESSON_HISTORY
uuiduser_idPK
textsession_id#lesson_idSK
intscore
timestampcompleted_at
LESSON_HISTORY โ”€โ”€refers toโ”€โ”€โ–ถ QUESTION_BANK
PK = partition/primary key ยท SK = sort key ยท FK = foreign key.

1. Learner progress: a write-heavy NoSQL store (DynamoDB or Cassandra)

At peak we expect ~90,000 writes per second of learner activity. That calls for a database built for massive write throughput, like DynamoDB or Cassandra. We split progress into two models: the raw history and a calculated summary.

๐Ÿ“œ lesson_history: every lesson ever completed

What: an append-only log (we only ever add rows, never change them) of every completed lesson. Access: written the moment a lesson ends; streamed to the data lake via DynamoDB Streams for model training.

FieldTypeDescription
user_idpartition keyWhich learner
session_id#lesson_idsort keyTwo IDs joined with "#", so a learner's lessons sort by session
scoreintThe learner's score
completed_attimestampWhen it finished
{ "user_id": "user_123",
  "session_id#lesson_id": "s_0912#l_44",
  "score": 80,
  "mistakes": ["q_17: ser vs estar"],
  "completed_at": "2026-11-10T19:42:05Z" }
๐Ÿ’ช skill_strength: how good the learner is at each skill

What: a summary table with the learner's current strength in each skill (e.g. "Spanish future tense: 72%"). Access: read constantly by the curator to choose difficulty; recalculated in the background from lesson_history, not on every answer.

FieldTypeDescription
user_idpartition keyWhich learner
skill_idsort key (text)e.g. skill_future_tense
strength_percentint0โ€“100
updated_attimestampLast recalculation
{ "user_id": "user_123",
  "skill_id": "skill_future_tense",
  "strength_percent": 72,
  "updated_at": "2026-11-10T20:00:00Z" }
Hot store vs cold store: where history lives over time
Lesson completed
write
๐Ÿ”ฅ Hot: DynamoDB + TTLLast 90 days onlyfast "already seen?" checks for the cold path
TTL deletes old rows automatically, for free
DynamoDB Streams (every write and delete)
Kinesis Firehosebatches โ†’ Parquet files
๐ŸงŠ Cold: S3 data lakeFull history (Parquet)model training ยท long-term analytics
โš ๏ธ Why not keep everything in DynamoDB?Keeping an endless, ever-growing log in a high-performance database is a money trap: you pay premium prices to store years of data you rarely read. So we keep only 90 days "hot". DynamoDB Streams captures every write (and every TTL delete), and Firehose batches them into Parquet files on S3, where storage is cheap.
๐Ÿง  Think of it likeโ€ฆHot store = the last three months' bills in your wallet (needed often). Cold store = years of bills in a file at home (needed once a year at tax time). Keep ten years of bills in your wallet and it bursts! ๐Ÿ‘›

2. Curated playlists: Redis lists

Each learner's ready-made playlist lives in a Redis list, with light RDB snapshots (Redis periodically saves a copy to disk) so a failed node can recover quickly. Redis answers in milliseconds, which is what makes lessons start in under 50 ms.

FieldTypeDescription
key: playlist:{user_id}textOne list per learner
valuelistUpcoming lessons, each a group of question IDs; served with LPOP

3. Questions awaiting review: questions_staging (PostgreSQL)

What: the holding area for AI-generated questions waiting for human review. Access: written by the generation pipeline; read by the review portal's dashboards.

FieldTypeDescription
idUUIDQuestion ID
job_idUUIDWhich generation job made it
difficulty_leveltextA1 โ€ฆ C2
languagetextLanguage being taught
contentJSONBThe question itself, as JSON
question_typetextfill in the blank, match, dialogueโ€ฆ
concept_tagstext[]Grammar or vocabulary concepts tested
statustextNEW / IN_REVIEW / ACCEPTED / REJECTED

4. The live question bank: question_bank (PostgreSQL + pgvector)

What: the single source of truth for all approved, live questions, with an embedding for each. Access: very read-heavy: by ID (warm path) or by tags and similarity (cold path and content creation). PostgreSQL + pgvector keeps structured data, flexible JSON and vectors in one database, so there's no separate vector database to run. Reads scale easily with read replicas; writes are light (a nightly batch).

FieldTypeDescription
idUUIDQuestion ID
difficulty_leveltextA1 โ€ฆ C2
languagetextLanguage
contentJSONBQuestion, options, answer, explanation
question_typetextFormat
concept_tagstext[]Concepts
embeddingvector(768), indexedFor "find similar questions"
๐Ÿ” Worked example: catching near-duplicate questions

Before a new question goes live, check whether the bank already has one that means almost the same thing:

SELECT id, content->>'text' AS text,
       1 - (embedding <=> :new_question_vec) AS similarity
FROM question_bank
WHERE language = 'Spanish' AND difficulty_level = 'A2'
ORDER BY embedding <=> :new_question_vec
LIMIT 3;

Output:

   id    |              text               | similarity
---------+---------------------------------+-----------
 q_5521  | El libro estรก ___ la mesa.      |      0.97   โ† near-duplicate, flag it
 q_8810  | La taza estรก ___ la mesa.       |      0.88
 q_3302  | El gato estรก ___ la silla.      |      0.81
๐Ÿš€ Going deeper: two kinds of vector indexpgvector offers two approximate-search indexes. IVFFlat groups vectors into clusters and searches only the nearest clusters: uses less memory. HNSW builds a multi-layer "shortcut" graph: usually faster with better accuracy, but uses more memory. Both trade a tiny bit of accuracy for big speed gains.
๐ŸŽฏ Interview tip"Polyglot persistence: write-heavy, key-based progress goes to DynamoDB (partitioned by user_id) with a 90-day TTL and Streams to S3; read-heavy content with duplicate detection goes to PostgreSQL + pgvector with read replicas; per-learner playlists live in Redis lists with atomic LPOP. If Redis is lost, personalisation dips for a while, but no learner loses any progress."

4.8 Deep dive: async generation, scaling and exact grading

RequirementHow the design meets it
Lesson generationAn offline "factory": LLMs create content in bulk, decoupled from learners; human experts review before anything goes live.
Adaptive curationPersonalised playlists prepared in advance in Redis (warm path); a rule-based fallback for learners without one (cold path).
High availabilityOrchestrator with retries, circuit breakers and rerouting to survive LLM outages.
Storing dataPostgreSQL + pgvector (content), DynamoDB (progress), Redis (playlists), S3 (history).
ScaleThis section: async worker patterns for generation spikes; read replicas for the bank.
Grading accuracyThis section: function calling so the LLM never "guesses" whether an answer is right.

โณ Asynchronous processing for content generation

When an admin asks for hundreds of questions, a normal blocking request would freeze their screen and almost certainly time out. Instead, we decouple the request from the work with a message queue:

1. Submit the job
The admin asks for 100 questions; the portal calls the API.
2. Accept and split
The lesson generation service validates the request, saves a job record with a unique job_id, and replies 202 Accepted immediately. Workers handle up to 10 questions at a time, so the 100-question job is split into 10 messages (this is called fan-out) on generation_jobs_queue.
3. The queue as a buffer
The queue decouples the service from the workers, absorbs spikes (backpressure), and keeps messages safe if a worker crashes, so no request is lost.
4. Generation workers
Workers inside the orchestrator take messages, call the LLM to write questions, and put the results on generation_results_queue.
5. Save to staging
A database worker takes results and inserts them into questions_staging. When all 10 child batches are done, the parent job is marked COMPLETED with a results URL.
6. The admin checks in
The admin's screen stays usable and polls the status endpoint (GET โ€ฆ/question-generation-jobs/{job_id}) to show "Processingโ€ฆ" then "Completed".

Hybrid rule: for tiny requests (5 questions or fewer), skip all this and answer synchronously. The queue's overhead isn't worth it, and the admin wants instant results.

๐ŸŽฌ Async question generation (press Play)
๐ŸŽฎ Try it: submit a generation job

Try 3 (sync) and 100 (async fan-out). Press "Check status" while it runs.

โ€”
๐Ÿง  Think of it likeโ€ฆFor 1,000 rotis at a wedding, you don't hire one cook. You hire 10 cooks (workers) and give each 100 (fan-out). The manager (generation service) ticks a register as each cook finishes, and only when all 10 say "done" does he announce "food is ready!" (COMPLETED). ๐Ÿซ“
๐Ÿš€ Going deeper: what can go wrong with queues

๐Ÿ“ˆ Scaling

Two sides to scale: the services (compute) and the data (storage and throughput).

๐Ÿงฑ Scaling services
Scale horizontally: run more copies. The curation service auto-scales on incoming API traffic. The orchestrator workers auto-scale on two signals: the number of messages waiting in the queue, and CPU use. More waiting messages โ†’ more workers.
๐Ÿ—„ Scaling data
Question bank (PostgreSQL): read-heavy, so cache each question by ID and add read replicas.
Progress (DynamoDB): scales horizontally for heavy writes; reads are spiky when learners fetch their next exercise.
Playlists (Redis): a Redis cluster. Even if the whole cluster is lost, no learner loses progress or history (that's in DynamoDB); the pipeline simply rebuilds playlists. Worst case: lessons are a bit slower and less personalised for a while (cold path).
๐Ÿ”— Scaling our dependence on LLM providers (the orchestrator's job)
Multiple providers
Integrate several LLM providers so there's no single point of failure; breakers, retries and rerouting keep traffic flowing.
Tiered models
Route by urgency and complexity: simple curation โ†’ small, cheap model; reserve top-tier models for premium conversation features.
Breakers everywhere
Wrap every provider in its own circuit breaker. On a latency spike or error burst, trip it and reroute to a fast backup model, or to a non-AI response (rule-based selection).

๐Ÿงฎ Exact grading with function calling

LLMs are probabilistic and can stumble on precise checks. Asking an LLM "is this answer correct?" will occasionally get a wrong verdict, and marking a correct answer wrong is a terrible experience for a learner. Instead, use function calling: the LLM is given a tool like check_answer(question_id, user_answer). The tool runs ordinary, deterministic code (string comparison, or maths in a sandbox for numeric answers) and returns a plain true/false. The LLM then uses that fact to write a friendly, encouraging message. Result: exact grading plus the warm, conversational tone of AI.

๐ŸŽฎ Try it: the tool decides, the LLM only explains
She ___ to the store yesterday.
๐Ÿ” Worked example: grading with a tool call
ANSWER_KEY = {"q_12483240": "went"}

def check_answer(question_id, user_answer):                 # deterministic: no AI involved
    correct = ANSWER_KEY[question_id]
    return {"is_correct": user_answer.strip().lower() == correct, "correct": correct}

TUTOR = "You are a friendly English tutor. Give one short line of feedback."
tools = [{"type": "function",                      # Responses API: name/parameters sit directly here
    "name": "check_answer",
    "description": "Check a learner's answer against the answer key. Always use this; never judge yourself.",
    "parameters": {"type": "object", "properties": {
        "question_id": {"type": "string"}, "user_answer": {"type": "string"}},
        "required": ["question_id", "user_answer"]}}]

r = client.responses.create(                         # tool calling on gpt-6.1-terra needs the Responses API
    model="gpt-6.1-terra", instructions=TUTOR, tools=tools,
    input="Question q_12483240: 'She ___ to the store yesterday.' My answer: go")
call = next(item for item in r.output if item.type == "function_call")   # the model asked for the tool
result = check_answer(**json.loads(call.arguments))
print("Tool result:", result)

final = client.responses.create(
    model="gpt-6.1-terra", instructions=TUTOR, tools=tools,
    previous_response_id=r.id,                       # continue the same conversation
    input=[{"type": "function_call_output", "call_id": call.call_id, "output": json.dumps(result)}])
print(final.output_text)

Output:

Tool result: {'is_correct': False, 'correct': 'went'}
Almost! Because of "yesterday" we need the past tense: "She went to the store yesterday." ๐Ÿ˜Š
Code note (GPT-6 API)On gpt-6.1-terra, tool calling only works through the Responses API, so this example uses client.responses.create: tools are listed with name and parameters directly (no nested "function" key), the tool request arrives as an item of type function_call in r.output, and we send the tool's result back as a function_call_output linked to the earlier turn with previous_response_id. The question-generation example earlier uses Structured Outputs (.parse with a Pydantic class) so every generated question is guaranteed to have the right fields.
โš ๏ธ Where this works, and where it doesn'tDeterministic checking is perfect wherever there is one exact right answer: multiple choice, fill-in-the-blank, numeric answers. For open answers like free-text translation ("the cat sleeps on the bed" has many correct versions), you need LLM-based grading with a clear rubric, and "100% exact" is no longer guaranteed.
๐Ÿง  Think of it likeโ€ฆThe teacher (LLM) says kindly, "Great effort, just one small mistake!", but the marks come from the answer key (the tool), never from her mood. โœ”๏ธ

4.9 Testing

๐Ÿ‹๏ธ Load testing
Goal: prove auto-scaling really works. Use a tool like k6 or JMeter to simulate thousands of learners starting lessons at once, and ramp up (10K โ†’ 50K โ†’ 100K virtual users) to find the breaking point, measure wait times and tune auto-scaling rules.
๐ŸŽฏ AI quality regression
LLM behaviour can "drift" when prompts or models change. Keep a dataset of hundreds of typical inputs with ideal outputs (questions to generate, playlists to sequence, feedback to write), and run it on every prompt tweak or model upgrade to confirm answers stay accurate, safe and in the right tone.
๐Ÿ” Worked example: a small k6 load test
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = { stages: [
  { duration: '5m',  target: 10000 },     // ramp to 10K virtual learners
  { duration: '10m', target: 50000 },
  { duration: '10m', target: 100000 } ] };

export default function () {
  const res = http.post('https://api.example-learn.app/api/v1/lesson-sessions',
    JSON.stringify({ skill_id: 'skill_past_tense_verbs', type: 'PRACTICE' }),
    { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${__ENV.TOKEN}` } });
  check(res, { 'status is 200': r => r.status === 200,
               'under 500 ms':  r => r.timings.duration < 500 });
  sleep(1);                                     // a learner "reads" for a second
}

Summary at the end (illustrative):

โœ“ status is 200 ......... 99.98%
โœ— under 500 ms .......... 98.70%   โ† 1.3% slower than target at 100K users
http_req_duration ....... p(95)=290ms  p(99)=640ms

Reading this: we meet the 500 ms target until about 100K users, then P99 slips. Next step: find the bottleneck (cache hit rate? database? too few curation instances?) and tune auto-scaling.

๐Ÿ’ Chaos testing: break things on purpose

While the system is under load, deliberately inject failures (this practice is called chaos engineering) to check that the safety nets really work:

ExperimentWhat we expect
Kill a random curation-service instanceNothing breaks: the service is stateless, so other instances keep serving and the load balancer routes around it.
Add network delay between services and RedisTimeouts and retries behave correctly; the cold path takes over if Redis is too slow.
Wipe the Redis clusterLearners still get lessons via the cold path; no progress is lost; playlists refill.
Make the LLM provider slow or return errorsThe circuit breaker trips and traffic fails over to a backup model or rule-based selection.
Pause the queue consumers (workers)The queue-depth alert fires; nothing is lost; work resumes when workers return.

4.10 Monitoring and alerts

SignalWhy it matters
โฑ P99 lesson-serving latencyEnd-to-end time to serve a lesson: the main measure of user experience.
๐ŸŽฏ Cache hit rateCritical alert. If the Redis hit rate drops, more learners are on the slower, less personalised cold path. Investigate right away.
๐Ÿ“ฅ Queue depthPrimary alert. If waiting messages keep growing, workers can't keep up: scale out.
โณ End-to-end job durationP99 time from "job queued" to "playlist ready in cache": reveals slow LLM or database steps.
๐Ÿฉบ Worker & dependency healthError rates of workers and outside services. A spike in LLM provider errors means fallbacks are probably active.
๐Ÿš— TrafficLoad on the system, especially requests per second to downstream dependencies.
โŒ ErrorsHTTP 5xx rates for internal services and external APIs (especially the LLM provider). A sudden jump means trouble.
๐Ÿ›ข SaturationHow close we are to capacity: server CPU, and especially Redis memory.

All of these go into one central observability platform (such as Grafana or Datadog), so the whole team sees the same real-time picture.

๐ŸŒ Learning-quality metrics worth tracking tooLesson completion rate ยท next-day return rate (streaks) ยท accuracy trend per skill (is difficulty well calibrated?) ยท rejection rate in human review (is generation quality slipping?) ยท share of lessons served by the cold path (how many learners got no personalisation).

4.11 Summary

LLMs are powerful for learning platforms in both directions: creating content and personalising it. On the creation side, LLMs speed up lesson writing while experts review and refine to guarantee quality. On the personalisation side, learners get lessons that match their pace and style.

The common thread in both flows is retrieval and context injection: fetching the learner's history to personalise the next lesson, or grounding a generated exercise in the approved curriculum. You'll see the same pattern in AI-powered e-commerce search, where the system adapts to a shopper's intent and behaviour the way this app adapts to a learner.

The complete system
๐Ÿญ Offline (quality)
Admin portal โ†’ gatewayGeneration servicesync if โ‰ค 5 ยท async fan-out ร— 10SQS โ†’ orchestrator workers โ†’ LLMquestions_stagingHuman reviewNightly ingestion + checks
โšก Online (speed)
App โ†’ gateway โ†’ curatorRedis playlist LPOPwarm path, under 50 msRule-based fallbackcold pathrefill queue โ†’ worker โ†’ SQS โ†’ LLM sequencingTool-based grading
๐Ÿ—„ Data
PostgreSQL + pgvectorquestion_bank ยท staging ยท read replicasDynamoDBlesson_history (90-day TTL) ยท skill_strengthS3 data lake (Parquet)Redis cluster

๐ŸŽฏ Interview framework: "Design Duolingo with AI" in 45 minutes

TimeWhat to doKey lines to say
0โ€“5 minRequirements"Two jobs: LLM content generation and adaptive curation. Scoring is out of scope. Safety is non-negotiable: teaching wrong grammar destroys trust."
5โ€“10NFRs + numbers"P99 under 500 ms. 50M DAU ร— 3 lessons ร— 10 questions โ‰ˆ 17K questions/s, ร— 3 calls โ‰ˆ 52K RPS, ร— 5 at peak โ‰ˆ 260K, + 35% โ‰ˆ 350K RPS, about 90K writes/s. So an LLM call per request is impossible."
10โ€“15Core insight"Separate quality from real time: an offline factory (LLM + human review) and an online tutor that only picks from approved content."
15โ€“25High-level design"Offline: admin API โ†’ generation service โ†’ SQS โ†’ workers โ†’ staging โ†’ review โ†’ nightly ingestion. Online: curator โ†’ Redis LPOP (warm) or rule-based (cold) โ†’ async refill via queue + LLM sequencing."
25โ€“30Data"DynamoDB for progress (90-day TTL + Streams to S3 Parquet), PostgreSQL + pgvector for the bank, Redis lists for playlists."
30โ€“40Deep diveAsync fan-out with polling, sync for 5 or fewer; resilience (3 retries + backoff, breaker at 5 failures / 30 s half-open, tiered rerouting, non-AI fallback); scaling (queue-depth auto-scaling, read replicas, losing Redis loses no data); tool-based grading.
40โ€“45Quality + operations"k6 load tests, chaos experiments (kill instances, add latency, degrade the LLM), a regression suite on every prompt or model change; alerts on cache hit rate, queue depth, P99, job duration, 5xx and Redis memory."
๐Ÿš€ Trade-offs worth saying out loud

๐Ÿ“‹ Cheat sheet

Numbers
50M DAU ยท 3 lessons ยท 10 questions ยท โ‰ˆ 17,400 questions/s ยท ร— 3 calls โ‰ˆ 52K ยท ร— 5 โ‰ˆ 260K ยท + 20% + 15% โ‰ˆ 350K RPS ยท โ‰ˆ 90K writes/s ยท P99 < 500 ms ยท lesson start < 50 ms ยท 50 languages (250 / 70 lessons) ยท refill when < 5 left ยท playlist of 20โ€“30 ยท last 50 lessons as context ยท 90-day TTL ยท sync if โ‰ค 5 ยท 10 per worker batch ยท 3 retries ยท breaker: 5 failures or 20% in 60 s, 30 s cooldown
Offline factory
Request (language, level, topic, format) โ†’ gateway โ†’ generation service โ†’ generation_jobs_queue โ†’ orchestrator workers โ†’ LLM โ†’ generation_results_queue โ†’ DB worker โ†’ questions_staging โ†’ human review โ†’ nightly job + checks โ†’ question_bank
Online tutor
Warm: Redis LPOP โ†’ content from the bank. Cold: LPOP returns nil โ†’ rule-based SQL (level + language โˆ’ recently seen) โ†’ serve + async refill. Refill: event โ†’ refill_check_queue โ†’ buffer check โ†’ context + candidates โ†’ SQS โ†’ LLM sequencing โ†’ Redis (and DB).
Orchestrator
Model router (simple โ†’ small in-house model; complex โ†’ strong mid-tier; premium โ†’ top tier) ยท prompt layer ยท resilience (retries + backoff, breaker, tiered rerouting, context preserved) ยท safety & validation (no invented IDs)
Data
DynamoDB: lesson_history (user_id PK, session#lesson SK), skill_strength (user_id PK, skill_id SK) ยท Redis lists + RDB snapshots ยท PostgreSQL + pgvector: staging, bank (vector 768) ยท S3 Parquet via Streams + Firehose
Quality & operations
Tool-based grading ยท k6 / JMeter load tests ยท chaos experiments ยท regression set ยท alerts: P99, cache hit rate, queue depth, job duration, dependency health, traffic, 5xx, saturation (Redis memory) ยท Grafana / Datadog
โœ… Key takeaways

๐Ÿ“ Quiz (click to reveal)

Q1. Why not have the LLM create lessons live for each learner?Safety and quality risk (errors, inappropriate content), plus latency and cost: at ~350K RPS, an LLM call per request is impossible. So content is generated offline and reviewed by humans, and the online path only selects from approved content.
Q2. What's the difference between the warm and cold paths?Warm: the learner's Redis playlist has ready lessons โ†’ atomic LPOP โ†’ served instantly. Cold: LPOP returns nil (new or returning learner) โ†’ skip the LLM, run a rule-based query (same level and language, excluding recently seen) โ†’ serve one lesson and trigger an async refill.
Q3. Why must LPOP be atomic?It takes and removes the item in one step, so the same lesson can never be served twice, even if the learner opens the app on two devices at the same moment.
Q4. When and how does a playlist get refilled?When a lesson is completed (or another activity happens), {userId} goes onto refill_check_queue. A worker checks the buffer (fewer than 5 left?), gathers context (last 50 lessons + a few hundred unseen candidates), and sends it via SQS to the orchestrator, which asks the LLM to choose and order 20โ€“30 lessons and pushes them to Redis. A 5-minute scan catches anything missed.
Q5. How is a 100-question admin request processed?A job record is created (PENDING) and 202 Accepted + job_id is returned. The job fans out into 10 messages of 10 on generation_jobs_queue; workers call the LLM and publish to generation_results_queue; a DB worker inserts into questions_staging; when all 10 batches finish, the job becomes COMPLETED with a results URL. The admin polls meanwhile. For 5 or fewer questions, it's synchronous.
Q6. Name the three circuit-breaker states and the thresholds used here.Closed (normal); open (after 5 consecutive server errors or a 20% error rate within 60 s: stop traffic and reroute); half-open (after 30 s, send one test request: success โ†’ closed, failure โ†’ open).
Q7. Why not keep all lesson history in DynamoDB forever?An endlessly growing log in a premium database is a money trap. Keep 90 days hot (with TTL) for fast checks; stream every change via DynamoDB Streams โ†’ Kinesis Firehose โ†’ Parquet files on S3 for cheap long-term storage and training.
Q8. What happens if the whole Redis cluster is lost?No learner loses progress or history (that's in DynamoDB). Learners are served via the cold path while the pipeline rebuilds playlists; lessons are slightly slower and less personalised for a while.
Q9. Why use function calling for grading?LLMs are probabilistic and can misjudge exact answers. A deterministic tool returns true/false from the answer key; the LLM only writes friendly feedback. That gives exact grading for questions with one correct answer.
Q10. Which two alerts matter most, and why?Queue depth (workers can't keep up โ†’ scale out) and cache hit rate (more learners falling to the slower, less personalised cold path).
Q11. What are the three model-router rules?Simple grammar check โ†’ small in-house model; complex conversation โ†’ strong mid-tier model; premium deep explanation โ†’ top-tier model.
Q12. The LLM returns a playlist containing a question ID that wasn't in the candidate pool. What should happen?The validation layer rejects it: every returned ID must come from the candidates provided. Then retry, reroute, or fall back to rule-based selection.