Notes

Count Agent Tokens With FieldValue.increment Instead of a Transaction

Firestore, Tokenomics

When an agent fires tool calls in parallel, a read-then-write transaction on one usage document retries under contention, and every retry delays the call it is counting. FieldValue.increment(promptTokens) sends the addition instead of a new total, so Firestore applies each write without reading first and 50 concurrent tool calls still add up to the right count. They are still 50 writes to one document, and the Firestore docs say "you can't update a single document at an unlimited rate", so a sustained burst on one counter can hit contention; shard the counter if one user's calls get there.

The recipe records usage; it does not enforce a limit. Refusing a call once a user passes a budget means reading the total before the write, which brings the transaction back, and a retried call still counts twice unless it carries an idempotency key.

tokenCounter.ts
import { FieldValue, type Firestore } from "firebase-admin/firestore";

export async function recordTokenUsage(
  db: Firestore, userId: string, promptTokens: number, completionTokens: number,
): Promise<void> {
  const ref = db.collection("token_usage").doc(userId);
  await ref.set(
    {
      promptTokens: FieldValue.increment(promptTokens),
      completionTokens: FieldValue.increment(completionTokens),
      totalInvocations: FieldValue.increment(1),
      lastUpdated: FieldValue.serverTimestamp(),
    },
    { merge: true }
  );
}

All 7 notes