Last reviewed: November 10, 2026 (Asia/Shanghai).

Direct answer

Control TanStack Query CometAPI costs by making query functions read saved application state. Put paid generation behind an explicit mutation with retry: false, and enforce generation identity and budget admission on the server. Refocusing a window, reconnecting, remounting a component, or polling a job should never authorize another model attempt.

TanStack Query’s Important Defaults explains why this boundary matters: cached query data is stale by default, stale queries can refetch on mount, focus, and reconnect, and failed queries are retried three times. Those are useful data-fetching behaviors. If the query function creates a fresh CometAPI generation, the same behaviors can repeat paid work.

Who this is for

This guide is for React developers and AI budget owners using TanStack Query v5 for generated reports, summaries, or answers. It assumes the browser calls an application backend that owns the CometAPI credential and dispatches non-streaming text requests.

The code is an integration pattern with application-owned API helpers. The verification table gives acceptance criteria; no browser integration test, authenticated CometAPI call, or billing experiment was performed for this article. Check the installed library version and effective QueryClient defaults before implementing it.

Key takeaways

  • Use queries to retrieve stored results and job status, including missing or failed state.
  • Submit generation through a deliberate mutation; set its retry policy explicitly.
  • Treat query keys, mutation keys, and disabled buttons as interface controls, not durable duplicate protection.
  • Preserve the same generation identity after an uncertain submission.
  • Measure model-adapter dispatches separately from browser requests and accepted generation intents.
  • Keep automatic refetching where it benefits ordinary reads once those reads cannot generate.

Contract details to verify

Find the query function that spends

This abbreviated configuration creates the risk:

useQuery({
  queryKey: ['summary', documentId],
  queryFn: () => postNewSummary(documentId),
})

Here postNewSummary means an application helper that orders a new generation. Sending HTTP POST inside a query function does not remove TanStack Query’s query lifecycle. Trace what the helper actually does, including cache-miss fallbacks and server-side retries.

Review the effective settings rather than assuming the defaults survived application configuration:

BehaviorDocumented controlSpending risk if the query generates
Stale query mounts, window refocuses, or network reconnectsstaleTime and the corresponding refetch optionsAnother query execution can order another generation
Periodic pollingrefetchInterval, independent of staleTimeEach poll can create new work
Query failureretry and retryDelayOne failure can invoke the spending helper again
Inactive cache entry is collectedgcTime; five minutes by defaultA later visit cannot rely on that entry to suppress work

Increasing staleTime can reduce ordinary refetch traffic. It does not establish permission to spend, and it does not disable an independently configured polling interval. A warm cache can hide the problem during a quick demonstration. A different tab, an empty cache, or a later visit can expose it again.

The existing Next.js prefetch guide covers generation reached during route rendering. Audit this query boundary separately: a client-side query can repeat generation even when server rendering is already free of that side effect.

Give reads and generation different contracts

Define two application operations:

OperationServer responsibilityMay dispatch to CometAPI?
Read report or generation statusAuthorize access; return saved, missing, pending, failed, or unresolved stateNo
Submit generation intentAuthorize the action; claim its identity; reserve budget; record durable dispatch ownershipOnly after admission

A missing summary is a state to display. It should not cause readSavedReport to call a hidden generateIfMissing helper. Likewise, reading a failed job should return its recorded outcome, not restart it. An explicit regeneration is a separately approved action.

CometAPI’s chat-completion reference documents POST /v1/chat/completions, model and message fields, output controls, and response usage. The application must decide when to reach that upstream endpoint. A browser query key supplies neither account authorization nor a financial allowance.

Express generation as an explicit mutation

The useMutation reference describes mutations as the hook for server side effects and gives their retry default as zero. Set retry: false on this mutation so its intended policy remains visible even if shared defaults change.

The helpers imported below are application interfaces: readSavedReport returns existing state without generation, while submitGeneration returns a durable acceptance receipt. They must implement the server contracts above.

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { readSavedReport, submitGeneration } from './reportApi'

type GenerationIntent = {
  intentId: string
  documentId: string
  sourceRevision: string
}

export function useReportFlow(
  accountScope: string,
  documentId: string,
  sourceRevision: string,
) {
  const queryClient = useQueryClient()
  const reportKey = [
    'report-state', accountScope, documentId, sourceRevision,
  ] as const

  const report = useQuery({
    queryKey: reportKey,
    queryFn: () => readSavedReport(documentId, sourceRevision),
    staleTime: 30_000,
  })

  const generate = useMutation({
    mutationKey: ['submit-report-generation'],
    mutationFn: (intent: GenerationIntent) => submitGeneration(intent),
    retry: false,
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: reportKey })
    },
  })

  return { report, generate }
}

Call generate.mutate(intent) only from the explicit submit flow. The caller creates and retains one intent identity for that action before submission; an error must not silently replace it with a fresh identity. Preserve the intent across reloads when recovery requires it, then use the application’s status lookup to resolve uncertainty. The backend derives the authenticated owner independently of browser-supplied fields and rejects conflicting reuse of an identity.

The example’s 30-second freshness window is an illustrative UI choice. It is not a spending limit. Successful acceptance invalidates the saved-state query, whose next read still cannot call the model. Add polling for an accepted job only after verifying that every status read has that property.

