> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gloo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Budgets and cost

> Operating envelope and org-unit budgets — scopes, periods, the spend pipeline, and how to read the analytics that fall out of it.

Last updated 2026-11-11

·
applies to 2026-09-03

·
main

This page is for operators who own cost. Budgets prevent runaway agent spend by enforcing ceilings at multiple levels of the organization. Every agent dispatch passes through three budget gates — the agent-level monthly budget, the envelope budgets, and the org-unit budget hierarchy — before execution. When any budget is exhausted, execution is blocked immediately.

For the analytics surfaces that consume the same data, see [Observability](https://docs.gloo.com/forge/run/observability.md). For the gate-level mechanics, see [Trust Fabric in production](https://docs.gloo.com/forge/run/trust-fabric.md).

When to reach for something else

Budgets are a **hard cap** mechanism — they block dispatch when a ceiling is hit. If you need a soft cap that warns but does not block, write a policy with `action: warn`. If you need to attribute spend without enforcing a ceiling (read-only analytics), use the cost aggregates directly without configuring a budget envelope. If you need real-time per-call cost, the analytics rollup runs hourly — a single dispatch's cost lands in the rollup with up to a 1-hour lag; for sub-hour latency, read an agent's token events (`GET /api/v3/agents/{agentId}/token-events`).

Coverage

Budget gating is **not workflow-only**. Workflow steps and every other agent dispatch (chat, factory, personal agent, Architect, copilot) give the same governance engine the dispatch's budget envelopes and its org unit's budget path, so the agent, envelope, and org-unit budget gates evaluate on every dispatch surface. Procedures run their own gate sequence, which has a compute-budget gate.

***

## Two layers — envelopes and org-unit hierarchy

Forge runs **two budget layers in series** at dispatch time. A dispatch must satisfy both — the tightest constraint wins.

| Layer | Designed for | Scopes / hierarchy | Periods |
| - | - | - | - |
| Envelope budgets | Operational rate limiting — capping runaway spend on a specific agent, gateway, or platform-wide | Flat, scope-based: `global`, `gateway`, `agent`, `externalApp` | `daily` / `weekly` / `monthly` |
| Org-unit budgets | Financial governance — department heads and controllers managing spend over a planning period | Hierarchical, anchored to `orgUnits._id`: budget tree mirrors the org tree | `monthly` / `quarterly` / `annual` |

A workflow node dispatching the Refund Agent for the Customer Success team in May must satisfy: the agent's monthly envelope, the org-wide envelope, *and* every org-unit budget on the ancestor path (Customer Success team → Support department → Company). If the team's monthly org-unit budget is at $4,950 of $5,000 and the dispatch would cost \$100, the gate blocks with `budget_hierarchy_exceeded` even when the envelope layer has headroom.

***

## Org-unit budgets — the canonical anchor

Org-unit budgets are anchored to `orgUnits._id` via `budgetHierarchy.orgUnitId`. The budget tree mirrors the org-unit tree: if org unit A is the parent of org unit B, then A's budget node (if it exists) is the parent of B's budget node. Not every org unit needs a budget — unset tiers are skipped at enforcement.

This is the change from the prior model. Pre-2026-05, hierarchical budgets used a stringly-typed `entityId` ("factory:abc123") to connect to the org tree. The current model uses `orgUnitId` as a first-class foreign key, which lets the gate resolve the full ancestor path in O(1) at dispatch time via the `by_org_unit` index plus a `parentBudgetId` walk.

**How operators configure them.** From Analytics → Budgets in the Forge Console, an operator with `cost:manage` picks any org unit and creates a budget node: `limitCents`, `periodType` (`monthly` / `quarterly` / `annual`), and an optional alert threshold. The system looks up the parent org unit's budget and wires `parentBudgetId` automatically. A soft warning fires if the sum of sibling budgets at the same level exceeds the parent's limit — the write succeeds anyway because hard enforcement happens at spend time, not at definition time.

**What the spent counter represents.** Each `budgetHierarchy` row carries a running `spentCents` counter. One batched writer applies spend: oldest first, it takes each token event that has not been charged yet and, in a single transaction, charges the agent's monthly spend, the envelopes, and every ancestor org-unit node. It then marks the event with the exact amount it contributed, so clearing a retried attempt reverses precisely what it charged. There is no "transaction sum at dispatch time" — the counter is the truth. The `budgetTransactions` rows still record every write for historical audit, but the gate never reads them.

**Period resets.** At each monthly, quarterly, or annual period boundary, Forge zeroes `spentCents` and moves `currentPeriodStart` forward. Alert `triggered` flags clear on reset so they can re-fire in the new period. Transaction log rows are preserved.

**Operator controls.** A node's `status` can be flipped to `FROZEN` (block all dispatch against this subtree until unfrozen) or `CLOSED` (permanent end of life). `switches:use` is the permission for envelope freeze; `cost:manage` covers everything else, with no subtree restriction — a financial controller can configure budgets across the entire org.

***

## Budget periods

Each budget has a period that determines its reset cycle. Periods differ by layer because the two layers solve different problems — envelopes cover short windows for rate limiting, org-unit budgets cover planning horizons.

| Layer | Period | Reset | Use case |
| - | - | - | - |
| Envelope | `daily` | Daily 00:00 UTC | High-frequency agents, rapid iteration |
| Envelope | `weekly` | Monday 00:00 UTC | Sprint-aligned envelopes |
| Envelope | `monthly` | 1st of month, 00:05 UTC | The default envelope period |
| Org-unit | `monthly` | 1st of month, 00:10 UTC | Most team and department budgets |
| Org-unit | `quarterly` | 1st of quarter, 00:12 UTC | Planning-cycle budgets |
| Org-unit | `annual` | January 1st, 00:15 UTC | Annual departmental allocations |

A budget configured with `periodType: monthly` and `limitCents: 500000` enforces \$5,000 per calendar month. On the 1st, the spend counter resets to zero, alert flags clear, and the gate is re-armed for the new period.

Daily and weekly periods are intentionally absent from the org-unit layer — they belong to rate limiting, not financial planning.

***

## The spend pipeline — where every token flows

Every LLM call produces a `tokenEvents` row with the model, agent, gateway, token counts, and the cost computed against the pricing snapshot in effect at capture time. From there, the data fans out:

* **`tokenEvents`** — the canonical raw record. Indexed by agent, model, run, gateway, chat session, trigger message. Reactive — analytics surfaces query this table directly.
* **`factoryTokenEvents`** — fan-out copy for factory-scoped events. Powers the Factories tab in Analytics.
* **`costAggregates`** — pre-rolled aggregates across hourly / daily / weekly / monthly buckets. Three crons keep them current: hourly rollup (every hour, 2-hour lookback), daily rollup (every 24 hours, 2-day lookback), and a compaction pass that also runs hourly (hourly → daily past 30 days, daily → weekly past 90 days).

Cost is computed at write time and the pricing snapshot is stored on the event for audit. **This is critical**: if a model's price changes later, your historical analytics stays reproducible. The cost-at-capture is what was charged; the snapshot is the price book in effect when the call was made. Compliance does not need to reconcile against a moving pricing API.

***

## Token attribution — two parallel hierarchies

Every token event is attributed through two parallel hierarchies, both originating from the same `tokenEvents` row.

| Chain | Rolls up through | Question it answers |
| - | - | - |
| **Task chain** | Token → Task → Workflow → Project → Objective | "How much did this objective cost to deliver?" |
| **Worker chain** | Token → Worker → Team → Department → Company | "How much did each team or worker spend this month?" |

The two chains let finance and engineering ask different questions of the same data. Finance asks the worker chain ("what did the Customer Success team cost?"). Engineering asks the task chain ("how much did we spend running the refund workflow?"). Both queries hit the same `tokenEvents` rows; the indexes resolve the rollup.

For a factory specifically, every token event is attributed through `factoryTokenEvents` with `factoryId` attached. This is what powers Analytics → Cost → Factories — cost-per-factory over time, sorted by spend, so operators can see which factories consume the most resources without manual aggregation.

***

## Reading the analytics surfaces

Once the spend pipeline is live, the operator-facing surfaces in Forge Console (Analytics — The Ledger) read from the aggregates:

| Surface | What it answers |
| - | - |
| **Cost** | Total \$ over time, by agent, model, team, factory. The top-line number. |
| **Throughput** | Latency / throughput / queue wait per agent and per gateway. |
| **Reliability** | Failure rate and retry rate per agent / model / gateway. |
| **Agent Performance** | Per-agent cost, success rate, dispatch count. The agent fleet leaderboard. |

All four surfaces query `costAggregates` for time-series data and `tokenEvents` directly when sub-hour latency is required. CSV export is available on every surface. Per-gate pass and block counts, and governance reports, live in Trust Fabric → Decisions.

***

## Operator runbook

When you set up budgets and ongoing spend ops:

1. **Build the org-unit tree first.** Hierarchical budgets anchor to `orgUnits._id`. Before you can configure a department budget, the department has to exist as an org unit. Run org-structure setup once, then layer budgets on top.
2. **Start with team-level org-unit budgets.** They are the load-bearing constraint for most teams. Set a monthly limit at the team org unit, let the parent department and company budgets be larger (or unset) until you have evidence you need them. The gate walks ancestors — the tightest constraint wins.
3. **Layer envelopes only where you need a hard agent or gateway ceiling.** Envelope budgets are the rate-limit layer. Use them when a specific agent or gateway has known cost-explosion risk; reach for them after the org-unit hierarchy is in place.
4. **Configure the global envelope last.** The platform-wide envelope is the nuclear option — set it high enough that the org-unit hierarchy fires first. Global is the backstop, not the daily lever.
5. **Read the cost-snapshot field.** Every `tokenEvents` row has `costAtCapture` and `pricingSnapshot.input` / `pricingSnapshot.output`. If your monthly spend looks off, check whether a model's price changed mid-month. Forge will not retroactively re-cost old events; that is by design.
6. **Watch routing decisions.** When agents go through Gloo-AI's routing tier, the chosen tier and confidence land on `tokenEvents.routingTier` and `routingConfidence`. Tiered routing is one of the biggest cost levers — confirm the router is making the choices you expect.
7. **Remember the non-workflow surfaces.** Budget gates evaluate on chat, factory, personal-agent, architect, and copilot dispatch through the same Trust Fabric gate sequence, exactly as they do on workflow steps. An org-unit budget you set covers all of them — size it for total workload, not just for scheduled workflow runs.

***

## Do it over the API

These calls use the `FORGE_BASE` set up in the Raw HTTP tab of the [quickstart](https://docs.gloo.com/forge/quickstart.md). These operations refuse an External App token: send a [Personal key](https://docs.gloo.com/forge/console/settings/personal-keys.md#choose-a-credential) or a platform API key as the bearer instead of the quickstart's `ACCESS_TOKEN`, with scopes that include `cost:manage` and `cost:read`. `cost:manage` is elevated, so tick **Include elevated permissions** when you choose the key's scopes (see [Approve and administer scopes](https://docs.gloo.com/forge/console/settings/personal-keys.md#approve-and-administer-scopes)). They manage org-unit budgets; envelope budgets have their own operations under `/api/v3/cost-limits`.

Create a monthly \$5,000 budget at an org unit. `data` is the new budget's id; add `parentBudgetId` to place it under a parent budget.

```bash theme={null}
BUDGET_ID=$(curl -sS -X POST "$FORGE_BASE/api/v3/cost-budgets" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: budget-customer-success-monthly-v1" \
  -d "{\"name\": \"Customer Success monthly\", \"orgUnitId\": \"$ORG_UNIT_ID\", \"limitCents\": 500000, \"periodType\": \"monthly\"}" \
  | jq -r '.data')
```

Add a spend-threshold alert at 80% of the limit:

```bash theme={null}
curl -sS -X POST "$FORGE_BASE/api/v3/cost-budgets/$BUDGET_ID/alerts" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: budget-customer-success-alert-80-v1" \
  -d '{"thresholdPercent": 80}' \
  | jq '.data'
```

Both writes need `cost:manage`. Read the budget's spend against its limit, which needs `cost:read`:

```bash theme={null}
curl -sS "$FORGE_BASE/api/v3/cost-budgets/$BUDGET_ID/utilization" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  | jq '.data | {budgetName, limitCents, totalSpent, remainingCents, utilizationPercent}'
```

`GET /api/v3/cost-budget-tree` returns the whole hierarchy, up to 200 budgets, with each one's period spend, burn rate and status.

Over MCP, create the budget with `forge_call_operation`:

```json theme={null}
{
  "operationId": "createBudgetAdmin",
  "input": { "name": "Customer Success monthly", "orgUnitId": "<org unit id>", "limitCents": 500000, "periodType": "monthly" },
  "idempotencyKey": "budget-customer-success-monthly-v1"
}
```

and read its utilization with `forge_call_read_operation`:

```json theme={null}
{ "operationId": "getBudgetUtilizationAdmin", "input": { "budgetId": "<budget id>" } }
```

***

## Related

* [Trust Fabric in production](https://docs.gloo.com/forge/run/trust-fabric.md)
* [Observability](https://docs.gloo.com/forge/run/observability.md)
* [Audit](https://docs.gloo.com/forge/run/audit.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.