Skip to content

Monitor cost and latency of a production integration

Wrap the client file in a monitoring layer that turns the billing and timing of every answer into Prometheus metrics (credits by model and unit, calls by outcome, encoding-cache hits and what they saved, queue and processing time, and the balance of a key) and trips a spend guard before the budget is gone. Nothing is asked of the API except an optional, free GET /v1/whoami.

Models: ppocr-v6, sam-lite, sam3 · Without a key: Smoke run · Languages: Python · Try in Playground (opens in a new tab) · Source on GitHub (opens in a new tab)

An integration that works on the day it ships can still go wrong in production without a single error: a loop that re-sends the same image, a prompt that grows from one to ten per call, a batch job that doubles in size, or a model whose queue time creeps up when everyone else is busy. The API tells you everything you need on each answer, but only for that one call. What you want is a few numbers over time and someone told when they move:

  • how many credits per hour, by model and by unit (image, prompt, encode_image, …), and how much of it was really debited to a key rather than run free on the free tier;
  • how often a SAM call reuses an image that was already encoded (the encoding fee is waived on a cache hit), and what that saved;
  • how long calls wait in the queue and how long they are processed, as the server measured them;
  • what is left on the account (when you use a key), and an alert before it is gone, or a refusal to send more calls when the spend of the last hour is out of line.

This example is that layer for Python: one file, monitoring.py, that you copy next to stack_client.py. It does not modify the client file. It wraps a client object, reads each answer (cost, billing, cache, timing, balance, the error code) and, for batches, each item event. A replay of 21 calls (assets/workload.jsonl) exercises it end to end and checks that the metrics and the client’s own ledger agree.

The monitoring layer between your code and the client file

