Skip to content
cost-accrual-tracker logo

Cost Accrual Tracker

cost-accrual-tracker

Track real-time API cost accrual during LLM execution. Activate on 'cost tracking', 'token usage', 'API costs', 'budget monitoring', 'usage metrics'. NOT for cost estimation, pricing tiers,

SKILL.md

Full skill instructions

Cost Accrual Tracker

Real-time tracking of API costs during LLM execution with support for partial costs on abort.

When to Use

✅ Use for:

  • Implementing real-time cost tracking during execution
  • Capturing partial costs when executions are aborted
  • Building cost display widgets for execution UIs
  • Integrating token counting into execution pipelines
  • Adding budget thresholds with auto-stop

❌ NOT for:

  • Cost estimation before execution (use pricing calculators)
  • Billing system design (use billing-system skill)
  • Price tier management or discounts
  • Historical cost analytics dashboards

Core Patterns

1. Token-Based Cost Calculation

interface TokenUsage {
  inputTokens: number;
  outputTokens: number;
  cacheReadTokens?: number;   // Prompt caching hits
  cacheWriteTokens?: number;  // Prompt caching misses
}

interface CostCalculation {
  inputCostUsd: number;
  outputCostUsd: number;
  cacheSavingsUsd?: number;
  totalCostUsd: number;
}

function calculateCost(usage: TokenUsage, model: string): CostCalculation {
  const pricing = MODEL_PRICING[model];

  const inputCostUsd = (usage.inputTokens / 1_000_000) * pricing.inputPerMTok;
  const outputCostUsd = (usage.outputTokens / 1_000_000) * pricing.outputPerMTok;

  return {
    inputCostUsd,
    outputCostUsd,
    totalCostUsd: inputCostUsd + outputCostUsd,
  };
}

2. Incremental Accrual Pattern

Track costs as they accrue, not just at completion:

class CostAccrualTracker {
  private totalInputTokens = 0;
  private totalOutputTokens = 0;
  private accruedCostUsd = 0;
  private readonly model: string;

  constructor(model: string) {
    this.model = model;
  }

  /​**
   * Called after each API response (streaming or complete)
   */
  recordUsage(usage: TokenUsage): void {
    this.totalInputTokens += usage.inputTokens;
    this.totalOutputTokens += usage.outputTokens;

    const cost = calculateCost(usage, this.model);
    this.accruedCostUsd += cost.totalCostUsd;
  }

  /​**
   * Get current accrued cost (for real-time display)
   */
  getCurrentCost(): number {
    return this.accruedCostUsd;
  }

  /​**
   * Finalize on completion or abort
   */
  finalize(reason: 'completed' | 'aborted' | 'failed'): CostReport {
    return {
      totalInputTokens: this.totalInputTokens,
      totalOutputTokens: this.totalOutputTokens,
      totalCostUsd: this.accruedCostUsd,
      completionReason: reason,
      finalizedAt: Date.now(),
    };
  }
}

3. Abort-Aware Cost Capture

Critical: Always capture partial costs on abort:

// In execution handler
const tracker = new CostAccrualTracker(model);

try {
  for await (const chunk of executeStream(request)) {
    if (abortSignal.aborted) {
      // CRITICAL: Capture cost BEFORE throwing
      const partialCost = tracker.finalize('aborted');
      onCostUpdate(partialCost);
      throw new AbortError('Execution aborted');
    }

    tracker.recordUsage(chunk.usage);
    onCostUpdate(tracker.getCurrentCost());
  }

  return tracker.finalize('completed');
} catch (error) {
  if (error instanceof AbortError) {
    throw error; // Already handled
  }
  return tracker.finalize('failed');
}

4. Budget Threshold Pattern

Auto-stop execution when budget is exceeded:

interface BudgetConfig {
  maxCostUsd: number;
  warnAtPercentage: number;  // e.g., 0.8 for 80%
  onWarn?: (current: number, max: number) => void;
  onExceed?: (current: number, max: number) => void;
}

function createBudgetGuard(config: BudgetConfig) {
  return {
    check(currentCostUsd: number): 'ok' | 'warn' | 'exceed' {
      const percentage = currentCostUsd / config.maxCostUsd;

      if (percentage >= 1.0) {
        config.onExceed?.(currentCostUsd, config.maxCostUsd);
        return 'exceed';
      }

      if (percentage >= config.warnAtPercentage) {
        config.onWarn?.(currentCostUsd, config.maxCostUsd);
        return 'warn';
      }

      return 'ok';
    }
  };
}

Anti-Patterns

Lost Costs on Abort

Novice thinking: "Just throw an error when aborted"

Reality: If you don't capture costs before aborting, you lose:

  • Token usage data for partial execution
  • Accurate cost reporting for billing
  • Audit trail for debugging

Timeline: Always been an issue, but became critical with expensive models (GPT-4, Claude Opus)

Correct approach: Always call finalize() with partial data BEFORE throwing abort errors.

Polling Without Debounce

Novice thinking: "Poll cost endpoint every 100ms for real-time updates"

Reality:

  • Wastes bandwidth and CPU
  • Cost updates only happen after API responses
  • Polling faster than response rate is pointless

Correct approach: Poll at 1-2 second intervals, or use event-driven updates from the execution stream.

Ignoring Prompt Caching

Novice thinking: "Just multiply tokens by price per token"

Reality: Claude's prompt caching changes the cost model:

  • Cache reads are 90% cheaper
  • Cache writes cost extra on first use
  • Ignoring caching leads to inaccurate costs

Timeline:

  • Pre-2024: No caching, simple calculation
  • 2024+: Claude prompt caching requires separate tracking

Correct approach: Track cache_read_input_tokens and cache_creation_input_tokens separately.

