Frontend System Design18 min readPremium

Design Duolingo – Frontend System Design

69. Design Duolingo

We’ll walk through the frontend system design for a language-learning session like Duolingo: a machine that grades in a few milliseconds, audio that never stalls the next tap, a streak that respects the learner’s midnight, and packs that still work in airplane mode. Celebration is an overlay, not a state. Hearts and streak are server-repaired counters.

This is not a quiz widget. The interviewer will say “fifteen cards, offline, five hearts, Arabic prompts in an English shell, and a learner who taps faster than your animation.” Treating Check as await celebrate() falls apart.

Problem Statement

Design the frontend for a language-learning session like Duolingo.

Requirements:

  • A lesson of mixed exercise types: tap a translation, type a sentence, listen, match pairs, speak
  • Immediate local grading with a small typo window
  • Spaced repetition: due cards come back, new cards are capped
  • Short audio clips on almost every card, including offline
  • Hearts that run out, streaks that survive a missed day only with a freeze
  • Full lessons on a plane, then a clean sync
  • UI chrome in one language, course content in another, including RTL

Describe the session state machine, the card model, audio, offline packs, and how streaks and hearts stay honest.

Interviewers want a one-frame input loop after a local grade, a due index instead of a full-deck scan, offline play that cannot invent XP, and direction isolated so Arabic prompts do not mirror an English Back button.


Clarifying Questions

# Question Interviewer’s Answer
1 Web, native, or both? A PWA that also wraps as a native shell. Same session engine.
2 How long is a lesson? 10–20 cards, about two minutes when the learner is fast.
3 Must it work fully offline? Yes for downloaded skills. Shop, leagues, and new path unlocks wait for a network.
4 Hearts and Super (unlimited)? Five hearts, refill on a timer or with gems. Super is a server flag that skips the decrement.
5 How do we grade typed answers? Normalize, then exact match. One-edit typos on long tokens still count as correct.
6 Speaking exercises? Nice to have. On the web, treat on-device recognition as a fallback and send audio to ASR when online.
7 Who owns streak midnight? The learner’s IANA timezone, not the device clock and not UTC.

Question 2 is the latency budget: a 400ms lock after every card is six dead seconds. Question 3 means packs and an outbox, not a spinner on Check. Question 7 is the streak trap. UTC midnight is late afternoon in California.


Requirements

Functional

  • Start a lesson from a skill. Mix new cards and due reviews.
  • Grade tap, type, listen, and match locally. Reveal the answer. Continue.
  • Play a short clip on listen cards and from a speaker button. Prefetch the next clips.
  • Spend a heart on a miss unless Super is on. End the session at zero.
  • Qualify a streak on the first completed session of the local day. Spend a freeze on a gap.
  • Download a skill for offline. Queue grades until the device is back.
  • Render prompts in the target language’s direction. Keep chrome in the UI language.

Non-Functional

  • Check to revealed in well under 16ms on a mid-range phone. No network on that path.
  • Continue unlocks when the outbox write commits. Overlays never hold the machine.
  • A fifteen-card session stays at 60fps. Celebrating must not thrash layout.
  • Offline lessons survive a tab close. Outbox and review state share one IndexedDB transaction.
  • The server repairs hearts, XP, and streak. The client never goes negative and never invents a day.
  • Respect prefers-reduced-motion. Every exercise has a keyboard path.

The number that shapes the design is the input loop, not the animation. Grade, persist, reveal, unlock.

Napkin Math

Metric Estimate Calculation So what?
Cards per session 15 Typical skill practice Any per-card wait is multiplied by 15.
Blocked celebration 6 s 15 × 400ms overlay A fifth of a two-minute lesson is dead air.
Local grade ~8 ms Normalize + Levenshtein on a short string Fits in one frame. Do not put a fetch here.
Due deck 2,000 cards A year of daily practice Index dueAt. Never scan the table.
Lesson pack ~1.5 MB 20 cards + 20 × 60 KB Opus One skill download. Cache audio by hash.
Clip start < 50 ms Decoded AudioBuffer already in memory HTMLAudio with a cold URL misses the prompt.

Architecture

Duolingo frontend architecture: UI shell, session engine, spaced-repetition scheduler, audio service, offline pack store, outbox, and progress servers