Keep the application credential on the server and apply its normal session, CSRF or origin protections and resource permissions. Include the account scope in client cache identity, and clear or isolate account data when sessions change. Cache scoping complements server authorization; it cannot replace it.

Keep one authority for every upstream attempt

retry: false controls this mutation’s automatic retries. It does not disable retries in submitGeneration, a service worker, the server adapter, a worker queue, or an upstream SDK. Inventory those layers and give one owner responsibility for the permitted attempt count.

For example, explicitly configuring three browser retries permits up to four mutation-function invocations. If each invocation independently allows an initial server attempt plus two retries, the combined ceiling can reach twelve upstream attempts. That assumes every invocation reaches the adapter, consumes all retries, and has no duplicate suppression. It is a dispatch ceiling under stated settings, not evidence of twelve billed completions or a claim about any SDK’s default policy.

Claim an intent durably before creating executable work. Duplicate submissions with the same owner and payload should return the existing job or outcome. A rejected budget decision must leave no runnable generation. Use the site’s atomic budget reservation guide for concurrent admission and recovery requirements.

TanStack’s reference defines mutationKey as a way to inherit defaults and match mutation state. It is not a durable generation identity. It also documents that mutations sharing a scope.id run serially. Serial execution still runs each submitted mutation; it does not merge them into one purchase. Disable the button while pending for usability, then verify duplicate protection at the server.

Operator workflow

Verify browser events against a fake upstream

Use a test-owned backend with a fake CometAPI adapter and no usable live credential. Count browser query executions, generation submissions, accepted intent identities, and upstream adapter dispatches independently. Exercise the real component tree and QueryClient configuration, including an initially empty cache.

These are required observations for that test environment:

ScenarioRequired observation
Open a report with no saved resultMissing state shown; zero adapter dispatches
Refocus the window, reconnect, and remount the reportReads may repeat; zero generation submissions or dispatches
Enable configured job polling and advance its timerExisting status returned; zero additional dispatches
Submit one approved intent with the fake upstream succeedingOne accepted intent and one dispatch in the no-retry fixture
Fail the submission response with the mutation configured as shownNo automatic second mutation-function invocation
Send two concurrent copies of the same intent directly to the backendOne job and at most one dispatch in the no-retry fixture
Lose the acceptance response after dispatch, then reloadOriginal identity remains recoverable; status lookup creates no replacement
Deny authorization or budget admissionZero adapter dispatches
Accept the mutation, then refetch report stateRead activity cannot create a second generation

The backend duplicate test must bypass the disabled button. Otherwise it only demonstrates the interface state. Also check remounting after cache collection; a successful warm-cache test leaves that path unexamined. Run these checks whenever shared defaults or request wrappers change.

Reconcile attempt costs independently of UI state

Record the intent ID, attempt ID, workload, source revision, dispatch owner, retry reason, usage evidence, and settlement state. Keep prompts, output text, credentials, and sensitive document identifiers out of routine cost events. Browser read counts are useful diagnostics; only actual attempt records describe model exposure.

CometAPI’s pre-call cost guide combines model-specific prices with billable units and output limits, then directs readers to actual usage and billing records. Apply verified bounds to the selected route before admission. Do not convert a generic character heuristic or the example’s freshness window into a hard financial cap.

Compare upstream attempts per accepted generation intent before and after the change, alongside completed reports and unresolved attempts. A lower browser request count alone does not prove lower model cost. A timeout after dispatch can leave usage unknown; retain that exposure while following the ambiguous-attempt reconciliation workflow . A mutation error is not evidence that generation was free.

Failure modes

Only focus refetching is disabled. Mounting, polling, explicit refetching, or another caller can still reach generation. Make the query’s server operation a pure read.

The mutation runs from a mount effect. Visiting or remounting the component becomes the generation trigger. Require the approved submit action unless automatic generation has its own explicit product policy and budget.

A fresh intent ID is generated inside the request helper. Resubmission changes identity and defeats duplicate protection. Construct the identity before the helper runs and retain it through uncertainty.

A shared mutation key or scope is treated as deduplication. Matching state or serializing calls does not remove submitted work. Enforce identity and financial admission in durable server state.

The browser’s failure drives an unconditional server retry. The original attempt may still be running or billable. Preserve its evidence and make any replacement a bounded, owned decision.

Sources checked

Four primary public references were fetched on November 10, 2026:

These maintained technical references support an evergreen operating task, rather than a recent announcement. TanStack’s current documentation presents v5; confirm behavior against the installed release. The server admission rules and acceptance plan are recommendations derived from the documented interfaces.

FAQ

Does useQuery charge for every refetch?

It executes the configured query function according to its lifecycle and settings. Model spending occurs only if that execution reaches a paid generation path. An authorized read of stored state can refetch without creating a model attempt.

Is useMutation with retry disabled enough?

It removes automatic retries from that mutation configuration. Repeated submissions, other retry layers, and uncertain requests still require durable identity, budget admission, and attempt reconciliation.

Should status polling be removed?

Keep polling when the interface needs it, with an appropriate read frequency. Verify that polling an absent, failed, or unresolved job never creates another generation.

Reader next step

Trace one report query to its server handler. Replace any generation-on-read behavior with stored state, move submission into an explicit mutation, and run the empty-cache, focus, and lost-response checks with a fake adapter.

When those boundaries pass, Start with CometAPI for a bounded check of the selected model route. Retain the intent, attempt, and usage evidence before expanding traffic.