Monitoring
Reference for the built-in monitoring module’s endpoints and configuration. For how the system works conceptually, see Observability.
Install:
pip install "kirak[monitoring]"Enable: like every module, monitoring is off until you list it in modules in kirak.json (remove it to turn monitoring off):
{ "modules": ["monitoring"] }and set the bearer token its endpoints require:
KIRAK_MONITORING_INGESTION_KEY=a-long-random-secretAuthentication
Section titled “Authentication”Every endpoint except /monitoring/ping requires:
Authorization: Bearer <KIRAK_MONITORING_INGESTION_KEY>Compared with constant-time comparison. A request without a bearer token gets 401. If KIRAK_MONITORING_INGESTION_KEY is not set, a request with a token gets 503 (fail closed) rather than unauthenticated access. Endpoints that read monitoring data also return 503 until the module has started.
HTTP Endpoints
Section titled “HTTP Endpoints”| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /monitoring/ping |
none | Liveness check only. |
| GET | /monitoring/health |
bearer | The configured sinks; SQLite reachability (null without the sqlite sink), depth and dropped-record count of each queue (<queue>_queue_depth and <queue>_dropped_count for request, log, ai, mcp, integration and audit, for example mcp_queue_depth and mcp_dropped_count), flush_running (false once the background writer has stopped: nothing queued is written any more), DB size (db_size_bytes: the store plus its -wal and -shm files, the number the size cap uses; null without the sqlite sink), max_db_size_mb, Python version. |
| GET | /monitoring/metrics |
bearer | OpenMetrics-format text export of /monitoring/summary over its default 300-second window, all gauges: kirak_http_requests_in_window (requests in the window), kirak_http_requests_per_second, kirak_http_error_rate (5xx share, 0 to 1), kirak_http_request_duration_p95_ms. Values cover a moving window, not totals since start, so use them as they are (no rate()). |
| GET | /monitoring/summary |
bearer | RED aggregate plus trend deltas vs. the prior window. Query param: window_seconds (default 300). |
| GET | /monitoring/trace/{request_id} |
bearer | Full timeline for one request: {"request", "steps", "errors", "logs"}. See Request traces. |
| POST | /monitoring/alerts/evaluate |
bearer | Evaluate a batch of threshold checks. Body: {"checks": [...]}. See Alert checks. |
| GET | /monitoring/requests |
bearer | Per-route request breakdown. Query param: window_seconds. |
| GET | /monitoring/requests/timeseries |
bearer | Bucketed time series. Query params: window_seconds, bucket_seconds (default: window_seconds / 30). At most 1000 buckets (window_seconds / bucket_seconds); more is a validation error. |
| GET | /monitoring/requests/latency-histogram |
bearer | Fixed-edge latency buckets. Query param: window_seconds. |
| GET | /monitoring/requests/recent |
bearer | Recent individual requests. Query params: window_seconds, status (2xx, 3xx, 4xx, 5xx), limit (default 20, max 200). |
| GET | /monitoring/ai/summary |
bearer | AI runs in the window: run, completed and failed counts, error rate, total and average cost, input/output/total tokens, thinking and cached input tokens and thinking cost (total_thinking_tokens, total_cached_input_tokens, total_thinking_cost_usd), average and p95 duration. Query param: window_seconds. |
| GET | /monitoring/ai/cost-timeseries |
bearer | AI cost over time, in buckets. Query params: window_seconds, bucket_seconds (default: window_seconds / 30). At most 1000 buckets, as for /requests/timeseries. |
| GET | /monitoring/ai/agents |
bearer | AI runs broken down by agent. Query param: window_seconds. |
| GET | /monitoring/ai/models |
bearer | AI runs broken down by model. Query param: window_seconds. |
| GET | /monitoring/ai/tools |
bearer | Agent tool calls broken down by tool. Query param: window_seconds. |
| GET | /monitoring/ai/runs |
bearer | Recent agent runs, newest first: agent, model, provider, tokens (input, output, total, and thinking_tokens and cached_input_tokens: the part of the output that was the model’s thinking and the part of the input read from the provider’s cache, 0 when the provider reports none, empty for a run recorded by an older Kirak), cost and thinking_cost_usd (the thinking tokens’ share of the output price), duration, turns, tool calls, status, error code, conversation and user id. No prompt or output text is recorded. A failed run records the tokens, cost and tool calls of the requests it completed before failing (a cost or turn cap, retries used up); a request refused by the provider costs nothing and records none. A streamed run whose client disconnected is failed with error code CLIENT_DISCONNECTED. Query params: window_seconds, limit (default 20, max 200), status (completed, failed, pending_approval). |
| GET | /monitoring/ai/runs/{run_id} |
bearer | One run (run) and its tool calls (tool_calls: tool, duration, status, and for a failed call error_message – the tool’s error with emails and secrets masked, at most 300 characters). |
| GET | /monitoring/mcp/summary |
bearer | Per MCP server and tool: calls, errors, confirmation forms sent, average and p95 latency. Query param: window_seconds. |
| GET | /monitoring/mcp/calls |
bearer | Recent MCP tool calls, newest first: server, tool, operation ref, caller, status (ok, error, asked), error code, confirmation outcome, duration. Query params: window_seconds, limit (default 20, max 200), server, status. |
| GET | /monitoring/audit |
bearer | Recent audit events, newest first: {"window_seconds", "events": [{event_type, actor_id, actor_email, ip_address, user_agent, metadata, created_at}]}, metadata as an object (or null). Query params: window_seconds, limit (default 20, max 200), event_type (that type and the types under it: auth.login returns auth.login.success and auth.login.failure; auth returns every auth event), before (a created_at: only older events, to page back from the last event shown). Events are kept audit_retention_days. |
Every window_seconds is a positive number of seconds and defaults to 300.
Without the sqlite sink, every endpoint except /ping and /health answers 501 with error MONITORING_NO_STORE and a message naming monitoring.sinks, since there is no store to read. It is a setting, not an outage, so a client should not retry; it can read sinks from /monitoring/health to tell in advance. See Sinks.
Request traces
Section titled “Request traces”GET /monitoring/trace/{request_id} returns the request and everything recorded for it, oldest first:
{ "request": {"request_id": "6f1c0e2a", "method": "POST", "route": "/orders/create", "path": "/orders/create", "status_code": 200, "duration_ms": 42.5, "req_bytes": 118, "resp_bytes": 412, "user_id": "7", "created_at": 1792141923.481}, "steps": [{"module": "orders", "step": "create", "duration_ms": 12.8, "status": "success", "cache_status": null, "db_duration_ms": 12.1, "provider_duration_ms": null, "created_at": 1792141923.47}], "errors": [], "logs": [{"logger": "orders", "level": "WARNING", "message": "Stock low for item 12", "created_at": 1792141923.48}]}request is null when no request with that id is stored (it is older than retention_days, or the id is unknown). Each step is one whole operation of a model (fetch, create, …) or of another module, with the time it spent in the database and in provider calls; there is no finer breakdown. steps holds only the sampled requests’ steps (see sample_rate), and steps slower than slow_request_threshold_ms whatever the sampling. errors has the exception’s class name and its traceback, with secrets masked.
Alert checks
Section titled “Alert checks”POST /monitoring/alerts/evaluate evaluates a batch of threshold checks in one call:
{ "checks": [ {"id": "api_errors", "metric": "5xx_rate", "op": "gt", "value": 0.05, "window_seconds": 300, "routes": ["posts", "/webhook/stripe"]}, {"id": "ai_spend", "metric": "ai_cost_rate", "op": "gt", "value": 0.01, "window_seconds": 3600}, {"id": "alive", "metric": "health"} ]}| Field | Required | Description |
|---|---|---|
id |
yes | Your identifier, echoed back in the result. |
metric |
yes | One of the metrics below. |
op |
yes, except health |
gt or lt. |
value |
yes, except health |
Threshold to compare against: a number (not a string, not true / false). Rates are 0 to 1, so a 5% error rate is 0.05. |
window_seconds |
yes, except health |
How far back to look: a positive number of seconds. |
routes |
no | A list of strings. Limit the check to these routes. Each entry is a model name ("posts", its whole CRUD group) or a literal route ("/webhook/stripe"). HTTP metrics only. |
| Metric | Value |
|---|---|
5xx_rate, 4xx_rate |
Share of requests with that status class, 0 to 1. |
5xx_count |
Number of 5xx responses. A request whose handler raised an unhandled exception counts as a 500. |
request_rate |
Requests per second. |
p95_latency, p99_latency |
Latency in milliseconds; null (never breaching) when there were no requests. |
ai_cost_rate |
AI spend in USD per second, from recorded agent runs. |
ai_error_rate |
Share of agent runs that failed, 0 to 1. |
ai_token_rate |
AI tokens per second. |
health |
Breaching when the monitoring SQLite store is unreachable, or its file was deleted or replaced and not reopened yet. |
A window with no traffic reads 0 for the rate and count metrics, so an lt check on request_rate fires on silence. The response is {"results": [{id, breaching, value, sample_count}, ...]}, one entry per check. A malformed check (not an object, unknown metric or op, a missing field, or a field of the wrong type) rejects the whole batch with 422 VALIDATION_ERROR, naming the check and the field; an empty or missing checks list is a 422 too. Delivery (Slack, email, etc.) is up to you.
Configuration
Section titled “Configuration”Environment variables (secrets, KIRAK_MONITORING_ prefix)
Section titled “Environment variables (secrets, KIRAK_MONITORING_ prefix)”| Variable | Description |
|---|---|
KIRAK_MONITORING_INGESTION_KEY |
Bearer token required on every endpoint except /ping. |
kirak.json settings ("monitoring" section)
Section titled “kirak.json settings ("monitoring" section)”{ "monitoring": { "sinks": ["sqlite"], "db_path": "var/kirak/metrics.db", "batch_interval_seconds": 5, "retention_days": 7, "audit_retention_days": 30, "sample_rate": 1.0, "slow_request_threshold_ms": 500, "max_db_size_mb": 200, "queue_max_size": 10000, "log_capture_level": "WARNING", "log_queue_max_size": 5000 }}monitoring key |
Type | Description |
|---|---|---|
sinks |
array | Where records are written. “sqlite”: the local metrics file, which the query endpoints and alerts read. “stdout”: one JSON line per record, for the platform’s log collector on stateless instances. Default [“sqlite”]. |
db_path |
string | Path of the SQLite metrics file (sqlite sink only). Default “var/kirak/metrics.db”. |
batch_interval_seconds |
integer | Seconds between writes of collected data. Default 5. |
retention_days |
integer | Days metrics are kept (sqlite sink only). Default 7. |
audit_retention_days |
integer | Days audit events are kept (sqlite sink only), apart from retention_days. Default 30. |
sample_rate |
number | Share of requests whose per-operation timings (request steps) are recorded, from 0 to 1; every request itself is recorded. Default 1.0. |
slow_request_threshold_ms |
integer | Operations taking at least this many milliseconds have their timing recorded whatever sample_rate. Default 500. |
max_db_size_mb |
integer | Size cap of the metrics file in megabytes (sqlite sink only). Default 200. |
queue_max_size |
integer | Maximum records (requests, audit, AI) waiting in memory to be written. Default 10000. |
log_capture_level |
string | Lowest level of captured log records. Default WARNING. |
log_queue_max_size |
integer | Maximum log records waiting to be written. Default 5000. |
Monitoring runs when "monitoring" is in modules; the monitoring section has no on/off switch.
To send captured logs to a log platform, use the stdout sink ("sinks": ["stdout"], see Stateless deployments) or log_output for the app’s own lines. The monitoring module does not POST logs to an HTTP endpoint.
sinks chooses where monitoring records are written:
["sqlite"](the default): the local file atdb_path. The query endpoints, the alert checks and thekirak dev mcplive tools read it.["stdout"]: each record is printed as one JSON line, and no file is created. See Stateless deployments.["sqlite", "stdout"]: both. Each sink is written on its own, so a failing file does not stop the stdout lines, and a closed stdout does not stop the file.
Without sqlite, db_path, retention_days, audit_retention_days and max_db_size_mb do not apply: retention does not run, /monitoring/health reports sqlite_reachable and db_size_bytes as null, and the read endpoints answer 501 MONITORING_NO_STORE (see HTTP Endpoints). Queue depths, drop counts and flush_running are reported as before.
The app’s own log lines are set by log_output in kirak.json, not by sinks: kirak.log by default, stdout with "stdout". With stdout, each captured record appears once, as the app’s text line, so the stdout sink leaves its logs lines out.
Stateless deployments
Section titled “Stateless deployments”Containers, Cloud Run, Kubernetes and several replicas behind a load balancer have no disk that survives a restart, and each replica would keep its own file. For them, use the stdout sink: the platform collects stdout from every replica and keeps it, so the app only prints.
{ "monitoring": { "sinks": ["stdout"] } }The app’s own log lines go to stdout too with "log_output": "stdout" at the top level of kirak.json (see configuration). Set "log_format": "json" alongside it to emit each app log line as a JSON object with a severity field, which Cloud Logging and similar collectors use to assign severity. With both, the platform gets the app’s lines and the JSON records from monitoring, with no duplicates.
Each record is one line, a JSON object with the same fields as its table (see Data Tables) and three more:
{"kirak": "monitoring", "type": "http_requests", "ts": "2026-10-16T09:12:03.481Z", "request_id": "6f1c0e2a", "method": "GET", "route": "/posts/fetch", "path": "/posts/fetch", "status_code": 200, "duration_ms": 12.4, "user_id": "7", "req_bytes": null, "resp_bytes": 1832, "created_at": 1792141923.481}kirakis always"monitoring". Filter on it to tell these lines apart from uvicorn’s access log and other output.typeis the table name:http_requests,request_errors,request_steps,logs,audit_events,ai_runs,ai_tool_calls,mcp_callsorintegration_calls.tsis the time in UTC with milliseconds, for log tools that index on a timestamp.created_atis the same instant in epoch seconds.request_idis on every line that belongs to a request, so a log platform can rebuild a trace by filtering on it, as/monitoring/trace/{request_id}does for the store.- Lines are written once per
batch_interval_seconds, not once per request. Non-ASCII characters are escaped, so every line is ASCII.
Limits:
- Long lines are split. Docker’s
json-filedriver and containerd (Kubernetes) split a line longer than 16 KB into parts, and most collectors join them again; some do not. Only long tracebacks get near that size. - Other stdout output. uvicorn’s access log is plain text on stdout as well. With the
kirakmarker a collector can separate monitoring JSON lines from everything else. Withlog_format: "json", a third line type appears: app log JSON (nokirakfield, hasseverity). With the stdout sink, the access log repeats the request lines and can be turned off with--no-access-log. - Records waiting in memory are lost on SIGKILL. SIGTERM writes them out first. This is the same loss window as the SQLite sink.
- Volume. Every request is at least one line, and each CRUD step adds one. Log platforms bill by volume: lower
sample_rateto reduce the step lines. - Personal data. Audit events carry
actor_email,ip_addressanduser_agent, as theaudit_eventstable does. Thekirak.auditlog lines leave those three out and keep the event type, actor ID and metadata, because log handlers go to stdout and wherever the platform keeps its logs, often with wider access than the store. - No queries here. The
/monitoring/*endpoints, the dashboards and the alert checks need the SQLite sink. Query the lines with the platform’s log tooling.
Data Tables
Section titled “Data Tables”Monitoring data lives in tables inside the SQLite file at db_path (with the sqlite sink; the stdout sink writes the same records as lines, see Stateless deployments): http_requests, request_steps, request_errors, logs, audit_events (one row per security event, see below: event type, actor, IP address, user agent), ai_runs, ai_tool_calls and mcp_calls (one row per MCP tool call, when the mcp module is on too), and integration_calls (one row per outgoing call of an integration with audit_requests on: method, host, path without the query, status, duration, size, connection id). These are internal to the monitoring module – query them through the HTTP endpoints above rather than directly, since the schema is not a public contract.
Audit events
Section titled “Audit events”Auth and integrations record security events. Each one is always written to the kirak.audit logger as an audit event line at INFO, whatever log_level and log_capture_level are, and with or without monitoring. With monitoring on, it is also stored in audit_events, read with GET /monitoring/audit, and kept audit_retention_days (default 30), apart from the other records’ retention_days:
event_type |
When | Fields set |
|---|---|---|
auth.login.success |
A password login succeeds | actor_id, actor_email, ip_address, user_agent |
auth.login.failure |
A password login fails; metadata.reason is user_not_found or wrong_password |
actor_email, ip_address, user_agent |
auth.password_change.success |
/auth/change-password succeeds |
actor_id |
auth.password_change.failure |
/auth/change-password with a wrong current password (metadata.reason: wrong_current_password) |
actor_id |
auth.api_key.created |
An API key is created; metadata has key_prefix, target_user_id, name (never the key) |
actor_id |
auth.api_key_revoked |
An API key is revoked; metadata has key_id, key_owner_id |
actor_id (the caller) |
auth.logout |
A logout ends sessions; metadata has logout_type, deleted_tokens |
actor_id |
auth.refresh_reuse_detected |
A rotated refresh token is used again after the reuse interval and its session is revoked; metadata has family_id |
actor_id |
auth.password_reset_requested |
A reset link is sent to a registered address (none for an unknown one) | actor_id |
auth.password_reset |
A password is reset with a reset link; the sessions end | actor_id |
auth.mfa_setup_started |
An authenticator is added and waits for its first code | actor_id |
auth.mfa_disabled |
MFA is turned off | actor_id |
auth.email_changed |
An email change is confirmed; metadata has old_email and new_email, both masked |
actor_id |
auth.phone_linked |
A phone number is saved on the account | actor_id |
auth.role_changed |
A CRUD update on users changes a user’s role; metadata has role (the new value), user_ids, and complete (false when the update matched more users than one read covers) |
actor_id (the caller) |
auth.account_activation_changed |
A CRUD update on users changes a user’s is_active; metadata has is_active, user_ids, complete |
actor_id (the caller) |
auth.account_closed |
An account is closed; metadata has user_id, window, purge_at |
actor_id (the caller, or its role) |
auth.account_restored |
An admin restores a closed account; metadata has user_id |
actor_id |
auth.account_reopened |
A user reopens the account they closed (/auth/reopen-account); metadata has user_id |
actor_id (the user), ip_address, user_agent |
auth.account_purged |
A closed account’s data is deleted; metadata has user_id. Each enabled module first records its own <module>.account_purged |
none |
auth.key_rotation_started |
An admin starts an encryption key rotation; metadata has old_key_ids, batch_size, pause_seconds |
actor_id |
auth.encrypted_value_cleared |
A key rotation finds a stored secret no key can decrypt and clears it; metadata has table, row_id, reason |
actor_id (the row’s user) |
integrations.connected |
A user connects an integration; metadata has integration, connection_id, account_label |
actor_id |
integrations.reconnected |
A user’s existing connection of an integration is replaced by a new connect | actor_id |
integrations.disconnected |
A user disconnects an integration; metadata has integration, connection_id |
actor_id |
integrations.site_changed |
A user makes another of a connection’s sites active; metadata has integration, connection_id, site |
actor_id |
integrations.needs_reauth |
A connection can no longer be refreshed; metadata has integration, connection_id, reason |
actor_id |
integrations.webhook_rejected |
A webhook delivery’s signature is not valid; metadata has integration, reason (no body, no signature) |
none (the provider sends it) |
integrations.key_saved |
A user saves an API key; metadata has integration, connection_id, outcome (saved or replaced) |
actor_id |
integrations.key_removed |
A user removes an API key by disconnecting it; metadata has integration, connection_id |
actor_id |
integrations.refresh_failed |
A refresh failed for now (the connection stays active); metadata has integration, connection_id, reason |
actor_id |
Each row also has created_at and metadata (JSON text). Events are queued like requests (audit_queue_depth / audit_dropped_count in /monitoring/health), written by the same background writer, and pruned by the same retention. A row that a full queue drops is still in the kirak.audit log lines, so the log keeps every event even when audit_dropped_count rises.
A damaged or deleted store
Section titled “A damaged or deleted store”If the file at db_path is not a valid SQLite database at startup (disk fault, bad copy, partial restore), the app still starts: the file (and its -wal / -shm, if any) is renamed to <db_path>.corrupt-<UTC timestamp>, an ERROR naming the new path is logged, and an empty store is created. The renamed file is kept for inspection; delete it when you no longer need it. A store that cannot be opened at all (no permission, a directory at db_path) still stops startup, since that is a setup problem.
If the file at db_path is deleted or replaced while the app runs (on Linux an open file can be deleted, and SQLite would keep writing to the deleted file), /monitoring/health reports sqlite_reachable: false and a health alert check breaches until the next write cycle (batch_interval_seconds), which logs an ERROR and reopens the store at db_path (a new empty one if the file is gone). Records written between the change and that cycle are lost.