Step What happens Endpoint
Wrap MonitoredClient(StackClient(), Monitor(guard=...)): post and batch are measured, everything else is forwarded none
Call the wrapped client sends the call as usual: retries, throttling, idempotency and the credit cap are the client’s POST /v1/ocr, /v1/segment, …, POST /v1/batch/*
Read credits per billing.lines[], cost, cache, timing.queueMs / processingMs, balance; an error is counted by its code none
Guard the spend of the last hour is compared with the limit; alert once per crossing, or refuse new calls none
Refresh refresh_account() reads the balance of the key, or on the free tier today’s use and the daily limit per weight class; call it on a timer, refresh_every(client, 60) does GET /v1/whoami (free, not metered)
Expose monitor.serve(9108) serves GET /metrics; Prometheus scrapes it, Grafana and alert rules read it none

The metrics, all prefixed stack_:

Metric Labels Source
stack_credits_total model, unit, charged every priced line of billing.lines[]; charged="false" is the list price of work that ran free on the free tier; an item of an async job is counted at its own cost (a tenth of the list price) under async_<unit>, for example async_image
stack_calls_total model, status, code status is ok, replayed, error, expired or refused (never sent: credit cap or guard); code is the API error code, none for ok
stack_async_jobs_total model, status async jobs that reached a final status (completed, partial, failed, cancelled or expired), counted once per job; the metric exists from the first job on
stack_cache_hits_total, stack_cache_misses_total model cache of SAM answers
stack_cache_saved_credits_total model list price of the lines with waived: true
stack_latency_ms (histogram) model, phase queue and processing from timing; client_total is the time this process measured around the call, for your own dashboards
stack_balance_credits, stack_balance_updated_timestamp_seconds balance of the last answer or whoami refresh, and when
stack_free_used_today, stack_free_daily_limit class free tier only: today’s calls of this project and its daily limit per weight class, from the whoami refresh
stack_spend_window_credits, stack_spend_guard_tripped the guard’s window, and whether it is over the limit

Setup and run in each language

Commands for the smoke set, run from the repository root. The smoke set needs no API key: it runs on the free tier. The full set needs a key; the cap makes the client refuse calls that could exceed it.

Requires: Python 3.12, uv 0.5

cd use-cases/08-cost-and-latency-monitoring/python
uv sync --frozen
uv run --frozen python main.py --manifest ../assets/manifest.json --out out
# Full set: the full dataset is a release asset of the repository and needs an API key; unpack it and pass its manifest.
export FOLDBUN_API_KEY="fbs_..."
export FOLDBUN_MAX_CREDITS=2.75
uv run --frozen python main.py --manifest ../assets/manifest.json --out out
# no key needed: the replay runs on the free tier. With FOLDBUN_API_KEY set the calls are charged at list price;
# FOLDBUN_MAX_CREDITS=2.75 (optional) makes the client refuse calls that could pass it
cd use-cases/08-cost-and-latency-monitoring/python
uv run main.py --out out --hold 30 # 21 calls; /metrics on :9108 while it runs and 30 s after
curl -s localhost:9108/metrics | grep '^stack_' # from a second terminal
uv run main.py --out out --guard-mode reject --guard-max 0.2 # the guard refuses calls once the last hour is over 0.2 credits
uv run python ../evaluate.py --result out/result.json --overhead # check the books, print the cost of the layer

Arguments: --manifest, --out, --concurrency (default 1: with one call at a time, the call that trips the guard has a stable number), --limit, --resume (accepted; a replay always starts over), --metrics-port (default 9108, 0 to not serve), --hold, --guard-max (credits per hour, default 1.0), --guard-mode (alert or reject), --guard-basis (charged or list). Outputs: result.json (format of contract/result.schema.json: one item per call and a last item summary with what the layer counted) and metrics.prom, the text exposition at the end of the run.

The smoke replay needs no key and no sign-up. The full run needs FOLDBUN_API_KEY, as everywhere in the Cookbook. To run the replay without touching the real API at all, use the local fake of the API (see CONTRIBUTING.md); uv run python -m harness check --uc 08 does that.

On the free tier the replay is subject to its limits: when the server answers 429 the client waits for Retry-After and carries on, and a 403 free_tier_unavailable (the free tier is not offered in every region) is final: that call is recorded as failed with a message that points to FOLDBUN_API_KEY. Exit code 3 is a model locked for the key (403 model_locked), 4 the credit cap.

To wire it into your own service, copy monitoring.py and use it like this:

from stack_client import StackClient
from monitoring import Monitor, MonitoredClient, SpendGuard
guard = SpendGuard(max_per_hour=50, mode="alert", on_alert=notify) # notify(info) gets the call number, the spend and the limit
monitor = Monitor(guard=guard)
client = MonitoredClient(StackClient(), monitor) # use it where you used StackClient
monitor.serve(9108) # or mount monitor.exposition() in your own web app
monitor.refresh_every(client, 60) # balance (key) or free-tier use, every minute

Alerting rules and a Grafana dashboard for these metrics are in assets/alerts.rules.yml and assets/grafana-dashboard.json (import the dashboard, pick your Prometheus data source). assets/metrics.sample.prom is the exposition of one replay against the local fake API.

The wrapper. post, batch and the async job methods are measured; every other attribute (upload, models, get, calls, summary) is the wrapped client’s.

Source: python/monitoring.py (opens in a new tab)

class MonitoredClient:
"""Wraps a StackClient. `post`, `batch` and the async jobs (`create_job`, `get_job`, `job_results`) are measured; every
other attribute (`upload`, `models`, `get`, `calls`, `summary`, `ledger`, ...) is the wrapped client's."""
def __init__(self, client, monitor):
self._client, self.monitor = client, monitor
self._job_models, self._job_items, self._jobs_done = {}, set(), set() # job id -> model; (job id, index) and job ids already counted
def __getattr__(self, name):
return getattr(self._client, name)
@staticmethod
def _model(path, body):
return body.get("model") or sc.DEFAULT_MODEL.get(path) or "unknown"
def _replayed(self, tag):
"""Whether the client's ledger says the answer of this call was a replay of a stored one."""
ledger = getattr(self._client, "ledger", None) or []
for t, row in reversed(ledger[-32:]):
if t == tag:
return bool(row.get("replayed"))
return False
def post(self, path, body, idempotency_key=None, *, tag=None, **kwargs):
model = self._model(path, body)
tag = tag or self.monitor.next_tag()
try:
if self.monitor.guard:
self.monitor.guard.check()
except SpendGuardTripped as err:
self.monitor.failure(model, err)
raise
t0 = self.monitor.clock()
try:
result = self._client.post(path, body, idempotency_key, tag=tag, **kwargs)
except Exception as err: # a StackError, or anything unexpected: counted, then raised unchanged
self.monitor.failure(model, err, client_ms=(self.monitor.clock() - t0) * 1000)
raise
self.monitor.observe(model, result, replayed=self._replayed(tag), client_ms=(self.monitor.clock() - t0) * 1000)
return result
def batch(self, endpoint, body, idempotency_key=None, *, tag=None):
"""Like StackClient.batch (yields (event, data)); every `item` event is counted with its own cost and timing."""
model = self._model(f"/v1/{endpoint}", body)
if self.monitor.guard:
self.monitor.guard.check()
try:
for event, data in self._client.batch(endpoint, body, idempotency_key, tag=tag):
if event == "item":
status = data.get("status")
if status == "ok":
self.monitor.observe(model, data["result"], replayed=bool(data.get("replayed")))
else:
error = data.get("error") or {}
self.monitor.failure(
model, sc.StackError(0, error.get("code") or status, error.get("message", "")), status="expired" if status == "expired" else "error"
)
yield event, data
except Exception as err: # the stream itself failed (cut, timed out, refused)
self.monitor.failure(model, err)
raise
def create_job(self, model, items, idempotency_key=None, *, metadata=None):
"""Like StackClient.create_job. Nothing is spent yet: an async job is charged as its items finish, so its cost is
counted when `job_results` reads them. A guard in mode "reject" refuses the submit while the window is over its limit."""
try:
if self.monitor.guard:
self.monitor.guard.check()
job = self._client.create_job(model, items, idempotency_key, metadata=metadata)
except Exception as err: # refused by the guard or the credit cap, or an API error (402 insufficient_balance, 429 too_many_jobs, ...)
self.monitor.failure(model, err)
raise
self._job_models[job["id"]] = model
return job
def get_job(self, job_id):
"""Like StackClient.get_job; the first time a job is seen in a final status it is counted in `stack_async_jobs_total`."""
return self._seen(self._client.get_job(job_id))
def cancel_job(self, job_id):
return self._seen(self._client.cancel_job(job_id))
def _seen(self, job):
if job["status"] not in ("queued", "running") and job["id"] not in self._jobs_done:
self._jobs_done.add(job["id"])
self.monitor.job_finished(job)
return job
def job_results(self, job_id, *, tag=None, **kwargs):
"""Like StackClient.job_results (yields every finished item). Each item is counted once, however often it is read: an
`ok` item at its own `cost` (0 for a cache hit) and timing, any other item as a failed call with its error code."""
model = self._job_models.get(job_id, "unknown")
if self.monitor.guard:
self.monitor.guard.check()
for item in self._client.job_results(job_id, tag=tag, **kwargs):
if (job_id, item["index"]) not in self._job_items:
self._job_items.add((job_id, item["index"]))
if item["status"] == "ok":
self.monitor.observe(model, item["result"], asynchronous=True)
else:
error = item.get("error") or {}
status = item["status"] if item["status"] in ("expired", "cancelled") else "error"
self.monitor.failure(model, sc.StackError(0, error.get("code") or item["status"], error.get("message", "")), status=status)
yield item
def whoami(self):
return self.monitor.refresh_account(self._client)

Async jobs are not charged when they are submitted but as their items finish, at a tenth of the list price, so the wrapper counts them when the results are read: each item once, however often it is read, at its own cost (0 for a cache hit) and timing; an item that ended as an error, expired or was cancelled counts as a failed call with its code. stack_async_jobs_total counts a job once, when it is first seen in a final status. A spend guard in mode reject refuses a submit and a results read while the window is over its limit, and async spend counts in the guard’s window like any other.

What is read from one answer, and what becomes a metric:

Source: python/monitoring.py (opens in a new tab)

def observe(self, model, result, *, replayed=False, client_ms=None, asynchronous=False):
"""One successful call (or `ok` batch or async job item): `result` is the answer body. An async item is counted at its
own `cost`, under the unit `async_<unit>`: the async price is a tenth of the list price and is what was charged."""
model = result.get("model") or model
self.calls.labels(model, "replayed" if replayed else "ok", "none").inc()
if client_ms is not None:
self.latency.labels(model, "client_total").observe(client_ms)
billing = result.get("billing") or {}
cost = result.get("cost", 0)
if not replayed: # a replay returns the stored answer of a call that was already counted
timing = result.get("timing") or {}
for phase, key in (("queue", "queueMs"), ("processing", "processingMs")):
if key in timing:
self.latency.labels(model, phase).observe(timing[key])
charged = "true" if billing.get("charged", cost > 0) else "false"
lines = billing.get("lines") or [{"unit": "unknown", "amount": cost, "waived": False}]
for line in lines:
if line.get("waived"):
self.cache_saved.labels(model).inc(round(line["unitPrice"] * line["quantity"], 6))
elif line["amount"] and not asynchronous:
self.credits.labels(model, line["unit"], charged).inc(line["amount"])
if asynchronous and cost:
self.credits.labels(model, "async_" + lines[0]["unit"], charged).inc(cost)
if result.get("cache") == "hit":
self.cache_hits.labels(model).inc()
elif result.get("cache") == "miss":
self.cache_misses.labels(model).inc()
if "balance" in result:
self._set_balance(result["balance"])
by_list = self.guard is not None and self.guard.basis == "list"
self._guard_record(0 if replayed else billing.get("total", cost) if by_list else cost)
def failure(self, model, error, *, status="error", client_ms=None):
"""One failed call: `error` is a StackError (or anything with `.code`). Local refusals count as "refused"."""
code = getattr(error, "code", None) or type(error).__name__
if getattr(error, "status", None) == 0 and code in ("budget_exceeded", "spend_guard_tripped"):
status = "refused"
self.calls.labels(model, status, code).inc()
if client_ms is not None:
self.latency.labels(model, "client_total").observe(client_ms)
self._guard_record(0)
def job_finished(self, job):
"""A job reached a final status (call once per job). The metric `stack_async_jobs_total{model,status}` exists from the
first job on: a run that never uses async jobs does not expose it."""
with self._balance_lock:
if self.jobs is None:
self.jobs = Counter("stack_async_jobs_total", "Async jobs that reached a final status.", ["model", "status"], registry=self.registry)
self.jobs.labels(job.get("model") or "unknown", job["status"]).inc()
def _set_balance(self, value):
with self._balance_lock:
if self.balance is None:
self.balance = Gauge("stack_balance_credits", "Account balance after the last answer or whoami refresh.", registry=self.registry)
self.balance_at = Gauge("stack_balance_updated_timestamp_seconds", "When stack_balance_credits was last set.", registry=self.registry)
self.balance.set(value)
self.balance_at.set(self.wall())
def _guard_record(self, amount):
if self.guard:
self.guard.record(amount)
self.window_spend.set(self.guard.spent())
self.guard_tripped.set(1 if self.guard.tripped else 0)

The spend guard: a sliding window, in integer micro-credits so that sums do not drift, with a clock you can replace in tests. alert calls back once per crossing and re-arms when the spend falls back under the limit; reject refuses new calls while it is over.

Source: python/monitoring.py (opens in a new tab)

class SpendGuard:
"""Sliding-window spend rate. `max_per_hour` credits over the last `window_s` seconds (default one hour).
mode "alert": `on_alert(info)` runs once each time the spend crosses the limit; calls are not stopped.
mode "reject": `check()` raises SpendGuardTripped while the spend of the window is over the limit.
basis "charged" counts what the account is debited (a free-tier call counts 0); "list" counts the list price, which is the basis to use on the free tier.
Pure logic: pass `clock` (a function returning seconds) to test it without waiting."""
def __init__(self, max_per_hour, *, mode="alert", basis="charged", on_alert=None, window_s=3600.0, clock=time.monotonic):
if mode not in ("alert", "reject") or basis not in ("charged", "list"):
raise ValueError('mode is "alert" or "reject"; basis is "charged" or "list"')
self.max_per_hour, self.mode, self.basis, self.on_alert = max_per_hour, mode, basis, on_alert
self.window_s, self.clock = window_s, clock
self.records, self.alerts, self.tripped = 0, 0, False # calls recorded, alerts raised, over the limit right now
self._events, self._micro, self._lock = collections.deque(), 0, threading.Lock()
def _expire(self, now):
while self._events and self._events[0][0] <= now - self.window_s:
self._micro -= self._events.popleft()[1]
def spent(self):
"""Credits spent inside the window now."""
with self._lock:
self._expire(self.clock())
return self._micro / 1e6
def check(self):
"""Call before sending: in mode "reject", raises SpendGuardTripped while the window's spend is over the limit."""
if self.mode != "reject":
return
with self._lock:
self._expire(self.clock())
over, spent = self._micro > self.max_per_hour * 1e6, self._micro / 1e6
if over:
raise SpendGuardTripped(
f"call refused: {spent:g} credits in the last {self.window_s / 60:g} minutes pass the limit of {self.max_per_hour:g} credits"
)
def record(self, amount):
"""Add the spend of one finished call (0 is fine; it still counts as a call). Returns True when this call tripped the guard."""
with self._lock:
now = self.clock()
self._expire(now)
micro = round(amount * 1e6)
self._events.append((now, micro))
self._micro += micro
self.records += 1
over = self._micro > self.max_per_hour * 1e6
fired = over and not self.tripped
self.tripped = over
info = {
"call": self.records,
"spent": self._micro / 1e6,
"max_per_hour": self.max_per_hour,
"window_s": self.window_s,
"mode": self.mode,
"basis": self.basis,
}
if fired:
self.alerts += 1
if fired and self.on_alert:
self.on_alert(info)
return fired

The balance of a key, or the free tier’s use per weight class, from GET /v1/whoami, on demand or on a timer:

Source: python/monitoring.py (opens in a new tab)

def refresh_account(self, client):
"""GET /v1/whoami (not metered): the balance with a key; on the free tier today's use and the daily limit per class."""
info = client.get("/v1/whoami")
if info.get("tier") == "free":
for cls, limit in info.get("limits", {}).items():
self.free_limit.labels(cls).set(limit["daily"])
self.free_used.labels(cls).set(info.get("usedToday", {}).get(cls, 0))
elif "balance" in info:
self._set_balance(info["balance"])
return info
def refresh_every(self, client, seconds):
"""Refresh in a background thread; `.set()` the returned event to stop it. Errors are swallowed: the gauges just go stale."""
stop = threading.Event()
def loop():
while not stop.wait(seconds):
try:
self.refresh_account(client)
except Exception: # noqa: BLE001
pass
threading.Thread(target=loop, daemon=True, name="stack-whoami").start()
return stop

The replay wires the layer around the client and keeps going when one call fails (failures are data, not a crash); only a locked model (403 model_locked) or the credit cap stops it:

Source: python/main.py (opens in a new tab)

try:
client = sc.StackClient(max_concurrency=args.concurrency) # FOLDBUN_API_KEY (optional), FOLDBUN_API_BASE, FOLDBUN_MAX_CREDITS
if len(manifest["items"]) > FREE_MAX_ITEMS:
client.require_key(f"the free tier is meant for trying a recipe on a few items, and this manifest has {len(manifest['items'])}")
except sc.MissingApiKey as err:
print(err.message, file=sys.stderr)
return EXIT_NO_KEY
alerts = []
basis = args.guard_basis or ("list" if client.free else "charged")
guard = SpendGuard(args.guard_max, mode=args.guard_mode, basis=basis, on_alert=lambda info: (alerts.append(info), print(f"ALERT: {info}", file=sys.stderr)))
monitor = Monitor(guard=guard)
mc = MonitoredClient(client, monitor)
if args.metrics_port:
try:
monitor.serve(args.metrics_port)
print(f"metrics: http://localhost:{args.metrics_port}/metrics")
except OSError as err:
print(f"metrics not served: {err}", file=sys.stderr)

Source: python/main.py (opens in a new tab)

def run_call(mc, entry, images):
"""One workload line -> one result item. Failures are data (status `error`); only a locked model or the credit cap stop the run."""
body = {"model": entry["model"], "image": images[entry["image"]], **entry["request"]}
try:
result = mc.post(entry["endpoint"], body, tag=entry["id"])
except sc.StackError as err:
print(f" {entry['id']}: {err.status} {err.code}: {err.message}" + (f" (request {err.request_id})" if err.request_id else ""), file=sys.stderr)
if err.code in ("model_locked", "budget_exceeded"):
raise
return {"id": entry["id"], "status": "error", "calls": [], "output": None, "error": {"status": err.status, "code": err.code, "message": err.message}}
billing = result.get("billing") or {}
waived = sum(ln["unitPrice"] * ln["quantity"] for ln in billing.get("lines", []) if ln.get("waived"))
output = {
"kind": "call",
"model": entry["model"],
"endpoint": entry["endpoint"],
"cache": result.get("cache"),
"listCredits": billing.get("total", result.get("cost", 0)),
"chargedCredits": result.get("cost", 0),
"waivedCredits": round(waived, 6),
}
return {"id": entry["id"], "status": "ok", "calls": mc.calls(entry["id"]), "output": output}

The workload is assets/workload.jsonl: 6 ppocr-v6 reads of the Playground settings screenshot (use case 00), 10 sam-lite box calls on one photo, and 5 sam3 text calls on another photo (both from the smoke set of use case 01), interleaved so that every phase of the guard shows. Its list price is worked out call by call:

Calls Model Per call at list price Total
6 ppocr-v6 (image) 0.25 1.50
10, one image sam-lite (encode 0.20 once, then box 0.01) 0.21 first, 0.01 after 0.30
5, one image sam3 (encode 0.50 once, then prompt 0.05) 0.55 first, 0.05 after 0.75
21 2.55

On the free tier nothing is debited: the run prints the 2.55 credits labelled “free tier, not charged”. With a key, all 2.55 are charged. The credit cap FOLDBUN_MAX_CREDITS=2.75 is what a keyed replay needs: the client counts a call at its worst case (the encoding fee always included), so the cap must hold the 2.55 spent plus the worst case of the next call; the order of the workload keeps the SAM calls early for that reason, and a test checks it. Forty OCR reads, as a larger replay, would be 10 credits at list price on their own.

With the encoding cache, 13 of the 15 SAM calls reuse an encoding (9 of sam-lite, 4 of sam3), which saves 9 x 0.20 + 4 x 0.50 = 3.80 credits of encoding fees that would otherwise appear in stack_credits_total. The spend guard, set to 0.2 credits per hour on what is charged, trips on the first sam3 call (call 8: its encoding alone is 0.50), or on the fifth if the encoding was still cached from an earlier run. The books agree when credits.list and credits.charged of the metrics equal ledger.listTotal and ledger.chargedTotal of the client’s ledger; evaluate.py checks that and the three conditions above.

The monitoring layer costs about 20 microseconds per call on a 6-vCPU cloud VM, measured by evaluate.py --overhead against a client whose post returns a canned answer at once (guard on, a SAM answer with three billing lines, best of five rounds of 3,000 calls); the test suite asserts that it stays under 500. It is Python bookkeeping on one answer, small beside the tens to thousands of milliseconds of a call.

Measured on a real run, server-side timing of the answers and the numbers evaluate.py prints:

Metric Value
ledger_consistent 1
credits_list_gap 0
credits_charged_gap 0
calls_total 21
calls_failed 0
cache_hits 15
cache_misses 0
cache_hit_rate 1
cache_saved_credits 4.5
guard_triggered 1
guard_trigger_call 16
credits_list.ppocr-v6 1.5
credits_charged.ppocr-v6 0
credits_list.sam-lite 0.1
credits_charged.sam-lite 0
credits_list.sam3 0.25
credits_charged.sam3 0.25
cache_hits.sam-lite 10
cache_hits.sam3 5
queue_ms_p50.ppocr-v6 0
queue_ms_p95.ppocr-v6 0
processing_ms_p50.ppocr-v6 564
processing_ms_p95.ppocr-v6 656
queue_ms_p50.sam-lite 0
queue_ms_p95.sam-lite 0
processing_ms_p50.sam-lite 51
processing_ms_p95.sam-lite 79
queue_ms_p50.sam3 0
queue_ms_p95.sam3 0
processing_ms_p50.sam3 164
processing_ms_p95.sam3 249

Until a live run is recorded, expected/offline.json holds the replay against the offline fake API. It shows how the layer behaves, not how the models perform: the fake’s timings and cache state are scripted.

Run Calls List price (credits) Charged (credits)
smoke 21 2.55 0.75
full 21 1.85 0.25

The list price of a smoke run is 2.55 credits; it is free on the free tier and charged this much with a key (see Results). Full is the same replay and needs a key.

  • Your own workload: replace assets/workload.jsonl (one JSON object per line: id, endpoint, model, image as a manifest id, request as the body without image and model) and list the images in assets/manifest.json.
  • Your own service: you only need monitoring.py and stack_client.py. Create one Monitor per process, use one MonitoredClient where you used the client, and serve /metrics or return monitor.exposition() from your own endpoint. Several processes: each is its own Prometheus target; sum them in queries, as the dashboard does.
  • Limits and modes: SpendGuard(max_per_hour, mode="reject") refuses calls with SpendGuardTripped (code spend_guard_tripped); catch it where you can degrade gracefully. basis="list" counts the list price, which includes calls that ran free on the free tier. Choose the limit from your normal hourly spend with some headroom.
  • Labels: model has seven values and unit a handful, so the series count stays small. Do not add image ids, call ids or request ids as labels.
  • Async work: submit and read jobs through the MonitoredClient (create_job, get_job, job_results); the credits show under unit="async_image" (or the unit of the line) next to the synchronous ones, so a query such as sum(rate(stack_credits_total{unit=~"async_.*"}[1h])) gives the hourly spend on jobs.
  • Other languages: any client that reads billing, cost, cache, timing and balance of an answer can export the same metric names; the dashboard and the rules would carry over.
  • No end-to-end latency here. Latency seen from a client depends on its network path to the API, so the measurements of this use case do not include it; the queue and processing figures are the server’s own timing. The layer exports client_total (the time around the call in your process) so that you can watch your own environment, but this page publishes no such number.
  • The balance is as old as the last answer or refresh, and only exists for a key. stack_balance_credits moves when a call finishes or whoami is read, nothing else; a process that makes no calls shows a stale number (stack_balance_updated_timestamp_seconds tells how stale). Other keys of the same account move it too, and only a refresh sees that.
  • Not the bill. The metrics are your process’s view of the answers it received. The account console is the authority: calls made by other processes or keys never appear, and an answer that was lost on its way back was charged but never counted. Use the metrics to notice, and the console to settle.
  • Async jobs are counted when you read them. Nothing is metered at submit time: an item is counted (and its credits added) the first time job_results returns it, so a job nobody reads is not seen, and the spend guard sees its cost late. The metric for a job needs get_job or cancel_job to be called through the wrapper after it ended. Async items have no per-item client time.
  • Batches (SSE) are counted per item. The cost and timing of each item event are read from the event itself, as one call each; a batch has no per-item client time, so client_total is not recorded for items. A stream that is cut before its summary event is counted as one failed call, and the items that arrived before the cut stay counted.
  • Replays are recognised through the client’s ledger, which marks the answer of a retried call as replayed; they are counted as status="replayed" and add no credits. With several threads and no tag, that lookup can attribute the flag to a neighbouring call in rare cases.
  • A guard in one process. The sliding window lives in memory of one process and is lost on restart; for a fleet, alert from Prometheus on the sum (assets/alerts.rules.yml), and keep the guard as a local safety net.
  • Cache counts follow the API’s cache, which is not part of its promise: a replay that finds the image already encoded saves more than the numbers above, one that finds it evicted saves less.

The workload uses images that are already in this repository: the settings screenshot of use case 00 (../00-quickstart/assets/smoke/settings.webp, CC0, from the Playground samples) and two photos of the smoke set of use case 01 (../../datasets/smoke/01-dataset-prelabelling/images/, Open Images, CC BY 2.0). Their sha256 is in assets/manifest.json; the authors and licences are in the ATTRIBUTION.csv of those directories and in ATTRIBUTION.md. Nothing new is added. Rights holders can request removal of an image or dataset through the contact page (opens in a new tab).