A Reasoning Model Is a Job, Not a Very Slow HTTP Request
Long-running reasoning models can spend minutes planning, calling tools, and revising results. Treat them as durable jobs with explicit budgets, checkpoints, cancellation, leases, resumable events, and provider-state boundaries instead of stretching a synchronous request until it breaks.
On this page
A reasoning model can make a simple API call look deceptively familiar.
const result = await model.generate(input);return result.text;That mental model works while the call takes three seconds and has no tools.
It starts breaking when a request can spend several minutes reasoning, search several sources, execute tools, wait behind a provider queue, retry a dependency, compact context, or pause while the user is no longer connected.
At that point the question is no longer:
How do I increase the HTTP timeout?
It is:
What is the lifecycle of this piece of work?
Modern reasoning APIs increasingly expose background/asynchronous execution because long tasks do not fit neatly inside one client connection. That is useful, but I do not want the provider's background object to become my product's workflow model.
I still create an application-owned run with its own state, budgets, cancellation, audit trail, and recovery rules.
The provider request is one activity inside that run.
The first boundary is request versus run
A request is a transport event.
A run is durable application state.
I model them separately:
type ReasoningRun = { id: string; tenantId: string; actorId: string; workflow: string; workflowVersion: number; status: | "queued" | "running" | "waiting" | "cancelling" | "completed" | "failed" | "cancelled"; createdAt: string; startedAt?: string; completedAt?: string;};The browser can disappear and the run still exists.
A worker can crash and another worker can decide whether the run is resumable.
The provider can return a background task ID and that ID becomes metadata on the run—not the run's primary identity.
This sounds like ordinary job processing because it is ordinary job processing.
Create the run before expensive work begins
For long work I prefer an API shape like:
POST /analysis-runs -> validates request -> authorizes actor -> reserves budget -> creates durable run -> returns run IDThen:
GET /analysis-runs/:idGET /analysis-runs/:id/eventsPOST /analysis-runs/:id/cancelThe first request should not wait five minutes to discover whether the reasoning model eventually finishes.
type CreateRunResult = { runId: string; status: "queued" | "running";};async function createAnalysisRun(input: { tenantId: string; actorId: string; request: AnalysisRequest;}): Promise<CreateRunResult> { const run = await runStore.create({ tenantId: input.tenantId, actorId: input.actorId, workflow: "document-analysis", workflowVersion: 7, status: "queued", }); await runQueue.enqueue({ runId: run.id }); return { runId: run.id, status: "queued", };}A small synchronous endpoint can still return inline for fast paths. The durable run becomes valuable once slow-path execution is normal enough that disconnections, retries, or cancellation matter.
Background execution is a provider capability, not a durability guarantee
Suppose the model provider supports this pattern:
create response with background=truereceive provider response IDpoll or reconnect laterThat solves one problem: the provider does not require my TCP connection to remain alive while the model is working.
It does not automatically solve:
my database transactionmy tenant budgetmy tool side effectsmy approval workflowmy cancellation semanticsmy product audit trailmy retries after a worker crashI therefore wrap the provider object:
type ProviderActivity = { runId: string; provider: string; providerRequestId: string; state: "submitted" | "running" | "completed" | "failed"; submittedAt: string; lastObservedAt: string;};That record tells the next worker what remote work may already exist.
Without it, a worker restart can create a second expensive reasoning request simply because local memory forgot the first one.
Idempotency matters before generation too
A user double-clicks Run.
The frontend retries because it did not receive the first response.
The API gateway replays a request after a transient network failure.
If each attempt creates a new reasoning job, one user action can become three bills.
I use an idempotency key at the application run-creation boundary.
type RunCreationKey = { tenantId: string; actorId: string; clientOperationId: string;};async function getOrCreateRun( key: RunCreationKey, create: () => Promise<ReasoningRun>,): Promise<ReasoningRun> { const existing = await runStore.findByClientOperation(key); if (existing) return existing; return runStore.createIdempotently(key, create);}The real implementation needs an atomic uniqueness constraint or equivalent store primitive. A read followed by an unrelated insert still races.
The invariant is simple: one client operation should identify one application run.
Long reasoning needs multiple budgets
A time limit is only one dimension.
For a production run I care about:
wall-clock deadlinemodel/reasoning token allowancevisible output token allowancetool-call countpaid tool spendmodel spendretrieval countworker/subagent countI keep them in one run policy:
type RunBudget = { deadlineAt: string; maxModelCalls: number; maxToolCalls: number; maxOutputTokens: number; maxCostMicros: bigint; maxWorkers: number;};Provider APIs may expose their own reasoning effort, output-token, or tool-call controls. I use those where available, but I still enforce the product budget at the host layer.
A provider limit protects one provider request.
A run limit protects the whole workflow, including retries and other providers.
A deadline is not the same as a timeout
A timeout is usually local to one operation.
A deadline answers:
How much time is left for this run as a whole?
If a run has 12 seconds left, starting a tool with a 30-second timeout makes no sense.
function remainingMs(deadlineAt: string, now = Date.now()): number { return Math.max(0, Date.parse(deadlineAt) - now);}function childTimeoutMs( deadlineAt: string, requestedMs: number,): number { return Math.min(requestedMs, remainingMs(deadlineAt));}Every expensive child operation consumes from the same remaining wall-clock envelope.
This is especially important for reasoning loops that keep finding one more thing to investigate.
The model should know a budget summary, not control the budget
It can be useful to tell the model:
You have capacity for at most 3 more tool calls.The task should finish within the current run budget.That helps planning.
But the runtime still enforces it.
function assertToolBudget(state: { toolCallsUsed: number; maxToolCalls: number;}): void { if (state.toolCallsUsed >= state.maxToolCalls) { throw new Error("Run tool-call budget exhausted"); }}A prompt limit is guidance.
A counter in trusted state is control.
This distinction becomes more important with stronger reasoning models because they can generate convincing plans for why one more tool call would be useful.
Do not use chain-of-thought as your checkpoint format
A long-running system needs resumable state.
That does not mean persisting hidden chain-of-thought.
I checkpoint observable workflow state:
type RunCheckpoint = { runId: string; version: number; currentStep: string; completedStepIds: string[]; retrievedArtifactIds: string[]; toolResultIds: string[]; compactedContextId?: string; pendingApprovalId?: string; remainingBudget: { toolCalls: number; costMicros: bigint; }; createdAt: string;};If a provider offers a safe reasoning summary or opaque/encrypted state item intended for continuation, I can store that according to its contract.
My application checkpoint still describes what the workflow did, what it observed, and what work remains.
That is enough to resume without turning private reasoning into an application database schema.
Checkpoint after durable boundaries
Checkpointing after every generated token is wasteful.
I care about boundaries where repeating work is expensive or dangerous:
retrieval batch completedtool result committedside effect completedapproval requestedcontext compactedprovider background activity submittedmajor planning stage completedIf the worker crashes after one of those boundaries, another worker can continue from the recorded state.
The checkpoint should be written in the same consistency boundary as the state transition when possible.
A run that says tool completed while the tool result record was never committed is not resumable state. It is an optimistic story about state.
Worker leases prevent duplicate active execution
A queue can deliver the same job twice.
A worker can pause long enough that the queue assumes it died and redelivers.
Two regions can race to recover the same stale run.
I use a lease:
type RunLease = { runId: string; ownerId: string; leaseUntil: string; version: number;};The worker renews the lease while it is actively orchestrating.
A second worker may take over only after the lease expires and an atomic compare-and-set succeeds.
This is not a perfect exactly-once guarantee. External writes still need idempotency.
It does prevent two healthy workers from casually running the same reasoning loop at the same time.
Never assume polling is free
Background provider work often introduces a polling loop.
The naive implementation:
while not done: GET status sleep 1 secondworks for ten jobs.
It becomes noisy for 100,000 jobs.
I use provider callbacks/events when available, or adaptive polling when they are not.
function nextPollDelayMs(attempt: number): number { const base = Math.min(30_000, 1_000 * 2 ** attempt); const jitter = Math.floor(Math.random() * 500); return base + jitter;}If the provider publishes a recommended retry interval, use it.
The goal is not to discover completion within the smallest possible millisecond. It is to discover it quickly enough for the product without turning status checks into their own rate-limit problem.
Waiting should release scarce workers
If a provider background task will take two minutes, an application worker should not necessarily sit on a thread/process doing nothing for two minutes.
Persist:
run.status = waitingprovider activity IDnext poll timeThen release the worker.
A scheduler wakes the run when the provider is likely ready or an event arrives.
The same applies to human approvals and long rate-limit waits.
A durable workflow should distinguish waiting from executing so infrastructure capacity is not consumed merely because the run remains alive.
Cancellation is a state transition, not an exception
The user presses Stop while the provider is still reasoning.
The correct sequence is not:
close HTTP socketI record intent:
type CancellationRecord = { runId: string; requestedBy: string; requestedAt: string; reason?: string;};Then the orchestrator:
stops launching new workattempts provider cancellation if supportedpropagates cancellation to tools/workerswaits for ambiguous writes to reconcilemarks final run stateSome remote operations cannot be cancelled after submission.
In that case cancelling is an honest state while the system waits to know what actually happened.
Do not show cancelled simply because the UI no longer wants the result.
Unknown outcomes become more common with long calls
A reasoning request can run for minutes and then the client loses connectivity.
Did the provider finish?
Was usage billed?
Did the final tool call execute?
If the answer is unknown, model it.
type ActivityOutcome = "success" | "failure" | "cancelled" | "unknown";The cost-ledger article used the same principle: ambiguity should not be converted into a convenient zero.
Reconciliation jobs can later query provider state, external resource state, or idempotency records.
Long-running systems are easier to trust when they admit uncertainty explicitly.
Context growth needs its own lifecycle
A reasoning run that reads twenty documents and calls eight tools can accumulate a huge context.
Keeping every historical byte in every subsequent model call is expensive and often unnecessary.
I separate durable artifacts from the model's working context:
artifact store full documents tool outputs code patches query resultsworking context relevant excerpts stable IDs compact summaries current task stateThe run can compact older interaction state into a versioned artifact:
type ContextCompaction = { id: string; runId: string; sourceThroughEventId: number; summary: string; importantArtifactIds: string[]; compactorVersion: string; createdAt: string;};Once created, that compaction artifact is immutable.
I do not re-summarize the same history differently on every worker restart.
That gives both context stability and prompt-cache stability.
Artifact IDs are safer than giant tool outputs
A tool may return 2 MB of logs.
Passing all of it back to the model wastes context and can amplify untrusted instructions buried inside the data.
The tool adapter can persist the full result and return a bounded projection:
type ToolArtifactResult = { artifactId: string; mediaType: string; summary: string; byteLength: number; truncatedForModel: boolean;};If the model needs a specific section later, another read tool can retrieve that range.
Long reasoning works better when context can page data in rather than carrying the entire investigation in RAM-like prompt history.
Reasoning effort is a routing decision
Some provider APIs expose an effort level or similar control for reasoning models.
I do not automatically set everything to the maximum.
The model router can choose based on task requirements:
type ReasoningProfile = { tier: "fast" | "balanced" | "deep"; maxToolCalls: number; maxOutputTokens: number;};function reasoningProfile(task: { risk: "low" | "medium" | "high"; complexity: "simple" | "moderate" | "complex";}): ReasoningProfile { if (task.risk === "high" || task.complexity === "complex") { return { tier: "deep", maxToolCalls: 12, maxOutputTokens: 8_000, }; } if (task.complexity === "moderate") { return { tier: "balanced", maxToolCalls: 6, maxOutputTokens: 4_000, }; } return { tier: "fast", maxToolCalls: 2, maxOutputTokens: 2_000, };}Those numbers are illustrative policy values, not provider recommendations.
The point is that extra reasoning is a resource choice with latency and cost consequences.
Do not use visible verbosity as a proxy for reasoning quality
A deep reasoning model may spend substantial internal compute and still return a short answer.
A model producing three pages of explanation may have done less useful reasoning.
I evaluate the task result separately from visible length.
For a code migration, for example:
did tests pass?did the required files change?did the migration preserve behavior?were forbidden files untouched?did the run stay inside budget?Those are stronger signals than how thoughtful the prose sounds.
The same applies to reasoning summaries: they can improve UX and debugging, but they are not a substitute for outcome-based evaluation.
Store reasoning summaries only for a purpose
If a provider exposes concise reasoning summaries, they can help explain high-level progress or support debugging.
I still treat them as model-generated content.
They can be wrong, incomplete, sensitive, or unnecessary for the product.
I prefer structured application events where possible:
selected retrieval path Afound 6 relevant documentstool X failed validationretried with corrected argumentswaiting on approvalThose facts came from the orchestrator.
A reasoning summary can complement them when useful, but I do not turn it into the source of truth for what the system actually executed.
Provider background mode can change data-retention assumptions
This deserves explicit architecture review.
Some providers need to retain temporary server-side state to support background execution, polling, continuation, or caching. That can make a background feature incompatible with certain zero-retention modes or internal data-handling requirements.
So the routing decision is not only:
background mode is more reliable for a 5-minute jobIt is also:
Is this data class allowed to use that execution mode?Where is provider-side state stored?For how long?Can the workflow use our own durable orchestration with a different provider mode instead?I represent data policy in the model/provider eligibility rules just like region and capability.
Reliability optimizations should not silently change the privacy contract.
A reasoning run can outlive a deployment
A run starts on workflow version 17.
Ten minutes later version 18 deploys.
Which version should resume the run?
For durable work I pin the workflow definition and relevant policy versions at creation:
type RunVersions = { workflowVersion: number; promptVersion: string; toolSchemaVersion: string; policyVersion: string; modelRoutingVersion: string;};A normal deployment should not change the semantics of a run already halfway through a consequential operation.
For critical security revocations, I can deliberately stop or migrate old runs.
That is a policy decision, not an accidental effect of whichever container wakes up next.
Schema evolution needs backward-compatible checkpoints
If runs can live for hours or days, checkpoint formats will eventually cross deployments.
I version them.
type VersionedCheckpoint = { schemaVersion: 3; runId: string; state: RunCheckpoint;};A new worker either understands older versions or runs a migration before resuming.
Do not deploy a schema change that makes every paused approval workflow unreadable.
This is the sort of failure that appears only after the demo becomes a product.
Streaming belongs on top of the run, not inside the provider socket
The previous article built an agent event protocol.
Long reasoning is where it pays off.
The UI attaches to:
run.createdrun.startedstep.startedartifact.createdapproval.requiredtext.deltarun.completedIf the provider connection drops and the application later reconnects to the background activity, the user stream still belongs to one run.
The browser does not care whether step 4 came from one continuous provider socket, a polling recovery, or a new worker.
That separation makes long-running UX much more stable.
Partial results can be first-class
A five-minute research run may discover useful evidence before the final synthesis completes.
Whether to expose it depends on product semantics.
I distinguish artifacts from final conclusions:
type RunArtifact = { id: string; runId: string; kind: "source" | "finding" | "draft" | "final"; status: "intermediate" | "validated" | "final"; createdAt: string;};The UI can show validated sources or completed sub-results without pretending the whole run is done.
If the final synthesis fails, those artifacts can still help debugging or allow a user to retry only the missing stage.
That is better than throwing away four minutes of completed deterministic work because the last model call timed out.
Retry stages, not whole runs
This is one of the biggest cost savings in durable reasoning.
If retrieval completed, three tools succeeded, and final synthesis failed, retrying the entire user request repeats expensive work and risks duplicate side effects.
I resume from the last safe checkpoint:
checkpoint 1: retrieval completecheckpoint 2: external facts verifiedcheckpoint 3: approval completecheckpoint 4: final synthesis pendingA retry starts at checkpoint 4.
This only works if earlier tool results are immutable enough to reuse and if freshness policy says they remain valid.
When facts may have changed, the workflow can selectively refresh them rather than restart everything.
Freshness rules belong in the checkpoint
A run paused overnight may contain stale evidence.
I track validity metadata on artifacts:
type ArtifactFreshness = { artifactId: string; observedAt: string; validUntil?: string; sourceVersion?: string;};Before resuming, the workflow revalidates what matters.
A documentation snapshot may be reusable for days. A deployment status may need to be refreshed after 30 seconds. A human approval may become invalid if the action parameters changed.
Durability should not turn old state into permanent truth.
Reasoning runs need SLOs beyond latency
A five-minute job cannot be judged by p95 response time alone.
I monitor:
queue waitexecution timeprovider waiting timetool waiting timecompletion ratecancel rateresume/recovery ratestale-run countunknown-outcome countaverage checkpoints per runcost per successful runtool calls per successful runbudget-exhaustion rateI also track age of the oldest nonterminal run.
That catches workflows that get stuck in waiting forever because one scheduler path stopped waking them.
The operational question is not only “how long are successful runs?” but “does every run eventually reach a justified terminal state?”
Sweep orphaned runs
Workers crash. Provider callbacks fail. Queue messages disappear. Bugs happen.
A reconciler periodically finds old nonterminal runs:
type StaleRun = { id: string; status: string; lastTransitionAt: string; providerActivityId?: string;};Then it asks:
Is a worker lease still valid?Is a provider activity still running?Is an approval still pending?Did the deadline expire?Can this run resume safely?Does an unknown side effect need reconciliation?The sweeper does not blindly restart everything.
Its job is to restore the state machine to reality.
Evaluate long runs with failure injection
Happy-path reasoning demos prove very little about durability.
I test:
worker crashes after provider submissionworker crashes after tool side effectprovider returns 429 during reasoningbackground activity finishes while app is offlinestream disconnects and reconnectsuser cancels during tool executionrun crosses a deploymentcheckpoint schema migratesbudget exhausts before synthesisapproval expires before resumereconciler runs twiceThe important assertions are deterministic:
no duplicate side effectno duplicate run charge reservationone justified terminal statebudget never increases after restartresume begins at correct checkpointcancel stops new workold workflow version remains identifiableThat is where long-running architecture earns confidence.
When background jobs are unnecessary
Do not turn every AI call into a workflow engine.
If the task reliably finishes in a few seconds, uses no tools, has no durable side effects, and the user naturally waits for the result, a normal synchronous request is easier to operate.
The durable-job model becomes worth it when one or more of these are normal:
minutes of model executionmultiple external toolshuman approvalbackground operationreconnect/resume UXexpensive intermediate artifactsside effectshigh retry costsubagentsstrict budgetsReasoning models make those workloads more common because they can spend more compute deciding, checking, and iterating before answering.
That does not require exotic infrastructure.
It requires using the infrastructure patterns we already trust for long work: durable state, queues, leases, idempotency, checkpoints, deadlines, budgets, cancellation, reconciliation, and observability.
The model can reason for a long time.
The application should not have to hold its breath while it does.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article