Chrome and the lesson must not share a store that re-renders the path mid-card.

Layer Owns Runs on Talks to
UI Shell Path, shop, leagues, HUD React, main thread Reads a cached profile, sends “start lesson”
Session Engine Phase, draft, grades Plain TypeScript, main thread Grader, scheduler, overlay, outbox
Card Scheduler Due index, new cap, interleave Main thread + IndexedDB Pack store, review state
Audio Prefetch, decoded clips Web Audio CDN / Cache Storage
Offline Packs, outbox, service worker IndexedDB + SW Lesson API, Progress API

React mounts the lesson view. It does not own the phase. The session engine is a small store: intents in, a snapshot out. That keeps Check from tearing through the path and the shop.

“The lesson is a state machine next to React, not a tree of useState. Check writes a grade and unlocks Continue. The owl is a side effect. Hearts and streak are a cached profile the server can overwrite.”

A module-level store plus useSyncExternalStore is enough. Chrome can be stale after a flush. The card on screen cannot.


Data Model

Duolingo data model: Course, Card, ReviewState, Session, Profile, OutboxItem, and LessonPack

Cards and review state are local-first: a grade still updates the schedule if hearts later bounce. Hearts, streak, XP, and freezes are a cached profile: optimistic on screen, repaired on every flush.


type ExerciseKind = "tap" | "translate" | "listen" | "speak" | "match";
type Dir = "ltr" | "rtl";

interface Card {
  readonly id: string;
  readonly skillId: string;
  readonly kind: ExerciseKind;
  readonly prompt: LocalizedText;
  readonly accepted: readonly string[];
  readonly audioHash?: string;
  readonly choices?: readonly string[];
}

interface ReviewState {
  readonly cardId: string;
  readonly ease: number;
  readonly intervalDays: number;
  readonly dueAt: number;
  readonly reps: number;
  readonly lapses: number;
}

interface Profile {
  readonly hearts: number;
  readonly refillAt: number | null;
  readonly streak: number;
  readonly lastQualifiedLocalDate: string;
  readonly timezone: string;
  readonly freezes: number;
  readonly xp: number;
  readonly superActive: boolean;
  readonly serverRev: number;
}

interface OutboxItem {
  readonly id: string;
  readonly kind: "grade" | "session_complete";
  readonly sessionId: string;
  readonly cardId?: string;
  readonly quality?: 0 | 1 | 2 | 3 | 4 | 5;
  readonly clientTs: number;
}

interface LessonPack {
  readonly skillId: string;
  readonly version: number;
  readonly cards: readonly Card[];
  readonly audio: ReadonlyMap<string, Blob>;
}

Four choices are worth defending.

Accepted answers are stored normalized. The pack compiler lowercases, applies NFC, strips punctuation the language does not need, and collapses whitespace. Runtime grading is a comparison plus a small typo window.

Audio is a content hash, not a URL. The same clip can appear in three skills. The pack store and the service worker key on the hash, so a re-download does not duplicate 60 KB of Opus.

Session ids are client-generated UUIDs. Offline start cannot ask the server for an id. Flush is idempotent on sessionId, so a retry does not award XP twice.

Profile carries serverRev. The client only adopts a repaired profile with a higher rev. That stops a stale tab from clobbering a newer phone.


Lesson Session State Machine

Duolingo lesson states: loading, prompting, answering, grading, revealed, complete, and blocked for missing pack or zero hearts

Seven phases. Celebration is not among them.


type Phase =
  | { type: "loading" }
  | { type: "prompting"; index: number }
  | { type: "answering"; index: number; draft: Draft }
  | { type: "grading"; index: number; requestId: string }
  | { type: "revealed"; index: number; grade: Grade }
  | { type: "complete"; summary: SessionSummary }
  | { type: "blocked"; reason: "out_of_hearts" | "pack_missing" };

type Intent =
  | { type: "pack_ready"; queue: string[] }
  | { type: "input"; draft: Draft }
  | { type: "check" }
  | { type: "graded"; grade: Grade }
  | { type: "continue" };

loading reads the pack and the due index. If the skill was never downloaded and there is no network, go to blocked: pack_missing with a download CTA, not a spinner that never ends.

