Last reviewed: November 13, 2026 (UTC and Asia/Shanghai).
Direct answer
Keep CometAPI generation outside every Firestore transaction callback. Use the transaction to commit a budget reservation or a single dispatch claim, then let the successful caller perform one separately recorded model attempt. Persist the captured result in another transaction whose retries cannot reach the model adapter.
Firebase’s transaction reference says a transaction function can run again when a concurrent edit affects a document it reads. Firestore applies database writes at successful commit. A model request made inside that function is an external action: the database rollback cannot undo its generation. That last consequence is an application design inference from the documented transaction boundary.
This creates a spending trigger even when the CometAPI client has automatic retries disabled. A database retry can re-enter the code that sends the request.
Who this is for
This guide is for application engineers and AI cost owners using Firestore to coordinate summaries, document processing, or other CometAPI jobs. It assumes server-side credentials, an application-owned dispatcher, and durable attempt records. Clients must not be able to write their own dispatch authorization or reservation amounts.
The design below is a recommended integration pattern. It does not establish exactly-once external execution or a billing exemption for rolled-back database work. No authenticated CometAPI generation, Firestore deployment, or billing experiment was performed for this article.
Key takeaways
- Treat transaction callbacks as code that may execute repeatedly.
- Commit budget admission and dispatch ownership before generation.
- Return the decision from the transaction; avoid a mutable outer
shouldSendflag. - Generate once outside the callback, then retry persistence using the same captured response.
- Keep uncertain claims and remote outcomes visible instead of resetting them to ready.
- Count callback executions separately from upstream attempts and settled usage.
Contract details to verify
Find the callback that can spend
Trace every runTransaction callback into its helpers. Look for direct HTTP calls, SDK generation methods, cache-fill helpers, and error handlers that regenerate a missing result. A helper named ensureSummary still spends if a cache miss reaches CometAPI.
This abbreviated pattern is unsafe:
// Anti-pattern: generation is inside code Firestore can replay.
await db.runTransaction(async (tx) => {
const snapshot = await tx.get(jobRef);
if (snapshot.get("state") !== "ready") return;
const response = await callCometOnce(frozenRequest);
tx.update(jobRef, { state: "complete", response });
});
If the callback runs twice, both executions can reach callCometOnce, even if only one database result commits. If the transaction ultimately fails after generation, the database can contain no completed job while the remote work still needs accounting. The name callCometOnce describes one adapter invocation; it cannot prevent its caller from invoking it again.
Firebase’s contention and isolation reference
documents automatic transaction retries after contention and an eventual ABORTED failure after finite retries. It also distinguishes mobile/web concurrency behavior from server libraries and database settings. Review the deployed SDK and database configuration; do not assume every transaction uses the same locking mechanism or a universal retry count.
Freeze identity before entering the transaction
Assign the logical job and attempt identities outside the callback. Bind an attempt to the authorized workload, immutable input revision, request fingerprint, model route, output policy, and pricing revision. Repeated delivery of that job must find its existing attempt rather than create a new document every time.
Use an opaque application identity. A Firestore document ID is not automatically a CometAPI idempotency key. Upstream duplicate suppression requires documented support for the exact route; the design here does not depend on it.
Reserve the covered exposure in the same admission transaction that creates the ready attempt. Read the required job, attempt, and budget documents before scheduling writes, as Firebase requires. Validate existing identity bindings and check all applicable allowances. A duplicate returns existing state without another reservation.
Use the site’s atomic reservation workflow for the financial invariant. A configured average request cost is a forecast. A claimed monetary ceiling additionally needs verified bounds for the covered billable components.
Return the committed claim decision
The following Node.js integration fragment assumes an initialized server Firestore client and an existing, authorized, reserved attempt. Only the controlled dispatcher can change its state. ownerToken is created outside the callback for this worker invocation.
async function claimReadyAttempt(db, attemptRef, ownerToken) {
return db.runTransaction(async (tx) => {
const snapshot = await tx.get(attemptRef);
if (!snapshot.exists || snapshot.get("state") !== "ready") {
return false;
}
tx.update(attemptRef, {
state: "claimed",
ownerToken,
});
return true;
});
}
// Only the invocation receiving a confirmed true may proceed.
const mayDispatch = await claimReadyAttempt(db, attemptRef, ownerToken);
if (mayDispatch) {
// One bounded adapter invocation, outside every transaction callback.
// Capture its response before starting separate result persistence.
}
Firebase’s transaction reference demonstrates returning information from a transaction instead of changing application state inside its function. Apply that rule to authorization to spend. If a callback first returns true but its write loses a conflict, a later execution can observe another owner and return false. Only the final successful transaction result governs dispatch.
A mutable outer flag can retain the discarded execution’s true value. Resetting a flag by convention is fragile; returning the decision makes the required boundary explicit. If the transaction rejects or its outcome is uncertain, do not proceed to generation.
Treat the claim as consumed once granted. An existing claimed document returns false, including when its stored token equals the caller’s token. Token equality alone must not grant another send. Do not reset a claim on a timer or attach this fragment to an unbounded whole-workflow retry loop.
Operator workflow
Separate the four stages
Use this sequence for one admitted attempt:
| Stage | Allowed work | Failure treatment |
|---|---|---|
| Admission transaction | Read identity and budgets; reserve; create ready attempt | Retry database work within policy; no model call |
| Claim transaction | Change ready to claimed; return the decision | Unconfirmed outcome prevents dispatch |
| Generation outside transactions | Invoke the approved adapter once; capture result and usage | Preserve ambiguous remote outcome; no blind replay |
| Settlement transaction | Persist captured evidence and settle the reservation once | Retry persistence with the same evidence; no generation |
Keep retries owned by the correct stage. Audit SDK, gateway, and job-runner retries in addition to Firestore. For the initial no-retry fixture, the model adapter must make at most one outbound attempt. A later approved model retry needs its own attempt identity and reservation while retaining any earlier unresolved exposure.
A committed ready record also gives a recovery scanner durable work to find if scheduling fails. Duplicate scanner or queue deliveries must still pass the claim transaction. Creating durable work does not itself make external execution exactly once.
Settle captured evidence without generating again
CometAPI’s Chat Completions reference
documents POST /v1/chat/completions, a completion id, and the response usage object used for billing. Preserve those fields against the attempt when returned. Use the verified price revision to calculate usage cost, keeping invoice confirmation separate.
Once a response arrives, construct a fixed settlement record outside the persistence callback. Bind it to the attempt and evidence identity. In the settlement transaction, read current state first; the same already-applied evidence returns without another debit. Different evidence for an already-settled attempt opens reconciliation. Apply the usage cost and release its reservation together.
The callback may write the same captured result again during a database retry. It must never call generateAndSave() or any helper that regenerates when saving fails. If persistence remains unavailable, retain the captured evidence through the application’s approved durable recovery path. If a crash loses that evidence, keep the attempt unresolved and reconcile it; do not purchase a replacement automatically.
Preserve the uncertainty gap
A worker can stop after committing its claim but before sending. It can also stop after sending but before saving the response. Both can leave a claimed record. The record alone cannot distinguish those histories.
Keep the reservation until evidence supports release or settlement. A lease expiry, old timestamp, or missing completion document does not prove that dispatch never occurred. Releasing money also requires preventing a delayed old worker from sending afterward. Use the site’s ambiguous-attempt reconciliation guide for that recovery decision.
This conservative claim design trades automatic recovery for protection against repeated sends. Define an operator path for stalled work, including what evidence permits a newly admitted replacement. Do not silently turn stale claimed records back into ready.
Measure the cost of callback replay
Track logical jobs, transaction callback executions, confirmed dispatch claims, outbound attempts, and settlement events separately. A callback count is diagnostic activity, not a count of billable generations. An HTTP 2xx count also omits unresolved attempts.
Consider 1,000 logical jobs. Suppose 80 transaction callbacks execute one extra time, every callback execution reaches generation, and each model attempt costs a hypothetical average of $0.004. That produces 1,080 attempts and an illustrative $4.32 of model cost. One generation per job would be 1,000 attempts and $4.00: $0.32 less under those assumptions.
These are hypothetical costs, not CometAPI prices, observed savings, or a maximum exposure. Real usage varies. The corrected design can still incur Firestore activity, coordination cost, and separately approved model retries. Compare actual attempt usage and unresolved exposure before crediting savings.
Record attempt ID, job ID, transaction stage, callback execution count, claim outcome, route revision, provider response ID, reported usage, calculated cost, and evidence state. Keep prompts, generated content, credentials, and unrestricted error bodies out of routine cost logs.
Smoke-test workflow
Start with a counted fake adapter and no usable provider credential. Exercise callback replay directly, then validate concurrency and commit behavior against the actual Firestore integration in a disposable environment. A fake callback runner alone does not establish Firestore’s transaction semantics. The table describes acceptance criteria, not reported deployment results.
| Scenario | Required observation |
|---|---|
| Admission callback executes twice before one commit | One durable reservation; zero adapter calls from the callback |
| Claim callback first proposes ownership, then retries and finds another owner | Final decision is false; this worker makes zero adapter calls |
Two workers compete for one ready attempt | One confirmed grant and one fake generation in the successful no-retry fixture |
| Claim transaction ultimately rejects | Zero generation by that invocation; uncertainty remains visible |
| Settlement callback executes twice | Same captured response reused; one debit and reservation release; no new generation |
| Worker stops after claim, near dispatch, or after response | Attempt is held for reconciliation; no timer-based redispatch |
| Duplicate job delivery arrives after completion | Existing result or state returned; no new reservation or generation |
| Same attempt receives conflicting settlement evidence | Controlled reconciliation; no second automatic debit |
Instrument the real adapter boundary, not only the top-level handler. Confirm that a persistence failure cannot trigger a job-runner catch block that reruns the entire generation stage. Preserve candidate-specific logs for the competing-worker and losing-claim cases before rollout.
Failure modes
Disabling HTTP retries is treated as sufficient. Firestore replay can still invoke the adapter again. Remove generation from the callback and inspect each enclosing retry boundary.
A discarded callback leaves a spend flag behind. An outer variable says this worker won even though its claim did not commit. Use the returned successful transaction result.
Every retry allocates a new attempt ID. Duplicate delivery creates fresh reservations and permission to spend. Resolve the durable logical job identity before admission.
Saving is coupled to generating. A database write failure calls the provider again. Persist fixed captured evidence through a separate path.
A stale claim is treated as unused budget. The original worker may already have sent or may still send. Reconcile its identity and stop old dispatch before releasing funds or authorizing replacement.
Sources checked
Three primary public references were fetched successfully on November 13, 2026:
- Firebase: Transactions and batched writes — callback replay, read-before-write ordering, atomic database writes, and passing results out of transactions. The page displays a November 12, 2026 update.
- Firebase: Transaction serializability and isolation — contention retries, terminal failure, concurrency-control differences, and database isolation. The page displays a November 12, 2026 update.
- CometAPI: Create a chat completion — generation route, response identity, usage accounting, and output controls. The page displays an October 8, 2026 modification date.
These maintained technical references support an evergreen integration task. Their access and update dates do not imply a new feature release. The dispatch design, financial treatment, worked example, and acceptance matrix are application recommendations derived from the documented interfaces.
FAQ
Does a failed Firestore transaction cancel a CometAPI request?
The documented transaction covers Firestore reads and writes. Do not infer cancellation or reversal of a separate HTTP generation from a database failure. Preserve the remote attempt and reconcile its evidence.
Can moving the call after runTransaction solve everything?
It removes generation from that callback’s replay. It still needs a committed single-use claim, duplicate-delivery handling, controlled surrounding retries, and recovery for uncertain dispatch. Returning a job document after every transaction is not permission for every caller to send it.
Should the application reduce Firestore retries instead?
Review contention and retry configuration for database performance, but do not use a retry count as the financial boundary. The callback should remain safe to repeat. The useful acceptance condition is that database replay creates no extra model attempt.
Is an unresolved claimed attempt a failed generation?
It is an unresolved attempt. It might never have dispatched, or its response might have been lost. Keep cost and product outcome distinct until evidence resolves them.
Reader next step
Choose one Firestore callback that currently reaches your model adapter. Separate admission, claim, generation, and settlement, then run the losing-claim and repeated-settlement fixtures with a counted fake adapter.
When those checks pass, Start with CometAPI for one approved bounded integration check. Reconcile its attempt, response identity, and usage before enabling the worker for more jobs.