Skip to content

    Frontend System Design

    Long-Running Jobs and Cancellation in AI Interfaces

    Design the screen for slow AI jobs: job ids, polling, a Cancel that waits for the server, a cancel sent before the id exists, and what unmounting does.

    By Published 11 min read

    • frontend-system-design
    • ai-ui
    • cancellation
    • abortcontroller
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Streaming LLM Responses in the Browser, Request Cancellation, Timeouts and Race Conditions

    What you'll learn: By the end of this lesson you will be able to explain why Cancel on a slow AI job is three different messages (to the screen, to the request, to the server), design the job states a screen needs, handle a cancel pressed before the job has an id, say what to show while the server is still stopping, tell a cancel that came too late from one that worked, and decide what happens to a job when its screen closes.

    Imagine you drop off a parcel at a counter and get a receipt number. You can walk away, and the parcel is still being handled. If you change your mind, tearing up your receipt does nothing; you must tell the counter, and the counter can stop only at the next stage. If the parcel already left, the answer is "too late". A slow AI job works like this. Closing the screen, aborting the request and cancelling the job are three separate things.

    The running example is a "summarize these reports" button in a dashboard, a job that takes tens of seconds. The lab's server and numbers are made up. The streaming case, where tokens arrive over one open connection, is the subject of the lesson on streaming model responses in the browser; here the job has an id and the screen asks about it.

    The core idea

    1. A job outlives the request that started it. Once the server accepts a job, it runs on its own. The client holds an id and asks for the state.
    2. Cancel is a request to the server, and it takes time. Until the server says "cancelled", the honest screen state is "Stopping...", not "Stopped".
    3. The screen's state is a small state machine that decides what each click means in each phase. The hardest phase is the first one, when there is no job id yet.

    Three illustrations run through the lesson: a minimal example (a job that runs to the end), a realistic example (Cancel while it runs) and a failure example (the screen closes and the job keeps going).

    Two shapes of long work

    Shape How the screen learns progress How it cancels
    Stream: one open response Chunks arrive on the connection Abort the request; for a stream, cancel the reader
    Job: an id and a status The screen polls or listens Tell the server to cancel the job, then watch its state

    For a stream, MDN's AbortController page says abort() "is able to abort fetch requests, consumption of any response bodies, and streams", and ReadableStream.cancel() is for when you are finished and do not want more data: enqueued chunks are lost and the stream is no longer readable. Its reason is passed to the underlying source, "which may or may not use it". Both are about what the client stops doing.

    For a job, HTTP has a status for the first step: 202 Accepted. MDN says it means a request "has been accepted for processing, but processing has not been completed or may not have started", that it is "non-committal" (no way to send a later HTTP response with the outcome), and shows a response body that carries a task id and a monitor URL so the client can track the task. So the client must come back and ask. The same page says the actual processing is not guaranteed: it may fail later.

    Figure 1. A job outlives the request

    The screen holds a job id and polls; the server queue and worker run the job on their ownScreen to Job API (create, poll, cancel); Job API to Queue (enqueue); Queue to Worker (start)Screen: state machineScreenstate machineJob API: create, get, cancelJob APIcreate, get,cancelQueue: waiting jobsQueuewaiting jobsWorker: runs in stepsWorkerruns in stepscreate, poll, cancelenqueuestart

    How to read this: the screen only ever talks to the API. What happens in the queue and the worker is learned by asking.

    Cancel is three messages

    When the user presses Cancel, three parties need to hear about it, and they hear at different times.

    1. The screen knows at once. It can show "Stopping...".
    2. The request in flight can be aborted at once with an AbortSignal. This stops the client waiting. MDN describes an AbortSignal as a way to communicate with an asynchronous operation and abort it, with aborted, reason and an abort event. It says nothing about work a server has already started; that is a conclusion for you to draw, not a promise of the API.
    3. The server job hears only if you send it a cancel request, and may stop only when it next checks. HTTP's DELETE is one way to express it. MDN lists DELETE as idempotent, so repeating the cancel is safe, and says a 202 Accepted response to a DELETE means the request "has been accepted and will probably succeed, but the resource has not yet been deleted". A cancel can be accepted and still not finished.

    In the lab, the server checks for a cancel only at a step boundary. That is the lab's design and not a statement about any real service.

    Figure 2. Cancel while the job runs

    sequenceDiagram accTitle: Cancel while a job is running accDescr: The user presses Cancel. The screen shows Stopping and sends a cancel request. The server marks the job cancelling and keeps working until the end of the current step, then marks it cancelled. The screen keeps polling and shows Stopped only when a poll reports cancelled. participant U as User participant S as Screen participant J as Job server U->>S: Cancel S->>S: show "Stopping..." S->>J: cancel job J->>J: cancelling (still working) S->>J: poll J-->>S: running or cancelling J->>J: step ends, cancelled S->>J: poll J-->>S: cancelled (partial output) S->>S: show "Stopped"

    How to read this: the screen says "Stopping..." for the whole stretch in which the server is still working, and "Stopped" only after the server says so.

    The screen's states

    Figure 3. Phases of one job on the screen

    stateDiagram-v2 accTitle: Phases of one job on the screen accDescr: Idle goes to submitting on start. Submitting goes to running when the job id arrives, or to cancelling if Cancel was pressed meanwhile. Running goes to cancelling on Cancel. Running and cancelling end in succeeded, cancelled or failed according to what the server reports. [*] --> idle idle --> submitting: start submitting --> running: id arrives submitting --> cancelling: id arrives, Cancel was pressed running --> cancelling: Cancel running --> succeeded: server says succeeded running --> failed: server says failed cancelling --> cancelled: server says cancelled cancelling --> succeeded: server finished first cancelling --> failed: server says failed

    How to read this: Cancel never jumps straight to cancelled. It always goes through cancelling, and the server decides the final state.

    Four rules follow, each tested in the lab.

    • Cancel while submitting is remembered. There is no job id to cancel yet, so the screen records the wish and sends the cancel when the create reply brings the id. Dropping it would leave a job running that the user tried to stop.
    • A late "running" answer does not undo Stopping. A poll sent before the server saw the cancel can come back "running". The screen stays in cancelling.
    • A success after Cancel is "too late", not "cancelled". The lab says "Finished before it could be stopped" and keeps the result, because it exists and the user may want it.
    • Partial output is kept. A cancelled job reports the steps it finished; the screen shows them.

    Build the transition as a pure function that returns the next state and the effects to perform (send create, send cancel, schedule a poll). Then the rules can be tested without a clock.

    Closing the screen is not cancelling

    When a component unmounts, React's guidance for an effect that fetches is that the cleanup "should either abort the fetch or ignore its result", and the page adds that "fetch" needs either "cancel" or "ignore". Both options are about the client. Neither tells a server job to stop. So there is a product decision: when the user leaves, should the job keep running, perhaps to be shown later, or be cancelled?

    Figure 4. What should happen to the job when the screen goes away?

    flowchart TD accTitle: Deciding what happens to a job when its screen closes accDescr: If the result will be shown later, such as in a notification or history, let the job continue and stop only the polling. If the result is only useful on this screen, send a cancel request to the server and stop polling. If the job id is not known yet, remember to cancel when it arrives. Q{"Is the result useful
    after the screen closes?"} -->|"yes"| K["Keep the job.
    Stop polling only."] Q -->|"no"| C["Send a cancel request,
    then stop polling."] C --> I{"Job id known yet?"} I -->|"no"| R["Remember: cancel when
    the create reply arrives"] I -->|"yes"| D["Send it now"]

    How to read this: stopping the poll is always right. Cancelling the job is the product decision, and the unknown-id case is the one people forget.

    Build it: a job server, a screen and a virtual clock

    Goal. Run a fake job through six situations with Cancel at different moments, and see what the screen and the server each believe.

    Setup. The lab is examples/frontend/labs/ai-job-cancellation (Node 26.13.1, Vitest 5.1.0). The clock is virtual and the server is a fake; the controller uses Node's real AbortController and AbortSignal, because their abort is synchronous and deterministic. The delays (40 ms each way, a 100 ms queue, 4 steps of 200 ms, polling every 250 ms) are made up.

    cd examples/frontend
    pnpm install
    cd labs/ai-job-cancellation
    pnpm test           # 23 tests
    node src/demo.ts

    Steps. Run the tests, then the demo. In the first block find that "Cancel pressed" at t=450 is followed by the server hearing at t=490 and stopping at t=540, and that the screen says "Stopped" only at t=740, when its next poll asks.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 2 of the demo):

    === 2. Cancel while running at t=450: the server stops at its next step boundary, not at once
    t=   0 client: idle -> submitting: Starting (step 0/0)
    t=   0 client: send create
    t=  40 server: job-1 created (queued)
    t=  80 client: submitting -> running: Working (step 0/4)
    t= 140 server: job-1 running
    t= 450 client: Cancel pressed
    t= 450 client: running -> cancelling: Stopping... (step 1/4)
    t= 450 client: send cancel for job-1
    t= 490 server: job-1 cancel arrived while running: will stop at the next step boundary
    t= 540 server: job-1 cancelled after 1 of 4 steps
    t= 740 client: cancelling -> cancelled: Stopped (step 1/4)
    final: cancelled "Stopped", parts kept: 1, server steps run: 1, requests sent: create 1, poll 2, cancel 1

    Now the two edge cases: Cancel pressed so late that the job finishes first, and the screen closing with and without telling the server.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; sections 4 and 5 of the demo):

    === 4. Cancel pressed too late: the job finishes first, and the screen says so
    t=   0 client: idle -> submitting: Starting (step 0/0)
    t=  80 client: submitting -> running: Working (step 0/4)
    t= 900 client: Cancel pressed
    t= 900 client: running -> cancelling: Stopping... (step 2/4)
    t= 900 client: send cancel for job-1
    t= 940 server: job-1 succeeded
    t= 940 server: job-1 cancel arrived, already succeeded
    t= 980 client: cancelling -> succeeded: Finished before it could be stopped (step 4/4)
    final: succeeded "Finished before it could be stopped", parts kept: 4, server steps run: 4, requests sent: create 1, poll 3, cancel 1
    
    === 5. The screen closes at t=450, with and without telling the server
    cancelOnDispose false
    t= 140 server: job-1 running
    t= 450 client: screen closed (cancelOnDispose false)
    t= 940 server: job-1 succeeded
      server steps run: 4 of 4, requests sent: poll 1, cancel 0
    cancelOnDispose true
    t= 450 client: screen closed (cancelOnDispose true)
    t= 490 server: job-1 cancel arrived while running: will stop at the next step boundary
    t= 540 server: job-1 cancelled after 1 of 4 steps
      server steps run: 1 of 4, requests sent: poll 1, cancel 1

    Without telling the server, all four steps of work were done for nobody. Section 3 of the demo cancels at t=20, before the create reply: the cancel is sent at t=80 when the id arrives and the queued job is cancelled with no work done. The tests also press Cancel every 10 ms from 0 to 1200 and check that the screen always ends in the same state as the server.

    What the lab does not show. There is no network, no real service and no real time. Cooperative cancel at a step boundary, the rule that a finished job ignores a cancel, and the tie rule (events due at the same time run in the order scheduled, which is why the success at t=940 comes before the cancel at t=940) are this lab's design. It does not model a lost reply, a timeout or a server that cancels at once. It does not show a browser, fetch or a stream.

    Break it. In src/ui.ts, in the created case, replace !state.cancelWanted || isTerminal(next.state.phase) with true. A cancel pressed while the job is being created is forgotten, and three tests fail. Restore it.

    Trade-offs

    Choice Gain Cost
    Poll for status Works through any proxy; simple Delay between a state change and the screen; extra requests
    "Stopping..." until the server confirms The screen never lies The user waits for a step boundary
    Cancel the job on unmount No work done for nobody The result is lost if the user comes back
    Keep the job on unmount The result can be shown later The server pays for work nobody may read
    Keep partial output on cancel The user keeps what was done Partial output must be marked as partial

    In practice: the summarize button that kept running

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A dashboard has a "Summarize these reports" button. It starts a job that takes about a minute. The first version aborts its polling when the user closes the panel and shows "Cancelled". It does not tell the server.

    Starting architecture

    Figure 5. Starting point: the screen forgets, the server continues

    Starting architecture: closing the panel stops the polling and never reaches the workerPanel to Job API (polling stops); Job API to Worker (job continues)Panel: closes, shows CancelledPanelcloses, showsCancelledJob API: never toldJob APInever toldWorker: keeps runningWorkerkeeps runningpolling stopsjob continues

    How to read this: the screen says Cancelled, but nothing on the path to the worker was told.

    Options considered

    Option What it fixes What it costs Risk
    Send a cancel on close Stops wasted work One request; the id may be unknown Cancel lost if the tab closes at once
    Add a server limit on job age Bounds the waste whatever the client does Server work and a policy Kills a job somebody wanted
    Both, with "Stopping..." on screen Client and server agree More states to test Needs the state machine

    The decision

    Field Decision record
    Context Users close the panel mid-job, and the job's result is useless without the panel.
    Decision A phase machine with cancelling; Cancel and close both send a cancel, remembered if the id is unknown; a server-side age limit as backstop.
    Consequences, good Abandoned jobs stop at the next step, and the screen tells the truth.
    Consequences, bad A longer "Stopping..." state, and more tests.
    Revisit when Results become useful later (notifications or history): then close should keep the job.

    Rollout and verification

    1. Write the phase tests first, including Cancel at every moment from submit to finish.
    2. Log each cancel with the phase it was pressed in, and whether it came before the id existed.
    3. Compare the count of jobs that finish after the user left, before and after.

    The 2 a.m. failure

    The queue grows overnight and a nightly batch is late (illustrative). Many jobs were started by users who closed the panel after a few seconds, and nothing told the workers. First three checks: (1) how many running jobs have no client polling them; (2) whether cancels are sent when the id is not yet known; (3) whether the server ever stops a job nobody asks about. Mitigation: cancel the orphaned jobs and add the age limit. Follow-up: add the Cancel-while-submitting test, and alert on the share of jobs that finish after their user left.

    Architect's notes

    • Never show "Stopped" before the server says so. "Stopping..." costs nothing and is true.
    • Remember a cancel pressed before the id exists. It is a normal sequence, not an edge.
    • Decide what unmount means for each job type and write it in the design.
    • Keep partial results and label them.
    • Give the server its own limit. A client cannot be trusted to cancel.

    Common mistakes

    • Treating abort() as cancelling the job. It stops the client waiting.
    • Showing "Cancelled" at once, then a result arrives.
    • Dropping a cancel pressed while the create request is in flight.
    • Starting a second polling loop because a cancel reply also asks for a poll.
    • Throwing away the partial output of a cancelled job.

    Key takeaways

    • A job outlives the request that started it; the client holds an id and asks.
    • Cancel is three messages: the screen, the request, the server job. Only the third stops the work.
    • Show "Stopping..." until the server reports a final state.
    • A cancel pressed before the id arrives is remembered and sent later.
    • A success after Cancel is too late, not cancelled; keep the result.
    • Closing the screen stops the polling; whether it cancels the job is a product decision.

    Practice exercises

    Exercise 1 - Starter (45 min): In the lab, change the server so a queued or running job cancels at once, and list which lines of the demo change and which tests need updating.

    Exercise 2 - Intermediate (2 hours): Add a deadline to the controller: after a number of virtual milliseconds act as if Cancel was pressed, and show "Timed out" instead of "Stopped". Test it with the sweep from the lab.

    Exercise 3 - Advanced (half day): Model a lost reply: the server cancels, the client never hears. Decide what the screen shows, how a later poll repairs it, and write the test.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments