Skip to main content

Why budget control matters

An AI agent calling paid APIs in a loop can rack up costs fast. Budget control lets you:
  • Cap total spend per session
  • Set per-domain limits (e.g., max 100 sats/session on api.weather.com)
  • Receive a callback before each payment
  • Get a full spending report at any time

Global budget

When a 402 response includes a priceSats field and it would exceed the remaining budget, the client throws BudgetExceededError before paying — no satoshis are spent.

Per-domain budget

Per-domain limits are checked independently from the global limit — both must pass for the payment to proceed.

Callbacks

onBudgetExceeded / on_budget_exceeded is called just before BudgetExceededError is thrown — useful for logging or alerts.

Spending report

spendingReport() returns null / None when no budget is configured.

Handling BudgetExceededError


Concurrency notes

Do not share one L402Client instance across concurrent Promise.all calls when budget limits matter.BudgetTracker.check() and record() are separated by an await (the Lightning payment). Two concurrent client.fetch() calls to different endpoints can both pass the budget check before either records the spend — meaning the combined cost can temporarily exceed your budget cap by one payment.Safe pattern — sequential calls:
Risky pattern — parallel calls:
Mitigation for parallel workloads: set your budgetSats conservatively (e.g. 80% of your true limit) to absorb the over-spend from one concurrent payment. For strict enforcement, process calls sequentially.

Full options reference