Designing an Adaptive Learning App
A language-learning app like Duolingo that uses LLMs to create lessons and personalise them for every learner
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.
๐ 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.
๐ฏ Next: Unit 3, Travel
"Translate: the cat"
+10 XP
so it's "el", not "la"
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?
| Requirement | Target / meaning |
|---|---|
| โก Low latency | From submitting an answer to seeing feedback or the next question: P99 under 500 ms. |
| ๐ฏ High accuracy | A matter of trust: no wrong answers, no confusing explanations. |
| ๐ก High availability | An LLM provider outage must not take the whole app down. |
| ๐ค Personalised | Lessons fit the learner: not too hard, not too easy. |
| ๐ธ Cost-effective | LLM calls are expensive, so we need a clear strategy for when and where to use them. |
| ๐ Scalable | Handle peaks when busy hours in different time zones overlap. |
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.
- Questions served per day: 50M users ร 3 lessons ร 10 questions = 1.5 billion questions/day.
- Per second: 1.5 billion รท 86,400 seconds in a day โ 17,400 questions per second.
- API calls per question: at least 3:
GETthe question,POSTthe answer,GETthe feedback. So 17,400 ร 3 โ 52,000 RPS on average. - Peak (ร5): traffic isn't flat; evenings and overlapping time zones bring spikes. 52K ร 5 โ 260,000 RPS.
- Extra features: conversation practice (+20%) and real-time analytics (+15%): 260K ร 1.35 โ ~350,000 RPS at peak.
- 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
Peak writes โ one third of the peak API RPS (before extras):
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:
๐ 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." } ] }๐ฎ Try it: use the buttons in a sensible order (and in a silly order, to see the rules)
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:
Can be slow. Quality comes first.
Only picks from already-approved questions: fast and safe.
๐ญ 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.
๐ฑ 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.
A good generation prompt is precise about the count, the level, the theme, the answer format and the output shape:
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.)
๐ 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
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.
โก 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.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 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.
1. Cache miss
The learner asks for a lesson; RedisLPOP 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.-- 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.
- Decoupling: the personalisation engine is separated from what learners click, so the LLM sees steady, predictable load instead of sudden bursts.
- Buffering: keeping 20โ30 lessons ready means short hiccups in the background pipeline are invisible to learners.
- 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.
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.
- Duplicate refills: several "refill check" messages for the same learner can arrive together. Use a per-learner lock (for example Redis
SET refill:user_123 1 NX EX 60, which only succeeds if no lock exists) so only one LLM job runs per learner. - Stale playlists: if a learner jumps a level, the ready playlist may now be too easy. Give playlists a version or expiry, or clear them when a skill level changes.
- Memory estimate: 50M learners ร 30 IDs ร ~36 bytes โ 54 GB of raw data, before Redis overhead. That needs a sharded Redis cluster; keeping playlists only for recently active learners (with a TTL) shrinks it a lot.
- Cost win: one LLM call sequences 20โ30 lessons, so it's 20โ30ร cheaper than calling per question.
๐ง 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
| Rule | Condition | Route to |
|---|---|---|
| Rule 1: simple task | A simple grammar check? | A small, fast model hosted in-house (e.g. Llama 3.1 8B) |
| Rule 2: complex task | Part of a complex conversation practice? | A strong mid-tier model (e.g. Claude Sonnet 5.5 or gpt-6.1-terra) |
| Rule 3: premium feature | A 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 state | When | What the orchestrator does |
|---|---|---|
| ๐ข Closed (normal) | Everything is healthy | All 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)
โ 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.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.
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.
| Field | Type | Description |
|---|---|---|
| user_id | partition key | Which learner |
| session_id#lesson_id | sort key | Two IDs joined with "#", so a learner's lessons sort by session |
| score | int | The learner's score |
| completed_at | timestamp | When 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.
| Field | Type | Description |
|---|---|---|
| user_id | partition key | Which learner |
| skill_id | sort key (text) | e.g. skill_future_tense |
| strength_percent | int | 0โ100 |
| updated_at | timestamp | Last recalculation |
{ "user_id": "user_123",
"skill_id": "skill_future_tense",
"strength_percent": 72,
"updated_at": "2026-11-10T20:00:00Z" }TTL deletes old rows automatically, for free
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.
| Field | Type | Description |
|---|---|---|
key: playlist:{user_id} | text | One list per learner |
| value | list | Upcoming 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.
| Field | Type | Description |
|---|---|---|
| id | UUID | Question ID |
| job_id | UUID | Which generation job made it |
| difficulty_level | text | A1 โฆ C2 |
| language | text | Language being taught |
| content | JSONB | The question itself, as JSON |
| question_type | text | fill in the blank, match, dialogueโฆ |
| concept_tags | text[] | Grammar or vocabulary concepts tested |
| status | text | NEW / 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).
| Field | Type | Description |
|---|---|---|
| id | UUID | Question ID |
| difficulty_level | text | A1 โฆ C2 |
| language | text | Language |
| content | JSONB | Question, options, answer, explanation |
| question_type | text | Format |
| concept_tags | text[] | Concepts |
| embedding | vector(768), indexed | For "find similar 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.814.8 Deep dive: async generation, scaling and exact grading
| Requirement | How the design meets it |
|---|---|
| Lesson generation | An offline "factory": LLMs create content in bulk, decoupled from learners; human experts review before anything goes live. |
| Adaptive curation | Personalised playlists prepared in advance in Redis (warm path); a rule-based fallback for learners without one (cold path). |
| High availability | Orchestrator with retries, circuit breakers and rerouting to survive LLM outages. |
| Storing data | PostgreSQL + pgvector (content), DynamoDB (progress), Redis (playlists), S3 (history). |
| Scale | This section: async worker patterns for generation spikes; read replicas for the bank. |
| Grading accuracy | This 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) ongeneration_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 ongeneration_results_queue.5. Save to staging
A database worker takes results and inserts them intoquestions_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.
๐ฎ Try it: submit a generation job
Try 3 (sync) and 100 (async fan-out). Press "Check status" while it runs.
- Duplicate delivery: SQS may deliver the same message twice ("at-least-once"). Workers must be idempotent: if batch 7 was already processed, skip it. Otherwise you get 110 questions instead of 100.
- Poison messages: a batch that fails every time should go to a dead-letter queue (DLQ) for inspection, and the job should be marked PARTIAL or FAILED instead of retrying forever.
- Counting completions: increment "batches done" atomically (a database transaction or conditional update), so two workers finishing at once can't both write "10/10" wrongly.
- Semantic de-duplication: use pgvector to flag new questions that are near-identical to ones already in the bank.
๐ 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
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." ๐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.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.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:
| Experiment | What we expect |
|---|---|
| Kill a random curation-service instance | Nothing breaks: the service is stateless, so other instances keep serving and the load balancer routes around it. |
| Add network delay between services and Redis | Timeouts and retries behave correctly; the cold path takes over if Redis is too slow. |
| Wipe the Redis cluster | Learners still get lessons via the cold path; no progress is lost; playlists refill. |
| Make the LLM provider slow or return errors | The 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
| Signal | Why it matters |
|---|---|
| โฑ P99 lesson-serving latency | End-to-end time to serve a lesson: the main measure of user experience. |
| ๐ฏ Cache hit rate | Critical alert. If the Redis hit rate drops, more learners are on the slower, less personalised cold path. Investigate right away. |
| ๐ฅ Queue depth | Primary alert. If waiting messages keep growing, workers can't keep up: scale out. |
| โณ End-to-end job duration | P99 time from "job queued" to "playlist ready in cache": reveals slow LLM or database steps. |
| ๐ฉบ Worker & dependency health | Error rates of workers and outside services. A spike in LLM provider errors means fallbacks are probably active. |
| ๐ Traffic | Load on the system, especially requests per second to downstream dependencies. |
| โ Errors | HTTP 5xx rates for internal services and external APIs (especially the LLM provider). A sudden jump means trouble. |
| ๐ข Saturation | How 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.
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.
๐ฏ Interview framework: "Design Duolingo with AI" in 45 minutes
| Time | What to do | Key lines to say |
|---|---|---|
| 0โ5 min | Requirements | "Two jobs: LLM content generation and adaptive curation. Scoring is out of scope. Safety is non-negotiable: teaching wrong grammar destroys trust." |
| 5โ10 | NFRs + 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โ15 | Core insight | "Separate quality from real time: an offline factory (LLM + human review) and an online tutor that only picks from approved content." |
| 15โ25 | High-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โ30 | Data | "DynamoDB for progress (90-day TTL + Streams to S3 Parquet), PostgreSQL + pgvector for the bank, Redis lists for playlists." |
| 30โ40 | Deep dive | Async 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โ45 | Quality + 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." |
- Freshness vs latency: playlists are prepared in advance, so a mistake the learner made a minute ago isn't reflected immediately. Event-driven refills and a small buffer shrink this gap.
- Personalisation vs cost: a bigger buffer means fewer LLM calls but a higher risk of stale playlists; a smaller one is fresher but costs more.
- Human review throughput: experts guarantee quality but can become a bottleneck. Batch approvals, AI pre-scoring, and deep review only for low-confidence items help.
- Graceful degradation: LLM down โ rule-based; Redis down โ cold path; even with both down, learners keep getting lessons.
๐ 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 cooldownOffline 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_bankOnline 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 + FirehoseQuality & 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- Never put a slow, costly LLM call on the live path at 350K RPS; prepare results in advance.
- Separate the offline quality factory (LLM + human review) from the online tutor (approved content only).
- Warm path: atomic LPOP from a ready playlist. Cold path: fast rule-based query, then refill.
- Pick each database for its job: DynamoDB for heavy writes, PostgreSQL + pgvector for content, Redis for speed, S3 for history.
- Let deterministic tools grade; let the LLM explain kindly.
- Test by breaking things, and alert on cache hit rate and queue depth first.
๐ 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.