In an offline language-learning app, finishing a lesson updates its progress, the streak and fifty card due dates; how should the local store write them?
answer
- all or nothing on a kill
- compute first, then a short write
- no network call inside
- a completion id makes replay harmless
- observers see one commit
basics
~20 sCompute the changes first, then write them in one short transaction in one store, guarded by a unique completion id; a kill leaves all or none of it, and observing screens see one consistent change.
solid answer
~40 sEverything a lesson completion touches lives in one embedded relational database, so one transaction commits it: a completion record, the lesson's progress, fifty new due dates and the streak. If the process dies midway, the database is left with all of it or none, never a finished lesson whose cards are still due. I compute the new schedule before opening the transaction and keep the transaction short, with no network call inside, and run it off the UI thread. A unique completion id makes a double tap or a replay after relaunch a no-op, and I derive the streak from completion records instead of incrementing a counter. Observable queries re-run once after the commit, so no screen shows half the update.
code
pseudocode · 14 linesfinish_lesson(completion_id, lesson_id, answers, now):
updates = schedule_next_reviews(answers, now) -- computed before the transaction
day = local_calendar_day(now)
begin transaction
if completion exists with id = completion_id:
rollback
return -- already applied; nothing to do
insert completion(completion_id, lesson_id, day)
update lesson_progress set state = 'done' where lesson = lesson_id
for each u in updates:
update card set due_at = u.due_at, interval_days = u.interval where id = u.card_id
streak = count_consecutive_days(completion days, ending at day)
upsert learner_stats set streak = streak
commit -- observers re-run once, after this linego deeper
Recall that a transaction makes several writes succeed or fail together, and that one user action can touch many rows.
Explain the order: compute, begin, write every affected row, commit, and why observers should see only the committed result.
Show the production guards: one store so one commit covers the event, a completion id against replays, a short lock with no network call, and facts instead of counters.
Set the team rule for multi-record events across features, deciding which events need a transaction and who reviews new data that crosses store boundaries.
A **transaction** groups several writes so the database applies them as one unit: either every write in it becomes durable, or none does. Interviewers use lesson completion, checkout or "move an item between lists" to see whether a candidate notices that one user action is many rows, and what happens when the app dies in the middle. ## What one event touches When the learner finishes a lesson in the language-learning app, the app must: - record that the lesson was completed, on which local calendar day; - mark the lesson's progress as done and unlock the next one; - give each of the fifty reviewed cards a new due date and interval; - extend the streak if today had no completion yet. Written one at a time, a process ended after the twentieth card leaves a lesson marked done with thirty cards still showing as due, or a streak that grew while the cards did not move. On a phone the OS can end a backgrounded app at any time, so this is an expected case, not a rare one. ## One transaction, one store The fix only works if all four kinds of data live in the same store, which is one reason the store choice draws its boundaries around events like this one. The write then follows a fixed order: 1. **Compute** the new intervals and due dates in memory from the learner's answers. 2. **Begin** a transaction on the local database. 3. **Check** the completion id; if it is already recorded, roll back and stop. 4. **Write** the completion record, the progress row, the fifty card rows and the streak. 5. **Commit**. Only now do observing screens see the change. An embedded relational database is built so that a transaction is atomic: after a crash or a kill, the database reopens either with the whole commit or as it was before the transaction began. ## Guard against applying it twice The same completion can arrive twice: a double tap on "finish", or a relaunch that replays the last unsaved step. Two habits make that harmless: - **A unique completion id**, generated when the lesson starts and stored with a uniqueness constraint, so the second attempt finds it and does nothing. - **The learner's local day.** Each completion stores the calendar day as the learner experienced it, so a lesson finished at 23:30 still counts for that day even if the phone later changes time zone. - **Facts, not counters.** Store one completion record per lesson and day, and derive the streak from those records, in the same transaction or on read. A counter incremented on each completion drifts after any double application, and nothing records why; records can always rebuild the number. ## Keep the transaction short In a typical embedded database a write transaction holds the write lock until it commits, and other writes wait for it, so a long one delays the grade the learner gives on the next screen. - Compute schedules **before** beginning, not inside. - Never make a **network call** inside it: offline the call fails and would roll back the learner's progress for a network reason, and online it holds the lock for seconds. Commit locally first; reporting the completion to the server is a separate step, driven from a durable queue of pending writes whose entry joins this same transaction. - Run it **off the UI thread**, so even a slow device does not drop frames while fifty rows are written. ## What the screens see Many observable-query mechanisms re-run a query after each committed write. Fifty separate writes can therefore mean dozens of re-emissions, with the due count ticking down card by card while the progress screen lags behind. One transaction is one commit, so every observing screen re-runs once and sees a consistent state. ## Mistakes interviewers listen for | Weak answer | Why it fails | |---|---| | Write the fifty cards one by one | A kill midway leaves progress and cards disagreeing | | Keep the streak in a separate key-value store | No single commit covers both stores | | Include the server call in the transaction | Offline it rolls back local progress; online it holds the lock | | Increment a streak counter | Double application silently corrupts it |
- Why derive the streak from completion records instead of keeping a counter?A counter drifts: a double-applied completion adds two, and nothing records why. Completion records per local day are facts, and the streak is recomputed from them in the same transaction or on read, so a wrong value can always be rebuilt from the facts.
- What goes wrong if the transaction also includes the call that reports the completion to the server?Offline the call fails, and rolling back would discard the learner's progress for a network reason; online it holds the write lock for seconds, blocking other writes. Commit locally first, and send the change later from a durable queue of pending writes.
- How do observing screens behave if the fifty cards are written without a transaction?Many observable-query mechanisms re-run after each committed write, so the screens may re-emit dozens of times, showing the due count falling card by card and progress out of step with the cards. One transaction gives one commit and one consistent re-emission.
- Fifty separate card writes are fine because a kill in the middle is too rare to matter.
- Putting the server call inside the local transaction keeps the device and server in step.
- A kill during a transaction leaves the rows it had already written in the database.
- A streak counter incremented on every completion cannot drift.
- Keeping the streak in another store does not affect the update's atomicity.