Spend Ledger

A SpendLedger holds one budget for everything an agent spends: model calls and payments draw on the same limits. Set it on RunConfig::spend_ledger and every model call reserves its upper-bound cost before it is sent, while the payment tools reserve each checkout before it completes.

Reserve, commit, release

StepMethodEffect
Before spendingreserve(&key, amount)Holds the amount against every limit that covers the key, or fails with spend.limit_exceeded
After spendingcommit(id, actual)Records the actual amount and drops the hold
When nothing was spentrelease(id)Drops the hold

Amounts are integer micro-USD (1_000_000 is one US dollar). A hold that is neither committed nor released stops counting once its time to live passes (15 minutes by default), so a process that dies mid-call does not lock budget. A commit is recorded even when it exceeds the reservation or a limit: the money was already spent.

Keys and limits

A SpendKey names an organization and, optionally, one agent and one vendor. A reservation attributes spend to its key; a limit caps every entry its key covers within a period.

PeriodWindow
SpendPeriod::DayUTC calendar day
SpendPeriod::MonthUTC calendar month
SpendPeriod::LifetimeAll recorded spend
use adk_core::{InMemorySpendLedger, SpendKey, SpendLimits, SpendPeriod};

let ledger = InMemorySpendLedger::new(
    SpendLimits::new()
        // 50 USD per day for the whole app
        .limit(SpendKey::org("support-app").per(SpendPeriod::Day), 50_000_000)
        // 200 USD per month on Gemini
        .limit(
            SpendKey::org("support-app").with_vendor("gemini").per(SpendPeriod::Month),
            200_000_000,
        )
        // 5 USD per day for one agent
        .limit(
            SpendKey::org("support-app")
                .with_agent("urn:adk:agent:support-app/triage")
                .per(SpendPeriod::Day),
            5_000_000,
        ),
);

Every limit that covers a reservation is checked, so the app, vendor, and agent caps above apply together.

Backends

LedgerCrate and featureConcurrency
InMemorySpendLedgeradk-coreOne mutex; process-local, nothing survives a restart
SqliteSpendLedgeradk-session, sqliteBEGIN IMMEDIATE takes the write lock before the limit check
PostgresSpendLedgeradk-session, postgresSELECT ... FOR UPDATE on the organization's row
RedisSpendLedgeradk-session, redisOne Lua script per reservation
MongoSpendLedgeradk-session, mongodbCompare-and-set on the organization document
Neo4jSpendLedgeradk-session, neo4jTransaction that writes the organization node first
FirestoreSpendLedgeradk-session, firestoreSerializable transaction over the organization's documents

Concurrent reservations never overshoot a cap; every backend passes the same conformance suite (see Durable Stores). Limits are configuration, not data: give every process that shares a database the same SpendLimits. with_clock replaces the system clock, which tests use to cross a day or month boundary.

use adk_core::{SpendKey, SpendLimits, SpendPeriod};
use adk_session::SqliteSpendLedger;

let ledger = SqliteSpendLedger::new("sqlite://spend.db?mode=rwc")
    .await?
    .with_limits(SpendLimits::new().limit(SpendKey::org("support-app").per(SpendPeriod::Day), 50_000_000));
ledger.migrate().await?;

Model spend

With a ledger on the run config, every model call made on behalf of the run reserves before it is sent and commits once it completes, through adk_core::ModelCallScope. The key is the runner's app name, the calling agent's AgentId (see Agent Identity; urn:adk:agent:{app}/{agent} unless configured), and the vendor. The reservation precedes the response, so it names the vendor read from the model id (gemini-* is gemini, claude-* is anthropic, gpt-*, chatgpt*, codex*, o1, o3, and o4 are openai, deepseek-* is deepseek, grok-* is xai, Mistral model families are mistral; unrecognized ids are unknown). The cost is committed under the provider the response reports in LlmResponse::provider — bedrock for a Claude model served by Amazon Bedrock, for example.

Note: when a limit already refuses a zero-amount reservation under the reported provider, the cost is committed under the vendor read from the model id and a warning is logged. Organization and agent totals are correct either way.

Hard caps

The reservation is an upper bound on the call's cost, Llm::max_cost_micro_usd, so the committed cost never exceeds it and a cap is never overshot.

Bound termValue
Input tokensUTF-8 byte length of every text and JSON part, tool declaration and response schema (no tokenizer emits more than one token per byte), inline media at least 16,384 tokens per part, plus 2,048 tokens of framing and 16 per message and per tool
Input rateThe highest of the uncached, cache-read and cache-write rates, at the long-context tier when the input bound reaches it
Output tokensThe request's output cap (max_output_tokens, reasoning and thinking included), or the model's published output limit when the request sets none
Output rateThe model's output rate at the same tier
Built-in tool feesPer-response fees once each; per-use fees × each declared built-in tool's max_uses
ProviderOutput tokens used for the bound
Gemini, OpenAI (Chat and Responses), OpenAI-compatible, Azure AIRequest cap, else the model's output limit
AnthropicThe max_tokens the client sends (request cap, AnthropicConfig::max_tokens, or the model default)
Groq, DeepSeekThe model's output limit; neither vendor states whether reasoning counts toward the request cap
BedrockRequest cap only
Ollama (local), mistral.rsZero: local inference has no per-token price
OpenRouter, OpenCode, xAI without a request cap, unpriced modelsNo bound