prompting shows the card with an empty draft. Input is unlocked. Prefetch the next two clips here, not after the learner is already staring at Continue.

answering is prompting plus a non-empty draft. Check is enabled only when the draft is valid. Empty Check is a no-op, not a heart.

grading is the only short lock, so a double-tap cannot enqueue two grades. Normalize, compare, write the outbox and the new ReviewState in one IndexedDB transaction, then emit graded. If that write takes more than a frame you have an IDB problem, not an animation problem.

revealed shows correct or wrong, enables Continue immediately, and decrements the cached heart count on a miss. The overlay starts as a side effect. Continue does not wait for animationend.

From revealed you go to the next prompt, to complete when the queue is empty, or to blocked: out_of_hearts at zero. Complete writes a session_complete outbox row. XP on the HUD stays pending until flush returns the repaired profile.

A junior machine inserts celebrating and transitions on a timer. That couples learning to motion. A screen reader, a reduced-motion user, and a speed-runner all pay for the owl.


The Input Loop

Sequence diagram of a Duolingo card: local grade, outbox write, overlay, immediate Continue, prefetch, and later flush to the progress API

Timeline comparing a lesson loop that locks input during a 400ms celebration with a tight loop that enables Continue immediately while the overlay plays

Two commands drive the loop, and both live in the session view model.

  • Check only works in answering. It dispatches check synchronously, which moves the machine to grading and blocks a second tap. It grades the draft locally and computes the card’s next ReviewState. Then it writes three things in one IndexedDB transaction: the review, a grade row in the outbox, and a spent heart if the answer was wrong and the learner is not on Super. When the transaction commits, it dispatches graded, fires the correct or wrong effect without waiting for it, and prefetches audio for the next few cards.
  • Continue only works in revealed, and it dispatches continue immediately.

Three rules keep this tight.

Do not await the overlay. The effects player starts a CSS class or a short requestAnimationFrame loop and returns. If the next prompt mounts while the owl is still bouncing, cancel the old overlay. Two celebrations stacked is the bug, not an early Continue.

Do not grade in a useEffect. Effects run after paint. Dispatch check synchronously so the reducer ignores a second Check while grading.

Do not put network on Check. Flush is a background leader that wakes on online, on visibility, and on a timer. A 300ms POST would make every card feel like a form.

Match-pairs tempts people to block. A correct pair can ping. Do not ignore the next tap. Apply it to the remaining tiles, or queue it. The second pair should never wait on the first pair’s sparkle. On translate, the next <input> must already be focused. Losing keystrokes to an overlay is the desktop version of a locked Continue.

Respect prefers-reduced-motion: reduce. Skip the overlay. Keep the color change and the accepted answer. Motion is the enhancement. The grade is the product.


Grading

Pack-time normalization plus a tiny runtime window is enough.

Grading is a pure function from a card and a draft to a Grade. Normalize the typed text the same way the pack compiler normalized the accepted answers: NFC, locale-aware lowercase, Unicode punctuation and symbols replaced by spaces, whitespace collapsed. An exact match against any accepted answer is correct. Otherwise, if some accepted answer of at least five characters is exactly one Damerau–Levenshtein edit away, it is correct with a typo flag, so the UI can show “You have a typo” next to the right spelling. Anything else is wrong, and the result carries the accepted answers to reveal.

Damerau–Levenshtein (insert, delete, substitute, adjacent transpose) catches teh and a missed accent the pack kept. Keep the window at one edit and only on tokens of length five or more, or cat matches cut. Languages that treat accents as meaning (Spanish si vs sí) keep those code points in accepted. That is a pack flag, not a runtime guess.

Tap and match do not use Levenshtein. A wrong tap is a wrong tap. Listen grades like translate once the learner has answered.

Speak is the exception. The Web Speech API is a fallback, not the judge: dialects and noise miss a lot, and Safari’s implementation is a different product from Chrome’s. Record after a user gesture, show a hypothesis if you have one, and send the clip to ASR when online. Offline, skip the card or store the clip. Do not fail a heart on a bad on-device transcript.


Spaced-Repetition Cards

A session is not the next fifteen cards in the skill file. It is a mix from a due index plus a cap of new cards. Only-new forgets. Only-due never starts a skill.

