Traces in SQLite

Every request becomes a row. Ask the file what happened.

Which route is slow? What failed last night? What did this one request do? Stario records a span for every request, and with two environment variables those spans land in a file, one JSON object per line. The answers are then SQL queries against a file on disk, with no dashboard and no agent.

STARIO_TRACER=json STARIO_TRACERS_JSON=spans.ndjson uv run python main.py

That is the whole setup. The file is a local record of one process, not a distributed trace store; for several machines or a hosted backend, write a custom tracer.

STARIO_TRACER=sqlite wrote the same spans straight into SQLite through a bundled tracer. It is deprecated since 5.3 and removed in 6.0 — the JSON file plus a SQL reader covers it, and the JSON file works with other tools too.

Settings#

Only the variables you set change anything. The rest keep the constructor defaults.

VariableDefaultMeaning
STARIO_TRACERS_JSONstdoutPath of the NDJSON file; parent directories are created and the file is appended
STARIO_TRACERS_JSON_FLUSH_INTERVAL0.125Seconds between writer flushes
STARIO_TRACERS_JSON_MAX_PENDING_SPANS65536Queue size before finished spans are dropped
STARIO_TRACERS_JSON_MAX_BATCH_SPANS512Spans written per batch

In a container, point the path at a mounted volume: STARIO_TRACERS_JSON=/data/spans.ndjson. For anything these variables do not cover, a custom tracer module can return a JsonTracer(path=...) you constructed yourself.

What is in the file#

One JSON object per finished span: span_id, trace_id, name, start_ns, end_ns, duration_ns, status (ok or error), and error text when it failed. Children carry parent_id; roots do not. Events sit in an events array and links in links.

The request facts live inside attributes: request.method, request.path, response.status_code, and whatever your handlers added. The keys contain dots, so in SQLite quote them: attrs_json ->> 'request.path'. Not every root span is a request; server.startup and server.shutdown are roots too, so filter on request.path IS NOT NULL when you mean traffic.

Load it with SQLite#

The file is line-delimited JSON, so a short script makes it a SQLite database. It builds the same three tables the old tracer wrote:

"""Load a Stario NDJSON span file into SQLite."""
 
import json
import sqlite3
import sys
 
source = sys.argv[1] if len(sys.argv) > 1 else "spans.ndjson"
target = sys.argv[2] if len(sys.argv) > 2 else "traces.sqlite3"
 
spans, events, links = [], [], []
with open(source) as f:
    for line in f:
        if not line.strip():
            continue
        s = json.loads(line)
        spans.append(
            (
                s["span_id"],
                s["trace_id"],
                s.get("parent_id"),
                s["name"],
                s["start_ns"],
                s["end_ns"],
                s["duration_ns"],
                s["status"],
                s.get("error"),
                json.dumps(s.get("attributes")),
            )
        )
        for e in s.get("events", []):
            events.append(
                (
                    s["span_id"],
                    s["trace_id"],
                    e["time_ns"],
                    e["name"],
                    json.dumps(e.get("attributes")),
                    e.get("body"),
                )
            )
        for l in s.get("links", []):
            links.append(
                (
                    s["span_id"],
                    s["trace_id"],
                    l["span_id"],
                    l["name"],
                    json.dumps(l.get("attributes")),
                )
            )
 
db = sqlite3.connect(target)
db.executescript("""
    DROP TABLE IF EXISTS spans;
    DROP TABLE IF EXISTS span_events;
    DROP TABLE IF EXISTS span_links;
    CREATE TABLE spans (
        span_id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, parent_id TEXT,
        name TEXT NOT NULL, start_ns INTEGER NOT NULL, end_ns INTEGER NOT NULL,
        duration_ns INTEGER NOT NULL, status TEXT NOT NULL, error TEXT,
        attrs_json TEXT
    );
    CREATE TABLE span_events (
        span_id TEXT NOT NULL, trace_id TEXT NOT NULL, time_ns INTEGER NOT NULL,
        name TEXT NOT NULL, attrs_json TEXT, body TEXT
    );
    CREATE TABLE span_links (
        span_id TEXT NOT NULL, trace_id TEXT NOT NULL, target_span_id TEXT NOT NULL,
        name TEXT NOT NULL, attrs_json TEXT
    );
""")
db.executemany("INSERT INTO spans VALUES (?,?,?,?,?,?,?,?,?,?)", spans)
db.executemany("INSERT INTO span_events VALUES (?,?,?,?,?,?)", events)
db.executemany("INSERT INTO span_links VALUES (?,?,?,?,?)", links)
db.commit()
python load_spans.py spans.ndjson traces.sqlite3
sqlite3 traces.sqlite3

