skip to content

In a personal-budgeting phone app, the overnight job that imports transactions and retrains the on-device category model is often stopped partway; how should it be built to finish across runs?

level: seniorimportance: should knowfreq 50%

answer

  1. a wake is short and ends abruptly
  2. small steps, each committed
  3. the stop signal may never come
  4. safe to run twice
  5. swap the model in whole

basics

~20 s

Each wake lasts seconds to minutes and can end without warning, so split the job into small idempotent steps, commit a checkpoint with each step's data, stop between steps, and swap the retrained model in only when complete.

solid answer

~50 s

A background wake is short and ends on the OS's terms: on one platform a short refresh task gets up to about 30 seconds and the app is terminated if it does not report completion; on the other a job is stopped when a constraint stops holding, and the process can be killed for memory with no stop callback at all. So the job is a resumable state machine. The import fetches a page, upserts each transaction by the bank's id and saves the cursor in the same local transaction; retraining works in batches and saves its intermediate state to a scratch file. Before each step it checks the stop flag and a self-imposed time budget; on stop it returns "retry later". A lock with an expiry keeps a foreground refresh and a background run from overlapping, and the new model replaces the old with one atomic rename.

code

pseudocode · 32 lines
pseudocode
job overnight_import_and_retrain():
  if not acquire_lock("overnight", owner = run_id, expires_in = 10 minutes):
    return DONE                       # another run holds it
  try:
    state = load_checkpoint()         # first ever run: phase FINISHED, cursor none
    if state.phase == FINISHED:
      state.phase = IMPORT            # a new night; the cursor is kept
    while state.phase != FINISHED:
      if os_stop_requested() or elapsed() > SOFT_BUDGET:
        return RETRY_LATER            # the last committed checkpoint stands
      if state.phase == IMPORT:
        page = fetch_transactions(after = state.cursor, limit = 200)
        in_one_db_transaction:
          upsert_all(page.items, key = bank_transaction_id)
          state.cursor = page.next_cursor
          if page.is_last: state.phase = TRAIN
          save_checkpoint(state)
      else if state.phase == TRAIN:
        model = load_scratch_model() or copy_of(live_model_file)
        state.training = train_one_batch(model, state.training)
        if state.training.complete: state.phase = PUBLISH
        save_scratch_model_and_checkpoint(model, state)
      else if state.phase == PUBLISH:
        if exists(scratch_model_file):
          atomic_rename(scratch_model_file, live_model_file)
        state.phase = FINISHED
        state.training = none
        record_success_time(now())
        save_checkpoint(state)
    return DONE
  finally:
    release_lock("overnight", owner = run_id)

go deeper

for a junior

Recall that a background run is short and can be ended by the OS at any time, so long work must be able to stop and continue later.

for a middle

Explain the checkpoint: small steps, each committing its data and progress together, and a job that checks for a stop before every step.

for a senior

Show the job survives a kill with no callback, a duplicate run and an overlapping foreground refresh, and size the step from labelled assumptions about the soft budget.

for a principal

Decide whether heavy work such as model retraining belongs on the phone at all, given the run-time budget, versus training on the server and shipping a model.

## The constraint: a wake is short and ends on the OS's terms When the OS runs background work it grants a **run time** — a window that is short and not negotiable. Neither platform gives quiet, scheduled background work an open-ended run (on one platform, longer work must show the user a notification — a different bargain): - On one platform a short refresh task gets **up to about 30 seconds**; the app must report completion or the system terminates it, and an **expiration handler** fires if the system needs the time back sooner. Heavier processing tasks exist for low-activity periods such as overnight charging, but they too carry an expiration handler. - On the other platform urgent work is sized for **a few minutes**, ordinary jobs share a usage-based ration of run time, and a job is **stopped when a declared constraint stops holding** (the charger is unplugged) and retried later. The process can also be killed for low memory, and that platform's documentation for its data-transfer jobs tells apps to persist progress *even if the stop callback is never called*. "Up to" is a ceiling, not a promise, so a team picks a deliberately small **soft budget** of its own and treats the OS's stop as possible at any instant. ## Shape the job as resumable steps The personal-budgeting app's overnight job has two phases: import the night's transactions from several accounts, then retrain the on-device spending-category model on the updated history. Each becomes a sequence of small steps. 1. **Import a page.** Fetch the next page after the saved cursor, **upsert** each transaction keyed by the bank's own transaction id, and save the new cursor *in the same local database transaction* as the rows. If the process dies mid-step, nothing half-applied remains and the next run repeats that page harmlessly. 2. **Train a batch.** Retraining runs in batches; after each, the intermediate model state and the position in the training data are written to a scratch file, so the next run continues rather than restarting. 3. **Publish.** Training writes to a scratch copy of the model; when it completes, the scratch file is moved over the live one in a single atomic rename, so categorisation never sees a half-trained model, and a publish interrupted after the rename simply finishes on the next run. 4. **Finish.** Mark the checkpoint finished — keeping the import cursor for the next night — record the success time and report "done". A persisted **checkpoint** — phase, cursor, training position, attempt count — is what lets a stopped job continue where it left off. ## Stop well | Moment | What the job does | |---|---| | Before each step | check the OS's stop flag and the soft budget; if either says stop, return "retry later" | | Stop signal mid-step | let the small step commit, start nothing new, return "retry later" | | Killed with no signal | nothing to do — every committed step already saved its checkpoint | | Constraint lost | same as a stop; the OS retries when it holds again | The common bug is saving progress *in* the stop handler. That handler may not run, and when it does it has almost no time. ## Safe to run twice, never at once - **Idempotency.** Because every write is an upsert by the bank's id, an import that runs twice in a week — once overnight, once when the user opens the app — produces the same rows, not doubled purchases. - **Single flight.** A foreground refresh and the background job must not import the same pages concurrently. A lock row with an owner and an **expiry** lets one proceed; the expiry means a run killed while holding the lock does not block the next one forever. ## Sizing the step As the scenario's own assumptions: an old phone takes about 1.5 s to fetch and commit a page of 200 transactions, and the team sets a 20-second soft budget. Then one wake fits about thirteen pages in theory — call it ten with margin, or 2,000 transactions — before yielding, and a typical night's few dozen transactions finish in one wake. A first import of three years of history needs many wakes, which is why the checkpoint matters more than speed. ## What an interviewer listens for That the candidate treats the OS's stop as normal rather than exceptional, commits progress with the data instead of on the way out, and makes both repetition and interruption harmless.

  • Why give the lock an expiry instead of releasing it in the stop handler?
    Because the process can be killed without the stop handler or the cleanup block ever running. A lock that only a clean exit releases would block every later run, foreground or background, until someone reinstalled the app. An expiry somewhat longer than any single run bounds that damage.
  • The bank's aggregator offers only 'transactions since a date', with no stable cursor; what changes?
    Checkpoint the last fully committed date and re-fetch from slightly before it, relying on the upsert by transaction id to absorb the overlap. The overlap costs a few repeated rows per run; without stable ids from the bank, the import would need its own content-based key to stay idempotent.

  • The stop callback always runs, so progress can be saved there.
  • A background job that runs a little long just gets a few extra seconds.
  • Restarting the import from the beginning on each run is fine for a nightly job.
  • Running the import twice cannot cause duplicates if it worked once.
  • Overwriting the live model file batch by batch saves time and loses nothing.