Two pieces own this, both local and both testable without a network.

  • Session builder. Query up to 15 due reviews from the dueAt index. Take up to four weak ones (ease under about 1.8) first, then the rest of the due cards, then up to five new cards from the skill. Interleave and spread them, and cap the result at 15 card ids.
  • Scheduler. SM-2 over a 0 to 5 quality score. Below 3 is a lapse: reset reps, count the lapse, set the interval to one day, and lower ease by 0.2 with a floor. Otherwise adjust ease with the SM-2 formula, clamped to 1.3 to 2.5. The interval is one day after the first success, six after the second, then the previous interval times ease. dueAt is now plus the interval, in epoch ms.

That is SM-2 with the usual knobs. You do not need to name SuperMemo. You do need to say: a miss resets the interval, ease never drops below 1.3, and dueAt is epoch ms so a timezone change does not reshuffle the deck. The streak uses a civil date. The scheduler uses an instant.

Query an IndexedDB index on dueAt, not getAll(). Two thousand rows is small today. A full scan on lesson start is how a cheap phone hitch shows up as “the lesson is slow to open.”

Interleave so a new card is not buried, and so the same prompt is not adjacent when a miss requeues a practice copy. The extra copy is practice. The schedule update happens once, on the first grade.

If the interviewer asks about a neural scheduler: send features (latency, typo, kind) with the grade and let the server propose the next dueAt on flush. Until then SM-2 is honest, testable, and offline. Do not pretend the phone is running a model.


Audio

Almost every card has a clip. Cold-loading <audio src> on prompt is late: the learner has started reading, then the file talks over them. Decode ahead of the prompt.

A clip player owns one lazily created AudioContext and a map from content hash to decoded AudioBuffer.

  • Prefetch decodes a list of hashes in parallel, reading each blob from the pack store and skipping ones already decoded.
  • Play looks up the buffer. If it is missing, it decodes first and then plays. It resumes the context if suspended, creates a one-shot buffer source, connects it to the output, and starts it.

Autoplay policy is why this is tied to the session, not page load. The first gesture (Start, or the first tap) resumes the AudioContext. After that, programmatic start() on a listen card is legal. Calling play() on a new <audio> from a prefetch promise can still be rejected if the gesture is gone. A resumed Web Audio context is the more reliable path for short clips.

Keep a tiny LRU of decoded buffers. Twenty clips is plenty. Opus at 60 KB becomes a much larger PCM buffer; a whole course decoded at once will get you killed on a cheap phone. Prefetch two or three ahead, not the skill. The speaker replays the same buffer. A second tap while decoding queues one play, not two.

Offline audio is the pack’s Map<hash, Blob> plus a service worker that caches GET /audio/:hash as immutable. The SW is a speedup. IndexedDB is the source of truth for a downloaded skill, because a cache eviction should not delete a pack the learner paid bandwidth for.


Offline Lessons

Offline is a pack plus an outbox, not “the CDN is fast.” The budgeting design uses the same outbox shape. Here the payloads are smaller and the conflicts are counters, not dollar amounts.

A skill is in memory, downloadable, or blocked. Download fetches the pack JSON and each missing audio hash, then writes one IndexedDB transaction. The path node flips to ready only after that commit. A half-written pack is worse than a missing one: you start a session and die on card 8.

While offline:

  • Opening a ready skill starts a session from local cards and local ReviewState.
  • Grades and session_complete append to the outbox in the same transaction as the review update.
  • Hearts decrement on the cached profile. If the cache says zero, you do not start.
  • Shop, leagues, and undownloaded skills show an explicit offline state. Do not spin.

On flush the server applies grades to the review log, then recomputes hearts, XP, and streak. The interesting case is two devices. The phone finished a lesson with two hearts. The laptop had already spent them. The server accepts the grades (the schedule should move) and awards zero XP if the heart balance cannot cover the misses. The HUD snaps to the repaired profile. If that feels harsh, Super is the product answer, not a client that invents hearts.

Idempotency is sessionId. A flush that dies after apply but before the client deletes the outbox row must not add XP again. Delete only after a 200 that echoes the id. Write the outbox with the review row, not after. Same IndexedDB transaction, or it did not happen.