Or just ask DuckDB#

DuckDB reads the NDJSON file directly — no load step:

SELECT
  attributes ->> 'request.path' AS path,
  status,
  duration_ns / 1e6 AS dur_ms
FROM read_json('spans.ndjson')
WHERE parent_id IS NULL
ORDER BY duration_ns DESC;

Every query below works in both files once the columns are named the same way; in DuckDB read from read_json('spans.ndjson') instead of spans, and attributes instead of attrs_json.

Which routes are slow?#

The average over all requests:

SELECT
  ROUND(AVG(duration_ns) / 1e6, 3) AS avg_ms,
  COUNT(*) AS n
FROM spans
WHERE parent_id IS NULL
  AND attrs_json ->> 'request.path' IS NOT NULL;

The twenty slowest, with their paths:

SELECT
  attrs_json ->> 'request.method' AS method,
  attrs_json ->> 'request.path' AS path,
  attrs_json ->> 'response.status_code' AS status,
  duration_ns / 1e6 AS dur_ms,
  datetime(end_ns / 1e9, 'unixepoch') AS ended_utc
FROM spans
WHERE attrs_json ->> 'request.path' IS NOT NULL
ORDER BY duration_ns DESC
LIMIT 20;

What failed?#

Responses with a 5xx status:

SELECT
  attrs_json ->> 'request.method' AS method,
  attrs_json ->> 'request.path' AS path,
  attrs_json ->> 'response.status_code' AS status,
  duration_ns / 1e6 AS dur_ms,
  datetime(end_ns / 1e9, 'unixepoch') AS ended_utc
FROM spans
WHERE CAST(attrs_json ->> 'response.status_code' AS INTEGER) >= 500
ORDER BY end_ns DESC
LIMIT 50;

Spans the code marked as failed, with the error text:

SELECT
  name,
  error,
  attrs_json ->> 'request.path' AS path,
  datetime(end_ns / 1e9, 'unixepoch') AS ended_utc
FROM spans
WHERE status = 'error'
ORDER BY end_ns DESC
LIMIT 50;

The exceptions themselves, from the events table:

SELECT
  e.name AS event_name,
  s.attrs_json ->> 'request.path' AS path,
  e.body AS detail,
  datetime(e.time_ns / 1e9, 'unixepoch') AS event_utc
FROM span_events AS e
JOIN spans AS s ON s.span_id = e.span_id
WHERE e.name = 'exception'
ORDER BY e.time_ns DESC
LIMIT 50;

What happened just now?#

The last twenty requests, newest first:

SELECT
  attrs_json ->> 'request.method' AS method,
  attrs_json ->> 'request.path' AS path,
  attrs_json ->> 'response.status_code' AS status,
  duration_ns / 1e6 AS dur_ms,
  datetime(end_ns / 1e9, 'unixepoch') AS ended_utc
FROM spans
WHERE attrs_json ->> 'request.path' IS NOT NULL
ORDER BY end_ns DESC
LIMIT 20;

What did one request do?#

Child spans share the request’s trace_id, and the ids are plain strings in the file. Add trace_id to any query above, then list that trace in order:

SELECT
  name,
  parent_id,
  duration_ns / 1e6 AS dur_ms,
  status
FROM spans
WHERE trace_id = '01a18776-…'
ORDER BY start_ns;

Spans linked from elsewhere, such as a background job that records which request started it:

SELECT
  s.name AS from_span,
  l.name AS link_name,
  l.target_span_id AS target_span,
  datetime(s.end_ns / 1e9, 'unixepoch') AS ended_utc
FROM span_links AS l
JOIN spans AS s ON s.span_id = l.span_id
ORDER BY s.end_ns DESC
LIMIT 50;

By the way#

  • The tracer keeps its own health in memory, not in the file: tracer.stats() reports dropped_spans and writer_error_count on a JsonTracer you constructed yourself.

  • Telemetry design explains why a span looks the way it does, and Telemetry lists what you can put on one.

To try the queries on real data, run Tiles with STARIO_TRACER=json STARIO_TRACERS_JSON=spans.ndjson and click around for a minute.