Per-Request Cost Objects

Novice thinking: "Create new tracker for each request"

Reality: For DAG execution with multiple nodes:

  • Need aggregate cost across all nodes
  • Need to attribute costs to specific nodes
  • Need rollup for parent execution

Correct approach: Hierarchical tracking - per-node trackers that roll up to execution-level.

State Flow

                    ┌─────────────────────────────────────────┐
                    │           CostAccrualTracker            │
                    └─────────────────────────────────────────┘
                                        │
              ┌─────────────────────────┼─────────────────────────┐
              │                         │                         │
              ▼                         ▼                         ▼
    ┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
    │  recordUsage()  │     │ getCurrentCost()│     │   finalize()    │
    │                 │     │                 │     │                 │
    │ After each API  │     │ For real-time   │     │ On completion,  │
    │ response        │     │ display         │     │ abort, or fail  │
    └─────────────────┘     └─────────────────┘     └─────────────────┘
              │                         │                         │
              │                         │                         │
              ▼                         ▼                         ▼
    ┌─────────────────────────────────────────────────────────────────┐
    │                        CostReport                               │
    │  { inputTokens, outputTokens, totalCostUsd, completionReason }  │
    └─────────────────────────────────────────────────────────────────┘

UI Display Pattern

For real-time cost display in execution UIs:

// Poll every 2 seconds while executing
useEffect(() => {
  if (status !== 'running') return;

  const interval = setInterval(async () => {
    const response = await fetch(`/​api/​execute/​${executionId}`);
    const data = await response.json();
    setAccruedCost(data.cost.accruedUsd);
    setTokens({
      input: data.cost.inputTokens,
      output: data.cost.outputTokens,
    });
  }, 2000);

  return () => clearInterval(interval);
}, [executionId, status]);

// Display format
<div className="cost-display">
  <span className="cost-amount">${accruedCost.toFixed(4)}</​span>
  <span className="token-count">
    {tokens.input.toLocaleString()} in / {tokens.output.toLocaleString()} out
  </​span>
</​div>

Integration Points

ComponentResponsibility
CostAccrualTrackerPer-execution token counting and cost calculation
ExecutionManagerAggregates costs across DAG executions
BudgetGuardThreshold monitoring and auto-stop
/​api/​execute/:idExposes current cost via polling
Cost Display WidgetReal-time UI rendering

References

See /​references/​claude-api-pricing.md for current Claude API pricing.

More skills from curiositech

recovery-education-writer logo
curiositech/some_claude_skills

recovery-education-writer

Write neuroscientific, peer-oriented drug education content that roots experiences in body/brain mechanisms. Use when creating educational articles, explaining neurological phenomena, demystifying

242 0
View
crisis-response-protocol logo
curiositech/some_claude_skills

crisis-response-protocol

Handle mental health crisis situations in AI coaching safely. Use when implementing crisis detection, safety protocols, emergency escalation, or suicide prevention features. Activates for crisis

242 0
View
websocket-streaming logo
curiositech/some_claude_skills

websocket-streaming

Implements real-time bidirectional communication between DAG execution engines and visualization dashboards via WebSocket. Covers connection management, typed event protocols, reconnection

242 0
View
document-generation-pdf logo
curiositech/some_claude_skills

document-generation-pdf

Generate, fill, and assemble PDF documents at scale. Handles legal forms, contracts, invoices, certificates. Supports form filling (pdf-lib), template rendering (Puppeteer, LaTeX), digital

242 0
View
drone-cv-expert logo
curiositech/some_claude_skills

drone-cv-expert

Expert in drone systems, computer vision, and autonomous navigation. Specializes in flight control, SLAM, object detection, sensor fusion, and path planning. Activate on "drone", "UAV", "SLAM",

242 0
View
openapi-spec-writer logo
curiositech/some_claude_skills

openapi-spec-writer

Expert in writing OpenAPI 3.0/3.1 specifications for REST APIs. Specializes in schema design, documentation best practices, API-first development, and tooling integration. Generates comprehensive

242 0
View
recovery-app-onboarding logo
curiositech/some_claude_skills

recovery-app-onboarding

Expert guidance for designing and implementing onboarding flows in recovery, wellness, and mental health applications. This skill should be used when building onboarding experiences, first-time

242 0
View
skill-coach logo
curiositech/some_claude_skills

skill-coach

Guides creation of high-quality Agent Skills with domain expertise, anti-pattern detection, and progressive disclosure best practices. Use when creating skills, reviewing existing skills, or when users mention improving skill quality, encoding expertise, or avoiding common AI tooling mistakes. Ac...

242 0
View
windows-3-1-web-designer logo
curiositech/some_claude_skills

windows-3-1-web-designer

Modern web applications with authentic Windows 3.1 aesthetic. Solid navy title bars, Program Manager navigation, beveled borders, single window controls. Extrapolates Win31 to AI chatbots (Cue

242 0
View
logging-observability logo
curiositech/some_claude_skills

logging-observability

Structured logging, distributed tracing, and metrics for production applications. [What: OpenTelemetry setup, log level strategy, correlation IDs, SLI/SLO alerting thresholds, Grafana dashboard

242 0
View
form-validation-architect logo
curiositech/some_claude_skills

form-validation-architect

End-to-end form handling with react-hook-form, Zod schemas, validation patterns, error messaging, field arrays, and multi-step wizards. Use for complex forms, validation architecture, autosave,

242 0
View
code-review-checklist logo
curiositech/some_claude_skills

code-review-checklist

Generate context-aware code review checklists from PR diffs — tailored to language, codebase patterns, and team standards. Identifies what reviewers should focus on. NOT for automated code

242 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View