Streaks and Hearts

These two counters are why candidates get cute with Date.now() and then fail the follow-up.

Streaks

A streak is consecutive local civil days with at least one completed session. Store the IANA timezone and the last qualified civil date as an ISO date string. Do not store “last completion UTC midnight.”

Two pure functions own the streak. Civil date formats an instant as YYYY-MM-DD in the profile’s IANA timezone, using Intl.DateTimeFormat with the en-CA locale because it already emits ISO order. Next streak compares that date with the last qualified date. The same day changes nothing. The next civil day increments the streak. A one-day gap with a freeze available spends the freeze and still increments. Anything else resets the streak to 1. Every branch stores the new qualified date.

The client can preview so the flame updates offline. The server runs the real function from receive time and the stored timezone. A flipped device clock cannot mint a thirty-day streak. Say the late-flush rule out loud: count the local day of completedAt if it arrives within 36 hours, otherwise the day it arrived.

Freeze items are inventory. Spending one is a server decrement when a gap is detected. A double-spend across devices is the server’s reject.

Hearts

Five hearts, minus one per miss, refill on a timer or with gems. Super sets superActive and the decrement is a no-op. Render a countdown from server refillAt. Do not start a local setInterval that writes hearts; the clock drifts and two tabs race. Recompute remaining from refillAt and now on render, and revalidate on focus.

Optimistic decrement is fine. Optimistic refill is not. When refillAt is in the past, preview the refilled count and confirm on the next profile GET. Zero hearts is a hard stop. Continue must not sneak through on the last miss. The overlay can still play. The machine is already done.


i18n and RTL

Two languages live on one screen: chrome (menus, Check, Continue) and the target (prompts, choices, typed answers). They can disagree on direction.

Set dir and lang on the content root from the course, not on <html>. An English speaker learning Arabic wants an LTR shell. The prompt, the choices, and the translate input flip.

The chrome wrapper pins direction: ltr. The prompt, choices, and translate input inherit direction from the content root, and the progress fill uses transform-origin: inline-start with a logical inline-size, so it fills from the correct side in both directions.

Use logical properties (margin-inline-start, inset-inline-end, padding-inline) for gutters and the progress bar. Physical left / right is how you ship a bar that empties the wrong way on an RTL course.

Do not mirror every icon. Chevrons follow the chrome direction. The speaker does not: it is not a directional arrow. Flags are not languages.

Load the target face with the pack and scope it to the content root so the home screen does not download Noto for every script. Arabic needs a joining font. German answers overflow a button sized for English: measure after font load, or wrap. Do not truncate mid-grapheme. Intl.Segmenter is how you count glyphs for the typo window.

The translate <input> sets lang and dir to the expected answer, plus autocapitalize="off" autocomplete="off" spellcheck="false", so the OS does not “help” a Spanish answer with English autocorrect.


API


// REST
GET  /api/path                              // units, skills, download state
GET  /api/skills/:id/pack?version=n         // cards + audio hashes
GET  /audio/:hash                           // immutable Opus, CDN
GET  /api/me/profile                        // hearts, streak, timezone, super, rev
POST /api/me/sessions/:sessionId/grades     // idempotent; body = outbox batch
POST /api/me/sessions/:sessionId/complete
POST /api/asr                               // optional speak clip, multipart

interface GradeBatch {
  sessionId: string;
  items: ReadonlyArray<{
    cardId: string;
    quality: 0 | 1 | 2 | 3 | 4 | 5;
    typed?: string;
    ms: number;
    clientTs: number;
  }>;
}

interface ProfilePatch {
  hearts: number;
  refillAt: number | null;
  streak: number;
  lastQualifiedLocalDate: string;
  freezes: number;
  xp: number;
  serverRev: number;
}

There is no WebSocket on the lesson path. Flush is request-response. A notifications socket can poke profile.updated to other devices. Do not open a socket so the flame can tick at midnight. The next lesson load is soon enough.

Packs are versioned and cacheable. Audio is content-addressed. Profile GET is private. The grades POST must be idempotent and must return the repaired profile in the same body so the HUD does not need a second round trip.


Optimizations