A call with no bound reserves UNBOUNDED_HOLD_MICRO_USD, which every cap refuses: it is refused wherever a limit covers its key, and runs only where none does. It then commits its reported cost, or the LlmSpendEstimate when it reports none. Set an output cap on the agent (LlmAgentBuilder::max_output_tokens) to keep reservations small under a tight cap.

Important: a custom Llm wrapper must forward max_cost_micro_usd to the model it wraps; without it the wrapper's calls are unbounded and refused under a cap.

use adk_core::{RunConfig, SpendKey, SpendLimits, SpendPeriod};
use adk_runner::{LlmSpendEstimate, Runner};
use adk_session::SqliteSpendLedger;
use std::sync::Arc;

let ledger = Arc::new(
    SqliteSpendLedger::new("sqlite://spend.db?mode=rwc")
        .await?
        .with_limits(SpendLimits::new().limit(SpendKey::org("support-app").per(SpendPeriod::Day), 50_000_000)),
);
ledger.migrate().await?;

let runner = Runner::builder()
    .app_name("support-app")
    .agent(agent)
    .session_service(sessions)
    .run_config(RunConfig::builder().spend_ledger(ledger).build())
    .build()?
    // Committed by calls to unpriced models whose responses report no cost.
    .with_llm_spend_estimate(LlmSpendEstimate::per_call(50_000));
What the call returnedLedger action
A response reporting usage_metadata.costCommit that cost at the turn-complete response
Responses, but no costCommit the bound (or, for an unbounded call, the estimate) and log a warning
No response (the call failed)Release

The committed cost includes the published fees of provider-executed built-in tools — web search, file search, Google Search grounding — the call used; see Built-in tool uses and fees. The bound covers them: per-response fees once each, per-use fees up to each declared built-in tool's max_uses. A request declaring a fee-bearing built-in tool without max_uses has no bound, so it is refused under a cap.

A refused reservation fails the model call with the ledger's spend.limit_exceeded error, so the run stops before it spends past the cap.

What is metered

Every model call made on behalf of a run reserves, commits and releases through the same ledger and counts against the same run budget.

Model callMetered throughAttributed to
LlmAgent and CodeActAgent turnsModelCallScope::for_runThe calling agent
LlmConditionalAgent routingModelCallScope::for_runThe routing agent
Post-run compaction (EventsCompactionConfig)ModelCallScope, made current around the summarizerThe agent whose context is compacted
Auto-compaction (IntraCompactionConfig)ModelCallScope, made current around the summarizerThe agent whose history is compacted
Auto-compaction with a strategy (context-compaction feature)ModelCallScope, made current around the strategyThe agent whose history is compacted
MCP sampling (mcp-sampling feature)ModelCallScope of the run whose tool call is in flightThe agent that called the MCP tool

The built-in summarizers (LlmEventSummarizer, SummarisationCompaction) and LlmSamplingHandler call their model through adk_core::generate_metered, which meters against the scope the runner or the MCP client made current. A custom BaseEventsSummarizer, CompactionStrategy or SamplingHandler is metered the same way when it calls its model through generate_metered or wraps it in adk_core::MeteredLlm.

BehaviourDetail
RefusalA call the ledger or the budget refuses is never sent; a refused compaction is skipped with a warning and the run continues, a refused sampling request returns an error to the MCP server
Hold sizeThe call's upper bound; see Hard caps
Sampling outside a runCounts against the scope attached with McpToolset::with_sampling_scope, otherwise unmetered
Several runs on one MCP connectionA sampling request counts against the run whose tool call started most recently
use adk_core::{InMemorySpendLedger, ModelCallScope};
use std::sync::Arc;

// Calls outside any run: meter them explicitly.
let scope = ModelCallScope::new()
    .with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "support-app")
    .with_agent("nightly-digest");
let stream = scope.generate(model.as_ref(), request, false).await?;

Out of scope: evaluation judges, prompt optimizers and simulators in adk-eval run in the evaluation harness, not on behalf of a run; wrap their model in MeteredLlm with an explicit scope to meter them. OpenAIResponsesClient::compact_response is called by application code, not by the runner. Realtime sessions (adk-realtime) are billed per session and audio minute and do not go through the Llm trait.

Calls billed in units

Image generation, transcription and speech synthesis bill per image, per second of audio or per character, not per token. They go through ModelCallScope::meter, or adk_core::meter_usage against the current scope, which applies the same two gates:

StepSpend ledgerRun budget
Before the callReserves UsageCall::max_cost_micro_usd, or the unbounded hold when no price is knownRefuses when a limit is reached, when no price is known under a cost cap (budget.cost_unknown), or when UsageCall::units would take a unit past RunBudget::max_units (budget.units); otherwise holds those units
After the callCommits MeteredUsage::cost_micro_usd in micro-USDCounts the cost and tokens, and every unit in BudgetTracker::units, in place of the units held
Call failedReleases the holdCounts nothing; returns the units held
CallUnitPriceVendor key
MuseImagesClient::generate, editimages returned$0.01 per image (muse-image-1.0); the hold covers the requested nmuse
MuseAsrClient::transcribeaudioMillis reported$0.18 per hour, whole seconds rounded down; the hold covers the WAV file's duration, or the 10-minute file limit when the header cannot be readmuse
TranscribeToolaudioMillis sentThe provider's AudioBilling rate; none for the bundled cloud providersThe provider's
SpeakToolcharacters sentThe provider's AudioBilling rate; none for the bundled cloud providersThe provider's
VisionRuntime::analyze_video with SamVideoTrackerframes of the clip, per concept request$0.20 per 1,000 frames, at least 50 frames per request (sam-3.1)muse

adk_model::pricing::PricingCatalog::unit_cost_micro_usd prices a UsageVector from the catalog's per-unit prices (muse-image-1.0, muse-voice-transcribe-1.0, sam-3.1 images and video frames). Units are never ledger amounts: the ledger stays in micro-USD, and a unit call is not a model call.

A UnitRate prices one unit: micro_usd per per units, billed in whole multiples of its granularity, and at least minimum_per_request units for any request that uses the unit at all. UsageUnit::Frames counts video frames analysed.

use adk_core::{UnitRate, UsageUnit};

// $0.20 per 1,000 frames, at least 50 frames per request.
let rate = UnitRate::new(UsageUnit::Frames, 200_000, 1_000).with_minimum_per_request(50);
assert_eq!(rate.cost_micro_usd(12), 10_000);
assert_eq!(rate.cost_micro_usd(900), 180_000);

A run that caps a unit holds each declaring call against the cap before it is sent. A run capped at 20 images that makes 30 calls of one image each sends 20, refuses the 21st with budget.units before any request, and commits 20 holds to the ledger:

use std::sync::Arc;

use adk_core::{
    BudgetTracker, MeteredUsage, ModelCallScope, RunBudget, UsageCall, UsageUnit, UsageVector,
};

async fn segment_all(images: &[Vec<u8>]) -> adk_core::Result<usize> {
    let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 20)));
    let scope = ModelCallScope::new().with_budget(tracker);
    let one = UsageVector::new().with(UsageUnit::Images, 1);
    let mut segmented = 0;
    for _image in images {
        let call = UsageCall::new("meta", "sam-3.1")
            .with_max_cost_micro_usd(2_500)
            .with_units(one.clone());
        // The 21st call returns `budget.units` here, before the closure runs.
        scope
            .meter(call, async {
                Ok(((), MeteredUsage::new(one.clone()).with_cost_micro_usd(2_500)))
            })
            .await?;
        segmented += 1;
    }
    Ok(segmented)
}
BehaviourDetail
Inside a toolLlmAgent, CodeActAgent and the realtime runtimes make the run's scope current around every tool call (ModelCallScope::within_tool), so media calls a tool makes count against the run and its agent
Unknown priceRefused under any covering ledger limit, and under a budget cost cap unless the budget allow_unpriced_models(); without a cap the ledger commits the run's per-call spend estimate
Local modelsThe bundled local audio providers report no AudioBilling and are not metered. A local backend that meters itself declares with_max_cost_micro_usd(0) and commits its units at zero cost, so per-unit caps and unit counts cover local and remote calls alike
Kernel totalsA harness-hosted process's spend is read from its run budget, so media cost reaches the partition's daily total and Quotas::daily_spend_cap
Outside a runUnmetered unless a scope is made current
use std::sync::Arc;

use adk_core::{InMemorySpendLedger, ModelCallScope, SpendKey, SpendLimits, SpendPeriod};
use adk_model::muse::{ImageOptions, ImagesResponse, MuseConfig, MuseImagesClient};

async fn render(api_key: &str) -> adk_core::Result<ImagesResponse> {
    let cap = SpendKey::org("studio").with_vendor("muse").per(SpendPeriod::Day);
    let ledger = Arc::new(InMemorySpendLedger::new(SpendLimits::new().limit(cap, 1_000_000)));
    let scope = ModelCallScope::new().with_spend_ledger(ledger, "studio");
    let images = MuseImagesClient::new(MuseConfig::new(api_key, "muse-image-1.0"))?;
    // Holds $0.04 for four images, then commits $0.01 for each image returned.
    let options = ImageOptions { n: Some(4), ..ImageOptions::default() };
    scope.within(images.generate("a red barn at dawn", options)).await
}

Payment spend

The payment tools reserve each checkout total at completion under the key app / agent id / merchant_id, commit it when the checkout completes, and release it when the checkout fails. See Payments and Commerce.

Error codes

CodeCategoryMeaning
spend.limit_exceededForbiddenThe reservation would exceed a limit; the details carry the limit key, cap, consumed, and requested amounts
spend.ledger_unavailableUnavailableThe backing store failed; nothing was reserved
spend.unknown_reservationNotFoundThe reservation was never taken or was already settled
spend.amount_too_largeInvalidInputThe amount does not fit the ledger's storage