Skip to content

Observability

Kirak includes a built-in monitoring subsystem: request-level RED metrics (rate, errors, duration), structured request tracing, log capture, and threshold-based alert checks – all served from the runtime’s own endpoints, with no third-party APM required.

This page covers how it works. For the exact endpoints and configuration keys, see Monitoring Reference.


Monitoring is a module like payments or storage – it does nothing until you enable it in kirak.json:

"modules": ["monitoring"]

MonitoringMiddleware is actually added to every Kirak app unconditionally, but it’s a true no-op until the module is enabled – so there’s zero overhead if you never opt in.


flowchart LR
Req["HTTP request"] --> MW["MonitoringMiddleware"]
MW --> Ops["Model and module operations (step hooks)"]
MW --> Q["In-memory queues (bounded; the oldest record is dropped when full)"]
Ops --> Q
Logs["Captured log lines, AI runs, MCP calls, audit events"] --> Q
Q -->|"every batch_interval_seconds"| S{"sinks"}
S -->|"sqlite (default)"| DB[("var/kirak/metrics.db")]
S -->|"stdout"| OUT["One JSON line per record"]
DB --> API["/monitoring/* endpoints and alert checks"]

Nothing is written on the request path: records wait in memory and a background task writes them in batches. Each sink is written on its own, so a failing one does not stop the other.

Monitoring data (requests, timing, errors, logs) is written to its own SQLite database (var/kirak/metrics.db by default), completely isolated from your application’s own database pool. This means monitoring can’t contend with your app for connections, and it works the same way regardless of whether your app runs on MySQL, PostgreSQL or SQLite (a SQLite app database is a separate file).

On a stateless platform (containers, Cloud Run, several replicas) a file does not survive a restart, and each replica would keep its own. There, set "sinks": ["stdout"] in the monitoring section: each record is printed as one JSON line for the platform’s log collector, and the app needs no disk. The query endpoints and alert checks then need the SQLite sink. See Stateless deployments.


  • Every HTTP request – via MonitoringMiddleware: method, route, path, status code, duration, request and response size, user. The duration runs until the whole response has been sent, so a streamed response (an AI stream over SSE, a download) counts its full length; a client that disconnects mid-stream is recorded up to the disconnect. A path that matches no route (a scanner probing random URLs) is not recorded.
  • Operation timing – via hooks, sampled (see below): one step per model operation (fetch, create, …) and per operation of the other modules (payments, notifications, storage, AI, …), with the time spent in the database and in provider calls, and whether the query cache was hit.
  • Unhandled exceptions – captured with a full stack trace (secrets masked), linked to the request that triggered them, and counted as a 500. Exceptions your code raises deliberately as KirakException/HTTPException are not treated as monitoring errors – they’re expected control flow, not incidents.
  • Application logs – captured up to log_capture_level (default WARNING) and linked to the request that produced them.
  • AI runs, MCP tool calls and integration calls, when those modules are on.
  • Security audit events – always logged to the kirak.audit logger; stored with the other records when monitoring is on. See Audit events.

To keep overhead low on high-traffic apps, operation timing can be sampled – controlled by sample_rate (default 1.0, i.e. every request). The decision is made per request, so a request’s steps are all kept or all left out. Every request itself is always recorded. A step that takes at least slow_request_threshold_ms (default 500 ms) is kept whatever the sampling, so slow operations are never lost.


Every request gets a request ID (the same X-Request-ID used for log correlation elsewhere in Kirak – see Middleware). Pull the full timeline for one request – the request itself, its steps, any errors, and any logs it produced – from GET /monitoring/trace/{request_id} (shape: Request traces). This is the primary way to debug a single problematic request: read the trace, don’t add print statements.


POST /monitoring/alerts/evaluate evaluates a batch of threshold checks (5xx rate, p95/p99 latency, request rate, AI cost and error rate, and more) against the stored metrics and returns which ones are breaching:

{"checks": [{"id": "api_errors", "metric": "5xx_rate", "op": "gt", "value": 0.05, "window_seconds": 300}]}

Kirak does not ship Slack/email/PagerDuty delivery, firing-state tracking, or rule storage – it’s pure computation. Wire the response into whatever notification path you already have (a scheduled job that calls this endpoint and posts to Slack on a breach, for example). Every field and metric is in Alert checks.


Two-tier cleanup of the SQLite store, run daily (not at all without the sqlite sink; the platform keeps stdout lines by its own rules): with the scheduler module, as a cron job at 03:00 UTC; without it, by an asyncio loop that runs once at startup and then every 24 hours (so an app restarted more often than daily is still pruned).

  1. Time-based – rows older than retention_days (default 7) are deleted across every monitoring table, except audit events, which are kept audit_retention_days (default 30).
  2. Size-cap safety valve – if the store is still over max_db_size_mb (default 200) after step 1, its free space is reclaimed first (VACUUM; deleted rows do not shrink an SQLite file by themselves). If it is still over, the oldest 15% of rows across the monitoring tables other than audit events are dropped regardless of age, and the space is reclaimed again. Only if the store is still over the cap after that are the oldest 15% of audit events dropped too. The size counts the store’s -wal and -shm files too. Reclaiming rewrites the file, so monitoring writes wait while it runs; it only happens when the store is over the cap.