Problem Technique Effect
Check feels laggy Local grade, no fetch, no await overlay Revealed in one frame
Path re-renders on every tap Session store outside React chrome Only the lesson view subscribes
Listen clip starts late Prefetch + decoded AudioBuffer Play on the same gesture window
Lesson open hitch IndexedDB index on dueAt No full-deck scan
Duplicate audio downloads Hash-keyed pack + SW cache One blob per clip, ever
Overlay jank CSS transform/opacity, cancel on next card No layout, no stacked owls
Huge choice labels Measure after font load, wrap German and Arabic still fit

Virtualize the path, not the lesson. A lesson is fifteen cards. The path can be hundreds of nodes. Idle-prefetch the next skill on Wi-Fi. Do not prefetch on a metered connection without asking. navigator.connection is a hint; a user toggle wins.


Handling Edge Cases

  • Double Check. The reducer ignores Check unless the phase is answering. Disable the button on dispatch, not after the write.
  • Continue during overlay. Allowed. Cancel the overlay. Focus the next input.
  • Backgrounded mid-card. Persist phase and draft. A five-minute background keeps the draft. A two-day background expires the session; hearts already spent stay spent.
  • Pack version skew. Unknown cardIds still record as grades. The client drops retired cards on the next download.
  • Clock rollback. dueAt in the past means due. Streak ignores the device clock on flush.
  • Two tabs. One leader flushes, via Web Locks or a BroadcastChannel heartbeat. Both tabs adopt the higher profile rev.
  • Audio decode fail. Disable the speaker. A listen card without audio degrades to translate. Skip a card with an empty accepted list; do not take a heart.
  • Timezone change. Store the new IANA zone. Do not rewrite history. The next qualification uses the new zone.

Accessibility and Security

Accessibility

  • Check and Continue are real buttons. Enter submits a valid draft. Escape does not abandon without a confirm.
  • Announce the grade in an aria-live="polite" region: “Correct.” or “Incorrect. The answer is the cat.” Do not rely on color or the overlay.
  • Focus the translate input on prompt, Continue after reveal, the next input after Continue. Never tab into a dead overlay.
  • Match tiles are a listbox or toggles with a spoken remaining count, not absolute-positioned divs only.
  • Hearts and streak have text: “3 of 5 hearts,” “12 day streak.” The flame is decoration.
  • prefers-reduced-motion skips the overlay. Grade colors stay. Contrast the fills against the card.

Security

  • Grades and session ids are authenticated. The server ignores a session the caller does not own.
  • XP, hearts, streak, and freezes are computed on the server. A patched local profile is a display hack, not a grant.
  • Pack JSON is data. Never eval or innerHTML a prompt. Furigana, if you allow it, is a tiny markup allowlist, not HTML.
  • ASR uploads are short, authenticated, and discarded. Timezone and locale strings are allowlisted (IANA, BCP 47) before they touch HTML lang.

What a Strong Answer Sounds Like

Topic Junior answer Senior answer
Session A list of questions and a score A phase machine; celebration is an overlay; Check is a local transaction
Input await the animation, then enable Continue Unlock on persist; 15 × 400ms is six seconds of dead air
SRS Random cards from the skill Due index, new cap, interleave, one schedule write per card
Offline Service worker caches the SPA Versioned pack + outbox in one IDB transaction; server repairs counters
Streak Date.now() and UTC days IANA timezone, civil date, server receive time, freeze as inventory
RTL dir="rtl" on <html> Content dir from the course; chrome stays on the UI locale; logical CSS

The budgeting app is the closest sibling for the outbox. The theme switcher covers reduced-motion and keeping React off a visual switch.


Conclusion: How to Design Duolingo

Start with the session machine: load, prompt, answer, grade, reveal, complete. Grade on the device, persist the outbox and the new review row together, and enable Continue before any overlay runs. That one rule is the product. A language lesson is a tight input loop with a bird on top, not a bird with a form inside it.

Schedule cards from a due index, play clips you decoded one card early, and treat hearts and streak as a cached profile the server can overwrite. Isolate direction on the course content so Arabic prompts do not flip an English shell. If you can explain why celebration is not a state, why UTC midnight breaks a California streak, and why a flushed lesson with stale hearts still updates the schedule, you have answered the question.