# Redline > A request profiler, backend analyzer and load tester for Django, FastAPI, Flask and Litestar. N+1 detection with fix diffs, one-click EXPLAIN, flamegraphs, load testing and a fast web UI. --- --- title: Redline hide: - navigation - toc ---
![Redline](assets/logo-mark.svg){ .rl-hero-mark } # See inside every request

A self-hosted request profiler, backend analyzer and load tester for Django, FastAPI, Flask and Litestar. Find the slow query, get the fix as a diff, then push load at it and see what breaks first.

[Get started](getting-started.md){ .md-button .md-button--primary } [View on GitHub](https://github.com/Pythondeveloper6/redline){ .md-button }
![The N+1 issue of the Django demo shop in Redline: 30 queries from one line, with a prefetch_related diff](assets/screenshots/django-n-plus-one-light.png){ .rl-shot .rl-only-light } ![The N+1 issue of the Django demo shop in Redline, dark theme](assets/screenshots/django-n-plus-one-dark.png){ .rl-shot .rl-only-dark } !!! tip "Built for AI agents" Redline ships an MCP server, fix briefs, a verify-a-fix command, LLM-call observability and machine-readable docs ([`llms.txt`](llms.txt)). See [Working with AI agents](agents.md). !!! warning "Beta: 0.5 development release" This checkout contains the next release's features; PyPI can contain an earlier version. See [Getting started](getting-started.md#install) for published and local workspace installs. APIs and settings can change. Start with development/staging, and use the deployment-specific [production validation gate](production.md) before recording real traffic. ## Install in a minute === "Django" ```bash pip install \ "django-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/django-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` ```python # settings.py INSTALLED_APPS = [..., "django_redline"] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_redline.middleware.RedlineMiddleware", # as high as possible ..., ] ``` ```python # urls.py from django.urls import include, path urlpatterns = [ ..., path("redline/", include("django_redline.urls")), ] ``` Run your app, make a few requests, and open `/redline/` as a superuser. === "FastAPI" ```bash pip install \ "fastapi-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/fastapi-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` ```python from fastapi import FastAPI from sqlalchemy.ext.asyncio import create_async_engine from fastapi_redline import install app = FastAPI() engine = create_async_engine("sqlite+aiosqlite:///app.db") # access="local": localhost only (unset, Redline answers 404 outside debug mode) install(app, engine=engine, settings={"access": "local"}) # UI at http://localhost:8000/_redline/ ``` === "Flask" ```bash pip install \ "flask-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/flask-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` ```python from flask import Flask from sqlalchemy import create_engine from flask_redline import Redline app = Flask(__name__) engine = create_engine("sqlite:///app.db") # access="local": localhost only (unset, Redline answers 404 outside debug mode) Redline(app, engine=engine, settings={"access": "local"}) # UI at http://localhost:5000/_redline/ ``` With Flask-SQLAlchemy, omit the engine. === "Litestar" ```bash pip install \ "litestar-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/litestar-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` ```python from litestar import Litestar from sqlalchemy.ext.asyncio import create_async_engine from litestar_redline import RedlinePlugin engine = create_async_engine("sqlite+aiosqlite:///app.db") app = Litestar( route_handlers=[...], # access="local": localhost only (unset, Redline answers 404 outside debug mode) plugins=[RedlinePlugin(engine=engine, settings={"access": "local"})], # UI at http://localhost:8000/_redline/ ) ``` That is the whole setup. Traces go to their own SQLite file (`.redline/redline.db`), never to your application database. The source-install commands name adapter and core together to keep their exact-version pin aligned. Published prereleases can instead be installed with `pip install --pre` and the framework adapter name. For unreleased features, use the matching local workspace. [Details](getting-started.md#install). ## What you get
- :material-timeline-clock-outline:{ .lg .middle } **Profile every request** --- A waterfall of spans for middleware, view, SQL, cache, templates, serializers, transactions and outbound HTTP, with logs, exception locals and opt-in flamegraphs. [:octicons-arrow-right-24: How it works](how-it-works.md) - :material-database-search-outline:{ .lg .middle } **Analyze, with the fix attached** --- N+1 queries mapped back to your source line and written as a diff (`prefetch_related`, `selectinload`...). One-click EXPLAIN, an index advisor, event-loop blocking, long transactions, huge results, slow serializers and external calls. [:octicons-arrow-right-24: N+1](n-plus-one.md) · [Detectors](detectors.md) - :material-speedometer:{ .lg .middle } **Load test and find the knee** --- `redline load` drives your app at a real arrival rate, corrects for coordinated omission, finds the knee, and shows which query went from 3 ms to 410 ms at which step. [:octicons-arrow-right-24: Load testing](load-testing.md) - :material-check-decagram-outline:{ .lg .middle } **Prove a refactor is safe** --- `redline check` replays a set of read-only requests against the old code and the new, and reports what changed in the responses, which endpoints got faster or slower (with a significance test), and which queries appeared or went away. Exit code and PR comment included. [:octicons-arrow-right-24: Refactor check](refactor-check.md) - :material-chart-timeline-variant:{ .lg .middle } **Compare releases** --- Hourly rollups kept for 90 days, stamped with your release. Compare two releases and get a verdict per endpoint, plus the issues that are new or resolved. [:octicons-arrow-right-24: History](history.md) - :material-puzzle-outline:{ .lg .middle } **Five integrations** --- Django (with Ninja and DRF), FastAPI, Flask, Litestar and a framework-free core, plus `requests`, httpx, Redis, asyncpg, psycopg, Marshmallow, Strawberry and Graphene hooks. [:octicons-arrow-right-24: Integrations](integrations.md) · [Extending](extending.md) - :material-shield-lock-outline:{ .lg .middle } **Redacted and locked down** --- Secrets are masked before anything is stored. One access policy for every framework, read-only mode and a production preset. State lives in `contextvars`, so async is attributed correctly. [:octicons-arrow-right-24: Security](security.md) · [Access control](access-control.md)
## Five integrations, one tool | Framework | Package | Read | |---|---|---| | Django (including Ninja and DRF) | `django-redline` | [Django](django.md), [Django Ninja](django-ninja.md) | | FastAPI + SQLAlchemy | `fastapi-redline` | [FastAPI](fastapi.md) | | Flask (and Flask-SQLAlchemy) | `flask-redline` | [Flask](flask.md) | | Litestar + SQLAlchemy | `litestar-redline` | [Litestar](litestar.md) | | Anything else | `redline-core` | [Extending](extending.md#using-the-core-directly) | ## A closer look === "Requests" ![Requests list](assets/screenshots/fastapi-light-requests.png){ .rl-shot .rl-only-light } ![Requests list](assets/screenshots/fastapi-dark-requests.png){ .rl-shot .rl-only-dark } === "Timeline" ![Request timeline](assets/screenshots/fastapi-light-detail-timeline.png){ .rl-shot .rl-only-light } ![Request timeline](assets/screenshots/fastapi-dark-detail-timeline.png){ .rl-shot .rl-only-dark } === "Issues" ![Deduplicated issues](assets/screenshots/django-issues-light.png){ .rl-shot .rl-only-light } ![Deduplicated issues](assets/screenshots/django-issues-dark.png){ .rl-shot .rl-only-dark } === "EXPLAIN" ![EXPLAIN drawer](assets/screenshots/django-explain-light.png){ .rl-shot .rl-only-light } ![EXPLAIN drawer](assets/screenshots/django-explain-dark.png){ .rl-shot .rl-only-dark } === "Flamegraph" ![Flamegraph](assets/screenshots/django-flamegraph-light.png){ .rl-shot .rl-only-light } ![Flamegraph](assets/screenshots/django-flamegraph-dark.png){ .rl-shot .rl-only-dark } === "Endpoints" ![Endpoint aggregates](assets/screenshots/fastapi-light-endpoints.png){ .rl-shot .rl-only-light } ![Endpoint aggregates](assets/screenshots/fastapi-dark-endpoints.png){ .rl-shot .rl-only-dark } === "Redaction" ![Redacted headers and body](assets/screenshots/django-redaction-light.png){ .rl-shot .rl-only-light } ![Redacted headers and body](assets/screenshots/django-redaction-dark.png){ .rl-shot .rl-only-dark } === "FastAPI N+1" ![SQLAlchemy N+1 with a selectinload diff](assets/screenshots/fastapi-light-detail-issues.png){ .rl-shot .rl-only-light } ![SQLAlchemy N+1 with a selectinload diff](assets/screenshots/fastapi-dark-detail-issues.png){ .rl-shot .rl-only-dark } ## Why another profiler Request profilers split into two camps. In-page toolbars show one request, in development, and forget it. Hosted APMs see production but not your source lines, and they are another vendor. The self-hosted middle ground is thin: [django-silk](https://github.com/jazzband/django-silk) is Django-only and has no async story, and nothing comparable exists for FastAPI, Flask or Litestar. Redline is built for that middle: a **persistent** record of recent requests, in your own process and your own disk, that knows enough about your ORM to say *which line to change*, and can push load at the same app to show where it bends. It is not trying to replace a hosted APM for fleet-wide production monitoring (see the [comparison](#how-it-compares) and the [FAQ](faq.md)). ## How it compares | | **Redline** | django-silk | django-debug-toolbar | Kolo | Sentry / Logfire | Locust / k6 | |---|---|---|---|---|---|---| | Django | Yes | Yes | Yes | Yes | Yes | n/a (black box) | | FastAPI, Flask, Litestar / SQLAlchemy | Yes | No | No | Not its focus | Yes | n/a | | Async-correct recording | Yes (`contextvars`) | No async support | Partial (async views supported in recent versions) | n/a | Yes | n/a | | Names the call that blocks the event loop | **Yes** | No | No | No | Partial | No | | Persists traces across requests | Yes, own SQLite file | Yes, in your app DB | History panel only | Local trace store | Hosted | Results only | | N+1 detection | Yes, grouped and deduplicated | Manual (count queries) | Query counts and "similar" markers | Shows repeated queries | Yes (performance issues) | No | | Fix suggestion as a diff | **Yes** (Django and SQLAlchemy) | No | No | No | No (generic advice) | No | | EXPLAIN | Yes, safe by default | No | Yes (per query, in page) | No | No | No | | Plan analysis + index advice | Yes, per query and workload-wide | No | No | No | No | No | | Flamegraphs | Opt-in, per request | cProfile call tree | Optional profiling panel | Call traces | Profiling products | No | | Secrets redacted on write | Yes, by default | Stores bodies and headers as captured | n/a (not persisted) | Local only | Scrubbing is configurable | n/a | | Before/after across releases | Yes (90 days of rollups) | No | No | No | Yes (releases) | Results only | | Runs in production | Possible, with care ([preset](production.md#the-production-preset)) | Heavy; not advised | No | No | **Built for it** | Against staging | | Distributed tracing across services | **No** | No | No | No | **Yes** | n/a | | Load testing | **Yes**, open model, shows the culprit query per step | No | No | No | No | **Yes**, far more mature and flexible | | Hosted, zero ops | No | No | No | Editor extension | Yes | Yes | Read this table with its omissions in mind. If you need cross-service traces, alerting, or fleet dashboards, use Sentry or Logfire (Redline can sit beside them). If you need a mature, scriptable, large-scale distributed load generator, use Locust or k6: Redline's load tester is scenario-file driven (HTTP, held streams and WebSockets, optionally spread over a few generator hosts), and its value is the correlation with what happened inside the server. Where this table says "No" for another tool it means "not as a built-in feature", and tools change: check theirs. ## Requirements | | Python | Framework | Other | |---|---|---|---| | `redline-core` | 3.10+ | none | no runtime dependencies | | `django-redline` | 3.12+ | Django 5.2, 6.0 or 6.1 | | | `fastapi-redline` | 3.10+ | FastAPI 0.110+ | SQLAlchemy 2.x | | `flask-redline` | 3.10+ | Flask 3.0+ | SQLAlchemy 2.x | | `litestar-redline` | 3.10+ | Litestar 2.12+ | SQLAlchemy 2.x | Flamegraphs need the `profile` extra (pyinstrument); the load tester needs the `load` extra (httpx). There is no Node.js requirement: the web UI ships prebuilt inside `redline-core`. ## All pages ??? abstract "Every page, with what is in it" **Get started and guide** | Page | What is in it | |---|---| | [Getting started](getting-started.md) | Install, mount, first look, for all four frameworks | | [How it works](how-it-works.md) | Recording, `contextvars`, sampling, storage and the overhead model | | [The UI](the-ui.md) | A tour of every page, filter, shortcut and action | | [Server-Timing and the badge](server-timing-badge.md) | The header and the floating pill | | [N+1 detection](n-plus-one.md) | Detection rules, thresholds, fix suggestions with real diffs | | [EXPLAIN](explain.md) | Vendors, safety, findings, index suggestions | | [Flamegraphs](flamegraphs.md) | Opt-in profiling, modes, speedscope export | | [Custom spans](custom-spans.md) | Timing your own code with `redline_core.span` | | [Issues and endpoints](issues-and-endpoints.md) | Aggregates, percentiles, issue deduplication | **Analysis** | Page | What is in it | |---|---| | [Detectors overview](detectors.md) | Every issue kind, threshold and span kind | | [Blocking in async](async-blocking.md) | The event-loop lag monitor | | [Transactions and locks](transactions.md) | Long transactions, HTTP in a transaction, pool waits | | [Large and unbounded results](result-size.md) | Rows, missing `LIMIT`, `len(qs)` vs `.exists()` | | [Slow serializers](serializers.md) | DRF, Pydantic and Marshmallow | | [External calls](external-calls.md) | Slow, duplicated and retried outbound HTTP | | [Cache efficiency](cache-efficiency.md) | Hit rate, unread writes, stampedes | | [Logs and exceptions](logs-and-exceptions.md) | Logs per request, locals in exceptions | | [Database](database.md) | SQL search, index advisor, unused indexes | | [Static N+1 scan](static-scan.md) | Find N+1s in templates and serializers without running code | | [GraphQL](graphql.md) | Resolver spans and N+1 over GraphQL | **Load and history** | Page | What is in it | |---|---| | [Load testing](load-testing.md) | Open model, the knee, scenarios, CLI, CI, bottlenecks | | [History and releases](history.md) | Rollups, release compare, regressions, retention | **Integrations** | Page | What is in it | |---|---| | [Django](django.md), [Django Ninja](django-ninja.md) | Middleware, URLs, settings, permission, CSRF, hooks, checks, commands, DRF | | [FastAPI](fastapi.md) | `install()`, engines, auth dependencies, CSRF, lifespan | | [Flask](flask.md) | `Redline(app)`, Flask-SQLAlchemy, factories, `flask redline` | | [Litestar](litestar.md) | `RedlinePlugin`, engines, guards | | [Integrations](integrations.md) | requests, httpx, Redis, asyncpg, psycopg, Marshmallow | | [Extending](extending.md) | `FixSuggester` and the `Store` protocol | **Operations and reference** | Page | What is in it | |---|---| | [Configuration](configuration.md) | Presets, `redline.toml`, environment variables, precedence | | [Access control](access-control.md) | Policies and recipes for VPNs, proxies, Kubernetes | | [Production](production.md) | The production preset, sampling, retention, what not to do | | [Security](security.md) | Redaction, what is stored, exposure, load-from-UI safety | | [Storage](storage.md) | The SQLite store, schema v2, the writer thread, retention | | [Performance and overhead](performance.md) | The cost model and the measured overhead | | [Settings reference](settings.md) | Every setting, its type, default and effect | | [The HTTP API](http-api.md) | Every endpoint with examples | | [Command line](cli.md) | `redline` and the framework commands | | [Roadmap](roadmap.md) | What shipped in 0.2 and what comes next | | [FAQ](faq.md) | How finished it is, how it differs from other tools | ## Licence Redline is open source under the [MIT licence](https://github.com/Pythondeveloper6/redline/blob/main/LICENSE), copyright © 2026 Mahmoud Ahmed. --- # Getting started [← Index](index.md) This page takes a Django, FastAPI, Flask or Litestar project from nothing to a populated Redline UI in a few minutes, then shows you how to confirm everything is wired up and what to do next. ## Install Redline is a core and one adapter per framework, released in lockstep: | Distribution | Import name | Install it when | |---|---|---| | `redline-core` | `redline_core` | always (the engine, the JSON API, the bundled UI and the `redline` command) | | `django-redline` | `django_redline` | you run Django (including Django Ninja) | | `fastapi-redline` | `fastapi_redline` | you run FastAPI with SQLAlchemy | | `flask-redline` | `flask_redline` | you run Flask, with or without Flask-SQLAlchemy | | `litestar-redline` | `litestar_redline` | you run Litestar with SQLAlchemy | Published prereleases are available on PyPI. Choose your framework's adapter; it installs its matching core. The checkout may contain newer features than the published version, so use a local workspace when testing unreleased changes. === "Django" ```bash pip install --pre django-redline ``` === "FastAPI" ```bash pip install --pre fastapi-redline ``` === "Flask" ```bash pip install --pre flask-redline ``` === "Litestar" ```bash pip install --pre litestar-redline ``` Each adapter pins the exact core it was tested with. Pin both to the same release in your deployment lock file; do not mix an unreleased adapter with an older core. Review the [PyPI project](https://pypi.org/project/django-redline/) and release history when choosing a published version. Beta releases require deployment-specific validation before use with real traffic; see [Production](production.md). Add extras to the **core** requirement: | Extra | Brings | For | |---|---|---| | `profile` | pyinstrument | [flamegraphs](flamegraphs.md) | | `load` | httpx | the [load tester](load-testing.md) | | `httpx`, `requests`, `redis`, `asyncpg`, `psycopg`, `strawberry`, `graphene` | the library at a compatible version | the matching [integration](integrations.md) | ```bash pip install --pre "redline-core[profile,load]" ``` Use the core version pinned by your installed adapter when adding extras. `uv pip install` accepts the same requirements. If installing directly from Git, install adapter and core from the same reviewed commit in one command; pin that commit instead of a moving branch. To work on Redline itself, or to try the demos, clone the repository instead: ```bash git clone https://github.com/Pythondeveloper6/redline cd redline uv sync --all-packages # every package, editable, plus the dev tools ``` ### Supported versions | | Supported | |---|---| | Python for `redline-core`, `fastapi-redline`, `flask-redline`, `litestar-redline` | 3.10, 3.11, 3.12, 3.13, 3.14 | | Python for `django-redline` | 3.12, 3.13, 3.14 | | Django | 5.2 LTS, 6.0, 6.1 (`>=5.2,<6.2`) | | FastAPI | 0.110 and later, below 1.0 | | Flask | 3.0 and later, below 4 | | Litestar | 2.12 and later, below 3 | | SQLAlchemy | 2.x | | Databases for EXPLAIN | PostgreSQL, MySQL (and MariaDB), SQLite | ## Mount it === "Django" Three edits to your project. ```python # settings.py INSTALLED_APPS = [ # ... "django_redline", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", # "django.middleware.gzip.GZipMiddleware", # if you use it, keep it above Redline "django_redline.middleware.RedlineMiddleware", # as high as possible "django.contrib.sessions.middleware.SessionMiddleware", # ... ] ``` ```python # urls.py from django.urls import include, path urlpatterns = [ # ... path("redline/", include("django_redline.urls")), ] ``` There is no migration: Redline never touches your database. Run the system checks to confirm the wiring: ```bash python manage.py check ``` A missing middleware, a missing URL mount, a `GZipMiddleware` placed wrongly and an unwritable storage directory are all reported with a hint. The complete list is in [Django: system checks](django.md#system-checks). === "FastAPI" One call, after the app is built and before it starts. ```python from fastapi import FastAPI from sqlalchemy.ext.asyncio import create_async_engine from fastapi_redline import install app = FastAPI() engine = create_async_engine("sqlite+aiosqlite:///app.db") # ... your routers ... # access="local": localhost only (unset, Redline answers 404 outside debug mode) install(app, engine=engine, settings={"access": "local"}) # UI at /_redline/ ``` `engine` takes a sync `Engine`, an `AsyncEngine`, a list of them, or a dict of `{alias: engine}`. Omit it and Redline still records requests, but no SQL. See [FastAPI: engines](fastapi.md#engines). With no `dependencies` argument the UI answers **only to loopback clients that address it as `localhost`, `127.0.0.1` or `[::1]`** and logs a warning at startup. That is right for `uvicorn` on your laptop; read [FastAPI: access control](fastapi.md#access-control) before you deploy. === "Flask" One line, after the app is created (or `init_app` in a factory). ```python from flask import Flask from sqlalchemy import create_engine from flask_redline import Redline app = Flask(__name__) engine = create_engine("sqlite:///app.db") # ... your blueprints ... # access="local": localhost only (unset, Redline answers 404 outside debug mode) Redline(app, engine=engine, settings={"access": "local"}) # UI at /_redline/ ``` With **Flask-SQLAlchemy** omit the engine: `db = SQLAlchemy(app); Redline(app)` finds its engines, binds included. With no `permission` argument the UI answers only to loopback clients. See [Flask](flask.md). === "Litestar" One plugin. ```python from litestar import Litestar from sqlalchemy.ext.asyncio import create_async_engine from litestar_redline import RedlinePlugin engine = create_async_engine("sqlite+aiosqlite:///app.db") app = Litestar( route_handlers=[...], # access="local": localhost only (unset, Redline answers 404 outside debug mode) plugins=[RedlinePlugin(engine=engine, settings={"access": "local"})], # UI at /_redline/ ) ``` With no `guards` the UI answers only to loopback clients. See [Litestar](litestar.md). ## Look at it Start your server, make a few requests, then open the UI. === "Django" ```bash python manage.py runserver ``` Open `http://127.0.0.1:8000/redline/` while signed in as a **superuser**. An anonymous visitor is redirected to the admin login; a signed-in non-superuser gets a 403. See [Django: access control](django.md#access-control). === "FastAPI" ```bash uvicorn app:app --reload ``` Open `http://127.0.0.1:8000/_redline/` from the same machine. === "Flask" ```bash flask run ``` Open `http://127.0.0.1:5000/_redline/` from the same machine. === "Litestar" ```bash litestar run --reload ``` Open `http://127.0.0.1:8000/_redline/` from the same machine. You will see the **Requests** page filling up, live. Open one. The tabs are **Timeline**, **SQL**, **Issues**, **Profile**, **Logs**, **Exception** (when it raised) and **Request / Response**; the [UI tour](the-ui.md) explains each. Press `Ctrl-K` (`Cmd-K` on a Mac) for the command palette. !!! tip "Nothing in the list?" Work through this short list. - **Is the request under an ignored path?** `/static/`, `/media/` and `/favicon.ico` are ignored by default, as is Redline's own mount. - **Django:** is `RedlineMiddleware` in `MIDDLEWARE`? `manage.py check` says so (`django_redline.W001`). Is `REDLINE["ENABLED"]` true? - **FastAPI:** was `install()` called on the app that uvicorn serves, before startup? Redline wraps the app it was installed on. - **Flask:** was `Redline(app)` (or `init_app`) called on the app you run? With Flask-SQLAlchemy, SQL appears after the first request. - **Litestar:** is `RedlinePlugin` in the `plugins` of the app you serve? - **Is the sample rate below 1?** In Django, `DEBUG = False` defaults it to 0.1, so 9 in 10 fast requests are not stored. See [Sampling](how-it-works.md#sampling). - **Writer lag.** Traces are written by a background thread. Reload the page after a second. ## Find your first N+1 Both demo shops ship with deliberately bad endpoints. Clone the repository (see above) and run one. === "Django" ```bash uv run python examples/django/manage.py migrate uv run python examples/django/manage.py seed # ~400k reviews, a few seconds uv run python examples/django/manage.py runserver ``` Visit `http://127.0.0.1:8000/orders/`, then open `http://127.0.0.1:8000/redline/` and sign in as `admin` / `admin` (a demo-only account). The request shows an N+1 on `shop_orderitem` with a `prefetch_related("items")` diff. === "FastAPI" ```bash cd examples/fastapi uv run --project ../.. python seed.py # creates shop.db uv run --project ../.. uvicorn shop.main:app --port 8000 ``` Visit `http://127.0.0.1:8000/orders`, then open `http://127.0.0.1:8000/_redline/`. The request shows an N+1 on order items with a `selectinload(Order.items)` diff. === "Flask" See `examples/flask/README.md` for the commands. The demo has deliberately bad views and shows the same N+1 with a `selectinload` diff. Open the request, go to **Issues**, and copy the diff. The full tour of the demos' broken endpoints is in each example's README (`examples/django/README.md`, `examples/fastapi/README.md`, `examples/flask/README.md`). ## Your own spans The only part of Redline your own code touches is `span`: ```python import redline_core @redline_core.span("pricing.compute") def compute_price(order): ... ``` Outside a recorded request it does nothing. See [Custom spans](custom-spans.md). ## Configure it Everything is optional. Settings are a dict: === "Django" ```python # settings.py REDLINE = { "SAMPLE_RATE": 1.0, "SLOW_QUERY_MS": 50, "IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"], "PERMISSION": "myproject.redline.can_view", # Django-only } ``` === "FastAPI" ```python install(app, engine=engine, settings={ "sample_rate": 1.0, "slow_query_ms": 50, "ignore_paths": ["/static/", "/favicon.ico", "^/health"], }) ``` === "Flask" ```python app.config["REDLINE"] = { "sample_rate": 1.0, "slow_query_ms": 50, "ignore_paths": ["/static/", "/favicon.ico", "^/health"], } Redline(app, engine=engine) ``` === "Litestar" ```python RedlinePlugin(engine=engine, settings={ "sample_rate": 1.0, "slow_query_ms": 50, "ignore_paths": ["/static/", "/favicon.ico", "^/health"], }) ``` === "redline.toml" The same settings, framework-independent, in a file at your project root: ```toml sample_rate = 1.0 slow_query_ms = 50 ignore_paths = ["/static/", "/favicon.ico", "^/health"] ``` Keys are case-insensitive (`SAMPLE_RATE` and `sample_rate` are the same) and an unknown key is an error with a "did you mean" hint, so a typo never silently falls back to a default. The complete table is the [Settings reference](settings.md). Presets, `redline.toml` and `REDLINE_*` environment variables are covered in [Configuration](configuration.md). ## Where things are stored Traces go to `.redline/redline.db` (Django: under `BASE_DIR`; the others: relative to the working directory), a SQLite file of Redline's own. Add `.redline/` to your `.gitignore`. It holds redacted request data: see [Storage](storage.md) and [Security](security.md). ## Next steps - Understand what is recorded and what it costs: [How it works](how-it-works.md). - Learn the UI: [The UI](the-ui.md). - Fix something: [N+1 detection](n-plus-one.md), [EXPLAIN](explain.md). - See what else it finds: [Detectors overview](detectors.md). - Find out how much load you can take: [Load testing](load-testing.md). - Before real traffic: [Production](production.md), [Access control](access-control.md) and [Security](security.md). --- # How it works [← Index](index.md) Redline is a small pipeline. Understanding it explains every setting and every limitation, so this page is worth reading once. ```mermaid flowchart TD req([request]) --> mw[adapter middleware] mw --> app[your app] app --> res([response]) mw -- "start_trace()" --> tb[TraceBuilder] app -- "hooks: SQL, cache, template, httpx, span()" --> tb tb -- "state in contextvars" --> fin["finish_trace()"] fin --> samp{"sampling decision
keep? why?"} samp -- kept --> proc["redact, detect issues, suggest fixes"] proc --> save["Store.save()"] save -- queue --> wr[writer thread] wr --> db[(".redline/redline.db")] db --> ui["JSON API and UI"] ``` Five packages share this pipeline: - **`redline-core`** owns everything in the middle: the data model, the recorder, SQL fingerprinting, callsite capture, redaction, sampling, the detectors, EXPLAIN analysis, the store, the JSON API and the UI bundle. It imports no web framework and has no runtime dependencies. - **`django-redline`**, **`fastapi-redline`**, **`flask-redline`** and **`litestar-redline`** own the edges: how a request starts and ends, how SQL and cache calls are observed, how URLs and auth work, and which ORM the fix suggester understands. They all enforce the same [access policy](access-control.md). - **`redline_core.contrib`** holds the optional hooks (SQLAlchemy, httpx, requests, redis, asyncpg, psycopg, Marshmallow, Strawberry, Graphene). Nothing there is imported unless you ask. See [Integrations](integrations.md). ## A trace and its spans One request is one **trace**. A trace has request and response metadata and a flat list of **spans** that form a tree through `parent_id`. | Trace field | Meaning | |---|---| | `id` | 32-character hex id | | `framework` | `django`, `fastapi` or `other` | | `method`, `path` | the verb and the concrete path (`/orders/42/`) | | `route` | the **template** (`/orders//` or `/orders/{order_id}`), known once routing ran | | `view` | dotted name of the view or endpoint (`shop.views.order_detail`) | | `status`, `duration_ms` | response status and wall time | | `query_count`, `query_ms` | SQL query count and their summed duration (exact even when the trace is truncated) | | `request`, `response` | redacted headers, query, body, truncation flags, size | | `issues` | what the [detectors](n-plus-one.md) found | | `tags` | free-form; `run_id` and `step` (load-test correlation), `sampled_by`, `profile_error` | | `error` | `{type, message, traceback}` for an unhandled exception; never set for a 4xx (Django's `Http404` is not an error) | | `truncated` | `{dropped_spans, max_spans}` when the request hit `max_spans_per_trace`, else `null` | Span kinds and the data each carries: | Kind | Produced by | `data` keys | |---|---|---| | `sql` | the database hook | `sql`, `params`, `fingerprint`, `db_alias`, `vendor`, `rows`, `many`, `explainable` | | `cache` | Django cache wrappers | `op`, `key`, `hit`, `backend` | | `http_out` | `instrument_httpx()` | `method`, `url` (secrets redacted), `status` | | `template` | Django template rendering | `template` | | `middleware`, `view` | the adapters | adapter-specific (`async` for Django views) | | `custom` | your `redline_core.span(...)` | whatever you pass | SQL spans also carry a **callsite**: the project file, line, function and source text that issued the query, plus up to 12 project frames of stack. That is what makes "30 queries from `shop/views.py:37`" possible. ## Recording When a request arrives the adapter calls `start_trace()`. That does four things: 1. Asks the sampler whether the path is **ignored** (`ignore_paths`, or Redline disabled). An ignored request gets an inert builder: nothing is recorded or stored. 2. Rolls the sample-rate dice once. 3. Reads the `X-Redline-Run` header into the `run_id` and `step` tags. 4. Starts a profiler if profiling was requested and is enabled. From then on the hooks add spans as they finish. When the response is done the adapter calls `finish_trace()`. ### What is recorded for every request, and what only for kept ones This split is the heart of the overhead model. | Work | When | |---|---| | Timing, span objects, SQL fingerprint, callsite capture, parameter redaction by column | **every non-ignored request**, as the query runs | | Header, query and body redaction, log and exception-local redaction | only when the trace is **kept** | | The detectors (N+1, duplicates, slow, too many, and the 0.2 detectors) and fix suggestions | only when the trace is **kept** | | Serialising and writing to SQLite, including the derived summary rows | only when the trace is **kept**, on the writer thread | | Log records, event-loop lag samples | while the request is in flight (a log record outside a request is one `ContextVar.get()`) | So lowering `sample_rate` removes the analysis and the disk cost of the requests you discard, but **not** the per-query recording cost. See [Performance and overhead](performance.md). ## Why `contextvars` Two context variables carry all state: the builder of the request being recorded, and the id of the innermost open span. The consequences: - Every `asyncio` task copies the context of the code that created it, so concurrent requests on one event loop never see each other's trace, and tasks spawned inside a request record into that request. - `asgiref.sync_to_async`, `loop.run_in_executor` with `contextvars.copy_context()` and Starlette's threadpool (which runs your `def` endpoints) copy context into the worker thread, so their queries attribute correctly. - A bare `threading.Thread` and a plain `ThreadPoolExecutor` do **not** copy context, so work started that way is not attributed to any request. If that work is part of the request, call [`instrument_threads()`](async-blocking.md#work-on-threads-and-pools): it copies the context into new threads and pool tasks, and spans recorded there carry the thread's name. The trace builder is thread-safe: spans from several threads are appended under a lock. - When no trace is active, every hook is one `ContextVar.get()` and a `None` check. - Once a trace is finished, late hooks (a background task that outlives the response) are ignored rather than attached to a closed trace. !!! note "Where the trace ends" FastAPI: right after the last body chunk is sent, so `BackgroundTasks` do not inflate the request's latency. Django: when the response comes back up through the middleware stack, so middleware placed *above* `RedlineMiddleware` is not timed. ## Callsites Walking the stack costs under a microsecond per frame; what makes naive implementations slow is classifying filenames and reading source lines. Redline caches the verdict per filename and reads source text only for the single innermost frame. A frame is **project code** when its file is under `project_root` and is not the standard library, anything under `site-packages` or `dist-packages`, Redline itself, or a synthetic file (``, ``). `project_root` defaults to the working directory (FastAPI) or `BASE_DIR` (Django). If your code lives elsewhere, set it, or callsites will be empty and the [fix suggester](n-plus-one.md#how-the-fix-is-found) will have nothing to locate. Queries issued from library code (a generic `ListView`, a DRF serializer, a lazily rendered `TemplateResponse`) have no project frame. The Django adapter attributes them to the project view that handled the request. See [Django: how it hooks in](django.md#how-it-hooks-in). ## SQL fingerprinting A **fingerprint** is the query with every literal replaced by `?`, so the 24 queries of an N+1 loop collapse into one group: ```sql SELECT "id", "qty" FROM "shop_orderitem" WHERE "order_id" = 17 SELECT "id", "qty" FROM "shop_orderitem" WHERE "order_id" = %s -- both become SELECT "id", "qty" FROM "shop_orderitem" WHERE "order_id" = ? ``` | Normalisation | Rule | |---|---| | Comments, whitespace | removed, collapsed | | Literals | strings (including `E'...'`, `N'...'`, `$tag$...$tag$`), numbers and hex blobs become `?` | | Placeholders | `%s`, `%(name)s`, `?`, `:name`, `$1` become `?` | | Lists | `IN (?, ?, ?)` becomes `IN (...)`; multi-row `VALUES` becomes `VALUES (...)` | | Keywords | upper-cased; identifiers keep their spelling | It is a tokenising pass, not a parser: fast (memoised) and good enough for grouping. It never executes SQL. ## Sampling Recording is cheap, storing is not, so the decision is split. **At the start**: ignored paths are dropped, and the sample-rate dice are rolled once. **At the end** the trace is **stored** if any of these is true, checked in this order: | Reason (`tags["sampled_by"]`) | Condition | |---|---| | `all` | the dice said yes and `sample_rate >= 1.0` | | `rate` | the dice said yes and `sample_rate < 1.0` | | `error` | `always_keep_errors` is on and the request returned 5xx, or raised without becoming a 4xx (a raised `Http404` is a 404, not an error) | | `slow` | `duration_ms >= always_keep_slower_than_ms` | | `profile` | the request was profiled | | `run` | the request carries `X-Redline-Run` of a load run that is registered in this store and running (or ended under a minute ago). A made-up run id keeps nothing | Otherwise it is dropped. The practical production recipe is therefore a low `sample_rate` with the two safety nets left on: you keep a sample of normal traffic **plus every slow request and every failure**. See [Production](production.md). One sharp edge: `always_keep_slower_than_ms = 0` keeps every request, because every duration is "at least" 0 ms. ## What the detectors read Each kind of finding reads a kind of span. The v0.1 four read `sql` spans; the 0.2 ones read the new kinds (`serializer`, `resolver`, `transaction`, `blocking`, `pool_wait`) and extra facts on `sql` spans (`rows`, `has_limit`, `in_transaction`). The adapters and integrations create them, and the detectors in `redline_core.detectors` read them when the trace is finished. One detector failing is logged and skipped. See [Detectors overview](detectors.md). ## Storage Kept traces are handed to `Store.save()`, which only puts them on a bounded queue. A daemon writer thread drains the queue in batches, one SQLite transaction per batch, and prunes by age and row count every 200 writes. In the same transaction it derives small summary rows (per-trace SQL, outbound-call and cache summaries, hourly rollups with latency histograms, the issue index) that power the [Database](database.md), [Cache](cache-efficiency.md), [External](external-calls.md) and [History](history.md) pages. If the queue is full the trace is **dropped and counted** (`store.dropped`, shown by `GET api/meta`) rather than slowing a request. Details in [Storage](storage.md). ## Redaction Header, query-string, body, SQL-parameter, log-message and exception-local redaction runs on kept traces before they reach the store, on by default. Secrets never reach disk. See [Security](security.md#redaction). ## The overhead model Cost has four sources: | Source | Scales with | Controlled by | |---|---|---| | Per-request bookkeeping | requests | `ignore_paths`, `enabled` | | Per-query recording (timing, fingerprint, callsite, param redaction) | queries | `enabled`; **not** reduced by `sample_rate` | | Per-kept-trace analysis (redaction, detectors, serialising) | kept traces | `sample_rate`, always-keep rules | | Profiling | profiled requests | `profile`, `profile_sample_rate` | Measured on an Apple M2 Pro (Python 3.14, 2026-10-27, `benchmarks/RESULTS.md`), the per-request bookkeeping is **0.04 to 0.09 ms**, and per-query recording **15 to 31 µs** (including SQLAlchemy event dispatch on FastAPI, Flask and Litestar) when nothing is kept, rising to **28 to 51 µs** when every trace is kept and analysed (v0.1 on Python 3.13: 12.5 to 44 µs). Disabled, Redline costs a few µs per request. See [Performance and overhead](performance.md#measured-numbers) for the full table and how to reproduce it. Memory: a trace's spans are held until the request ends, about **1.5 KB per SQL span**. At most `max_spans_per_trace` spans (default 2000) are kept per request; beyond that they are counted, folded into per-(fingerprint, callsite) counters so the N+1 and slow-query detectors still see every query, and the trace is marked `truncated`. Bodies are captured only up to `max_body_bytes`. ## Design choices worth knowing - **A separate SQLite file**, never your application database: no bloat, no migrations, and Redline's own writes can never be recorded as queries. - **A pure ASGI middleware** on FastAPI and Litestar, not `BaseHTTPMiddleware`, which would break context propagation for sync endpoints and buffer streaming responses. - **Recording never breaks a request.** Every adapter hook and `finish_trace` is wrapped: an error in Redline is logged on the `redline` logger and the request carries on. - **Unhandled exceptions are recorded and re-raised untouched.** --- # Example projects The repository ships a runnable shop project per framework under `examples/`. Each seeds a small database and exposes deliberately bad endpoints (N+1 queries, duplicate queries, a full table scan, a slow call, an unhandled error) so every feature has something to show. Names, data and endpoints are invented. | Framework | Directory | Port | |---|---|---| | Django | `examples/django` | 8013 | | FastAPI | `examples/fastapi` | 8011 | | Flask | `examples/flask` | 8012 | | Litestar | `examples/litestar` | 8014 | Each directory has its own README with the exact commands and an endpoint table. Typical run, from a checkout: ```bash uv sync --all-packages cd examples/fastapi uv run --project ../.. python seed.py uv run --project ../.. uvicorn shop.main:app --port 8011 # open http://127.0.0.1:8011/_redline/ ``` ## Agents and LLM calls The FastAPI example also shows the agent features. `GET /assistant` is a stand-in for LLM calls (no API key or network): it produces `duplicate_llm_call`, `serial_llm_calls` and `uncached_large_prompt` findings and `llm_call` spans with token counts. The folder includes a ready `.mcp.json` and an `AGENTS.md` generated by `redline agent-skill --format agents`; the commands are in [its README](https://github.com/Pythondeveloper6/redline/blob/main/examples/fastapi/README.md). ## Smoke test `scripts/smoke_examples.py` copies each example to a temporary directory, seeds a small database, boots the app in-process, requests its endpoints and the Redline UI, and fails if any response is not successful: ```bash uv run python scripts/smoke_examples.py # all four uv run python scripts/smoke_examples.py flask # one ``` --- # The UI [← Index](index.md) The web UI is a React single-page app, built ahead of time and shipped inside `redline-core`. Your adapter serves it from your own application (`/redline/` for Django, `/_redline/` for FastAPI), so there is nothing to host and no Node.js to install. It is a client of the [HTTP API](http-api.md), using relative URLs (`./api/...`) and hash routing (`#/requests`, `#/requests/`, `#/endpoints`, `#/issues`, `#/database`, `#/cache`, `#/external`, `#/history`, `#/load`, `#/checks`, `#/compare//`). That is why it works under any mount prefix and needs no catch-all route. Because it follows the system colour scheme and has a theme switch, every screenshot below is shown in the theme you are reading these docs in. ## The top bar ![Request detail page with the top bar](assets/screenshots/django-n-plus-one-light.png){ .rl-shot .rl-only-light } ![Request detail page with the top bar](assets/screenshots/django-n-plus-one-dark.png){ .rl-shot .rl-only-dark } | Control | What it does | |---|---| | **Requests**, **Endpoints**, **Issues** | The core pages | | **Database**, **Cache**, **External**, **History**, **Load** | The aggregate pages added in 0.2 (see [below](#aggregate-pages)) | | Search / command palette | Opens the [palette](#command-palette) (also `Ctrl-K` or `Cmd-K`) | | Framework and version label | `django v0.2.0a1`, `fastapi v0.2.0a1`, ...; hover for the storage path | | Theme switch | Light, system or dark. Remembered in the browser's `localStorage` (`redline-theme`) | | **Clear all** | Deletes every stored request, query, profile and issue, after a confirmation dialog. It calls `DELETE api/traces` and cannot be undone | ## Requests The live list of recorded requests, newest first. ![Requests page](assets/screenshots/fastapi-light-requests.png){ .rl-shot .rl-only-light } ![Requests page](assets/screenshots/fastapi-dark-requests.png){ .rl-shot .rl-only-dark } Each row shows the method, the concrete path with the route template beneath it (when they differ), the status, the duration with a bar, the query count, the time in queries, badges for any issue kinds found, and how long ago it happened. The duration bar is shaded by how much of the request was spent in queries, and turns amber at 100 ms and red at 500 ms. ### Filters | Filter | Options | API parameter | |---|---|---| | Search | text matched against path, route or view | `q` | | Method | any, GET, POST, PUT, PATCH, DELETE | `method` | | Status | any, 2xx, 3xx, 4xx, 5xx | `status` | | Duration | any, 50 ms, 100 ms, 500 ms, 1 s or more | `min_ms` | | Queries | any, 5, 10, 25, 50 or more | `min_queries` | | Has issues | checkbox | `has_issues=1` | The API accepts more than the UI offers (an exact status code, `route`, `tag=key:value`): see [The HTTP API](http-api.md#get-apitraces). **Reset** clears all filters. ### Live mode New requests stream into the list as they happen. The page subscribes to `api/stream` (Server-Sent Events: one event per new trace, a keep-alive comment every 15 seconds). The server closes the stream periodically (every five minutes on ASGI servers, about every 25 seconds on WSGI servers) and the page reconnects, resuming after the last trace it saw by its `seq`, so nothing is skipped or repeated. It falls back to polling every two seconds when streaming is unavailable. With the `sse` [feature switch](access-control.md#feature-switches) off, Live mode is hidden. The pulsing **Live** button pauses (**Pause**, then **Resume**) while you read. The counter shows how many rows are loaded of how many match. Older rows load with cursor pagination. Two more filters arrived with 0.2: **SQL** (`sql=`: only requests that ran a statement containing the text) and `replay_of=` (the replays of one request). ### Keyboard Press `?` anywhere for the list. | Key | Where | Action | |---|---|---| | `Ctrl-K` / `Cmd-K` | anywhere | Open the command palette | | `/` | Requests | Focus the search box (elsewhere: open the palette) | | `?` | anywhere | Show the shortcuts | | `j` / `k` | Requests | Move the selection down / up | | `Enter` | Requests | Open the selected request | | `x` | Requests | Select the request for comparing (at most two) | | `c` | Requests | [Compare](#compare-two-requests) the two selected | | `Esc` | anywhere | Leave a field; close a drawer, dialog or the palette | ### Command palette `Ctrl-K` (`Cmd-K` on a Mac) opens a fuzzy-search box over **pages**, recent **requests**, **endpoints** and **issues**. Type `orders` to jump to the Orders endpoint, part of an issue title to open that issue, `db` for the Database page. Arrow keys move, `Enter` opens, `Esc` closes. It is the fastest way around the UI. ![The command palette searching for "iss"](assets/screenshots/fastapi-palette-light.png){ .rl-shot .rl-only-light } ![The command palette searching for "iss"](assets/screenshots/fastapi-palette-dark.png){ .rl-shot .rl-only-dark } ### The empty state With nothing recorded yet the page shows a ready-to-copy installation snippet for your framework, which is a reasonable thing to see on a fresh install. ## Request detail Click a request. The header shows the method, path, status, start time, framework, route and view. If the request raised, a red box shows the exception type, message and a collapsible **traceback**. If it produced more than `max_spans_per_trace` spans, an amber **Trace truncated** notice says how many spans were counted but not stored (query counts, query time and the N+1 and slow-query issues still include them). Under it five cards: | Card | Shows | |---|---| | Status | the status code and the response size | | Duration | wall time and the number of spans | | Queries | the query count (amber from 50) and the average per query | | Query time | time in SQL and its share of the request | | Issues | the number of issues and their kinds, or "clean" | The header also has the request **actions**: [Copy as cURL](#copy-as-curl-and-httpie), Copy as HTTPie, [Replay](#replay) and [Download snapshot](#snapshots). Then the tabs. The selected tab is kept in the URL (`?tab=sql`). **Logs** and **Exception** are the 0.2 additions. ### Timeline ![Timeline of a request](assets/screenshots/fastapi-light-detail-timeline.png){ .rl-shot .rl-only-light } ![Timeline of a request](assets/screenshots/fastapi-dark-detail-timeline.png){ .rl-shot .rl-only-dark } A waterfall of the span tree: each row is a span, indented by depth, with a bar placed on the request's time axis. - Span kinds are colour-coded: `sql` blue, `cache` amber, `http_out` purple, `template` teal, `middleware` grey, `view` green, `custom` pink. The 0.2 kinds (`serializer`, `resolver`, `transaction`, `blocking`, `pool_wait`) have their own colours. - The chips above the chart **toggle a kind** on and off and show its count. Hiding `middleware` and `view` is a quick way to see only the I/O. - A triangle collapses a span's children. - A red dot marks spans that belong to an issue. - Hover for a tooltip with the kind, duration, start offset and callsite; click to open the span drawer. ### The span drawer Clicking a span opens a drawer from the side. For SQL it shows the formatted statement, **Copy SQL**, an **Explain** button (enabled only when the query is explainable), the parameters, the database alias and vendor, the row count and the fingerprint. For other kinds it shows their data: cache operation, key and hit; the outbound request and status; the template name. Below, the **call site**: file, line, function and source line, and the project stack, outermost first. ### SQL Queries grouped by fingerprint, sorted by total time. Each group shows the normalised statement, the callsite, an issue badge if it belongs to one, the total time, the number of executions and the slowest. Expand a group to see the full statement and a table of every execution (the first 50) with start, duration, parameters and rows, each with its own **Explain** button. ### Issues ![Issues tab with an N+1 and its diff](assets/screenshots/django-n-plus-one-light.png){ .rl-shot .rl-only-light } ![Issues tab with an N+1 and its diff](assets/screenshots/django-n-plus-one-dark.png){ .rl-shot .rl-only-dark } One card per issue: severity, kind, the number of occurrences and total time, a title, a plain-English detail, the offending source line, and the **suggested fix**: a summary, a one-line code hint, a unified diff with **Copy diff**, a link to the relevant documentation, and a confidence pill (`high`, `medium` or `low`). See [N+1 detection](n-plus-one.md). ### Profile The flamegraph, or an explanation of how to get one. See [Flamegraphs](flamegraphs.md). ### Logs The log records the application emitted during the request, with time offset, level, logger, message and the file and line of the call. See [Logs and exceptions](logs-and-exceptions.md). ### Exception For a request that raised: the type and message, and every **project frame** of the traceback with its source line and **local variables**, expandable. Names that look secret are masked. See [Logs and exceptions](logs-and-exceptions.md#exceptions-with-locals). ### Request / Response ![Redacted request](assets/screenshots/django-redaction-light.png){ .rl-shot .rl-only-light } ![Redacted request](assets/screenshots/django-redaction-dark.png){ .rl-shot .rl-only-dark } Trace tags as pills, then request headers, query parameters, the request body, response headers and the response body. Masked values are shown as a distinct **redacted** marker, a **truncated** pill flags a body cut at `max_body_bytes`, and JSON bodies are pretty-printed with a copy button. See [Security](security.md#redaction). ## The EXPLAIN drawer ![EXPLAIN drawer](assets/screenshots/fastapi-light-explain.png){ .rl-shot .rl-only-light } ![EXPLAIN drawer](assets/screenshots/fastapi-dark-explain.png){ .rl-shot .rl-only-dark } Opens when you click **Explain**, and immediately runs an estimate-only `EXPLAIN`. It shows the plan as a tree (with cost and row estimates and flag chips), the findings, the suggested `CREATE INDEX` statements with **Copy SQL**, and a **Raw plan** toggle. **Run with ANALYZE** is always visible; if `explain_analyze` is off, the drawer explains that instead of running it. See [EXPLAIN](explain.md). ## Endpoints ![Endpoints page](assets/screenshots/fastapi-light-endpoints.png){ .rl-shot .rl-only-light } ![Endpoints page](assets/screenshots/fastapi-dark-endpoints.png){ .rl-shot .rl-only-dark } A table of every route and method seen in the window (1 h, 24 h or 7 d): request count, error rate, p50, p95, p99, average and maximum queries, issue count and a p95 trend sparkline. Click a column header to sort. Percentiles and rates are defined in [Issues and endpoints](issues-and-endpoints.md#endpoints). ## Issues ![Issues page](assets/screenshots/django-issues-light.png){ .rl-shot .rl-only-light } ![Issues page](assets/screenshots/django-issues-dark.png){ .rl-shot .rl-only-dark } Problems deduplicated across requests: severity, kind, occurrences, first and last seen, the routes affected, the callsite and the suggested fix. **Open sample request** jumps to the latest occurrence. Filter by kind and window. ## Open in editor Every callsite in the UI (the span drawer, issue cards, exception frames, log rows) is a link that opens the file **at that line in your editor**. Choose the editor with the `editor` setting: | `editor` | Opens in | |---|---| | `"vscode"` (default) | Visual Studio Code | | `"cursor"` | Cursor | | `"pycharm"` | PyCharm | | `"idea"` | IntelliJ IDEA | | `"sublime"` | Sublime Text | | `"none"` | no links | | a template | your own URL, containing `{file}` (an **absolute** path) and `{line}` | ```python REDLINE = {"EDITOR": "cursor"} REDLINE = {"EDITOR": "myeditor://open?path={file}&line={line}"} ``` The absolute path is built from `project_root`, which `GET api/meta` reports. If the server runs in a container or on another machine, the paths on its disk are not your paths: set `project_root` to what your editor sees, or use `"none"`. ## Copy as cURL and HTTPie The request detail header has **Copy as cURL** and **Copy as HTTPie**. They build a command from the recorded method, path, query, headers and body, aimed at the origin you are viewing the UI from. Redacted headers and body values are replaced by shell variables with a note saying which to fill in, so a secret is never invented and `[redacted]` is never sent. ## Replay **Replay** sends the request again, from your browser, so you can see whether a fix helped or reproduce an error. A dialog shows the method, URL, headers and body; values that were redacted must be **re-entered** by you. You can ask for a flamegraph of the replay. - It uses `fetch` from the page, to the same origin, with **your** cookies: the server sees an ordinary request from you, with your permissions. - The request carries `X-Redline-Replay-Of: `. Redline turns it into the tag `replay_of`, so replays are findable (`GET api/traces?replay_of=`) and compare cleanly with the original. - Replaying a `POST`, `PUT` or `DELETE` **runs it again**. There is no undo. - It can be turned off with the `replay` [feature switch](access-control.md#feature-switches). ## Compare two requests ![Comparing two requests](assets/screenshots/fastapi-compare-light.png){ .rl-shot .rl-only-light } ![Comparing two requests](assets/screenshots/fastapi-compare-dark.png){ .rl-shot .rl-only-dark } Press `x` on two rows in the Requests list, then `c`. The page at `#/compare//` shows: - the difference in duration, query count and query time; - time by span kind, side by side; - the SQL fingerprints that changed, sorted by the biggest time difference; - issues only in A, only in B, and in both. Typical use: replay a request after a fix and compare the replay with the original. The data comes from `GET api/compare?a=&b=`. To compare whole releases rather than two requests, see [History](history.md#before-and-after-comparing-periods). ## Snapshots **Download snapshot** saves a trace as one standalone HTML file: the whole UI bundle inlined, with the trace (and its profile) embedded. Open it in any browser, offline, with no Redline running: attach it to a ticket, send it to a colleague, keep it as evidence. It is read-only; actions that need a server (Explain, Replay) are not available in it. The button is hidden when the `snapshot` feature is off, and the profile is left out when the `profile` feature is off. !!! warning "A snapshot contains the trace as stored" It holds the same data as the UI: SQL, parameters (redacted), bodies (redacted), source lines and exception locals. Treat the file with the care you would give the trace itself. See [Security](security.md). ## The floating badge In development, HTML pages carry a small pill with the request's duration, query count and issue count that links to the trace. See [Server-Timing and the badge](server-timing-badge.md). ## Aggregate pages Pages that look across many requests rather than one: | Page | Shows | Details | |---|---|---| | **Database** | SQL search by fingerprint, index advisor, unused indexes | [Database](database.md) | | **Cache** | hit rate, unread writes and stampedes per key pattern | [Cache efficiency](cache-efficiency.md) | | **External** | outbound HTTP by host and URL pattern: latency, duplicates, retries | [External calls](external-calls.md) | | **History** | latency, errors and queries over time, release markers, before/after compare | [History](history.md) | | **Checks** | [refactor check](refactor-check.md) suites, baselines and compare reports (the *More* menu; hidden when the `checks` feature is off) | [Refactor check](refactor-check.md) | | **Load** | load-test runs, an RPS vs p95 vs errors chart with the knee, bottlenecks per step, a start form when enabled | [Load testing](load-testing.md) | Each has a window picker like the one on Endpoints. A page whose data the current store cannot provide (a custom store) says so instead of failing. ## Checks **More → Checks** (`#/checks`) is the UI of the [refactor check](refactor-check.md): prove a refactor is safe and see what it gained. It has four pages. ![The Checks page: every suite with its last baseline and last compare](assets/screenshots/checks-list-light.png){ .rl-shot .rl-only-light } ![The Checks page: every suite with its last baseline and last compare](assets/screenshots/checks-list-dark.png){ .rl-shot .rl-only-dark } - **Suites** (`#/checks`): each suite with its request count, its last baseline (label, commit, age) and verdict badges of its last compare. *New suite* opens the builder. - **Builder** (`#/checks/new`, `#/checks/suites/{id}/edit`): pick from the read-only routes Redline has seen (search, sample path, last p50 and query count) or add a request by hand; per request Perf and Response switches, ignore paths, headers and expected status; suite settings for repeat, warmup and thresholds. *Save suite* (*Save changes* when editing), or *Export TOML*. - **Suite** (`#/checks/suites/{id}`): *Record baseline* and *Compare* buttons (disabled, with the reason, when `checks_from_ui` is off or the app is read-only), a baseline picker and the history of runs. - **Report** (`#/checks/runs/{id}`): summary cards, a sortable table with the verdicts, and per request the latency of both runs, the response diff, new and fixed issues and SQL. *Copy as Markdown* gives the PR-comment text. A running check shows live progress. Details, including how verdicts are decided, are on the [Refactor check](refactor-check.md) page. ## Login and the Settings page ![The login screen](assets/screenshots/fastapi-login-light.png){ .rl-shot .rl-only-light } ![The login screen](assets/screenshots/fastapi-login-dark.png){ .rl-shot .rl-only-dark } When the instance uses `access = "token"` or `"basic"` and you are not signed in, the API answers `401 login_required` and the UI shows a **login screen**: a token field, or a username and password for `basic`. It posts to `api/login` and reloads. **Log out** (in the header and the command palette) appears when a login is in use. The page shell itself is public; every `api/` call needs credentials, and the UI sends `X-Redline-UI: 1` so the browser shows no native dialog. The **Settings** page (`#/settings`, in the More menu and the palette) is a read-only view of the effective configuration, grouped, with a chip showing where each value came from and the warnings: `GET api/config`, including the settings you gave in code, which `redline config` cannot see. Secrets show as `***`. ![The Settings page](assets/screenshots/fastapi-settings-light.png){ .rl-shot .rl-only-light } ![The Settings page](assets/screenshots/fastapi-settings-dark.png){ .rl-shot .rl-only-dark } The UI hides what is switched off: `features` hide Explain, the Profile tab, Replay, snapshot download, the Load page, the Logs tab, locals and Live mode, and `read_only` hides Clear all, ANALYZE and the run controls. **Replay** only sends requests to the same origin as the UI; a path that points at another origin is refused. See [Access control](access-control.md) and [Configuration](configuration.md). ## On a phone The layout is responsive: the navigation wraps under the logo, columns drop out of the tables below breakpoints (p50, p99 and the query columns hide first). ## What the UI does not do - It does not edit your application: the mutating actions are **Clear all**, **Replay**, running an EXPLAIN, and (when `load_from_ui` is on) starting or stopping a load run. The Checks pages also save, edit and delete refactor-check suites and runs, stop a running check, and start check runs when `checks_from_ui` is on. - It cannot delete a single request (the API can: `DELETE api/traces/`). - It has no saved filters and no sharing links to filtered views. Its login screen is a front for the [access control](access-control.md) policy, not an account system. --- # Server-Timing and the badge [← Index](index.md) Two small features put Redline's numbers where you are already looking: in the browser's developer tools, and in the corner of the page you are developing. ## Server-Timing Every recorded response carries a standard [`Server-Timing`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Server-Timing) header. Chrome, Firefox and Safari show it in the Network panel's Timing tab, and `curl -i` shows it in plain text: ```text Server-Timing: total;dur=84.2, db;dur=51.7;desc="12 queries", cache;dur=3.1, http;dur=18.0, tpl;dur=6.4, redline;desc="9d4c1f0e7a2b4c6f8e1d3a5b7c9e0f21" ``` | Metric | Meaning | |---|---| | `total` | the whole request, in ms | | `db` | time in SQL, with the query count in `desc` | | `cache` | time in cache operations | | `http` | time in outbound HTTP calls | | `tpl` | time rendering templates | | `redline` | the **trace id**, so you can paste it into `#/requests/` | A metric appears only if the request had that kind of work. The header is added to **recorded** responses only: a request that is ignored (`ignore_paths`) does not get one. If your app already sets a `Server-Timing` header, Redline appends its metrics to it. The header is useful in two ways. In the browser it gives a per-request breakdown without opening Redline. In scripts and CI, `curl -sI` plus a one-line parse is a cheap performance assertion. !!! info "It is information about your app" `Server-Timing` is visible to anyone who can read the response, including the user's browser. It contains timings, a query *count* and a trace id, never SQL or data. Even so it is a side channel for anyone who can make requests, anonymous clients included (query counts can reveal, for example, whether an account exists). That is why it is on only in debug mode by default; the [production preset](configuration.md#presets) turns it, and the badge, off. | `server_timing` | Behaviour | |---|---| | `"auto"` (default) | on when the framework is in debug mode (Django `DEBUG`, `app.debug` in Flask, FastAPI and Litestar), off otherwise | | `True` | always on (Redline warns outside the `dev` preset) | | `False` | never | Upgrading from 0.1: the header used to be on whenever recording was on. Set `server_timing = True` to keep that. ## The floating badge In development, a small pill appears in the corner of your HTML pages: ```text 84 ms · 12 q · 2 issues ``` It shows the request's duration, query count and issue count. Click it to jump straight to that trace in the Redline UI. You do not edit any template. How it works: after the response is built, Redline inserts one tag before ``: ```html ``` The tag carries `data-*` attributes with the trace id, the mount URL and the summary. `badge.js` is a small dependency-free script shipped in the UI bundle and served from Redline's own mount. It is public under `token` and `basic` access (it holds no data); it sends `X-Redline-UI: 1` when it fetches the trace (for the issue count) on opening. ### When it is injected The badge is injected only when **all** of these hold: - the `badge` setting allows it (see below); - the response is HTML (`text/html`), not compressed, and not a streaming response (on ASGI only small pages are held back for injection: at most 2 MiB with a known length, or a single body message); - the status is 200 to 299; - the response has a ``; - the request was recorded; - the page's `Content-Security-Policy`, if any, allows the script (below). JSON responses, redirects, downloads and error pages are untouched. | `badge` setting | Behaviour | |---|---| | `"auto"` (default) | on when the framework is in debug mode (for example `DEBUG = True` in Django), off otherwise | | `True` | always on | | `False` | never | ### Content-Security-Policy If your pages send a strict `Content-Security-Policy`, the badge script must be allowed by `script-src-elem` (or `script-src`, or `default-src`). Because it is served from your own origin under Redline's mount, `'self'` covers it. A policy that uses **nonces or hashes only** (`script-src 'nonce-...'`) or `'strict-dynamic'` (which makes browsers ignore `'self'`) would block it, so Redline leaves such pages alone rather than cause a CSP error in the console. With several policies (several headers) every one must allow it. Allow `'self'` in development to see the badge. Redline does not rewrite your CSP header. ## Live mode and snapshots Two other features are wired by the same adapter work: - `GET api/stream` is a Server-Sent Events feed of new traces, used by [Live mode](the-ui.md#live-mode). It resumes by `seq` (`after=` or `Last-Event-ID`), and the server closes it so clients reconnect: after five minutes on ASGI, about 25 seconds on WSGI servers. - `GET api/traces/{id}/snapshot` downloads one trace as a standalone HTML file ([Snapshots](the-ui.md#snapshots)). Both are served by every adapter and are subject to the same [access control](access-control.md) as the rest of the API. The `sse` and `snapshot` [feature switches](access-control.md#feature-switches) disable them individually. --- # N+1 detection [← Index](index.md) An **N+1** is one query to fetch a list, then one more query per item to fetch something related. It is invisible in development (ten rows, one millisecond each) and ruinous in production. Redline finds them in every recorded request, groups the repeats, points at the line that causes them, and, for Django and SQLAlchemy, writes the patch. ## The four detectors The detectors run over each **kept** trace when it finishes. They are in `redline_core.detect` and are framework-free; the fix suggesters are the adapters' part. | Kind | Fires when | Default threshold | Setting | |---|---|---|---| | `n_plus_one` | the same read fingerprint comes from the same callsite at least *T* times | 5 | `n_plus_one_threshold` | | `duplicate_query` | identical SQL **and** identical params run at least *T* times | 2 | `duplicate_threshold` | | `slow_query` | a single query takes at least *T* ms | 100 | `slow_query_ms` | | `too_many_queries` | the request ran at least *T* queries | 50 | `too_many_queries` | ### N+1: the rules in detail - Only **read** queries count (`SELECT` and `WITH`, i.e. spans with `explainable: true`). Ten `INSERT`s in a loop are a different problem (use `bulk_create` or `executemany`) and are not flagged. - Queries are grouped by `(fingerprint, callsite file:line)`. The same statement from two different lines is two groups, so two unrelated queries that happen to share a shape do not add up to a false positive. - A group is an issue at `count >= n_plus_one_threshold`. - The title names the primary table and the line: `N+1: 30 queries on shop_orderitem from shop/views.py:37`. ### Duplicates Exactly the same SQL string with exactly the same parameters, run at least `duplicate_threshold` times. Typical causes are a helper called twice, or a property that re-queries. A duplicate group whose spans all belong to an N+1 is **not** reported again, so you see one issue, not two. ### Slow queries Grouped by fingerprint and callsite. The title shows the slowest run. The detail tells you to open [EXPLAIN](explain.md). Note `slow_query_ms = 0` flags **every** query: it is a threshold, not an off switch. ### Too many queries One issue per **endpoint** (`GET /orders//`), not per request, because it has no fingerprint or callsite. Set `too_many_queries` to `0` to turn it off. ## Severity *T* is the relevant threshold from the table above. | Kind | `critical` | `warning` | `info` | |---|---|---|---| | `n_plus_one` | at least 4×*T* repeats, **or** the repeats together take at least `slow_query_ms` | otherwise | n/a | | `duplicate_query` | n/a | at least 5 copies, or at least `slow_query_ms` in total | otherwise | | `slow_query` | slowest run at least 5×`slow_query_ms` | otherwise | n/a | | `too_many_queries` | at least 2×*T* queries | otherwise | n/a | Issues in a trace are sorted by severity, then by total time. ## Issue identity An issue id is `sha1("kind|fingerprint|file:line")[:16]`. The same problem at the same line therefore gets the same id in every request, which is what lets the [Issues page](issues-and-endpoints.md#issues) count occurrences. See that page for how deduplication behaves when a line moves. ## How the fix is found After the detectors produce an issue, **suggesters** run in registration order and the first one to return something wins. Exceptions in a suggester are logged and skipped: a broken suggester can never break a request. The framework-free `GenericSuggester` always comes last and gives low-confidence advice in words. Fix suggestion has two halves: 1. **Which relation?** Map the repeated SQL back to your models. 2. **Where is the queryset?** Read your source at the callsite, find the expression that builds the list being looped over, and edit it. If both succeed you get a **unified diff**. If only the first does, you get a one-line code hint at lower confidence. === "Django" The repeated statement is mapped through the app registry (table name to model): | Repeated query | Suggestion | |---|---| | `FROM child WHERE child.parent_id = ?` (reverse foreign key, `order.items.all()`) | `prefetch_related("items")` | | `FROM parent WHERE parent.id = ?` (forward FK or one-to-one, `item.product`) | `select_related("product")` | | reverse one-to-one (`customer.profile`) | `select_related("profile")` | | many-to-many, either side | `prefetch_related("tags")` or `prefetch_related("products")` | | nested loops (`for item in order.items.all(): item.product`) | `prefetch_related("items__product")` on the **outer** queryset | | `GenericRelation` | `prefetch_related(...)` | | `GenericForeignKey` | `prefetch_related(...)`, **low** confidence | | the relation is filtered per row (`order.items.filter(...)`) | a `Prefetch(..., queryset=..., to_attr=...)` hint, no diff | When several foreign keys point at the fetched model, the source text at the callsite (`item.product.name`) picks the right one. Then the source is read. In each project frame of the callsite stack, the loop variable on the offending line (`item` in `item.product`) is traced back through the enclosing `for` loops (across relation hops such as `for item in order.items.all()`) to the assignment that builds the root queryset (`Order.objects...`). Failing that, any queryset of the parent model in the frame's function or class is used. That covers: - loops in **templates** (`{% for item in order.items.all %}`): the diff goes on the queryset in the view's `render()` call; - **generic class-based views** (`model = Order`, `queryset = ...`, `get_queryset()`): the diff adds or edits the `queryset` attribute; - **DRF serializers** that read a relation: the diff targets the view's `queryset` or `get_queryset()`, because the middleware adds the view to the stack. The fix is inserted **before ordering and slicing**, **replaces** a bare `.all()`, or **extends** an existing `prefetch_related(...)` call. The `duplicate_query` issue kind also gets a suggestion when the duplicates are a forward relation re-read per object. A real diff from the demo shop (`/orders/`): ```diff --- a/shop/views.py +++ b/shop/views.py @@ -32,5 +32,5 @@ def order_list(request): """N+1: one query for the orders, then one per order for its items.""" - orders = Order.objects.select_related("customer").order_by("-id")[:30] + orders = Order.objects.select_related("customer").prefetch_related("items").order_by("-id")[:30] data = [] for order in orders: ``` The suggestion text that goes with it: *Add .prefetch_related("items") to the Order queryset (shop/views.py:34): one extra query for all Order rows instead of one per row.* Note how it extended the existing `select_related("customer")` chain rather than inventing a new statement. === "SQLAlchemy" The repeated statement is parsed into `(table, column)` equality filters and matched against the ORM relationships of your mapped classes (`registry.mappers`): | Repeated query | Suggestion | |---|---| | child table filtered by its foreign key column | `selectinload(Parent.children)` | | parent looked up by primary key, once per row | `joinedload(Child.parent)` | | association (secondary) table filtered by a parent column | `selectinload(Parent.tags)` | The suggester then walks the callsite's project frames looking for the `select(Parent)` or `session.query(Parent)` expression that builds the list, and appends `.options(...)` at the end of the chain, plus the import (`from sqlalchemy.orm import selectinload`) when it is missing. Both lazy-load forms (`order.items`) and explicit per-row queries (`select(OrderItem).where(OrderItem.order_id == order.id)`) are recognised. The demo's `GET /orders`: ```diff --- a/shop/api.py +++ b/shop/api.py - orders = (await session.scalars(select(Order).order_by(Order.id).limit(30))).all() + orders = (await session.scalars(select(Order).order_by(Order.id).limit(30).options(selectinload(Order.items)))).all() ``` (The real output also contains the import line and context lines.) The diff is mechanical: it appends to the end of the chain, so you may want to reformat. SQLModel needs nothing extra: its tables live in a normal SQLAlchemy registry. If the suggester cannot find your models, pass `install(app, models=Base)`. Only `n_plus_one` issues get SQLAlchemy suggestions in this version. Duplicates, slow queries and query budgets get the generic words. ### N+1 in raw SQL (`text()` and driver SQL) When the repeated statement is raw SQL, there is no relationship to eager-load, so Redline rewrites the loop itself. It takes the column the statement compares to a bound parameter (the one that varies between executions) and the callsite of the loop, and for a loop like ```python for order in orders: rows = conn.execute(text("SELECT id, qty, order_id FROM items WHERE order_id = :oid"), {"oid": order.id}).all() ``` it proposes one query over all the keys, chunked to the database's parameter limit and grouped back by the key (`IN :_ids` with an expanding bind parameter, then `rows = _rows_by_key.get(order.id, [])` in the loop), as a diff at the callsite with **high** confidence. The summary states the limit for your database (about 32,766 bound parameters for SQLite, 32,767 for PostgreSQL, 65,535 for MySQL, 2,100 for SQL Server) and the chunk size used. If the key column was not in the `SELECT` list it is appended, so each row gains that column; the summary says so. When the parent query is in the same trace, the summary also names the join alternative. The rewrite needs a plain `for` loop that directly assigns `x = .execute(text(""), {...}).all()` (or `.fetchall()`), iterating a name or attribute (not a call result), with one varying key and no per-parent `LIMIT`/`TOP`/`OFFSET`. Anything else (a statement built with an f-string, a result method other than `.all()`, several varying parameters) gets the same batched statement as a code block, with no diff and lower confidence. `redline check verify` then confirms the finding is gone after you apply it. ## Confidence Every suggestion carries one of three levels. The UI shows it as a pill. | Level | Meaning | Examples | |---|---|---| | **high** | The relation was identified **and** the queryset was located; a diff was produced | Django: one unambiguous relation, a path of at most two hops, an exact queryset match. SQLAlchemy: any suggestion that produced a diff | | **medium** | The relation is right but you must place it, or the match was less exact | a code hint without a diff; a path of more than two hops; several candidate relations; a queryset that already has the prefetch (so something *bypasses* it); a filtered relation (`Prefetch` hint) | | **low** | A guess, or generic advice | `GenericForeignKey`; an ambiguous hint; the framework-free `GenericSuggester` | !!! tip "Treat a diff as a starting point" `high` confidence means Redline is confident about the *relation and the line*, not that the change is right for your code. Eager loading changes memory use (a prefetch loads every related row), can change query count in other paths that share the queryset, and is wrong when you only need a count (use `annotate(Count(...))`). Read the diff, apply it, **re-run the request, and check the issue is gone**. ## When the suggester cannot help - The queryset is built in another module, dynamically, or through a helper the static walk does not follow: you get the hint without a diff, with lower confidence. - The callsite is in library code and the view cannot be identified. Check `project_root` (see [How it works](how-it-works.md#callsites)). - The relation is one the suggester does not model (custom managers that rewrite the queryset, `.extra()`): you get the generic advice. Raw SQL is handled [above](#n1-in-raw-sql-text-and-driver-sql). - The source file changed since the trace was recorded: the diff is computed against the **current** file on disk, at the line recorded then. Re-record after editing. ## Tuning | Situation | What to change | |---|---| | Too many N+1 reports for tiny loops | raise `n_plus_one_threshold` (it must be at least 2) | | A legitimate repeated query (a cache warm-up) | none to ignore one issue; lower noise with `ignore_paths` for the endpoint | | You want a stricter query budget in tests | there is no pytest plugin yet; it is planned for [v0.3](roadmap.md) | ## Write your own suggester For another ORM, or a house style, implement the `FixSuggester` protocol. See [Extending](extending.md#fixsuggester). --- # EXPLAIN [← Index](index.md) Any captured `SELECT` can be explained from the UI with one click. Redline runs the database's `EXPLAIN` on the query as it was recorded, turns the plan into a tree, flags the expensive parts, and suggests an index when one is likely to help. ![EXPLAIN drawer on a slow query](assets/screenshots/django-explain-light.png){ .rl-shot .rl-only-light } ![EXPLAIN drawer on a slow query](assets/screenshots/django-explain-dark.png){ .rl-shot .rl-only-dark } ## Where to click - **SQL tab**: every execution of a statement has an **Explain** button. - **Span drawer**: click any `sql` span in the timeline, then **Explain**. - **API**: `POST api/explain` with `{"trace_id", "span_id", "analyze": false}`. See [The HTTP API](http-api.md#post-apiexplain). The button is disabled when the query is not explainable (see below). ## Supported databases | Vendor | Statement Redline runs | Notes | |---|---|---| | PostgreSQL | `EXPLAIN (FORMAT JSON) ` | `ANALYZE` adds `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` | | MySQL, MariaDB | `EXPLAIN FORMAT=JSON ` | `ANALYZE` is **not supported** (`analyze_unsupported`, 400) | | SQLite | `EXPLAIN QUERY PLAN ` | no `ANALYZE` form; the flag is ignored | | anything else | none | `unsupported_vendor` (400) | Vendor names come from the adapter: Django's `connection.vendor`, SQLAlchemy's `dialect.name` (with `mariadb` mapped to `mysql`). ## What can be explained Only statements `redline_core.sql.is_explainable` accepts: **a single read-only `SELECT`** (or `WITH ... SELECT`, `VALUES`, `TABLE`). Redline refuses: - any write or DDL keyword, in any letter case (`INSERT`, `UPDATE`, `DELETE`, `MERGE`, `CREATE`, `DROP`, `ALTER`, `TRUNCATE`, `GRANT`, `REVOKE`, `CALL`, `COPY`, `INTO`). This covers data-modifying CTEs (`WITH x AS (DELETE ... RETURNING *) SELECT ...`) and `SELECT ... INTO`; - every **row-locking clause**: `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE` (PostgreSQL) and `LOCK IN SHARE MODE` (MySQL). Under `ANALYZE` they would take row locks until the rollback; - **more than one statement** (a `;` outside a literal; one trailing `;` is fine); - `executemany` spans (`many=True`), whose parameters are a list of rows. The check reads the statement several times and every reading must pass: 1. **Literal-aware**: over the normalised statement with literals and comments stripped, so `WHERE note = 'DELETE me'` or a column named `"update"` does not trip it. 2. **Dialect-pessimistic**: over the raw text, removing only what every database agrees is inert. Databases disagree about quoting: a backslash ends a standard PostgreSQL string but escapes the quote in MySQL; MySQL has no `$$` dollar quoting, executes `/*! ... */` "comments", needs a space after `--`, and ends a `#` comment at the newline (so a quote after `#` opens nothing). A statement that hides a `;` or a write keyword under one of those readings (`SELECT 'a\' ; DELETE FROM t; --'`, `SELECT 1 /*! INTO OUTFILE '/tmp/x' */`) is refused. The check errs on the side of refusing: an unusual but harmless statement may be refused, a harmful one is not let through. !!! note "Functions with side effects are out of scope" `SELECT nextval('seq')`, `SELECT pg_advisory_lock(1)` or a user function that writes all *look* like reads, and Redline does not try to know which functions have side effects. A plain `EXPLAIN` (the default) only plans the statement and never calls them. `EXPLAIN ANALYZE` does run them, which is one more reason it is off by default; it still runs inside a transaction that is always rolled back (and `READ ONLY` on PostgreSQL, which refuses most writes). Effects outside the transaction (a sequence advancing, an advisory lock held until the rollback, a sleep) can happen. The same check runs in the API **and** again in the explain runner, whatever the adapter passes: it is not left to the UI. ## Safety Explaining a query you did not write the text of is the riskiest thing Redline does, so the rules are strict and layered. | Rule | Where enforced | |---|---| | Only recorded queries, by id | The request names a `trace_id` and `span_id`. There is **no way to submit SQL**; Redline explains what it stored | | Only a single read-only `SELECT` | `is_explainable`, checked when the span is recorded, in the API, and in the runner | | Always rolled back | The adapter's executor runs the statement in a transaction it **always** rolls back | | `READ ONLY` on PostgreSQL | `SET TRANSACTION READ ONLY` before the statement (Django: only when Redline owns the outermost transaction) | | `ANALYZE` is opt-in | Refused with `403 analyze_disabled` unless `explain_analyze` is true | | Not recorded | Django: queries run by EXPLAIN are suppressed and never become spans | | CSRF-protected | `POST api/explain` needs the CSRF token (Django) or a same-origin `Origin` (FastAPI) | | Access-controlled | Behind the same permission as the rest of the UI | !!! warning "Rolled back is not the same as harmless" Plain `EXPLAIN` does not execute the query, only plans it. **`EXPLAIN ANALYZE` executes it.** That has three consequences. - It costs what the query costs, on your database, now. A 40-second report takes 40 seconds. - Even inside a rolled-back transaction a `SELECT` can have side effects, for example a function that writes elsewhere (PostgreSQL's `READ ONLY` blocks writes but MySQL and SQLite have no equivalent here). - The recorded **parameters are used verbatim**, including values that were redacted *in storage*: Redline cannot rerun a query whose parameter it masked (it would run with the placeholder text instead of the secret). Queries filtered on secret columns explain with `[redacted]` values and may produce a different plan. That is why `explain_analyze` is **off by default**. Turn it on in development, not on a production database you care about. ## What you get back ```json { "vendor": "sqlite", "analyzed": false, "plan": [[2, 0, 0, "SCAN shop_review"], [10, 0, 0, "USE TEMP B-TREE FOR ORDER BY"]], "text": "SCAN shop_review [full_scan]\nUSE TEMP B-TREE FOR ORDER BY [temp_sort]", "tree": { "label": "...", "detail": "...", "cost": null, "rows": null, "actual_ms": null, "children": [], "flags": ["full_scan"] }, "findings": [{ "severity": "warning", "title": "...", "detail": "..." }], "suggested_indexes": ["CREATE INDEX shop_review_body_idx ON shop_review (body);"] } ``` (Abbreviated: field values are illustrative, the shape is exact.) | Field | Meaning | |---|---| | `plan` | The **raw** plan: JSON for PostgreSQL and MySQL, rows for SQLite | | `text` | A rendered text tree with `[flag]` markers | | `tree` | The plan as nodes: `label`, `detail`, `cost`, `rows`, `actual_ms` (ANALYZE only), `children`, `flags` | | `findings` | Things worth your attention, each with a severity (`info`, `warning`, `critical`) | | `suggested_indexes` | `CREATE INDEX` statements. **Redline never runs DDL** | ## Findings and flags Each flag appears on the offending node and as a finding. | Flag | Meaning | Detected on | |---|---|---| | `seq_scan` | A sequential scan of a large table: at least 1,000 estimated rows, or cost at least 1,000. A *warning* when it filters rows (an index would help), *info* otherwise | PostgreSQL | | `full_scan` | A full table scan: MySQL `access_type: ALL` on at least 1,000 rows, or SQLite `SCAN ` where the table is filtered or joined in the query | MySQL, SQLite | | `sort_spill` | A sort that went to disk (`external merge`, `Disk`) | PostgreSQL | | `hash_spill` | A hash join that needed more than one batch | PostgreSQL | | `nested_loop_high_rows` | A nested loop driving at least 10,000 rows, or whose inner side ran at least 1,000 times | PostgreSQL (ANALYZE sharpens it) | | `temp_sort` | A sort using a temporary structure: SQLite `USE TEMP B-TREE`, MySQL `using_filesort` | SQLite, MySQL | | `automatic_index` | SQLite built a throw-away index for this query. It is the engine telling you which index you are missing | SQLite | The thresholds are module constants in `redline_core.plan_analysis` (`LARGE_TABLE_ROWS`, `SEQ_SCAN_COST`, `NESTED_LOOP_ROWS`, `NESTED_LOOP_LOOPS`) and are not settings. ## Index suggestions, and their limits When a scan is flagged, Redline derives a `CREATE INDEX` from the plan's `Filter` and `Hash Cond` (PostgreSQL), `attached_condition` (MySQL) or the SQL's `WHERE` and `ON` columns (SQLite). It emits the table name, up to three columns, and a safely quoted name such as `shop_review_body_idx`. It is deliberately **not naive**. It understands that a plain B-tree index cannot serve several common predicates, and tells you instead of suggesting an index that would not be used: | Predicate | What Redline says | |---|---| | `LIKE '%term%'` (leading wildcard) | No B-tree index can serve it. Suggests, as an alternative, a `pg_trgm` GIN index on PostgreSQL. Not a drop-in: it needs the extension and adds write cost | | `lower(col) = ?` or any function around the column | A plain index is ignored; only an expression index with exactly that expression matches | | `ILIKE` | B-trees are case-sensitive; index `lower(col)` or use trigrams | | `col IS NOT NULL` | Rarely helped; consider a partial index | | `!=`, `NOT IN`, `NOT LIKE` | Match most rows; filter on the positive set instead | | `LIKE 'abc%'` (prefix) | Needs `text_pattern_ops` on PostgreSQL, or `COLLATE NOCASE` on SQLite, with the statement | Columns used in different `OR` branches get an index each, not one compound index. !!! warning "A suggestion is a hypothesis" The analysis sees **one query**, with the estimates of one database at one moment. It cannot know: - how many other queries an extra index will slow down (every index costs writes and space); - whether an equivalent index already exists under another name or as a prefix of a compound one; - your data distribution tomorrow, or the planner's statistics being stale (run `ANALYZE` on the table first if estimates look wrong); - that a low-cardinality column (a boolean, a status) is rarely worth indexing alone. Test the index on a copy, re-run the explain, and measure the query. "What-if" index testing without creating anything (HypoPG) is on the [roadmap](roadmap.md), not here. ## Reading a plan | You see | It usually means | |---|---| | A scan node with big `rows` and a `Filter` | The filter is evaluated row by row: an index on the filtered column may help | | `actual_ms` much larger than the parent's estimate | The planner's estimate was wrong: refresh statistics | | Nested loop with a high inner `loops` count | A join that should be a hash or merge join, or a missing index on the join column | | A sort node flagged `sort_spill` | The sort exceeded `work_mem`; raise it for the session or add an index that provides the order | | `Rows Removed by Filter` very high (PostgreSQL ANALYZE) | You read many rows to keep few: selectivity is the problem | ## Errors | Code | Status | Cause | |---|---|---| | `not_explainable` | 400 | The span is not a single read-only `SELECT` | | `analyze_disabled` | 403 | `analyze` was requested but `explain_analyze` is off | | `analyze_unsupported` | 400 | `ANALYZE` on MySQL | | `unsupported_vendor` | 400 | The database is not PostgreSQL, MySQL or SQLite | | `trace_not_found`, `span_not_found` | 404 | The trace was pruned, or the id is wrong | | `explain_unavailable` | 501 | No connection or engine for that `db_alias` (a router-only alias, or an engine that was not passed to `install()`) | | `explain_failed` | 422 | The database rejected the statement. The message carries the driver's error, e.g. a table dropped since, or a type that cannot be bound from the recorded parameter | !!! note "Why a plan can differ from production" The plan is produced on **the database your app is connected to now**, with the **parameters of the recorded request**. A different parameter value can pick a different plan, and a development database with 400 rows will happily seq-scan a table that is 40 million rows in production. Explain against production-shaped data. --- # Flamegraphs [← Index](index.md) A flamegraph shows where a request spent its time **in Python**, call by call. Redline records them with [pyinstrument](https://pyinstrument.readthedocs.io), a statistical sampling profiler, on request, and draws them in the UI. ![A flamegraph of one request](assets/screenshots/django-flamegraph-light.png){ .rl-shot .rl-only-light } ![A flamegraph of one request](assets/screenshots/django-flamegraph-dark.png){ .rl-shot .rl-only-dark } Flamegraphs are **opt-in** because they cost more than the rest of Redline. Spans tell you *which query* or *which template* was slow; a flamegraph tells you what the Python between them was doing: a CPU loop, a slow serializer, a lock. ## Install the extra ```bash pip install "redline-core[profile] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` That adds `pyinstrument>=5.0,<6.0`. Without it, a profile request records no profile, sets the trace tag `profile_error`, and the **Profile** tab explains how to enable it. `GET api/meta` reports `profiler_available`. ## Ask for one Add a query parameter or a header to **one request**: ```bash curl "http://127.0.0.1:8000/slow/?_redline=profile" curl -H "X-Redline-Profile: 1" http://127.0.0.1:8000/slow/ ``` Then open the request in the UI and click **Profile**. | Trigger | Django and FastAPI | |---|---| | `?_redline=profile`, `1`, `true`, `yes` or `on` | yes | | `X-Redline-Profile: profile`, `1`, `true`, `yes` or `on` | yes | The values are case-insensitive, and both adapters parse them with the same core function (`redline_core.sampling.profile_requested`), so a URL that profiles on one framework profiles on the other. Any other value (`?_redline=0`) is ignored. A profiled request is **always stored**, even if it is fast and the sample rate would have dropped it (`tags["sampled_by"]` is then `profile`). !!! note "Who may ask" The trigger is honoured only when the framework is in debug mode or the request carries valid Redline credentials under the active `access` policy: a client `local` lets in, `Authorization: Bearer ` / Basic credentials (or the login cookie), or your `access_check`. Anyone else's trigger is ignored, so strangers cannot make you profile and store their requests. With `access = "framework"` only debug mode counts. On a server, send the token: ```bash curl -H "X-Redline-Profile: 1" -H "Authorization: Bearer $REDLINE_TOKEN" https://app.example/slow/ ``` The `production` preset sets `profile = "off"`. ## Modes The `profile` setting chooses who gets profiled. | `profile` | Who is profiled | |---|---| | `"off"` | Nobody. The trigger is ignored | | `"opt_in"` (default) | Only requests carrying the trigger | | `"sampled"` | Triggered requests, **plus** a random `profile_sample_rate` fraction (0 to 1) of the rest | | `"all"` | Every request that is recorded | ```python REDLINE = {"PROFILE": "sampled", "PROFILE_SAMPLE_RATE": 0.01} # Django ``` ```python install(app, settings={"profile": "sampled", "profile_sample_rate": 0.01}) # FastAPI ``` `"all"` is for short local sessions. Every request pays the profiler's overhead. Do not use it on shared or production servers. `"sampled"` is the way to get a representative profile of real traffic at a bounded cost. A sampled profile is chosen at the *start* of the request, before anyone knows it will be slow, so to catch a *specific* slow request, reproduce it with the trigger. ## Async correctness On ASGI many requests share one thread and one event loop. A naive profiler started in one request would sample everyone's work. Redline runs pyinstrument with `async_mode="enabled"`: a profiler started inside one request's task only attributes **that task's** work. Time spent awaiting appears as an `[await]` frame instead of someone else's code. Concurrent requests each get a clean profile. Starlette's threadpool (your `def` endpoints) and Django's `sync_to_async` are covered by the same mechanism that carries the trace ([`contextvars`](how-it-works.md#why-contextvars)). !!! warning "One profiler at a time" A profiler such as pyinstrument hooks the interpreter's own profiling machinery, and two profilers generally cannot share it. If a profiler cannot be started (the extra is missing, or another profiler is running) the request is **still recorded without a profile**, with `tags["profile_error"]` set to the exception. Redline never fails a request because of its profiler. If you use another profiler in the same process (New Relic's, a Sentry profiler) expect conflicts. ## Reading the UI The **Profile** tab draws an **icicle** (flamegraph turned upside down: the entry point on top, callees below). - The **width** of a box is the time spent in that function **and everything it called**. - **Click** a box to zoom into it; **Reset zoom** returns to the root. - **Hover** for the function, `file:line`, the **total** time with its share of the whole, and the **self** time (time in the function's own code, excluding callees). - The **search box** highlights frames whose function name or file contains the text. Type your app's package name to find your code among the framework's. - Grey boxes are the synthetic root and any frame without a known source location. Small boxes (under half a pixel) are not drawn. Zoom in to see them. ## Export to speedscope The profile is stored as [speedscope](https://github.com/jlfwong/speedscope) JSON. - In the UI, **Download speedscope JSON** saves `redline-.speedscope.json`. Drag it onto (or the local app) for time-order, left-heavy and sandwich views. - Over HTTP: `GET api/traces//profile` returns the same document, or `404 profile_not_found`. ## Storage Profiles live in their own table, apart from the trace, so listing requests never loads them. They can be large (a deep call tree is hundreds of kilobytes of JSON). They are removed with their trace by retention, by `DELETE`, and by **Clear all**. Profiles of many requests are the fastest way to grow `.redline/redline.db`: see [Storage](storage.md#size). ## Limits - A statistical profiler **misses anything shorter than its sampling interval** (1 ms here) and is noisy for short requests. Profile a request that takes tens of milliseconds or more, and repeat it. - It profiles **Python**. Time inside a C extension or the database driver appears as one box (the call into it), not what the native code was doing. Use the SQL spans and [EXPLAIN](explain.md) for that. - It cannot see other processes. A request that waits on a worker, a queue or another service shows as `[await]` or a blocking call. - The profile is of the **request handler**, from where the adapter starts the profiler to where it ends. Work done after the response is sent (FastAPI background tasks) is outside it. --- # Custom spans [← Index](index.md) Redline records SQL, cache, template and outbound HTTP automatically. Everything else your code does, a pricing calculation, an image resize, a call to a library Redline does not know about, is invisible until you wrap it in a **span**. It then appears in the timeline, nested under whatever contained it, with its own duration and any data you attach. `span` is the **only** part of Redline your own code needs to touch. ```python import redline_core ``` Django re-exports it: `from django_redline import span`. ## Three ways to use it === "Decorator" ```python import redline_core @redline_core.span("pricing.compute") def compute_price(order): ... @redline_core.span # bare: named after the function def apply_discounts(order): ... @redline_core.span() # same, with parentheses async def fetch_rates(): ... # coroutine functions work too ``` === "Context manager" ```python with redline_core.span("render-pdf", pages=3): pdf = render(document) ``` === "Async context manager" ```python async with redline_core.span("fetch-rates", provider="ecb"): rates = await client.get(url) ``` ## Signature ```python span(name: str | None = None, kind: SpanKind = "custom", **data) -> SpanContext ``` | Argument | Meaning | |---|---| | `name` | The label shown in the timeline. When omitted on a decorator, the function's `__qualname__` is used; on a `with` block, `"span"` | | `kind` | One of `sql`, `cache`, `http_out`, `template`, `middleware`, `view`, `custom`. Default `custom` (pink in the timeline) | | `**data` | Extra keyword arguments become the span's `data`, shown in the span drawer. Values are made JSON-safe (long strings are cut, objects become `str()`) | The returned object has a `span_id` property (the id of the open span, or `None` when nothing is being recorded). If the block raises, the span is recorded with `data["error"]` set to the exception class name, and the exception propagates untouched. ## Nesting Spans nest through `contextvars`, so a span opened inside another becomes its child, in async code and threads as well: ```python @redline_core.span("checkout") def checkout(cart): with redline_core.span("validate"): validate(cart) with redline_core.span("charge", provider="stripe"): charge(cart) # SQL run here appears under "charge" ``` SQL, cache and outbound HTTP spans recorded inside a custom span are its children, which is the quickest way to see "which part of my function issued these 12 queries". ## Cost, and outside a request - Outside a recorded request (a management command, a test, a request that was ignored, or after the trace finished) `span` does **nothing** and costs one `ContextVar.get()`. You can leave it in permanently, even in libraries. - Inside a request it costs two `perf_counter()` calls, a span object and a lock to append it. Do not wrap a function that runs a million times per request; wrap the unit of work you want to see. - It does not capture a callsite or SQL. It is a timer with a name. ## A span instance cannot be shared One `SpanContext` must not be entered concurrently with itself. Decorator form is safe everywhere (a fresh context is created per call); with the context-manager form, create it inside the code that uses it rather than as a module-level constant: ```python # do not do this BIG = redline_core.span("big") # shared, entered from many threads ... # do this with redline_core.span("big"): ... ``` ## Tagging the whole request To attach information to the **trace** rather than a span, use the builder: ```python from redline_core import current builder = current() if builder is not None: builder.tag("tenant", "acme") ``` Tags are strings, show as pills in the **Request / Response** tab, and can be filtered with `GET api/traces?tag=tenant:acme`. `current()` returns `None` outside a recorded request. --- # Issues and endpoints [← Index](index.md) The request list shows single requests. Two pages answer the questions you ask next: **which routes are slow** (Endpoints) and **which problems keep happening** (Issues). Both are aggregates over the traces in the store, so they share one caveat that is worth reading before the details. !!! warning "Aggregates describe what was stored, not all traffic" Endpoints and Issues are computed from **stored** traces. With `sample_rate = 1.0` (the development default) that is every request. In production you will sample, and you will also **always keep** slow requests and errors. Together that means stored traces over-represent the bad ones: - **Counts** are counts of stored traces, not requests served. - **Percentiles** are biased upward: the fast majority is thinned out while every slow request is kept. Treat p95 and p99 as an upper bound on a sample, not a measurement of your traffic. - **Error rate** is the share of *stored* requests that were errors, so it is inflated by the `always_keep_errors` safety net. For true rates and latency distributions in production use your metrics system or an APM. Use Redline to find *which* endpoint and *which query*. ## Endpoints ```text GET api/endpoints?window=1h|24h|7d ``` One row per **(route, method)**. The route is the **template** (`/orders/{order_id}`, `/orders//`), so `/orders/1` and `/orders/2` are one row. A request with no resolved route (a 404 for a path no route matches) is grouped by its concrete **path**. !!! warning "Unmatched paths multiply rows" Scanners and typos that match no route each become their own row, because there is no template to group them by. If you see hundreds of rows for paths like `/wp-login.php`, that is the cause. Add a prefix or `^` regex to `ignore_paths`, or filter them at the proxy. | Column | Definition | |---|---| | Requests | stored traces in the window for this route and method | | Errors | the share with **status >= 500**. A 4xx is not an error here | | p50, p95, p99 | percentiles of `duration_ms`, linearly interpolated between the two nearest samples; `0` for an empty set | | Avg queries, Max queries | mean and maximum of `query_count` | | Avg query time | mean of `query_ms` (the API field `avg_query_ms`) | | Issues | the **sum** of `issue_count` over those traces: the same issue seen in 40 requests counts 40 | | p95 trend | a sparkline of p95 per time bucket | ### Windows and buckets `window` accepts `1h`, `24h` (default) and `7d`, or any `m`, `h`, `d`. It is measured back from now. The window is divided into **48 equal buckets** (a 24 h window has 30-minute buckets). `series` lists only the **non-empty** buckets, each as `{t, p95_ms, count}` with `t` the bucket start in epoch seconds. A route with a single request therefore has a one-point series, and the sparkline shows `-`. Rows are ordered by request count, then p95, then route name. The UI re-sorts as you click headers. ### How to use it | You see | It suggests | |---|---| | High p95, low average queries | time is not in SQL: look at the [flamegraph](flamegraphs.md) or outbound HTTP spans | | High average queries | an [N+1](n-plus-one.md) or missing eager loading on this route | | High p99 but modest p95 | a tail problem: lock contention, a cache miss path, GC; open the slowest requests from the list (filter by route) | | Rising sparkline | a regression: look for what changed around the bucket where it started | | Errors above 0 | open the 5xx traces: the traceback is stored | ## Issues ```text GET api/issues?window=...&kind=n_plus_one|duplicate_query|slow_query|too_many_queries ``` Every kept trace's issues are stored in a table of their own, and the Issues page **groups them by issue id**. The id is `sha1(kind | fingerprint | file:line)[:16]`, so "the same problem at the same line" is one group however many requests hit it. | Field | Meaning | |---|---| | `occurrences` | the number of stored traces that contained this issue in the window | | `first_seen`, `last_seen` | epoch seconds of the earliest and latest trace | | `routes` | every route (or path) the issue appeared on | | `sample_trace_id`, `sample_span_ids` | the **latest** occurrence, which **Open sample request** links to | | `title`, `detail`, `severity`, `suggestion`, `callsite` | taken from the **latest** occurrence | Groups are ordered by severity (critical first), then by occurrences, then by recency. ### Why a finding fired, and ranking by impact Each item also carries `why`: `rule` (what the detector checks), `observed` (what the sampled occurrence showed), `threshold` (the configured limit, or `null`), `grouping` (how spans were combined into one finding) and `limits` (what the data cannot tell you; truncated traces are called out). The Issues page shows it under **Why this fired**. `GET api/issues?sort=impact` orders groups by sampled observed time, then occurrences, with suppressed groups last; any other `sort` value returns `400 invalid_sort`. Every item has an `impact` object with `basis: "sampled"` and `additive: false`. Concurrent or nested spans overlap, so impacts must not be summed into "time saved". ### Behaviour worth knowing - **The counts in a title are from the latest sample.** "N+1: 30 queries" reflects the most recent request. A list that grew since will say a bigger number. Use `occurrences` for "how often" and open the sample for "how bad". - **Moving a line makes a new issue.** The line number is part of the id, so editing a file above the offending line splits one issue into two (the old one fades out as retention removes its traces). Fix the cause rather than watching the counter. - **`too_many_queries` is per endpoint**, not per line: its location is `" "`. - **One shared line is one issue.** The id uses the innermost project frame, so an N+1 in a helper called by two views is a single issue with both routes in `routes`. - **Nothing is ever "resolved".** An issue disappears from the list when its stored traces age out of the window or retention. After you deploy a fix, re-exercise the endpoint and watch `last_seen` stop advancing. ### Filtering | Filter | Effect | |---|---| | Kind | one of the four issue kinds. Any other value returns `400 invalid_kind` | | Window | `1h`, `24h`, `7d` (or `m|h|d`). A bad value returns `400 invalid_window` | ## Using both together A good loop is: 1. **Endpoints**, sorted by p95: find the worst route. 2. **Requests**, filter by that route (the API supports `route=`) and `min_ms`: open the slowest. 3. **Issues** tab of that request: the fix, with confidence. 4. Apply it, re-exercise, and watch the route's p95 and **Issues** count drop. --- # Refactor check [← Index](index.md) You are about to change code that works. You want two answers afterwards: **did anything break**, and **did it get faster** (or at least not slower)? The refactor check answers both by replaying the same read-only requests against the old code and the new code and comparing what came back and how long it took. You pick a set of `GET` endpoints, record a **baseline** against the code as it is today, change the code, and run the suite again. Redline gives you a report per endpoint: - **Response:** the same, changed (with a diff of the fields that differ) or broken. - **Performance:** faster, slower, same or too noisy to say, decided by a significance test and not by one lucky run. - **Server side:** how many queries each endpoint ran, which SQL statements appeared or went away, and which N+1 issues are new or fixed. - **Overall:** one number for how much faster or slower the suite got, and an exit code you can put in CI. It works from the UI and from the command line (`redline check`). !!! info "What it is not" It is not a load test (see [Load testing](load-testing.md); requests run one at a time), it does not send writes (`POST`, `PUT`, `PATCH` and `DELETE` are refused), it does not compare two live servers side by side, and it does not check out your code for you. You run the old code, then the new code. ## The workflow in three steps ```mermaid flowchart LR S["1. Suite
which GET requests"] --> B["2. Baseline
run on the OLD code"] B --> C["3. Compare
run on the NEW code"] C --> R["Report + exit code"] ``` === "In the UI" The UI is at **More → Checks** (`#/checks`). ![The Checks page: suites with their last baseline and last compare](assets/screenshots/checks-list-light.png){ .rl-shot .rl-only-light } ![The Checks page: suites with their last baseline and last compare](assets/screenshots/checks-list-dark.png){ .rl-shot .rl-only-dark } **1. Build a suite.** *New suite* opens the builder. It lists the read-only routes Redline has seen, with a sample path and the last p50 and query count of each. Tick the ones you want, or add a request by hand. For each request you can turn **Perf** and **Response** on or off, add ignore paths, headers and an expected status. Suite-level settings are the base URL, repeat, warmup and the thresholds. *Save suite* stores it in the Redline store; *Export TOML* gives you the same suite as a file you can commit. ![The suite builder: routes Redline has seen, with a sample path, p50 and queries](assets/screenshots/checks-builder-light.png){ .rl-shot .rl-only-light } ![The suite builder: routes Redline has seen, with a sample path, p50 and queries](assets/screenshots/checks-builder-dark.png){ .rl-shot .rl-only-dark } **2. Record a baseline.** On the suite page press *Record baseline*, ideally with a label ("before the eager-loading change"). Redline runs the suite in a background process and shows live progress. ![A suite page: record a baseline, compare, and the history of runs](assets/screenshots/checks-suite-light.png){ .rl-shot .rl-only-light } ![A suite page: record a baseline, compare, and the history of runs](assets/screenshots/checks-suite-dark.png){ .rl-shot .rl-only-dark } **3. Change the code, restart the app, press *Compare*.** The report opens when the run ends. See [Reading the report](#reading-the-report). !!! note "Starting runs from the UI is opt-in" The Compare and Baseline buttons need `checks_from_ui`, which by default is on only in debug mode, and off under the `production` preset. When it is off the buttons are disabled and say why; you can still look at runs made on the command line. See [Settings](#settings-and-access). === "On the command line" ```bash pip install "redline-core[load] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` **1. Write a suite**, either from the traffic Redline has already recorded: ```bash redline check init --from-traces -o checks/orders.toml ``` or by hand (see the [suite file](#the-suite-file)). **2. Record a baseline** with the old code running: ```bash redline check record checks/orders.toml --label before # wrote checks/orders.baseline.json ``` **3. Change the code, restart the app, compare:** ```bash redline check compare checks/orders.toml --markdown report.md --junit report.xml echo $? # 0 = nothing slower, changed or broken ``` `redline check run SUITE` does step 2 when there is no baseline file yet and step 3 when there is one, which is handy for a quick loop. The exit code makes the compare a CI gate, see the [CI recipe](#ci-recipe). !!! tip "Run both sides on the same machine, from a quiet state" Timings are only comparable when the machine, the database content and the load on both are the same. Close what you do not need, use the same data, and let the suite's warmup do its job. If a request shows as *noisy*, raise `repeat`. ## The suite file A suite is TOML or JSON (`.toml` or `.json`). Python 3.10 needs the `tomli` package to read TOML; JSON always works. Unknown keys are errors, and every error names the file and the request, for example `checks/orders.toml: requests[1].method ('delete orders'): DELETE is refused: ...`. ```toml name = "orders refactor" base_url = "http://127.0.0.1:8000" headers = { Authorization = "Bearer ${env:API_TOKEN}" } timeout_s = 10 repeat = 20 warmup = 3 [thresholds] slower_pct = 10 slower_ms = 2 max_query_increase = 0 [[requests]] name = "list orders" path = "/orders?page=1" ignore = ["data[*].created_at", "meta.request_id"] [[requests]] name = "order detail" path = "/orders/1" expect_status = 200 [[requests]] name = "health" path = "/healthz" perf = false ``` ### Top-level keys | Key | Default | Meaning | |---|---|---| | `name` | the file name without its extension | A non-empty name; shown in reports and used for the exported file. `"refactor check"` for a suite given as an object | | `base_url` | none | `http://` or `https://` URL of the app under test. The CLI's `--base-url` overrides it. Required unless you pass `--base-url` | | `headers` | `{}` | Headers sent with every request. Values may contain [`${env:NAME}`](#environment-placeholders) | | `timeout_s` | `10` | Per-call timeout in seconds. More than `0`, at most `600` | | `repeat` | `20` | Timed calls per request. Whole number from `1` to `1000` | | `warmup` | `3` | Untimed calls per request before timing starts. Whole number from `0` to `100` | | `thresholds` | see below | When a change is big enough to matter | | `requests` | required | A non-empty list of requests | ### `[thresholds]` | Key | Default | Meaning | |---|---|---| | `slower_pct` | `10` | The median must change by more than this many percent (`0` or more) | | `slower_ms` | `2` | ...and by more than this many milliseconds (`0` or more) | | `max_query_increase` | `0` | More queries per call than the baseline by more than this number makes the request `slower`, whatever the clock says (whole number, `0` or more) | `--slower-pct` and `--slower-ms` override the first two for one run. Both conditions must hold, so a 50% change of 0.4 ms is not "slower" and a 1 ms change on a 5 s request is not either. ### `[[requests]]` | Key | Default | Meaning | |---|---|---| | `name` | `" "` | Unique within the suite. This is what reports show and what a baseline is matched by | | `method` | `"GET"` | `GET`, `HEAD` or `OPTIONS`. Anything else is an error | | `path` | required | Path and query, starting with a single `/`, no whitespace. A full URL (`https://...`, `//host/...`) is refused: set `base_url` instead | | `headers` | `{}` | Merged over the suite headers (same name wins). Same `${env:NAME}` rules | | `perf` | `true` | Compare timing and queries | | `response` | `true` | Compare status, headers and body. At least one of `perf` and `response` must be on | | `ignore` | `[]` | JSON paths excluded from the body diff, see [Ignore paths](#ignore-paths) | | `ignore_headers` | `[]` | Response headers to leave out of the comparison (names, case-insensitive). `content-type` is always compared | | `expect_status` | none | A status code or a list of them (`100` to `599`). A response with any other status is `broken` | A request with `perf = false` only makes two calls (the first and last timed round) because that is enough to capture its response; it does not add `repeat` calls to the run. ### Environment placeholders Put secrets in the environment, not in the file. `${env:NAME}` in a header value is replaced when a run starts: ```toml headers = { Authorization = "Bearer ${env:API_TOKEN}", Cookie = "${env:SESSION_COOKIE}" } ``` - `NAME` is letters, digits and underscores, not starting with a digit. - If the variable is not set the run stops before sending anything: `environment variable API_TOKEN is not set`. - The placeholder, never the value, is what is stored, exported and written to baselines (see [Security](security.md#refactor-checks)). ### Ignore paths `ignore` removes fields from the response comparison. The syntax is the same one the diff prints. | Path | Matches | |---|---| | `meta.request_id` | the key `request_id` inside `meta` | | `data[*].created_at` | `created_at` of every item of the list `data` | | `data[0].price` | `price` of the first item only | | `*.updated_at` | `updated_at` of any key directly under the top level | | `["a.b"]` | a key that contains a dot (also use this form for brackets, quotes, spaces or a literal `*`) | | `items[*]["a b"]` | a key with special characters inside a list | | `$` | the whole body | A rule also covers everything **below** the path it names, so `meta` ignores `meta.request_id` and `meta.generated_at` together. A leading `$.` is allowed (`$.data[*].id`). A rule that does not parse is an error naming the request and the rule. !!! note "Text bodies" For a body that is not JSON (HTML, plain text) there are no paths. The diff is a unified diff of the lines, and lines that changed between two calls are ignored as volatile (below). ### Why only read-only methods A check replays every request many times: a warmup, `repeat` timed calls, and then again for the baseline. For a `GET` that is harmless. For a `POST /orders` it would create dozens of orders in whichever database you pointed it at, and the second run would not even see the same data as the first. Redline refuses `POST`, `PUT`, `PATCH`, `DELETE` and the rest with a message that says so, in the file loader, in the builder and in the API, so a suite cannot be saved with one in it. If an endpoint has side effects on `GET`, do not put it in a suite. ## How fields that change on every call are found Many responses carry a timestamp, a request id or a random token. Compared byte for byte they would be reported as changed on every run. Redline handles this in two ways. 1. **During `record`**, the full response is kept for two of the timed calls, the first and the last. Everything that differs between those two responses is **volatile** and is excluded from later comparisons. JSON bodies are compared path by path (`meta.request_id`), text bodies line by line (`line:7`), and a differing header is volatile too. 2. **During `compare`**, the same is done to the new run's own first and last responses, so a field that only started varying with the new code does not show up as a difference. The report lists what was ignored ("changes on every call") next to what you ignored by rule, so nothing is hidden: the UI shows them under *Ignored*, and the builder offers them as `ignore` suggestions once a baseline exists. A field that changes only now and then (a timestamp rounded to the minute) can slip past this check. If you see it reported as `changed`, add it to `ignore`. Secrets in responses are masked by the [redactor](security.md#redaction) on **both** sides before comparing, so a masked token never shows as a difference. ## How verdicts are decided For each request the report has two independent verdicts. ### Performance: `faster`, `slower`, `same`, `noisy`, `n/a` The runner does the following, per request: 1. **Warmup.** `warmup` calls that are not measured, so connection set-up, import costs, caches and the database's own cache do not count against whichever side happened to run first. 2. **Interleaving.** The timed calls are made round-robin across the whole suite (request 1, 2, ..., N, then 1, 2, ..., N again) and not all 20 of one request in a row. Slow drift on the machine (thermal throttling, a background job, a cache filling up) spreads over every request instead of landing on one of them. 3. **Samples.** Each timed call records wall-clock time, response body read included. Then the two sets of samples (before and after) are compared: - **Change** is the after median against the before median, in milliseconds and percent. - **Significance.** A two-sided **Mann–Whitney U test** on the samples. It asks whether one side's timings are systematically higher than the other's, without assuming a bell curve, which timings do not follow (they have a long tail of slow outliers). A change counts only when `p < 0.01`. - **`slower`** needs the change to be significant **and** bigger than both `slower_pct` and `slower_ms`. **`faster`** is the mirror image. Anything else is **`same`**. - **`noisy`** replaces all of that when either side's **coefficient of variation** (standard deviation over mean) is above `0.5`. The numbers are too scattered to trust a verdict; raise `repeat`, or quiet the machine. - **`n/a`** when `perf` is off, the request is not in the baseline, there are no timed samples, or its response is `broken` (below). A broken request shows its numbers but is **not judged** ("perf not judged: response broken"): an error page is fast, and an error handler that skips the queries looks like an N+1 fix. Its fixed issues, gone SQL and query decrease are not counted as wins, and it is left out of the overall speed and the query totals. **The query rule.** When server-side metrics are available (see [below](#server-side-metrics)), a request whose median query count rose by more than `max_query_increase` is `slower` with the reason `queries`, even if the clock says `same`. A refactor that adds a query per row is a regression even on a fast development database with five rows. Newly appearing N+1 or duplicate-query issues are listed as *new issues*, and issues that disappeared as *fixed issues*. ### Response: `same`, `changed`, `broken`, `missing`, `n/a` - **`broken`**: the status went from below 400 to 400 or above (`200 → 500`), or the request has `expect_status` and got another one, or at least half of its calls failed (connection error or timeout). That last rule applies even if `response` is off. - **`changed`**: any other status change, a different content type, or a body difference outside the ignored and volatile fields. Compared headers are `content-type` plus `location`, `cache-control`, `content-encoding`, `content-language`, `content-disposition`, `vary`, `allow` and `access-control-allow-origin`, minus your `ignore_headers`. - **`missing`**: the baseline has no request of that name (the suite grew since it was recorded). It fails by default; the report also carries a warning. If *none* of the suite's requests is in the baseline, the compare stops with exit code `2`: "baseline … has none of this suite's requests — was it recorded from a different suite?". - **`same`**: none of the above. JSON differences are a list of `added`, `removed`, `changed` and `type` entries with the path and the before and after values (each cut at 200 characters, at most 50 entries per request, with a count of the rest). Text differences are a unified diff of up to 200 lines. **Arrays are compared index by index**, so inserting one item at the start of a list shows as every later item changing. Bodies over 1 MiB, and binary bodies, are compared by SHA-256 and size only. ### A worked example The suite has three requests; `repeat` is 20, the defaults are in force, and both runs had server-side metrics. | Request | Median before → after | Δ | Queries | What happens | |---|---|---|---|---| | `list orders` | 48.0 ms → 30.5 ms | −36.5% | 31 → 3 | Significant (`p ≈ 1e-7`), −17.5 ms is past 2 ms and −36.5% is past 10%: **faster**. Queries fell by 28 and a `duplicate_query` issue is listed as **fixed** | | `order detail` | 12.0 ms → 12.9 ms | +7.5% | 4 → 4 | Even if the test were significant, 7.5% is under `slower_pct`: **same** | | `customer export` | 20.0 ms → 20.4 ms | +2.0% | 2 → 5 | Time is **same**, but the median went 2 → 5 queries and `max_query_increase` is 0: **slower (queries)** | Say `order detail`'s response also lost the field `customer.email`. Its response verdict is **changed**, with the diff entry `customer.email removed`. With the default `--fail-on slower,changed,broken` the run fails on `customer export` (slower) and `order detail` (changed), and the overall speed change is the geometric mean of the three time ratios (0.635, 1.075 and 1.020), about **−11%**: ratios multiply, so a 2× speed-up and a 2× slow-down cancel out, which an arithmetic mean of percentages would get wrong. ## Server-side metrics The client side alone knows how long the response took. To also report queries, query time and SQL, Redline needs the app's own traces of the check calls. Every call of a check carries a header `X-Redline-Check: ;req=;n=` (`n=0` for warmup calls). An app instrumented with Redline stores it as tags (`check_run_id`, `check_req`, `check_n`) on that request's trace. After the run, the checker reads those traces and gives each request: - the median server duration, the median and maximum query count, and the query time; - the SQL statements by fingerprint with their counts per call (so a statement that appeared or went away is listed as *new SQL* or *gone SQL*, with a link to a sample trace); - the issues seen (so *new issues* and *fixed issues*). What this needs: - **The same store.** The checker reads the same SQLite file the app writes to. In the UI that is automatic, because the run is started by the Redline that serves the app. On the command line pass `--store PATH` (it defaults to the configured `storage_path` when that file exists). Against a remote app, or an app whose store you cannot read, use `--no-store` or let it find nothing: the report says *server-side metrics: unavailable* and the client-side verdicts still work. - **An app that runs Redline**, with the check calls kept. Sampling does not drop them: a tagged call is kept even when `sample_rate` would have dropped it. - **A real, running check.** The store only honours a `check_run_id` it knows: a check that is running, or ended less than a minute ago. The CLI writes the run into the store before it sends the first request. **Why a made-up tag does nothing.** A header is controlled by whoever sends the request, so if any tag were believed anyone could make Redline store requests, or fill its tables, just by adding a header. Run ids are random 128-bit values that only users of Redline see. A request with a tag for a run that does not exist keeps its normal sampling decision and loses the `check_*` tags; a request that would only have been kept *because of* the tag is dropped. See [Security](security.md#refactor-checks). ## Reading the report ![The report: summary cards and a table with one row per request](assets/screenshots/checks-report-light.png){ .rl-shot .rl-only-light } ![The report: summary cards and a table with one row per request](assets/screenshots/checks-report-dark.png){ .rl-shot .rl-only-dark } **In the UI** (`#/checks/runs/{id}`) the top shows cards for passed, changed, broken, faster and slower requests, the overall speed change and the total change in queries, plus the five biggest wins and regressions. The table has a row per request: the performance verdict, median before → after, the change in percent, queries before → after and the response verdict. It is sortable. A row expands to show: - the **latency** of both runs side by side; - the **response diff** (paths with before and after values, or a unified text diff); - **new and fixed issues** and **new and gone SQL**, with links to sample traces; - the **ignored** fields, split into changes on every call and your own rules. *Copy as Markdown* puts the PR-comment version on the clipboard. While a run is going the page shows its live progress. ![A request expanded: latency, the response diff and the SQL that went away](assets/screenshots/checks-report-expanded-light.png){ .rl-shot .rl-only-light } ![A request expanded: latency, the response diff and the SQL that went away](assets/screenshots/checks-report-expanded-dark.png){ .rl-shot .rl-only-dark } **In the terminal**, `compare` prints a table and a verdict line (colour when it is a TTY, `--no-color` to disable): ```text redline check: orders refactor – compared with baseline 'before' 3f9a2c1e 2026-10-27 09:14 request perf median before → after Δ queries response list orders faster 48.0 ms → 30.5 ms -36.5% 31 → 3 same order detail same 12.0 ms → 12.9 ms +7.5% 4 → 4 changed (1 difference) customer export slower (q) 20.0 ms → 20.4 ms +2.0% 2 → 5 same order detail: - customer.email: removed (was "ada@example.com") list orders: fixed issue: duplicate_query – 28 identical queries 3 requests · perf: 1 faster, 1 slower, 1 same · response: 1 changed, 2 same · overall 11.4% faster · queries 37 → 12 (-25) FAIL: 2 of 3 requests match --fail-on slower,changed,broken,missing: order detail, customer export ``` (Column spacing and wording are illustrative.) `redline check show report.json` prints a saved JSON report again, and can write the Markdown and JUnit files from it. ## Outputs and exit codes `compare` and `run` can write any of these in the same run: | Flag | Output | |---|---| | `--json OUT` | the full report: suite, baseline, run, summary and every request's performance, server and response results | | `--markdown OUT` | a PR comment: a PASS/FAIL line, a summary, a table, and a collapsible diff per changed request | | `--junit OUT` | JUnit XML, one test case per request; a request whose verdict matches `--fail-on` is a failure with the diff as its text | | `--ruff [PATH]` | include Ruff JSON (or run `ruff check --select F --output-format json`) as a table in Markdown and a `ruff` suite in JUnit; findings fail the command | | Exit code | Meaning | |---|---| | `0` | Nothing matched `--fail-on` (or `record` finished) | | `1` | At least one request matched `--fail-on` | | `2` | Usage, suite or baseline error (bad file, unset `${env:NAME}`, missing baseline) | | `3` | The app could not be reached at all: every call of the first round failed to connect | | `130` | Interrupted with Ctrl-C or SIGTERM. A `record` writes no baseline; a `compare` prints the partial report | `--fail-on` takes a comma-separated list of `slower`, `changed`, `broken`, `noisy`, `faster`, `missing` and `none`. The default is `slower,changed,broken,missing`. Use `--fail-on broken,changed` to gate on correctness only (for example when the baseline was recorded on other hardware), or add `noisy` if you want an unstable measurement to fail the build. ## CI recipe The most reliable setup records the baseline and runs the comparison **in the same job on the same runner**, so both sides see the same hardware and the same data: check out the base commit, record, check out the pull request, compare. The Markdown goes in as a PR comment and a regression fails the job. ```yaml title=".github/workflows/refactor-check.yml" name: refactor check on: pull_request permissions: contents: read pull-requests: write jobs: check: runs-on: ubuntu-latest env: API_TOKEN: ${{ secrets.CHECK_API_TOKEN }} # used by ${env:API_TOKEN} in the suite steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/setup-python@v5 with: python-version: "3.12" - run: | pip install -r requirements.txt pip install "redline-core[load] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" - name: Keep the suite from this PR run: cp checks/orders.toml "$RUNNER_TEMP/orders.toml" - name: Record the baseline on the base commit run: | git checkout --detach ${{ github.event.pull_request.base.sha }} ./scripts/serve-for-check.sh start .redline/check.db # migrate, load fixtures, start the app redline check record "$RUNNER_TEMP/orders.toml" \ --store .redline/check.db --label "base ${GITHUB_BASE_REF}" \ --out "$RUNNER_TEMP/baseline.json" ./scripts/serve-for-check.sh stop - name: Compare on the pull request run: | git checkout --detach ${{ github.event.pull_request.head.sha }} rm -f .redline/check.db* ./scripts/serve-for-check.sh start .redline/check.db redline check compare "$RUNNER_TEMP/orders.toml" \ --baseline "$RUNNER_TEMP/baseline.json" --store .redline/check.db \ --markdown check.md --junit check.xml --json check.json \ --fail-on slower,changed,broken # a failing compare fails this step; the next two still run - name: Comment on the PR if: always() && hashFiles('check.md') != '' uses: marocchino/sticky-pull-request-comment@v2 with: header: redline-refactor-check path: check.md - uses: actions/upload-artifact@v4 if: always() with: name: refactor-check path: | check.md check.xml check.json ``` `scripts/serve-for-check.sh` is yours: it must bring the application up with the same database content every time and with Redline's store at the given path (for example by exporting `REDLINE_STORAGE_PATH=$2`), wait until it answers, and stop it again. Keep Redline's `access` as it is for the app; the check only sends ordinary requests to your routes. !!! warning "Baselines from another machine" If you would rather keep one baseline file, either as a CI artifact from a run on `main` or committed to the repository, remember that **timings are only comparable on the same hardware**. A baseline recorded on your laptop will make a CI runner look slower. Response comparison does not have that problem, so with a committed baseline gate on `--fail-on changed,broken`, and keep the `slower` gate for the same-runner setup above. Baselines are redacted, so committing one is safe to the same extent as committing a response fixture. ### The GitHub Action For the common case the repository root is a composite action. It installs Redline, runs `redline check run`, writes the Markdown report to the job summary and keeps **one** sticky comment on the pull request up to date (found again through a hidden HTML marker, so reruns edit it instead of adding another). Start the app in an earlier step. ```yaml permissions: contents: read pull-requests: write steps: - uses: actions/checkout@v4 - run: ./scripts/serve-for-check.sh start # your app, listening on :8000 - uses: Pythondeveloper6/redline@main # pin a tag or commit in real use with: suite: checks/orders.toml baseline: checks/orders.baseline.json # compared when it exists, recorded otherwise base-url: http://127.0.0.1:8000 fail-on: slower,changed,broken ``` | Input | Default | Meaning | |---|---|---| | `suite` | required | Suite file | | `baseline` | `.baseline.json` | Compared with when present, recorded there when absent | | `base-url` | the suite's `base_url` | The running app | | `fail-on` | `slower,changed,broken` | Verdicts that fail the job, or `none` | | `python-version` | `3.12` | Python used to run Redline | | `package` | `redline-core[load]` | pip requirement; pin a version or use a git URL | | `comment` | `true` | Post the sticky comment (pull request events only) | | `github-token` | `github.token` | Needs `pull-requests: write`; without it the comment is skipped | | `marker-id` | `redline-check` | Use one per suite when several suites comment on one PR | | `extra-args` | | Extra `redline check run` arguments | The step outputs `exit-code` and `report` (the JSON path). The comment is posted by `redline check comment REPORT` (a `--json` report or a `--markdown` file; `--dry-run` prints the body, `--no-comment` only writes the job summary). It does nothing outside `pull_request` events, and a failed API call (for example the read-only token of a fork PR) only prints a warning: the check's own verdict decides the job result. The token is sent only to `GITHUB_API_URL` over https (plain http only to a loopback address), redirects are never followed, and `extra-args` is split on whitespace but never glob-expanded or evaluated; still, do not build it from pull-request-controlled text such as branch names. A baseline produced in CI can be opened in the UI: `POST api/checks/baselines/import` takes the JSON file (see [the HTTP API](http-api.md#checks)) and the run appears on the suite's page. ## Settings and access | Setting | Default | Meaning | |---|---|---| | `checks_from_ui` | `"auto"` | Allow starting baseline and compare runs from the UI. `"auto"` means only while the framework is in debug mode; `true` or `false` force it. The `production` preset sets it to `false`. Off whenever `read_only` is on or the `checks` feature is off | | `features.checks` | `true` | The Checks page and everything under `api/checks`. Off: those routes answer `404 feature_disabled` and the UI hides the page | | `base_url` | `None` | Where UI-started checks send their requests, the same setting load runs use. Unset: the server's own listening port on `127.0.0.1`, never the `Host` header | Runs started from the UI are capped at 200 requests, 5 000 calls in total (each request's warmup plus repeat, added up) and 15 minutes. See [Settings](settings.md#developer-experience), [Access control](access-control.md) and [Security](security.md#refactor-checks). ## Try it on the demo shop Each demo shop in `examples/` (Django, FastAPI, Flask and Litestar) ships a ready suite, `examples//check.toml`, and an environment toggle, `SHOP_REFACTOR=1`, that turns the shop into "after a refactor". All four shops get the same changes, so one compare shows every kind of verdict: - **fixes the N+1** on the orders list (faster, and far fewer queries); - **slows one endpoint** down on purpose (a `slower` verdict); - **changes one field** in a response (a `changed` verdict with a diff); - **breaks one endpoint** (a `broken` verdict). The `/status` endpoint is in every suite too. The toggle does not change it, but some of its fields differ on every call, so it shows how the check ignores fields that change on their own and still reports `same`. From the repository root, install the workspace once with `uv sync --all-packages`. Then pick a framework. ### What `SHOP_REFACTOR=1` changes === "Django" | Endpoint | What `SHOP_REFACTOR=1` does | Expected verdict | |---|---|---| | `GET /orders/` | adds `prefetch_related("items")` | faster, queries 31 -> 2, fixed N+1 | | `GET /dashboard/` | adds a 50 ms sleep | slower | | `GET /api/products/` | `price` now has one decimal (`1528.00` -> `1528.0`) | changed (`products[n].price`) | | `GET /async/summary/` | raises an error | broken (200 -> 500) | | `GET /status/` | unchanged; `now` and `request_id` differ on every call | same (volatile fields ignored) | === "FastAPI" | Endpoint | What `SHOP_REFACTOR=1` does | Expected verdict | |---|---|---| | `GET /orders` | fixes the N+1 with `selectinload` | faster, queries 31 -> 2, fixed N+1 | | `GET /orders/1` | adds a 50 ms sleep | slower | | `GET /report/duplicates` | `products` becomes a string | changed (`products`, type) | | `GET /sync/orders` | raises an error | broken (200 -> 500) | | `GET /status` | unchanged; `now` and `request_id` differ on every call | same (volatile fields ignored) | === "Flask" | Endpoint | What `SHOP_REFACTOR=1` does | Expected verdict | |---|---|---| | `GET /orders` | fixes the N+1 with `selectinload` | faster, queries 31 -> 2, fixed N+1 | | `GET /orders/1` | adds a 50 ms sleep | slower | | `GET /report/duplicates` | `products` becomes a string | changed (`products`, type) | | `GET /orders/tags` | raises an error | broken (200 -> 500) | | `GET /status` | unchanged; `now` and `request_id` differ on every call | same (volatile fields ignored) | === "Litestar" | Endpoint | What `SHOP_REFACTOR=1` does | Expected verdict | |---|---|---| | `GET /orders` | fixes the N+1 with `selectinload` | faster, queries 31 -> 2, fixed N+1 | | `GET /orders/1` | adds a 50 ms sleep | slower | | `GET /report/duplicates` | `products` becomes a string | changed (`products`, type) | | `GET /sync/orders` | raises an error | broken (200 -> 500) | | `GET /status` | unchanged; `now` and `request_id` differ on every call | same (volatile fields ignored) | Every other request in `check.toml` is unchanged, so it should come out `same`. ### Run the check Use the same three steps for every framework: record a baseline on the code as it is, restart the app with the toggle, then compare. The `redline` commands run from the repository root, and the `--store` path points at the demo's own store (see the note in the example README). === "Django" ```bash # 1. old code: set up the demo and start the app (in its own terminal) uv run python examples/django/manage.py migrate uv run python examples/django/manage.py seed # ~400k reviews, takes a few seconds uv run python examples/django/manage.py runserver 8000 --noreload ``` Generate some traffic from another terminal, with the curl loop from the example README: ```bash for u in / /orders/ /items/ /orders/page/ /dashboard/ "/reviews/search/?q=battery" \ /slow/ "/slow/?_redline=profile" /boom/ /async/summary/ /cached/ /cached/; do curl -s -o /dev/null -w "%{http_code} $u\n" "http://127.0.0.1:8000$u" done curl -s -o /dev/null -H "Authorization: Bearer sk-live-123" http://127.0.0.1:8000/api/products/ ``` Record the baseline, from the repository root in another terminal: ```bash uv run --package redline-core --extra load redline check record examples/django/check.toml \ --base-url http://127.0.0.1:8000 --store examples/django/.redline/redline.db ``` ```bash # 2. "refactored" code: stop the server (Ctrl-C), restart it with the toggle SHOP_REFACTOR=1 uv run python examples/django/manage.py runserver 8000 --noreload ``` Compare, from the repository root: ```bash uv run --package redline-core --extra load redline check compare examples/django/check.toml \ --base-url http://127.0.0.1:8000 --store examples/django/.redline/redline.db --markdown report.md --junit report.xml echo $? # 1: the refactor made things slower, changed a response and broke an endpoint ``` In the UI, the Checks page is at **http://127.0.0.1:8000/redline/#/checks** (log in as admin / admin first; `DEBUG = True` here, so `checks_from_ui` is on). === "FastAPI" ```bash # 1. old code: set up the demo and start the app (in its own terminal) cd examples/fastapi uv run --project ../.. python seed.py # creates shop.db (~2 s) uv run --project ../.. uvicorn shop.main:app --port 8000 ``` Generate some traffic by hitting the endpoints in the table in the example README (open http://127.0.0.1:8000/ or use curl). Then record the baseline, from the repository root in another terminal: ```bash uv run --package redline-core --extra load redline check record examples/fastapi/check.toml \ --base-url http://127.0.0.1:8000 --store examples/fastapi/.redline/redline.db ``` ```bash # 2. "refactored" code: stop the server (Ctrl-C), restart it with the toggle, still in examples/fastapi SHOP_REFACTOR=1 uv run --project ../.. uvicorn shop.main:app --port 8000 ``` Compare, from the repository root: ```bash uv run --package redline-core --extra load redline check compare examples/fastapi/check.toml \ --base-url http://127.0.0.1:8000 --store examples/fastapi/.redline/redline.db --markdown report.md --junit report.xml echo $? # 1: the refactor made things slower, changed a response and broke an endpoint ``` In the UI, the Checks page is at **http://127.0.0.1:8000/_redline/#/checks** (local access only; the UI starts runs because `checks_from_ui` defaults to on in debug mode). === "Flask" ```bash # 1. old code: set up the demo and start the app (in its own terminal) cd examples/flask uv run --project ../.. python seed.py # creates shop.db (~2 s) uv run --project ../.. flask --app shop.main run --port 8000 # http://127.0.0.1:8000/ ``` Generate some traffic by hitting the endpoints in the table in the example README (open http://127.0.0.1:8000/ or use curl). Then record the baseline, from the repository root in another terminal: ```bash uv run --package redline-core --extra load redline check record examples/flask/check.toml \ --base-url http://127.0.0.1:8000 --store examples/flask/.redline/redline.db ``` ```bash # 2. "refactored" code: stop the server (Ctrl-C), restart it with the toggle, still in examples/flask SHOP_REFACTOR=1 uv run --project ../.. flask --app shop.main run --port 8000 ``` Compare, from the repository root: ```bash uv run --package redline-core --extra load redline check compare examples/flask/check.toml \ --base-url http://127.0.0.1:8000 --store examples/flask/.redline/redline.db --markdown report.md --junit report.xml echo $? # 1: the refactor made things slower, changed a response and broke an endpoint ``` In the UI, the Checks page is at **http://127.0.0.1:8000/_redline/#/checks** (local access only; the UI starts runs because `checks_from_ui` defaults to on in debug mode). === "Litestar" ```bash # 1. old code: set up the demo and start the app (in its own terminal) cd examples/litestar uv run --project ../.. python seed.py # creates shop.db (~2 s) uv run --project ../.. uvicorn shop.main:app --port 8000 # http://127.0.0.1:8000/ ``` Generate some traffic by hitting the endpoints in the table in the example README (open http://127.0.0.1:8000/ or use curl). Then record the baseline, from the repository root in another terminal: ```bash uv run --package redline-core --extra load redline check record examples/litestar/check.toml \ --base-url http://127.0.0.1:8000 --store examples/litestar/.redline/redline.db ``` ```bash # 2. "refactored" code: stop the server (Ctrl-C), restart it with the toggle, still in examples/litestar SHOP_REFACTOR=1 uv run --project ../.. uvicorn shop.main:app --port 8000 ``` Compare, from the repository root: ```bash uv run --package redline-core --extra load redline check compare examples/litestar/check.toml \ --base-url http://127.0.0.1:8000 --store examples/litestar/.redline/redline.db --markdown report.md --junit report.xml echo $? # 1: the refactor made things slower, changed a response and broke an endpoint ``` In the UI, the Checks page is at **http://127.0.0.1:8000/_redline/#/checks** (local access only; the UI starts runs because `checks_from_ui` defaults to on in debug mode). ### Read the compare report This is the Django run, from the steps above. The other frameworks print the same table, with their own rows (one per request in their `check.toml`): ```text request perf median before → after Δ queries response list orders (N+1) faster 7.94ms → 3.02ms -61.9% 31 → 2 same dashboard slower 1.59ms → 57.1ms +3485.5% 3 → 3 same products API same 1.50ms → 1.78ms +18.7% 1 → 1 changed (20 differences) async summary slower 2.46ms → 9.11ms +269.7% 3 → 0 broken (status 200 → 500) slow view same 362ms → 364ms +0.6% 0 → 0 same cached top products same 1.08ms → 1.03ms -4.9% 0 → 0 same status (volatile fields) same 0.86ms → 0.85ms -1.2% 0 → 0 same list orders (N+1): fixed issue: n_plus_one – N+1: 30 queries on shop_orderitem from shop/views.py:45 products API: ~ products[0].price: 1528.00 → 1528.0 … 8 more status (volatile fields): ignored (changes on every call): now, request_id 7 requests · perf: 1 faster, 2 slower, 4 same · response: 5 same, 1 changed, 1 broken · overall 78.0% slower · queries 38 → 6 (-32) FAIL: 3 of 7 requests match --fail-on slower,changed,broken: dashboard, products API, async summary ``` What each row says: - **list orders (N+1)**: `faster`, and the queries drop from 31 to 2. The N+1 is reported as a fixed issue, with the line that caused it. - **dashboard**: `slower` on the clock alone. The query count did not change; the 50 ms sleep did. - **products API**: the speed is `same`, but the response is `changed`. The `price` field of the products now has one decimal place, so 20 values differ. Expand the row to see the paths. - **async summary**: `broken`, because the status went from 200 to 500. The timings of the failing calls are still measured, which is why this row also reads `slower`; the response column is the verdict that matters here. - **slow view** and **cached top products**: untouched by the toggle, so `same`. They are there to show that an unchanged endpoint stays quiet. - **status (volatile fields)**: `same`. `now` and `request_id` change on every call, so the check lists them as ignored instead of reporting them as differences. The last line is the exit code's reason. `compare` exits with 1 when any request matches `--fail-on`, which defaults to `slower,changed,broken`. Here that is three requests, so the command exits with 1. ### In the UI The same run is on the Checks page, with the steps from [the workflow above](#the-workflow-in-three-steps). Open the page for your framework (the URLs are in the tabs above) and: 1. Build a suite from the routes Redline has seen: *New suite* lists them, and you tick the ones you want. ![The Checks page: suites with their last baseline and last compare](assets/screenshots/checks-list-light.png){ .rl-shot .rl-only-light } ![The Checks page: suites with their last baseline and last compare](assets/screenshots/checks-list-dark.png){ .rl-shot .rl-only-dark } ![The suite builder: routes Redline has seen, with a sample path, p50 and queries](assets/screenshots/checks-builder-light.png){ .rl-shot .rl-only-light } ![The suite builder: routes Redline has seen, with a sample path, p50 and queries](assets/screenshots/checks-builder-dark.png){ .rl-shot .rl-only-dark } 2. Press *Baseline* on the suite page while the app runs the old code. ![A suite page: record a baseline, compare, and the history of runs](assets/screenshots/checks-suite-light.png){ .rl-shot .rl-only-light } ![A suite page: record a baseline, compare, and the history of runs](assets/screenshots/checks-suite-dark.png){ .rl-shot .rl-only-dark } 3. Restart the app with `SHOP_REFACTOR=1`, press *Compare*, and the report opens when the run ends. Its cards and table match the terminal output above. ![The report: summary cards and a table with one row per request](assets/screenshots/checks-report-light.png){ .rl-shot .rl-only-light } ![The report: summary cards and a table with one row per request](assets/screenshots/checks-report-dark.png){ .rl-shot .rl-only-dark } Expand a row to see the latency of both runs, the response diff and the SQL that went away. ![A request expanded: latency, the response diff and the SQL that went away](assets/screenshots/checks-report-expanded-light.png){ .rl-shot .rl-only-light } ![A request expanded: latency, the response diff and the SQL that went away](assets/screenshots/checks-report-expanded-dark.png){ .rl-shot .rl-only-dark } See [Performance workflows](performance-workflows.md) for per-endpoint budgets, keyed arrays, numeric tolerances, environment warnings and UI verification. ## Limits and what's next - **Read-only requests only.** `GET`, `HEAD` and `OPTIONS`. There is no way to replay a write safely, and the check does not try. - **Arrays use index order by default.** Opt in to `array_keys` for paths where order is not part of the contract; invalid identities fail comparison. - **No concurrency.** Requests run one at a time on one connection. That makes the numbers stable, and means it says nothing about behaviour under load: use [`redline load`](load-testing.md) for that. - **One app at a time.** You record against the old code, then run again against the new code; it does not drive two live servers or check out commits for you (the CI recipe does the checkout). - **Bodies are compared up to 1 MiB**; bigger ones by hash. - **UI runs are capped** (200 requests, 5 000 calls, 15 minutes). The command line has no cap beyond the suite limits (`repeat` up to 1000). `redline analyze` and its UI are documented in [Performance workflows](performance-workflows.md). ## Verify a fix `redline check verify REPORT.json --kind n_plus_one [--fingerprint FP] [--min-samples 5]` reads a saved compare report and answers three questions about one finding: is it `gone`, `still_present` or `inconclusive`; are the responses `equal` or `changed`; is the request `faster`, `slower` or `unchanged`. A finding is only called `gone` when it was seen in the baseline, is absent after the change, and the after-change run has at least `--min-samples` calls with complete server-side metrics. Absence from sampled data is not proof of a fix, so too few samples or missing metrics give `inconclusive`. The exit code is 0 only for `gone`. ## Compare two running versions `redline check compare-live SUITE --old http://old:8000 --new http://new:8001 --rounds 5` sends every request to both servers back to back and flips the order each round, so drift and warm-up affect both sides alike. Suites only contain read-only methods, so nothing is written to either server. Both servers must serve equivalent data (same dataset and configuration). Timings include network time and are not a substitute for a load test. A server that fails is reported per request and the run continues. The exit code is 1 when any response differs. ## When server-side metrics are unavailable "server-side metrics: unavailable" means no traces tagged with the run id were found in the store passed with `--store` within 5 seconds of the run ending. Known causes: `--store` points at a different file than the app writes to, the app is not instrumented or drops traces (check `redline instrumentation`), the app's sampling rate is below 1, or the store is on a filesystem the app cannot write. An intermittent case was reported once after `record`; 30 consecutive record-then-compare runs against the FastAPI demo (`scripts/check_metrics_loop.py`) did not reproduce it. If you see it, run that script against your setup and keep the output. --- # Detectors overview [← Index](index.md) Version 0.1 found four kinds of problem: N+1 queries, duplicate queries, slow queries and requests with too many queries. Version 0.2 adds ten more, plus aggregate pages that look across requests. This page is the map; each family has its own page. Additional v0.3 development findings and their settings are described in [Performance workflows](performance-workflows.md#additional-runtime-findings). ## Every issue kind An *issue* is something the detectors found in one trace. Issues with the same identity (kind, query or call, and callsite) are deduplicated across requests on the [Issues](issues-and-endpoints.md#issues) page, with first seen, last seen and a count. | Kind | Fires when | Default threshold | Page | |---|---|---|---| | `n_plus_one` | the same read from the same line, at least N times | `n_plus_one_threshold = 5` | [N+1 detection](n-plus-one.md) | | `duplicate_query` | identical SQL and parameters repeated | `duplicate_threshold = 2` | [N+1 detection](n-plus-one.md) | | `slow_query` | a query takes at least this long | `slow_query_ms = 100` | [N+1 detection](n-plus-one.md) | | `too_many_queries` | a request runs at least this many queries | `too_many_queries = 50` | [N+1 detection](n-plus-one.md) | | `blocking_in_async` | the event loop was stalled by synchronous work | `blocking_ms = 20` | [Blocking in async](async-blocking.md) | | `long_transaction` | a transaction stayed open this long | `long_transaction_ms = 200` | [Transactions and locks](transactions.md) | | `external_in_transaction` | an outbound HTTP call was made inside a transaction | any | [Transactions and locks](transactions.md) | | `large_result` | a SELECT returned this many rows | `large_result_rows = 1000` | [Large and unbounded results](result-size.md) | | `unbounded_query` | a SELECT with no `LIMIT` returned this many rows | `unbounded_rows = 200` | [Large and unbounded results](result-size.md) | | `inefficient_count` | `len(qs)`, `if qs:`, `bool(qs)` or `.count() > 0` on a full-row query | pattern | [Count and exists](result-size.md#count-and-exists) | | `slow_serializer` | a serializer takes at least this long | `slow_serializer_ms = 50` | [Slow serializers](serializers.md) | | `slow_external` | an outbound call takes at least this long | `slow_external_ms = 500` | [External calls](external-calls.md) | | `duplicate_external` | the same method and URL called twice or more | 2 | [External calls](external-calls.md) | | `retry_storm` | three or more calls to one host with at least one failure | 3 | [External calls](external-calls.md) | | `repeated_writes` | Repeated individual INSERT/UPDATE calls | 5 | [Performance workflows](performance-workflows.md) | | `deep_offset` | Large observed OFFSET | 10000 rows | [Performance workflows](performance-workflows.md) | | `database_round_trips` | Many queries with substantial cumulative cost | 10 queries and 100 ms | [Performance workflows](performance-workflows.md) | | `connection_pool_wait` | Long captured checkout wait | 50 ms | [Performance workflows](performance-workflows.md) | | `duplicate_llm_call` | Identical LLM prompt repeated in a request | 2 calls | [LLM-call observability](llm.md) | | `serial_llm_calls` | LLM calls that ran back to back | 3 calls | [LLM-call observability](llm.md) | | `llm_in_transaction` | LLM call while a transaction was open | always | [LLM-call observability](llm.md) | | `llm_call_loop` | Many LLM calls in one request | 8 calls | [LLM-call observability](llm.md) | | `uncached_large_prompt` | Large Anthropic prompt without prompt caching | 4000 characters | [LLM-call observability](llm.md) | | `repeated_scan` | Distinct aggregates with matching predicate shape | 2 | [Performance workflows](performance-workflows.md) | | `large_response` | Response bytes exceed the threshold | 1000000 bytes | [Performance workflows](performance-workflows.md) | | `many_orm_instances` | Many model objects constructed or loaded | 500 | [Performance workflows](performance-workflows.md) | | `large_cache_entry` | Known binary cache payload size exceeds the threshold | 1000000 bytes | [Performance workflows](performance-workflows.md) | | `slow_cache_decode` | Explicitly instrumented cache decode exceeds the threshold | 50 ms | [Performance workflows](performance-workflows.md) | | `json_decode_hotspot` | Sampled standard-library JSON decoding cost | 50 ms | [Performance workflows](performance-workflows.md) | | `unattributed_time` | at least half of a web request is covered by no span | `unattributed_time_ratio = 0.5`, `unattributed_time_ms = 100` | [Unattributed time](#unattributed-time) | Severity is `info`, `warning` or `critical`. For most of the new detectors, a value at five times its threshold is `critical`. ## Where the data comes from The detectors read **spans**, and the new ones need new span kinds. The adapters and the [integrations](integrations.md) create them. | Span kind | Created by | Used by | |---|---|---| | `sql` (with `rows`, `has_limit`, `in_transaction`) | ORM and driver hooks | result-size detectors, N+1 | | `serializer` | DRF, FastAPI response serialization, Marshmallow | `slow_serializer` | | `resolver` | Strawberry, Graphene | N+1 over [GraphQL](graphql.md) | | `transaction` | Django, SQLAlchemy | transaction detectors | | `blocking` | the event-loop lag monitor, sync-driver hooks | `blocking_in_async` | | `pool_wait` | SQLAlchemy connection checkout | shown in the timeline | | `http_out` | httpx, requests integrations | external detectors | | `cache` | Django cache, redis-py | the Cache page | ## Aggregate pages Detectors look at one request. Some questions are about many requests, so Redline derives small per-request summary tables at write time and the UI queries those: | Page | Question | Source table | |---|---|---| | [Database](database.md) | Which SQL costs the most in total? Which index is missing or unused? | `trace_sql` | | [Cache](cache-efficiency.md) | Which key patterns miss, are written but never read, or stampede? | `trace_cache` | | [External calls](external-calls.md) | Which third parties are slow, duplicated or retried? | `trace_ext` | | [History](history.md) | How did p95 change per release? What is new, resolved or regressed? | `rollups`, `issue_index` | ## Logs and exceptions Two pieces of context are not issues but make every issue easier to understand: the **log records** emitted during the request, and the **local variables** of the project frames in an exception. See [Logs and exceptions](logs-and-exceptions.md). ## Unattributed time Every other detector reports something redline recorded. `unattributed_time` reports what it could not record: time inside a request that no span covers. It fires when the uncovered time is at least `unattributed_time_ms` (default 100 ms) **and** at least `unattributed_time_ratio` of the request (default 0.5; `0` turns the detector off). Both can be changed in [settings](settings.md#detectors) and in the analysis preview. How the time is counted: - Spans of every kind except the wrappers `view`, `middleware` and `transaction` count as covered. A wrapper encloses work without saying what it was, so it does not hide the gap. A [custom span](custom-spans.md) counts: a named block is attributed. - Overlapping spans (SQL on several [threads](async-blocking.md#work-on-threads-and-pools), for example) are merged, so time is never counted twice. - Severity is `info` just over the floor and `warning` from twice the minimum. When the trace has a [profile](flamegraphs.md), the finding names the project frame that held most of the uncovered time. Without one it only says how much time is unaccounted for. The time is either your own code (CPU work, a loop) or a client library redline has no integration for. For a client, wrap it once and the time gets a name: ```python from redline_core import instrument_client_method instrument_client_method(acme_sdk.Client, "put", client="acme", target=lambda self, args, kwargs: args[0]) ``` See [Extending](extending.md#instrumenting-a-client). The finding disappears once the uncovered share falls below the thresholds. It is deliberately conservative: it looks only at requests recorded by the Django, FastAPI, Flask and Litestar adapters (jobs and hand-made recordings are mostly their own code and would always trip it), and it is silent when `max_spans_per_trace` dropped spans, because the coverage would be understated. On a [load run](load-testing.md#bottlenecks) the same uncovered time appears as an `other` row. ## Tuning Thresholds are ordinary [settings](settings.md#detectors). A noisy detector is usually a threshold that is too low for your data: raise `large_result_rows` for a reporting app, or `slow_external_ms` for a service that calls a slow vendor on purpose. There is no switch to turn a single detector off; the registry is code (see [Extending](extending.md)). All detectors run when a trace is **finished**, and only on kept traces, so a request that is sampled out pays nothing for them. One detector raising an exception is logged and skipped; it never fails the request. --- # Performance checks and analysis tools [← Index](index.md) The v0.3 development build connects findings, response comparison and regression checks. The UI exposes the same analysis engines as the command line. Open **More → Analysis** for source analysis, recording health, suite coverage and suppressions. ## Try it in the UI 1. Run one of the demo shops and visit `/patterns/` (Django) or `/patterns` (the other shops). Open the recorded request's **Issues** tab. The original implementation runs four queries and deliberately repeats aggregates, uses deep OFFSET pagination and constructs full model objects. 2. Press **Try detector thresholds** to evaluate different thresholds against the recorded evidence. This preview does not change server settings or saved findings. Missing or truncated evidence cannot be reconstructed. 3. In **Analysis → Detector samples**, record the nine synthetic samples to inspect additional findings, including pool waits, large binary cache entries and sampled JSON decoding. Their operations and timings are illustrative, not application measurements; synthetic requests cannot be replayed as real endpoints. 4. Create a check suite with the rules below, record a baseline, then restart the shop with `SHOP_REFACTOR=1` and compare. The pattern endpoint drops from four queries to two and avoids full model construction. It deliberately reverses the response array and changes `total` by 0.005 to exercise the explicit comparison rules. The demo settings explicitly enable check runs and source analysis from the UI. Keep these development settings scoped to the demo. For test servers, use ports 8011 or higher. The examples' existing READMEs explain the two terminals: the app directory for the server, and the repository root for the commands. For an in-process check of all four demos without opening server ports: ```bash uv run --no-sync python scripts/check_demo_patterns.py ``` ## Endpoint budgets and response rules In **Checks → New suite**, each request has **Budgets and response rules**. Saving, editing and exporting a suite preserves these rules. ```toml name = "product report" repeat = 20 warmup = 3 environment = { dataset = "shop-fixture-1", database = "SQLite fixture" } [[requests]] name = "performance patterns" path = "/patterns" array_keys = { items = "id" } tolerances = { total = { absolute = 0.01 } } budgets = { max_queries = 4, max_median_ms = 500, forbidden_issues = [] } ``` Use `/patterns/` for Django. Choose budgets for your environment; the example's latency limit is illustrative. | Rule | Meaning | |---|---| | `max_queries` | Maximum observed queries in any timed call; a whole number | | `max_external_calls` | Maximum observed outbound HTTP calls in any timed call; a whole number | | `max_median_ms` | Upper bound on the current run's client-side median latency | | `max_p95_ms` | Upper bound on the current run's interpolated p95; use enough repeats | | `min_samples` | Whole number ≥ 1. Latency budgets (`max_median_ms`, `max_p95_ms`) fail with "insufficient samples" instead of judging a run with fewer timed calls | | `forbidden_issues` | Issue kinds that must not occur, for example `n_plus_one` | | `array_keys` | Match elements at a configured JSON path by an identity field | | `tolerances` | Allow a numeric difference at a configured JSON path | Budgets are independent of improvement against the baseline. A slow baseline does not make a budget pass. Missing required measurements, incomplete server metric collection, and broken responses cannot pass a budget. Query counts remain usable when spans are truncated; issue and external-call coverage require complete evidence. Budget failures appear in the suite badges, report summary, per-request details, JSON, Markdown, terminal output and JUnit. The default `--fail-on` includes `budget`; use an explicit list or `none` to change that policy. Array matching is opt-in: ordering may be part of an endpoint's contract. Every element must have a unique non-null string or numeric identity; missing or duplicate identities fail comparison. Added and removed elements remain differences. Paths within a matched array refer to the aligned baseline order, so prefer wildcard ignore paths inside it. Numeric tolerance accepts a difference no greater than `max(absolute, relative * abs(baseline))`. Relative values are fractions: `0.01` means 1%. Booleans, missing fields and type changes are not hidden by a numeric tolerance. Ignored paths retain precedence. The report lists the configured comparison rules; a `same` verdict under these rules means equivalent under those rules, not byte-identical. ## Environment and coverage Kept requests record the target process's Python version, framework and installed framework version when available. Check reports warn when observed target runtime metadata changes or disappears. This is the application's runtime, not the runner's. **Target environment labels** in the suite editor add dataset, database, Python, framework and configuration labels. These are user declarations, not automatic database-version or dataset verification. Hardware, data contents and shared-service state are not proven equivalent by matching labels. Older baselines may lack metadata. **Analysis → Suite coverage** compares a suite with the latest 500 retained traces. It recognizes common Django, Flask, FastAPI and Litestar route parameters, shows missing and single-input routes, and lists suite requests absent from observed traffic. Distinct configured paths and headers count as different suite inputs. Unobserved routes and unexercised branches remain unknown; this is not a completeness guarantee. ## pytest and no-query assertions The core package registers a pytest plugin. Tests still need an installed adapter and an instrumented in-process test client. The suite editor displays a pytest assertion snippet for each request's query, outbound-call and issue policy. ```python import pytest @pytest.mark.redline(max_queries=5, max_external_calls=0, no_n_plus_one=True) def test_products(client): assert client.get("/products").status_code == 200 ``` Each captured request must meet the limits. No captured requests fails the assertion rather than silently passing. Capture is context-local and includes sampled-out active requests; it does not enable disabled instrumentation or ignored paths. Work in another process or a thread that does not inherit context is outside this capture. ```python from redline_core.testing import assert_no_queries # Inside an active instrumented request, for example during serialization: with assert_no_queries(): result = serialize_preloaded_objects(objects) ``` Unexpected access raises with a callsite when available; an existing exception is preserved. A route-wide no-SQL policy can also use `max_queries = 0` in a suite. Stored test requests carry a `test_name` tag. Inspect them through **Analysis → Recording health** and open the request for SQL, findings and exceptions. The UI configures and explains policies; it does not execute arbitrary pytest or shell commands. ## Additional runtime findings | Kind | Evidence | Setting and default | |---|---|---| | `repeated_writes` | Repeated individual INSERT/UPDATE statements; excludes executemany | `repeated_writes_threshold = 5` | | `deep_offset` | Observed terminal OFFSET literal or integer bind | `deep_offset_rows = 10000` | | `database_round_trips` | Many queries and substantial cumulative query cost | `round_trip_count = 10`, `round_trip_ms = 100` | | `connection_pool_wait` | Captured connection checkout waits | `pool_wait_ms = 50` | | `repeated_scan` | Distinct aggregates with the same table and predicate shape | `repeated_scans_threshold = 2` | | `large_response` | Adapter-observed response bytes | `large_response_bytes = 1000000` | | `many_orm_instances` | Django model construction or SQLAlchemy objects loaded into a session | `orm_instances_threshold = 500` | | `large_cache_entry` | Known byte length of an already available binary value | `large_cache_bytes = 1000000` | | `slow_cache_decode` | Explicitly instrumented decode block | `cache_decode_ms = 50` | | `json_decode_hotspot` | Time attributed to standard-library JSON decoding in a profile | `json_decode_ms = 50` | A zero threshold disables its corresponding rule. Counts are per request unless noted. Round-trip findings avoid duplicating the existing count budget and repeated-query groups. Similar aggregate shapes do not prove identical parameters or redundant work. Bulk writes can change signals, validation and return behavior. Model counts do not prove objects are unnecessary; Django includes newly constructed objects as well as database-loaded ones. Response bytes do not measure network compression. Redis reads and supported writes, and Django cache reads, can observe binary values without copying them. Arbitrary objects and strings are not serialized or encoded just to measure size. Network/cache operation time is not mislabeled as decode time. For a decode block you control: ```python import json from redline_core.cache_payload import cache_decode with cache_decode("reports:daily", payload=raw_bytes, backend="redis"): report = json.loads(raw_bytes) ``` Only size and duration are recorded, not the payload. Existing cache efficiency analysis continues to report misses, unread writes and stampedes. ## Python source analysis Use **Analysis → Python source** to paste or open a Python file, load the example, or scan the configured `project_root`. Set `analysis_from_ui = true` explicitly, or leave it at `"auto"` in framework debug mode. The production preset disables it; read-only mode refuses the POST operations. The UI never accepts an arbitrary server filesystem root. ```bash redline analyze ./app --json redline analyze ./app --fail # Explicit larger-project budget (defaults remain conservative): redline analyze ./app --max-files 1000 --max-project-bytes 16000000 --json ``` Exit codes: `0` completed, `1` findings with `--fail`, `2` invalid/unreadable input or an incomplete scan. Code is parsed and never imported or executed. Source inputs are capped at 200 KB each; projects at 200 Python files, 2 MB and 20,000 visited entries. Dependency/generated directories and symlinks are skipped. CLI users can raise the project budget with `--max-files` (up to 10,000) and `--max-project-bytes` (up to 64,000,000). The same options are available on `redline check-sql`; the per-file and 20,000-entry limits still apply. UI scans keep the defaults. Errors, skipped files and limits remain visible. Supported candidates include queryset operations inside loops, Python-side aggregation and filtering, repeated fixed-range scans, repeated sorting, list membership inside loops, and known blocking calls inside async functions. Queryset inference recognizes Django-style chains and known SQLAlchemy Session/AsyncSession annotations or direct constructors; Known `get`, `scalar`, `scalars`, `execute` and `query` calls are recognized. Module-level local helpers are summarized through up to eight call edges; shadowed helper names are excluded. A query in the first iterable is evaluated once and is not classified as repeated by that loop; calls in later iterables can repeat. Session identity-map hits, short-circuit branches and intentional chunking still need runtime review. Helpers outside the scanned project, unknown factories and dynamic aliases may be missed. Findings are suggestions for review, not proof of runtime evaluation, unused data or a safe transformation. Preserve null, precision, duration rounding, hashing, ordering and mutation behavior when fixing them. ## On-demand database checks Expand a request's **SQL** group and press **Inspect columns / indexes**. Redline reads catalog metadata through the adapter's executor and reports selected TEXT/JSON/binary columns, covering-index candidates for supported aggregate shapes, and an indexed generated JSON expression that matches the query. Existing indexes are inspectable. This first pass requires a single unqualified table and conservative expression matches. Generated expressions are read for PostgreSQL/MySQL; SQLite column inspection does not reconstruct generated expressions from DDL. Unsupported shapes remain explicit limitations. No application query, DDL or index creation is executed by this inspection. EXPLAIN additionally flags plans that actually discard many more rows than they return. That evidence does not prove the planner selected the wrong index. Compare plans and measured behavior before changing indexes; consider write cost and visibility effects. ## Evidence, impact and verification The **Issues** page can sort by observed cumulative issue time or occurrences. These describe retained traffic, reflect sampling and can overlap across findings; they are not predicted savings. Each request's Issues tab shows supporting spans, thresholds and evidence completeness. **Verify a fix** opens a suite seeded from the affected real request, with that issue kind forbidden. Record before the change and compare afterwards. Missing metrics cannot satisfy the policy. Review response differences and measured gains alongside issue resolution; absence from an incomplete observation is not proof of a fix. **Analysis → Suppressions** accepts an exact route, fingerprint and/or callsite with an issue kind, reason and optional expiry. Multiple selectors must all match. Suppressed findings remain stored and can be shown on the Issues page. Expired rules stop matching. Suppressions affect presentation; pytest assertions and check budgets still inspect raw findings. Removing a suppression does not delete traces. **Recording health** shows retained/drop counts, profiling availability and recorded test requests. A request's **Time breakdown and recording health** partitions wall time into database-only, external-only, pool-wait-only, cross-category overlap and remaining time. Concurrent spans are not added twice. Remaining time is uninstrumented time, not measured CPU. Truncated spans, dropped logs and profile errors remain visible. ### Project imports and SQL literal coverage Project scans now follow explicit imports only between files included by the configured scan budgets. Stable aliases, relative imports and package re-exports propagate query helper summaries for up to eight project passes. The JSON `project_inference` field reports the pass count, inferred helper exports and limitations. Exceeding the propagation cap marks the scan incomplete. Wildcards, dynamic imports, unknown application factories and class dispatch may still hide queries; single-file/pasted-source analysis cannot follow imports into other files. Known SQLAlchemy `Session`/`AsyncSession` annotations include Optional, Annotated and bounded string forms. Known sessionmaker/async_sessionmaker factories and their context-manager bindings establish session provenance without importing SQLAlchemy. Arbitrary `get_sessionmaker()` functions and variable names are not assumed to be sessions. `redline check-sql` recovers stable SQLAlchemy text clauses, literal wrappers, small pure SQL templates and imported literal constants from the same bounded scanned set. It never imports the application or evaluates arbitrary Python. Unknown ORM expressions and dynamic SQL remain unresolved and cause exit 2. Runtime capture and isolated explicit compilation remain necessary for those shapes; zero lint findings is not full SQL validation. --- # Database failures, jobs and shared environments These tools are part of the **0.5.0b1 development release**. They extend the existing request profiler; they do not replace application tests, a database migration system or production error monitoring. Recording does not start an exporter. Active load/check, online compilation and export commands contact only their explicitly selected targets. Production rollout is gated by the deployment-specific evidence described in [Production](production.md). ## SQL failures that the application catches An instrumented SQLAlchemy statement that raises now leaves a SQL span with its error category, SQLSTATE/native code when available, duration and source location. A handler may catch the exception and return HTTP 200; its recording still has a `sql_error` issue. Failed statements are counted as attempted queries. A later successful statement does not inherit the error. Sampling's error keep rule includes observed SQL failures, and a span-limit overflow keeps a failure count with an incomplete-evidence finding. Open **Requests → a recording → Issues**, then open the affected SQL span. The drawer shows the driver error, raw rowcount and available connection evidence. Request search also searches the configured request ID, user ID and job ID tags. Existing tag filtering works through `GET api/traces?tag=request_id:example-id`. `application_error` groups unhandled request/job exceptions by type and source location. The existing Issues and release-history views can therefore compare those occurrences across releases. Handled application exceptions outside database instrumentation are not inferred automatically. ## Engine and connection coverage Explicitly registered SQLAlchemy engines work as before. For engines created dynamically: ```python settings = {"instrument_engines": "all"} ``` This installs process-level discovery hooks and lazily instruments engines used by an active opted-in recorder. The mode must be enabled in each worker process that needs it. `explicit` is the default; Flask-SQLAlchemy discovery continues to work in the Flask adapter. `flask_sqlalchemy` is also accepted as a descriptive compatibility setting. No database URL, password or connection string is used as an alias. SQL evidence can include physical-connection age, observed statement number, pool recycle and pre-ping settings, and bounded per-process hourly observations. `connection_churn` requires at least 100 observed creations with recycling configured; `fresh_connection_failure` requires three observed first-statement disconnects within five seconds of creation in an hour. These are correlations, not diagnoses. Initial connections or driver bootstrap statements made before observation can be unknown. Pool invalidation is a separate `connection_failure`; it does not invent an executed SQL statement. Per-process hourly gauges are also flushed to the store's `lifecycle_hourly` history as max-per-hour rows, including for traces that sampling drops. `GET api/lifecycle` returns them for dashboards. They are observed gauges, not a sum across processes, and carry no DSN or credentials. A raw rowcount of `-1` means unavailable. `dml_rowcount_unknown` on SQL Server can suggest reviewing NOCOUNT, OUTPUT/returning results, batches and driver behavior; it does not prove NOCOUNT is enabled or that a write failed. A 404 alone never establishes that cause. `sql_retry_storm` groups attempts of the same statement and callsite inside one trace. It requires at least three attempts after a transient, disconnect, deadlock or timeout failure (the threshold is configurable). It reports the categories and total time; it never retries or resets anything. Direct session switches are observed without issuing probes or resets. SQL Server's NOCOUNT/XACT_ABORT/ANSI/ARITHABORT switches, transaction isolation level, `IDENTITY_INSERT`, language/date/timeout/deadlock settings and `sp_set_session_context` keys are recognized alongside selected PostgreSQL `SET`/`set_config` options and MySQL session/user variables. A checkin finding requires a configured expected value. The default expectation is only `NOCOUNT = OFF`, and SQL Server context keys are declared explicitly: ```python settings = { "session_expected": {"NOCOUNT": "OFF", "XACT_ABORT": "OFF"}, "session_expected_context": ["person_id", "endpoint", "request_id"], } ``` Expected context keys are quiet when set with `@read_only = 1`; a leftover key set with `@read_only = 0`, or a key outside the list, is reported as a lower-severity finding. Values are stored as digests, never plaintext. Generic string-valued options are stored as digests; expected values use the same SQL value spelling. `SET LOCAL` is not treated as a persistent change, and observed PostgreSQL transaction rollbacks restore tracked state. Stored procedures, raw driver cursors and unobserved resets are unknown. Checkin findings require an active recording at checkin; a connection returned after recording ends cannot retroactively amend a stored trace. No automatic connection reset or query retry is performed. ## SQL Server plans and catalogs SQLAlchemy's `mssql` dialect is recorded as `mssql`. On-demand estimated plans use a dedicated connection, separate SHOWPLAN ON/query/OFF calls and rollback. If restoring the session fails, the connection is invalidated. Permission failures are returned as EXPLAIN errors; the database login needs SHOWPLAN and permissions on referenced objects. The parser shows operators, estimated costs/rows, plan-affecting conversions and missing-index candidates. Suggestions never create indexes. Catalog inspection supports one simple `schema.table` reference, selected large column types, existing index columns and visible enabled triggers. Unqualified names use `dbo`; workload catalog verification is limited to `dbo`. Missing metadata permissions produce a limitation, not a clean bill of health. Actual XML plans are opt-in through `explain_analyze = true`, require a synchronous driver with `nextset()`, execute the read query and roll back the transaction. Result consumption is bounded to 100,000 rows and 5 MB of XML. STATISTICS IO summaries recognize English messages only. Rollback cannot undo external side effects of database functions. Async SQL Server actual-plan collection is not implemented. Estimated/actual driver behavior still requires validation against a live SQL Server before claiming production support; XML fixtures and fake executors are not that validation. ## SQL checks without importing an application ```bash redline check-sql app/ services/ --dialect mssql redline check-sql app/ --dialect mssql --json redline check-sql app/ --dialect mssql --junit sql-results.xml redline check-sql app/ --dialect mssql --write-baseline sql-baseline.json redline check-sql app/ --dialect mssql --baseline sql-baseline.json ``` The AST extractor recognizes `text()`/`sqlalchemy.text()`, literal execute calls, module constants and supported constant-only f-strings. Dynamic expressions, syntax errors and scan limits are visible as unresolved input. Source is capped at 200 KB per file; a scan is capped at 200 files, 2 MB and 20,000 filesystem entries. Dependencies and generated folders are excluded, and symlinks are not followed. Local bindings that shadow constants are not replaced with guesses. Rules include bind-like text in comments, bare SQL Server OUTPUT, switches without a reset in the same statement, INSERT SELECT star projections, and missing binds when the parameter mapping is literal. They are conservative candidates: a reset in a separate finally block is not currently proven. Bare OUTPUT does not prove a trigger exists. Use a reviewed baseline or `-- redline: ignore[rule-name]` for accepted candidates. Exit codes are 0 for no new findings, 1 for new findings, and 2 for invalid/unresolved input. An empty finding list does not prove schema correctness. **Analysis → SQL checker** uses the same offline engine on pasted source. It honors `analysis_from_ui` and read-only policy. It accepts no filesystem root, DSN or online SQL. ## Explicit online compilation and schema drift ```bash # Explicit Python files, isolated development database, optional SQLAlchemy dependency: redline check-sql app/queries.py --dialect mssql --dsn "$DEV_DATABASE_DSN" redline check-sql app/queries.py --dsn "$DEV_DATABASE_DSN" \ --schema-snapshot schema-snapshot.json --json ``` Run the snapshot command after a migration to compare the default schema's column names, types and nullability, plus SQL Server trigger and routine-parameter metadata. It updates the local snapshot and, when a previous snapshot exists, recompiles only extracted statements that reference an added, removed or changed table (including a table whose triggers changed). An unchanged schema skips statement compilation; routine-parameter changes recompile everything because those dependencies are not statically resolved. It does not automatically run migrations or certify that all application SQL was extracted. Snapshots are capped at 200 tables, 500 columns per table, 1000 triggers and 2000 routine parameters. Compilation uses SQLite EXPLAIN, PostgreSQL EXPLAIN without ANALYZE, MySQL server-side PREPARE/DEALLOCATE, or SQL Server NOEXEC with cleanup on a dedicated connection. SQL Server parameter types are read from `sp_describe_undeclared_parameters` and declared in the NOEXEC batch; a single read statement also gets `sp_describe_first_result_set` so a literal `row["col"]` read that the SELECT no longer returns is reported as a low-confidence candidate. Only supported single statements are accepted. Parameter values are NULL placeholders; type-dependent validity, temporary objects, stored procedures and runtime permissions may remain unresolved. In particular, SQL Server NOEXEC supports deferred name resolution. Use an isolated development login/database: server compilation can involve extensions or planner functions. Driver messages and DSNs are not included in machine-readable results. ### Watching a development schema ```bash # One check (exit 1 on drift or a compile error), suitable for cron: redline schema-watch app/queries.py --dsn "$DEV_DATABASE_DSN" \ --snapshot schema-snapshot.json # Poll every five minutes and raise a schema_drift Issue in the UI: redline schema-watch app/queries.py --dsn "$DEV_DATABASE_DSN" \ --snapshot schema-snapshot.json --interval 300 --store .redline/redline.db ``` The first run writes the baseline without alerting. Later runs compile only statements that reference affected tables, and `--full` forces a complete pass. `--store` writes one synthetic `TASK` trace carrying a `schema_drift` issue (affected table and routine names only; no rows or SQL text). The command can also run from a Celery beat task or a CI job. Exit `0` means no drift, `1` means drift or compile errors, and `2` means the watch could not run (driver, DSN or permissions). ## Safer shared-development recording ```toml preset = "shared-dev" access = "token" token_file = "/run/secrets/redline-token" storage_path = "/var/lib/redline/{role}.db" storage_role = "web" instrument_engines = "all" [redact] profiles = ["credentials", "pii", "health", "payment"] routes = { "POST /private/*" = "values", "PUT /medical/*" = "body" } ``` Generate a strong token and provide it through a private file or environment; do not put it in a repository. The preset disables bodies, locals, SQL values, replay, load/check/UI analysis and enables read-only UI behavior. Captured logs and free-text exception details are disabled; review application logging separately because Redline does not suppress the application's own handlers. Explicit settings override preset defaults. `capture_sql_params` accepts true, false or `reads_only`. False removes SQL literals and parameters, omits source snippets associated with those SQL spans, withholds SQL error messages that might echo values, and disables EXPLAIN for that recording. `reads_only` retains values only for conservatively recognized read queries. SELECT parameters can contain personal data too; shared-dev defaults to false. Profiles are key/table-pattern starting points, not compliance guarantees. Add `redact_keys`/`redact_tables` for application-specific patterns. Route rules match `METHOD route-template` with shell-style wildcards. `values` preserves JSON structure while masking values; `body` removes body contents. Both also mask SQL values, exception messages/locals, captured log messages and query values before persistence. Free-form text outside a known key cannot reliably be classified. Profile names are `pii`, `health`, `credentials` and `payment`. **Analysis → Redaction preview** uses current key/profile/route rules with invented JSON samples. It sends the sample to this instance but does not save a trace. Capture switches are separate from redaction. `redline audit-store --store /path/to/redline.db` reports bounded possible unmasked-key counts without printing stored values. `capture_loggers` and `ignore_loggers` accept logger-name glob patterns. With `features.replay_writes = false`, the browser only offers GET/HEAD replay. This is a UI control, not authorization for the application's own write endpoints. ## Request and user correlation Configured request/response ID headers become a `request_id` tag; response IDs take precedence at completion. Incoming IDs are available when a job is published. IDs are labels, never authorization credentials. The default headers are X-Request-ID, X-Correlation-ID and `traceparent`. A valid W3C `traceparent` also fills the OTel trace and parent-span ids, and published jobs carry a child `traceparent`. ```python from redline_core import tag from redline_core.users import from_attr settings = {"user_resolver": from_attr("state.user_id")} # ASGI request state # Django: from_attr("user.pk"); Flask: from_attr("person_id") tag("operation", "daily-summary") # no-op outside recording ``` Resolvers are synchronous Python callables invoked late in request handling. Return only an identifier string/integer, not a name or e-mail. Errors are recorded as a resolver-error tag and do not break responses. ## Jobs, stages and row outcomes ```python from redline_core import Recorder, Settings, job, stage, row_outcome from redline_core.storage import SQLiteStore settings = Settings(storage_path="/var/lib/redline/worker.db", capture_locals=False) store = SQLiteStore.from_settings(settings) recorder = Recorder(settings, store) with job("daily-import", recorder=recorder, task_id="run-123"): with stage("write"): row_outcome("succeeded") with stage("summary"): pass store.flush() ``` A job is a TASK recording, searchable by its name/id and visible on **Jobs**. Stage spans, SQL, outcomes and exception evidence use existing recording/issue views. Row outcomes are bounded counters grouped by a digest of the reason; row IDs and samples are not stored. An observed commit before a later failure is called out without claiming the whole job completed. Nested jobs restore the outer recording context. For Celery, install Celery in the worker environment and configure a recorder/store in that worker process: ```python from redline_core.contrib.celery import instrument_celery integration = instrument_celery(celery_app, recorder) # integration.uninstall() removes this instance's signal receivers. ``` Success, failure and retry outcomes are recorded. Publication can carry the current request/parent trace ID. Arguments and results are not captured. Eager-mode tests require no broker; prefork/broker behavior must be tested in the deployment. A task revoked before it starts has no recording. RQ (`instrument_rq`), Dramatiq (`instrument_dramatiq`) and FastAPI/Starlette background tasks are recorded the same way, with trace-context propagation from the enqueuing request; see [Integrations](integrations.md#rq). Their tests use fakeredis, `StubBroker` and a TestClient, so real broker and process-model behavior must still be checked in deployment. ## Storage and mixed frameworks Use private storage outside the repository, preferably a Docker named volume on a local filesystem. Non-dev presets refuse an in-repository path unless `allow_storage_in_repo = true`. Dev warns, and a `.redline` directory is ignored locally. `{role}`, `{hostname}` and `{pid}` placeholders are supported; they do not replace a filesystem/WAL compatibility check. SQLite remains unsuitable for arbitrary network shares. Set `extra_stores` to existing worker store files to browse their request/job traces from the web UI. Secondary files are opened read-only; they contribute browsing/profile lookup, not history, aggregates, live-tail events or mutations. Files should have independent trace IDs. Duplicate IDs are marked in lists; inspection, profiles and single-ID deletion are unavailable for those IDs. Independent file reads are not an atomic snapshot. EXPLAIN/catalog inspection of secondary traces is refused to avoid running a worker's SQL through an unrelated web-process database binding. For a Flask application mounted inside FastAPI, use the outer recorder/store: ```python flask_redline.Redline(flask_app, recorder=outer_redline.recorder, mode="nested") ``` An active outer recording receives Flask route/view spans and errors rather than a second trace. The adapter test uses the a2wsgi WSGI bridge and its copied context. It does not claim equivalent behavior for every WSGI/ASGI bridge. ## Tests, import checks and explicit export The pytest marker now defaults to rejecting SQL errors. It also accepts `no_session_leaks`, `max_round_trips`, and existing query/outbound/issue budgets. `no_sql_errors=False` is an explicit opt-out. `--redline-all` applies SQL-error assertions to every test; a test that records nothing fails. Direct services can use `recorder.recording()` inside `redline_capture()`. Truncation remains a failure for assertions that require complete evidence. `redline check-imports module:attribute` explicitly imports a development target in a subprocess, loads each registered task's module and then the `import`/`from` statements statically visible inside task functions, resolved against the same `sys.path`. It executes module and lazy-import code; run it only in the intended development environment. Runtime branches, dynamic imports and task execution are not covered. A missing lazy module is listed by module name and makes the command exit `1`. `redline check compare/run --ruff [PATH]` carries Ruff's JSON into the existing Markdown and JUnit report; with no `PATH` it runs `ruff check --select F --output-format json`. Redline is not a linter and does not fix findings. ```bash redline export --store /path/to/redline.db # OTLP JSON preview only redline export --store /path/to/redline.db \ --endpoint http://127.0.0.1:4318/v1/traces --send # explicit span transmission redline export --store /path/to/redline.db \ --endpoint http://127.0.0.1:4318/v1/traces \ --logs-endpoint http://127.0.0.1:4318/v1/logs --send ``` The exporter sends a root recording span plus sanitized SQL spans using `db.system`, `db.operation`, `db.statement` (the normalized fingerprint unless `--include-sql` is explicit; the raw statement is then redacted like the HTML export), `error.type` and selected numeric/status attributes. It also builds OTLP log records for recorded issues, with redacted titles. It omits bodies, parameter values, arbitrary tags and error messages. A valid incoming `traceparent` supplies the exported trace id and parent span; otherwise ids are derived from the recording id. It is not a production batching/retry pipeline, and no exporter runs automatically during recording. Routine CI and docs deployment run only on pushes to main, including merges. Package publication follows a successful CI run on main only when the repository variable `REDLINE_RELEASE_VERSION` opts in to the exact package version. The existing PyPI environment approvals still apply. Tags and manual dispatch do not publish this release. Local merges do not trigger remote jobs. ## Production validation targets The production targets are Flask, FastAPI and Django with MySQL and SQL Server. Support must be verified with the actual dialect/DBAPI and process model, not inferred from a shared detector or SQLite demo. | Combination | Required integration evidence | |---|---| | Flask + SQLAlchemy + MySQL | Handled errors, parameter style, counts, connection lifecycle, concurrency and shutdown | | FastAPI + SQLAlchemy + MySQL | The same, with the actual sync/async driver and event-loop behavior | | Django + MySQL backend | Native execute-wrapper failure metadata and row counts, transaction handling and framework middleware behavior | | Flask/FastAPI + SQLAlchemy + SQL Server | pyodbc or the actual selected driver, code classification, session changes, reconnects and first-use failures | | Django + SQL Server backend | The selected Django backend's vendor naming, native wrapper behavior and declared plan-executor capability | | Celery worker, where used | Broker delivery, failure/retry signals, prefork/restart, SQL spans and correlation using explicit worker recorders | The in-process demos exercise the common logic on disposable SQLite databases. Showplan XML fixtures and fake cursor cleanup tests exercise parser/protocol behavior. Neither is live SQL Server validation. Similarly, eager Celery execution does not prove broker or prefork behavior. Keep those distinctions in the release validation report. For production, record and inspect stored traffic with active tooling disabled. Do not copy a demo's debug access, full sampling or active-job routes into a production codebase. The detailed deployment and data-minimization recipe is on [Production](production.md). ### Native Django database evidence Django's execute wrapper records caught database exceptions as failed SQL spans even when the view returns HTTP 200. The trace retains a SQL failure count after its span budget is exhausted, marking the resulting finding as incomplete evidence. Failed statements cannot be explained. Native error codes are classified using the normalized vendor; `microsoft`, `sql_server` and `sqlserver` identify SQL Server. Messages require both `capture_error_details` and the SQL capture policy to allow them. Fetch counting remains active when SQL parameter capture is disabled, so SQLite and other cursors with unknown initial row counts can still report rows actually fetched. Partially consumed results report only consumed rows. An uninspectable cursor leaves rows unknown. Observation never consumes an `executemany` parameter generator. Django's plan executor supports its existing PostgreSQL, MySQL and SQLite paths. The Django SQL Server backend currently has **no estimated or actual plan executor**; recording and structured SQL evidence do not imply EXPLAIN support. SQLAlchemy SQL Server plan handling is a separate integration. Production disables plan execution by default. Native SQL Server and MySQL driver/backend behavior still needs live validation using the selected backend versions before rollout. ### Bounded capture in real workloads Test oversized SQL, custom span data and tags as well as ordinary requests. Separate `max_sql_bytes`, `max_span_data_bytes` and `max_tag_bytes` budgets limit captured values; `max_trace_bytes` checks the completed serialized trace before save. Incomplete evidence must be visible: preserved error counts do not reconstruct dropped SQL or parameters. Include cycles, deep metadata, Unicode, uninspectable objects and a full writer queue in the release checks. These limits complement privacy rules and deployment load tests. The production preset uses tighter budgets than development: queue `64`, span count `500`, SQL `16384`, span data `8192`, individual tags `2048` and completed trace `262144` bytes. Use [the settings table](settings.md#capture-byte-budgets) for minimum values and representation details. Incomplete SQL is not eligible for EXPLAIN; clients and tests must keep the incomplete-evidence warning even when there are no retained error spans. --- # Database [← Index](index.md) ![The Database page: the slowest queries of the demo shop](assets/screenshots/fastapi-database-light.png){ .rl-shot .rl-only-light } ![The Database page: the slowest queries of the demo shop](assets/screenshots/fastapi-database-dark.png){ .rl-shot .rl-only-dark } The request detail page tells you what *one* request did to the database. The **Database** page answers the questions that only make sense across all of them: - Which SQL costs the most in total, even though no single execution is slow? - Where is a given table or column used? - Which index would help the *workload*, rather than a single query? - Which indexes does nobody use? It has three tabs: **Queries**, **Index advisor** and **Unused indexes**, with a window picker (1 h, 24 h, 7 d) applying to all of them. ## Queries: SQL search Every kept trace is summarised by SQL fingerprint at write time (the `trace_sql` table: one row per trace and fingerprint with its count, total and maximum time, and rows). The Queries tab aggregates those rows. Each row is one **fingerprint**, the normalised statement with literals replaced by `?`: | Column | Meaning | |---|---| | SQL | the normalised statement. Click to open a sample request on its SQL tab | | Executions | how many times it ran in the window | | Requests | how many traces ran it | | Total | summed time, the default sort. A cheap query run a million times beats a rare slow one | | Mean, max | per execution | | Mean rows | rows per execution, where the driver reports them | | Routes | which endpoints run it | The search box matches the **normalised SQL** as a case-insensitive substring, so you can type a table (`shop_order`), a column (`customer_id`) or a keyword (`LEFT JOIN`). It is the fastest way to answer "where do we query this table?" and "does anything still use that column before I drop it?". The request list has the same filter: `GET api/traces?sql=shop_order` returns only requests that ran a matching statement. !!! note "Normalised, not raw" Search runs over the normalised statement, so you cannot search for a literal value (`WHERE id = 42`). That is deliberate: it is what lets thousands of executions collapse into one row, and it keeps parameter values out of the aggregate table. ## Index advisor The EXPLAIN drawer already suggests an index for a single query. The **advisor** looks at the whole recorded workload instead, and proposes the indexes that would help the most queries at once. How it works, in order: 1. It takes the 100 SELECT fingerprints that cost the most time in the window and works out, per table, which columns they filter and sort on: equality columns first (`=`, `IN`, `IS NULL`), then one range column (`<`, `BETWEEN`, a prefix `LIKE 'abc%'`) or, without a range, the `ORDER BY` columns. A leading-wildcard `LIKE` or an `ILIKE` becomes a text-search suggestion (`pg_trgm`, FTS5 or `FULLTEXT`) instead of a B-tree. 2. It reads the database's catalog, through the same always-rolled-back connection EXPLAIN uses, and drops every requirement an existing index already serves. 3. It runs a plain `EXPLAIN` (never `ANALYZE`) for the 20 heaviest remaining queries to see which tables are read by a sequential or full scan. Catalog and EXPLAIN share a three-second budget; what does not fit is left unverified. 4. It picks the smallest set of indexes, up to 10, that covers the most query time. Nothing here ever runs DDL. For each candidate you see: | Field | Meaning | |---|---| | Table, columns | the proposed index, with its columns in order | | `CREATE INDEX` statement | ready to copy, for your database's dialect | | Covers | the query fingerprints it would speed up | | Executions | how often those queries ran in the window | | Total time | what those queries cost in the window | | Estimated saving | a heuristic: 80% of the covered time when EXPLAIN showed a scan of that table, 40% otherwise | | Confidence | `high` when a scan was seen, `medium` for an unverified B-tree, `low` for text-search alternatives (not drop-in) and for queries that already avoid a full scan | How to use it: take the top candidate, create the index on a **staging copy**, re-run the [EXPLAIN](explain.md) for one of the covered queries, and compare. The advisor reads recorded SQL, not table statistics, so it can suggest an index that the planner would not use because the table is small or the column has few distinct values. Treat it as a ranked list of things to check. !!! warning "An index is not free" Every index slows down writes and takes disk. Do not create every suggestion. Prefer the ones that cover many queries, and look at the unused-index list before you add the tenth index to the same table. If the store cannot compute the workload (a custom store without `sql_workload`), the tab says the advisor is not available and the API answers `501 not_supported`. ## SQL Server permissions and capabilities Every SQL Server plan and catalog feature needs one specific database permission. Application logins are normally least-privilege, so Redline asks the server once (`HAS_PERMS_BY_NAME`, which reads nothing from your tables and changes nothing) and reports four capabilities: | Capability | Needs | Used for | |---|---|---| | `estimated_plan` | `SHOWPLAN` | the **Plan** button (`SET SHOWPLAN_XML ON`) | | `actual_plan` | `SHOWPLAN` and the right to run the query | actual plans (`SET STATISTICS XML ON`) | | `index_usage` | `VIEW SERVER STATE` (`VIEW DATABASE STATE` on Azure SQL and SQL Server 2022+) | unused indexes (`sys.dm_db_index_usage_stats`) | | `object_definitions` | `VIEW DEFINITION` | seeing the existing indexes, so a suggestion is not for an index that exists | Each is `granted`, `missing` (with the exact `GRANT` for your administrator) or `unknown` (the probe itself failed). See them with `GET api/database/capabilities?db=default`, and `redline doctor` lists them when a plan login is configured (`explain_url` or the `REDLINE_DATABASE_URL` environment variable): ```text ok database SQL Server at mssql+pyodbc://svc:***@host/shop as svc warn db:estimat This login cannot read estimated plans (SHOWPLAN). Ask the DBA: GRANT SHOWPLAN TO [svc]; ok db:index_u Read index usage statistics (VIEW ... STATE). ``` A plan request that hits a missing permission now answers `403 explain_permission` naming the permission and the grant, instead of a raw driver error. Three ways around a missing grant: - **A separate plan login.** Set `explain_url` (a synchronous SQLAlchemy URL such as `mssql+pyodbc://planner:***@host/shop?driver=ODBC+Driver+18+for+SQL+Server`). EXPLAIN, plan and catalog requests for SQL Server databases use it, so the application's own login stays least-privilege. The password is masked everywhere settings are shown. - **Paste or upload a plan.** Save the XML plan from SSMS or Azure Data Studio and `POST api/explain/plan` with `{"vendor": "mssql", "plan": ""}`; it is analysed with the same Showplan analysis, nothing is executed and no database is touched (it works even when `read_only` is on). - **Ask for the grant** shown above. Index suggestions list the **evidence** they were built from (workload, whether a scan was seen in a plan, whether the existing indexes could be read), and their confidence drops one level when the probe shows catalog visibility is partial, because a login that cannot see every object may be missing an index that already exists. ### Managed SQL Server (Azure SQL and similar) Known differences from a self-managed instance, from the vendor documentation. A live managed instance is not yet part of the qualification matrix, so treat this as expected behaviour to verify, not a tested claim: - Index usage counters reset on a **failover**, a restart or a scale operation, so "unused" only means unused since then; Redline says so next to every unused-index result. - Server-level views are restricted; use `VIEW DATABASE STATE` (the probe reports which grant is needed on a managed instance). - Tier limits and automatic tuning can change plans and may drop or create indexes on their own; compare Redline's suggestions with what the service already recommends. ## Unused indexes On **PostgreSQL** and **SQL Server**, Redline lists indexes that have **never been scanned** since the statistics were last reset (primary keys, unique indexes and indexes backing a constraint are excluded). SQL Server additionally resets its usage counters when the instance restarts: | Column | Meaning | |---|---| | Table, index | what it is | | Scans | how many times the planner has used it (0) | | Size | disk it occupies | | Copy DROP | the `DROP INDEX` statement | PostgreSQL reads `pg_stat_user_indexes`; SQL Server reads `sys.dm_db_index_usage_stats` and sizes from `sys.dm_db_partition_stats`. For SQLite and MySQL the page says the detection is not supported (`unused_supported: false` in the API). If the database connection for the alias is missing or the statistics query fails on a supported vendor, `unused_error` carries the reason. The advisor result is cached for 30 seconds per window and database, because it runs catalog reads and EXPLAINs. Add `refresh=1` to recompute at once; the response says `"cached": true` when it was served from the cache. Before dropping anything: - Statistics **reset** on restart, failover or `pg_stat_reset()` (SQL Server also resets on restart). A freshly restarted database makes every index look unused. - Check a **replica** and a **full business cycle**: month-end reports use indexes that nothing else touches. - Unique and primary-key indexes enforce constraints even when they are never scanned. Do not drop them. Redline only reads statistics. It never runs `DROP INDEX` for you. MySQL is qualified against live servers with the pymysql, aiomysql and asyncmy drivers: EXPLAIN findings, verified index suggestions and the recovery from a killed connection. ## Stored procedures Calls to stored procedures are a query kind of their own. `EXEC`/`EXECUTE [schema].[proc] ...` (SQL Server) and `CALL proc(...)` (MySQL, PostgreSQL, also the ODBC `{CALL proc(?)}` form) are recorded with `query_kind: "procedure"` and the procedure name (`dbo.usp_orders`) on the span. Their fingerprint is the procedure alone (`EXEC dbo.usp_orders`), so the SQL list and the [index advisor](#index-advisor) workload aggregate per procedure whatever arguments it was called with. Dynamic-SQL runners such as `sp_executesql` are not named and keep their normal fingerprint. Detectors treat procedure calls with care, because Redline cannot see whether a procedure reads or writes: - **N+1** still groups repeated calls from one line of code (`N+1: 24 queries calling procedure dbo.usp_item_for_order`) and suggests a set-based call. - **Duplicate queries** report repeated identical calls as `info` only, never a warning. - Procedures are never EXPLAINed. ### Ignoring session housekeeping Statements that connection setup runs on every checkout (`EXEC sp_set_session_context ...`, `SET search_path ...`, `SET NAMES ...`) would otherwise flood every trace and inflate query counts. They are skipped by default through the [`ignore_sql`](settings.md) setting, a list of regexes; a batch is only ignored when all of its statements match. Replace the list to ignore more (`ignore_sql = ["^SET\\s", "^EXEC dbo\\.usp_audit_login"]`) or use `[]` to record everything. Failed statements are always recorded, and [session-state tracking](settings.md) still observes ignored statements. ## From the API ```text GET api/sql?q=shop_order&window=24h&limit=100 GET api/indexes?window=24h ``` See [HTTP API](http-api.md#get-apisql) and [HTTP API: indexes](http-api.md#get-apiindexes). --- # Static N+1 scan [← Index](index.md) Runtime detection finds an N+1 only after something has run it, and only on a path your test traffic reached. The **static scan** reads your templates (and, for Django, your serializers) *without running anything*, and flags the patterns that are almost always an N+1. Use it in CI to catch the problem before it ships. ```bash python manage.py redline_scan # Django flask redline scan # Flask ``` ## What it finds ### Template loops A loop whose body reads a relation off the loop variable: ```django {% for order in orders %}
{# one query per order, unless prefetched #} {# a COUNT per order #} {% endfor %} ``` Each of `order.customer.name`, `order.items.count` and `order.items.all` costs a query per iteration unless the view fetched the relation up front with `select_related` or `prefetch_related`. The scanner understands Django and Jinja syntax: comments (`{# #}` and `{% comment %}`), `{% verbatim %}` and `{% raw %}`, nested loops, `{% with %}` and `{% set %}` aliases, filters (`order.customer.name|upper`) and Jinja subscripts (`order['customer'].name`). A template it cannot make sense of is **skipped with a warning**, never an exception. It is dependency-free and best-effort. ### DRF serializers (Django) A `ModelSerializer` with a nested relation serializer, used by a view whose queryset lacks the matching `select_related` or `prefetch_related`. The check is on by default and skipped with `--no-drf`. ## Fewer false positives in Django Without help, any `x.a.b` in a loop could be a plain attribute. In Django the scanner asks the app registry whether the **first hop is a real relation** (a foreign key, one-to-one, many-to-many or reverse relation) and keeps only those chains. It also uses the relation's kind to choose the right fix: `select_related` for a forward foreign key, `prefetch_related` for a reverse or many-to-many relation. Flask has no model registry, so the Jinja dialect cannot check that a hop is a relation and you triage its findings by hand. ## Running it === "Django" ```bash python manage.py redline_scan # every template directory python manage.py redline_scan templates/shop/ # specific files or directories python manage.py redline_scan --json # machine-readable python manage.py redline_scan --fail # exit 1 if anything is found python manage.py redline_scan --dialect jinja templates/jinja/ python manage.py redline_scan --no-drf # skip the serializer check ``` === "Flask" ```bash flask redline scan [--json] [--fail] ``` Runs the Jinja dialect over the template folders of the app and its blueprints (it takes no paths). Output and exit codes are the same. Text output is an aligned table: ```text LOCATION KIND SEVERITY CHAIN SUGGESTION shop/orders/list.html:14 template warning order.customer.name select_related("customer") shop/orders/list.html:17 template warning order.items.all prefetch_related("items") shop/api/serializers.py:22 serializer warning items (nested) prefetch_related("items") on OrderViewSet.queryset 3 possible N+1 finding(s). ``` `--json` prints `{"findings": [...], "warnings": [...]}` where each finding is: ```json { "file": "shop/orders/list.html", "line": 14, "loop_var": "order", "chain": "order.customer.name", "kind": "template", "severity": "warning", "message": "...", "suggestion": "select_related(\"customer\")" } ``` ## In CI ```yaml - name: Static N+1 scan run: python manage.py redline_scan --fail ``` `--fail` exits with status 1 when anything is found. Start by running it without `--fail` to see the baseline, fix or accept what it finds, then turn it on so a new loop with a relation inside cannot slip in. ## Limits - It is **static**. It cannot know that the view already prefetched `customer`, so a finding is "check this", not "this is slow". The runtime detector is the confirmation. - It reads templates and DRF serializers. Python code that does `for o in orders: o.customer.name` is what the runtime detector and its fix diff are for. ## Source analysis: cross-module helpers, dynamic SQL and precision The template scan above has two Python-source companions, `redline analyze` (performance patterns such as a query inside a loop) and `redline check-sql` (raw SQL lint). Neither imports your code; both read the syntax tree within the usual file and byte budgets. **Cross-module helpers.** `analyze` follows a helper that runs a query across files of the scanned project: `from pkg.b import load_user`, `import pkg.b as b; b.load_user()`, `from . import b` and re-exports through a package `__init__` all count. A loop in module A that calls such a helper is reported as a `query_in_loop` candidate. Resolution is bounded (a fixed number of propagation passes), has cycle protection, and only follows files included in the scan; dynamic imports, wildcard imports and class dispatch may be missed. **Dynamic SQL.** `check-sql` evaluates SQL text built from constants without running anything: f-strings with constant parts, `+`, `%` and `.format()` on module-level constants, `" ".join([...])` of literals, `+=` accumulation, and straight-line local reassignments inside a function. Anything inside a branch, loop or `try`, a parameter, a call result or an attribute stays unresolved. `.format()` fields with attribute or index access are refused. Unresolved inputs are counted by reason in the report (`--json`): ```json {"unresolved_by_reason": {"call": 2, "sqlalchemy_expression": 1, "unknown_name": 4}} ``` Each entry of `skipped` also carries a `category`. Categories: `unknown_name`, `call`, `attribute_or_subscript`, `operand`, `unsafe_format`, `unsafe_helper`, `sqlalchemy_expression`, `too_large`, `too_deep`, `limit`, `invalid_source`, `unreadable`, `compilation` and `dynamic` (anything else). **Measuring false positives.** `scripts/measure_static_precision.py` runs both analyzers over a labelled corpus (`packages/redline-core/tests/fixtures/static_precision`) and prints precision, recall and false-positive rate; a test keeps precision above a floor. Lines marked `# expect: ` are true positives; `# fp: ` marks a shape the analyzer is known to report wrongly (it counts against precision until fixed). ```bash uv run python scripts/measure_static_precision.py # the bundled corpus uv run python scripts/measure_static_precision.py --json ``` On your own codebase: ```bash uv run python scripts/measure_static_precision.py src/ > findings.txt # lists finding ids # review them; put the ids that were wrong into reviewed.json, e.g. ["a1b2...", "c3d4..."] uv run python scripts/measure_static_precision.py src/ --false-positives reviewed.json --json ``` The result gives the false-positive rate overall and per finding kind for your code, which is the number to use when deciding whether to gate CI on a rule. --- # Large and unbounded results [← Index](index.md) A query can be perfectly indexed and still be the slowest thing in the request, because of how much it returns. Fetching, building model objects and serializing 40,000 rows costs far more than finding them. Three detectors cover the ways this goes wrong. They all read two facts the adapters now record on every `sql` span: how many **rows** came back, and whether the statement has a **`LIMIT`**. | Kind | Fires when | Default | |---|---|---| | `large_result` | a SELECT returned at least this many rows | `large_result_rows = 1000` | | `unbounded_query` | a SELECT with no `LIMIT` returned at least this many rows | `unbounded_rows = 200` | | `inefficient_count` | a count or existence question answered by loading rows | a source-line pattern | Severity is `warning`, and `critical` once the row count is five times the threshold. ## Large result ```text Large result: 48,210 rows from shop_order (shop/reports.py:31) ``` The detail says what to do: paginate, stream in chunks, or select fewer columns. Where the adapter's fix suggester can tell which columns are wide (text, blob and JSON fields), the issue lists them (`extra["wide_columns"]`), because dropping those is often the cheapest fix: ```python # Before: every column, including a 40 KB `notes` field, for 48,000 orders orders = Order.objects.filter(status="open") # After: only what the report needs, and a chunked iterator orders = Order.objects.filter(status="open").only("id", "total").iterator(chunk_size=2000) ``` ## Unbounded query ```text Unbounded query: 1,350 rows, no LIMIT from shop_product (shop/views.py:12) ``` The query has no `LIMIT`, `FETCH FIRST`, `TOP` or `ROWNUM`, and returned a lot. It is fast today and keeps getting slower as the table grows, which is exactly why it is worth flagging at 200 rows and not waiting for 200,000. `has_limit` is computed from the SQL text; a limit inside a subquery does not count as the top-level limit. Add pagination (`[:50]`, `.limit(50)`, keyset pagination) or, if you really do need all of it, iterate in chunks. ## Count and exists `inefficient_count` looks at the **source line** that issued the query (the callsite) and recognises four idioms: | Source line | What went wrong | Suggested | |---|---|---| | `len(orders)` | loaded every row to count them | `orders.count()` | | `bool(orders)` | loaded every row to see if there are any | `orders.exists()` | | `if orders:` | same, through truthiness | `orders.exists()` | | `orders.count() > 0` (also `!= 0`, `>= 1`, `== 0`) | counted every match to compare with zero | `orders.exists()` | ```python # Before pending = Order.objects.filter(status="pending") if pending: # SELECT every column of every pending order notify(len(pending)) # After pending = Order.objects.filter(status="pending") if pending.exists(): # SELECT 1 ... LIMIT 1 notify(pending.count()) # SELECT COUNT(*) ``` When the source line can be located, the issue carries a one-line fix (`fix_line`) shown as a diff. Severity is `info` for small tables and `warning` when the query returned at least `unbounded_rows` rows or took at least `slow_query_ms`. A query that is already bounded (`first()`, `get()`, a slice) is skipped. The detector only inspects the callsite line itself, so `len([1, 2])` on a line that does not run a query never fires. The `.count()` and `.exists()` names are Django ORM spellings; for SQLAlchemy the hint is the same idea (`select(func.count())`, `select(exists())`). ## Where the numbers come from `rows` is the cursor's `rowcount` when the driver reports one, otherwise the number of rows the ORM or driver has fetched so far (adapters update the span as rows are fetched, so a lazily iterated queryset shows the rows actually read). When neither is known the span has no `rows`, and these detectors skip it: they never guess. The **Database** page ([Database](database.md)) shows mean rows per fingerprint across all requests, which helps spot a query that returns a lot only occasionally. ## Settings | Setting | Default | |---|---| | `large_result_rows` | `1000` | | `unbounded_rows` | `200` | See [Settings](settings.md#detectors). --- # Transactions and locks [← Index](index.md) A database transaction holds a connection from the pool and, once it has written anything, row locks that other requests can queue behind. The longer it stays open, the worse both get. Redline records every transaction as a span and reports the two patterns that hurt most. ## The `transaction` span | Adapter | Where the span comes from | |---|---| | Django | `transaction.atomic` (the decorator, the context manager and `ATOMIC_REQUESTS`). The first atomic block entered while a trace is active opens the span; nested blocks (savepoints) only bump a depth counter | | SQLAlchemy (FastAPI, Flask, Litestar) | the engine's begin, commit and rollback events | The span's data: | Key | Meaning | |---|---| | `db_alias` | which database | | `outcome` | `commit` or `rollback` | | `queries` | statements run inside | | `http_out` | outbound HTTP calls made while the transaction was open | Empty transactions and control statements such as `SAVEPOINT` are not counted, so a read-only request with `ATOMIC_REQUESTS` does not fill the timeline with noise. Queries inside the transaction carry `in_transaction: true` in their span data. ## Long transactions `long_transaction` fires when a transaction span lasts at least `long_transaction_ms` (default 200). `critical` at five times that. ```text Transaction open for 1,840 ms (12 queries, rolled back) shop/services.py:88 ``` Typical causes, in order of how often they show up: 1. **Work that does not need the transaction** inside it: rendering, serializing, sending an email, hashing a password. 2. **An outbound call** (see below). 3. **A loop of writes** that should be a bulk operation. 4. **Waiting on a lock** another transaction holds. The queries are fast; the time is spent waiting. Fix by narrowing the `atomic` block (or the `with session.begin()`) to the statements that must be atomic, and doing everything else before or after it. ## External call inside a transaction `external_in_transaction` fires when a `transaction` span has `http_out > 0`: ```text HTTP call to api.payments.example while a transaction was open shop/checkout.py:41 ``` This is worse than it looks. A slow or failing third party now holds your connection and your locks, and a rollback cannot undo the call: you may have charged a card for an order that no longer exists. The standard fix is to commit first and call afterwards, or to record the intent in the transaction and let a background job make the call (the *transactional outbox* pattern). Use `transaction.on_commit` in Django. ```python # Before: the charge happens inside the transaction with transaction.atomic(): order = Order.objects.create(...) gateway.charge(order) # http_out inside a transaction # After: charge only once the order is safely committed with transaction.atomic(): order = Order.objects.create(...) transaction.on_commit(lambda: gateway.charge(order)) ``` ## Pool waits When SQLAlchemy checks a connection out of its pool and has to wait, Redline records a `pool_wait` span if the wait is 1 ms or more. The data says which database, the pool size and how many connections were already checked out: ```text pool_wait db_alias=default pool_size=5 checked_out=5 waited 340 ms ``` A request that spends its time here is not slow because of its own queries. The pool is exhausted: other requests hold connections too long (often *because* of a long transaction or an external call inside one), or the pool is simply too small for the concurrency. Look at the `long_transaction` issues first. In a [load test](load-testing.md), pool waits are the typical shape of a knee: latency climbs while each individual query stays fast. ## Lock waits Redline does not read `pg_locks`. A lock wait appears as a slow query or a long transaction whose queries are individually trivial. The tell is a statement that is fast under `EXPLAIN` (see [EXPLAIN](explain.md)) but slow in the trace, concentrated on the same table or row from several requests. Reading `pg_locks` is on the [roadmap](roadmap.md). ## Settings | Setting | Default | Meaning | |---|---|---| | `long_transaction_ms` | `200` | Minimum open time reported as `long_transaction` | There is no setting for `external_in_transaction`: any outbound call inside a transaction fires it. To see outbound calls at all you must instrument the client ([Integrations](integrations.md)). --- # GraphQL [← Index](index.md) GraphQL is the natural home of the N+1: a query asks for `orders { customer { name } }` and the default resolver loads each customer separately. The SQL is fine one query at a time and bad in total, and the SQL alone does not tell you *which field* to fix. Redline adds a `resolver` span for each non-trivial field resolution. SQL that runs inside a resolver nests under that span, so the N+1 detector can name the field: ```text N+1: 24 queries on shop_customer from resolver orders.*.customer ``` List indexes in the path are shown as `*`, so `orders.0.customer`, `orders.1.customer` and so on are one issue. The path is also stored on the issue (`extra["resolver_path"]`). ## Strawberry ```python import strawberry from redline_core.contrib.strawberry import RedlineExtension schema = strawberry.Schema(Query, extensions=[RedlineExtension]) ``` Works for sync and async resolvers. Attribute resolvers that do no work are dropped, so the trace shows resolvers that ran SQL or took time. `strawberry-django` needs nothing extra: its resolvers run through the same hook, and the Django adapter already records the ORM queries they issue. The `redline-core[strawberry]` and `redline-core[graphene]` extras install the matching GraphQL library if you want them pinned together. ## Graphene ```python from redline_core.contrib.graphene import RedlineMiddleware result = schema.execute(query, middleware=[RedlineMiddleware()]) ``` Coroutine and promise results are handled. ## What it looks like In the request's **Timeline** a resolver span (kind `resolver`) sits between the view and its SQL, with `path`, `field` and `parent_type` in its data. In **Issues** the N+1 card names the resolver path and, for a Django project, the usual `select_related` or `prefetch_related` diff. For GraphQL the right fix is often a `DataLoader` rather than an ORM change; the diff is a hint for the ORM-level fix when the resolver reads a model relation directly. | Span data | Meaning | |---|---| | `path` | `orders.*.customer` with list indexes as `*` | | `field` | the field name | | `parent_type` | the GraphQL type that owns the field | ## Tips - **One endpoint, many operations.** All GraphQL requests hit `POST /graphql`, so they aggregate on the [Endpoints](issues-and-endpoints.md#endpoints) page as one route. The resolver paths in [Issues](issues-and-endpoints.md#issues) are how you tell operations apart. - **Query size.** A deeply nested query can create thousands of resolver spans. `max_spans_per_trace` (default 2000) still applies: counts stay exact, spans beyond the cap are folded. - **Load testing.** A scenario can POST a fixed query body: ```toml [[requests]] name = "orders" method = "POST" path = "/graphql" json = { query = "{ orders { id customer { name } } }" } ``` See [Load testing](load-testing.md). --- # Blocking in async [← Index](index.md) An `async def` handler runs on the event loop, one thread shared by every request. A synchronous call inside it, `time.sleep`, `requests.get`, a sync ORM query, a big `json.dumps`, does not just slow *that* request. It stops the loop, so every other in-flight request waits too. It is the most common way to make an async service slow, and it is invisible in a profiler that only times one request at a time. Redline detects it and names the call. ## What you see An issue of kind `blocking_in_async`: ```text Event loop blocked 412 ms by requests.get (shop/views.py:57) ``` with a `blocking` span in the Timeline at the moment of the stall, and the calling line as the callsite. Spans with the same call and callsite are one issue, so `time.sleep` in a loop is reported once with its count and total. | Severity | When | |---|---| | `warning` | a stall of at least `blocking_ms` (default 20 ms) | | `critical` | a stall at five times that or more | ## How it works Both mechanisms are active **only while at least one request is in flight** on a loop. An idle process pays nothing. 1. **A lag monitor.** A timer re-arms itself every 5 ms on the event loop (`loop.call_later`, no task) and measures how late it fires. A tick that is late by `blocking_ms` or more means the loop was stalled. The stall becomes a `blocking` span with `reason = "loop_lag"`. 2. **A watchdog thread.** One per process. When a tick is overdue by half of `blocking_ms`, it samples the loop thread's stack with `sys._current_frames()`. That sample gives the stall its callsite (the innermost project frame), the blocking call (`time.sleep`, `requests.get`, `sync ORM`, ...) and, through the running task, the request it belongs to. A sample without a project frame keeps the culprit unknown. A sampled SQLAlchemy frame is labeled `SQLAlchemy work`: compilation/materialization can block even with an async driver, so the sample alone does not establish synchronous database I/O. 3. **Sync driver hooks.** When a synchronous database driver is called on the loop thread itself (a sync ORM query inside an `async def` view), the SQL hook marks it as a `blocking` span with `reason = "sync_call"`, so you see "sync ORM" even for a query that was individually fast. If the culprit cannot be told apart from the other requests in flight, the stall is attributed to every request that was running on that loop at the time, because each of them really was blocked. A stall that is still in progress when the request finishes (`time.sleep(1)` followed by a `return`) is flushed when the trace is finished, so it is not lost. ## Fixing it | Blocking call | Fix | |---|---| | `time.sleep(n)` | `await asyncio.sleep(n)` | | `requests.get(...)` | `httpx.AsyncClient`, or `await asyncio.to_thread(requests.get, ...)` | | a sync ORM or driver call | the async driver (`asyncpg`, `aiosqlite`), `AsyncSession`, or `sync_to_async` / `run_in_threadpool` | | CPU-heavy work (hashing, parsing, image resize) | `await asyncio.to_thread(...)` or a process pool | | a threading lock held on the loop | restructure; do not block the loop on a lock | A plain `def` handler in FastAPI and Litestar (`sync_to_thread=True`) runs in a worker thread, not on the loop, so it cannot cause this issue. ## Settings | Setting | Default | Meaning | |---|---|---| | `detect_blocking` | `True` | Run the monitor in async adapters. Set it false to remove the monitor entirely | | `blocking_ms` | `20` | Minimum stall that is recorded and reported | The overhead is the timer callback, a few microseconds every 5 ms per busy loop. See [Performance](performance.md). ## Which adapters | Adapter | Behaviour | |---|---| | FastAPI | Lag monitor, watchdog and sync-driver hooks | | Django on ASGI | Lag monitor and the sync ORM hook, for `async def` views | | Litestar | Lag monitor (the app runs inside it while a request is recorded) | | Django on WSGI, Flask | No event loop to watch: not applicable | ## Work on threads and pools Offloading work to a thread is the usual fix for blocking the loop, and it creates a new blind spot: a plain `threading.Thread` or `ThreadPoolExecutor` worker does not inherit the request's `contextvars`, so the queries and calls made there are recorded against no request and the time shows up as [unattributed](detectors.md#unattributed-time). ```python from redline_core.contrib.threads import instrument_threads instrument_threads() # once, at startup ``` From then on, when a request is being recorded, `ThreadPoolExecutor.submit` (and so `map` and `loop.run_in_executor`) and `Thread.start` run the work in a copy of the current context, as `contextvars.copy_context().run` would: - the spans stay **under the request**, with the span that was open at the call as parent; - each span recorded on another thread has the thread's name in `span.data["thread"]` (`ThreadPoolExecutor-0_1`, or the `name=` you gave a `Thread`), so three queries run on a three-worker pool show as three SQL spans with three distinct thread names; - spans from several threads can be recorded at once; the trace builder appends them under a lock. `uninstrument_threads()` restores both methods; calling `instrument_threads()` twice is harmless. Outside a recorded request the wrappers do nothing. It is not enabled by `auto_instrument`, and `redline instrumentation` lists it as `threads`. Limits: - Work still running when the request finishes is **not** recorded. The trace is closed, so later spans are dropped; they are not attached to a finished request and are not turned into a separate job the way [background tasks](fastapi.md#in-process-background-tasks) are. Wait for the futures before returning if you want them counted. - Only threads started *inside* a recorded request get its context. Long-lived pool workers created earlier keep a clean context between tasks; each task gets its own copy. - Threads whose name starts with `redline` (the store's writer, the loop watchdog) are never touched. `ProcessPoolExecutor` and `multiprocessing` are not covered: a child process has no recorder. ## Limits - The lag monitor measures a loop that is *late*, which is the right signal but is not proof of a specific line. The sampled stack is the best available evidence. - A stall shorter than `blocking_ms` is invisible by design. Lower the setting to see smaller ones, at the cost of more noise. - Work in C extensions that release the GIL is not a stall; work that holds it is. --- # Slow serializers [← Index](index.md) Turning objects into a response is real work. A Django REST Framework serializer with nested relations, or a Pydantic response model over a few thousand items, can take longer than the query that fetched the data, and a profiler that only shows "the view" hides it. Redline times serialization as its own span kind and reports it when it is slow. ## The `serializer` span | Data key | Meaning | |---|---| | `library` | `drf`, `pydantic`, `marshmallow` or `other` | | `serializer` | the class or model name | | `items` | how many objects were serialized, when known | | `many` | whether it was a list | Where each comes from: | Library | How it is recorded | |---|---| | **DRF** (Django) | `BaseSerializer.data` for `Serializer`, `ModelSerializer` and `ListSerializer`. Only the outermost call is a span; nested serializers run inside their parent's `to_representation` and are part of its time | | **Pydantic** (FastAPI) | `fastapi.routing.serialize_response`: response-model validation plus the dump, nested models included | | **Marshmallow** | `Schema.dump`, if you call [`instrument_marshmallow()`](integrations.md#marshmallow); the outermost dump only | Serializers built by hand inside a `SerializerMethodField` are covered by the parent serializer's span. ## The `slow_serializer` issue `slow_serializer` fires when a serializer span takes at least `slow_serializer_ms` (default 50 ms). It is `critical` at five times that. Spans of the same serializer class from the same callsite are one issue, with the run count and the total. ```text Slow serializer: OrderSerializer took 340 ms for 1,200 items (shop/api.py:44) ``` The item count tells you whether the cost is **per item** or a fixed cost: 340 ms for 1,200 items is 0.28 ms each, and the fix is to return fewer items or cheaper ones; 340 ms for three items is something pathological inside the serializer. ## Usual causes and fixes | Cause | Fix | |---|---| | A nested serializer or a `SerializerMethodField` that runs a query per item (this will also be an [N+1](n-plus-one.md), and the serializer span *contains* those SQL spans) | `select_related` / `prefetch_related` on the view's queryset, or `selectinload` | | Returning every row | paginate; see [Large and unbounded results](result-size.md) | | Heavy per-item Python (date formatting, computed fields) | compute in the database (`annotate`), cache, or do it once outside the loop | | Validating a response model for data you built yourself | `response_model_exclude_unset`, a lighter model, or return the model instance directly | The static [N+1 scan](static-scan.md) also checks DRF serializers for nested relations whose queryset lacks the matching `select_related` or `prefetch_related`, before you ever run the code. ## In the UI A serializer span appears in the Timeline in its own colour, between the view and the response. Its drawer shows the library, the class and the item count. The span's SQL children, if any, nest under it. ## Settings | Setting | Default | |---|---| | `slow_serializer_ms` | `50` | --- # External calls [← Index](index.md) Most backends spend more time waiting on other services than on their own database. The payment gateway, the email API, the search cluster, a partner's REST endpoint: each is an `http_out` span in the trace, and together they are a page of their own. ## Recording them Outbound calls are recorded once you instrument the client you use ([Integrations](integrations.md)): ```python from redline_core.contrib.httpx import instrument_httpx from redline_core.contrib.requests import instrument_requests instrument_httpx() instrument_requests() ``` A span records method, URL (query-string secrets masked), status and duration. In the Timeline it is purple and named `GET api.example.com/v2/users/42`. ## Detectors Three detectors read `http_out` spans in one request: | Kind | Fires when | Severity | |---|---|---| | `slow_external` | a call takes at least `slow_external_ms` (default 500), grouped by method, URL without query string, and callsite | `critical` at 5x | | `duplicate_external` | the same method and **full URL** is called twice or more | `warning` at 5 copies, or when together they exceed `slow_external_ms` | | `retry_storm` | the same method and **host** is called three or more times with at least one failure | `critical` at 6 calls | A *failure* here means a 5xx, a 429, or no status at all (timeout, connection error). A group that is already a retry storm is not reported again as a duplicate. ```text Retry storm: 5 calls to api.mailer.example, 3 failed (shop/notify.py:19) Duplicate external call: GET api.rates.example/usd ×4 (shop/pricing.py:62) Slow external call: POST api.payments.example/charge, 1.8 s (shop/checkout.py:41) ``` Common fixes: cache the response for the duration of the request (a duplicate), cap the retries and add jitter (a storm), set a short timeout and move the call off the request path (slow), and never call out inside a transaction ([Transactions and locks](transactions.md#external-call-inside-a-transaction)). ## The External page Across requests, **External calls** groups every outbound call by method, host and a **URL pattern**: digit runs, UUIDs and hex strings of eight or more characters become `*`, so `/v2/users/42` and `/v2/users/77` are one row, `/v2/users/*`. | Column | Meaning | |---|---| | Method, Host, URL pattern | the group | | Calls | total calls in the window | | p95, max | latency. p95 is taken over each request's *mean* for the pattern (exact when a request calls it once) | | Errors, error rate | 5xx, 429 and status-less calls | | Duplicates | requests that called this pattern two or more times | | Retries | requests with three or more calls and at least one error | The window picker (1 h, 24 h, 7 d) and the sort let you find the slowest dependency first. The same data is served by `GET api/external?window=` ([HTTP API](http-api.md#get-apiexternal)). It is derived from the `trace_ext` table, so it reflects *kept* traces: with sampling, counts are of the sample. ## Settings | Setting | Default | |---|---| | `slow_external_ms` | `500` | --- # Cache efficiency [← Index](index.md) A cache that nobody checks tends to rot: keys that always miss, values written and never read, a hot key that expires and sends fifty requests to the database at once. The **Cache** page looks across recorded requests for those three things. ## Recording | Source | How | |---|---| | Django cache framework (any backend) | recorded by `django-redline` automatically | | redis-py, sync and asyncio | [`instrument_redis()`](integrations.md#redis) | Each operation is a `cache` span with `op`, `key`, `backend` and, for reads, `hit`. For the aggregate, keys are reduced to **patterns**: digit runs, UUIDs and hex strings of eight or more characters become `*`, but digits glued to a preceding letter or digit are kept. So `user:42:profile` and `user:77:profile` are both `user:*:profile`, while `v2` stays `v2`. Which commands count: | Class | Commands | |---|---| | Reads | `get`, `get_many`, `get_or_set`, `has_key`, `mget`, `hget`, `hmget`, `hgetall`, `exists`, `getex`, `getdel` (and Django's async `a...` variants) | | Writes | `set`, `add`, `set_many`, `setex`, `psetex`, `setnx`, `mset`, `hset`, `hmset`, `incr`, `decr`, `incrby`, `decrby` | | Deletes | `delete`, `delete_many`, `del`, `unlink`, `hdel`, `clear` | Spans with no key (a Redis pipeline is one keyless span) are skipped. ## The page One row per backend and key pattern: | Column | Meaning | |---|---| | Gets, hits, misses | reads, and how they resolved | | Hit rate | `hits / (hits + misses)`. Blank when the backend does not say (a plain `EXISTS`) | | Sets, deletes | writes and invalidations | | Unread sets | writes to a pattern that had **no reads at all** in the window | | Stampedes | bursts of three or more requests that missed the **same pattern within one second** | ### Reading it - **Low hit rate on a hot pattern.** The TTL is too short, the key includes something that varies (a timestamp, a random id), or the data is never reused. A pattern that is read often and hits rarely is wasted round trips. - **Unread sets.** You pay to compute and store a value that nothing ever fetched. Delete the write, or find the reader that uses a different key spelling. - **Stampedes.** The classic *thundering herd*: a popular key expires and every concurrent request recomputes it. Add a lock around the recompute, stagger expirations with jitter, refresh before expiry, or serve stale while one worker refreshes. ## API `GET api/cache?window=` returns the same rows. See [HTTP API](http-api.md#get-apicache). ## Limits - Statistics come from *kept* traces. With `sample_rate = 0.1` they describe a 10% sample; rates are still meaningful, absolute counts are not. - Stampede detection uses request **start times** and a one-second window, so it can miss a stampede spread over several seconds and can flag requests that merely arrived together. - A key built from a short alphanumeric id (`user:ab12`) is not collapsed, so such patterns stay separate rows. --- # Logs and exceptions [← Index](index.md) A slow or failing request is a story, and the SQL timeline is only half of it. The other half is what your own code said while it ran: the `logger.warning("retrying payment")` two lines before the 500, and the value of `order` at the moment it raised. Redline now keeps both with the trace. ## Logs Every record your application logs **during a recorded request** is filed under that request. Open a request and choose the **Logs** tab. ```text +12.4 ms INFO shop.cart Loaded cart for user 42 shop/cart.py:31 +96.0 ms WARNING shop.payments Gateway slow (retry 1) shop/payments.py:77 +311.8 ms ERROR shop.payments Gateway timeout, giving up shop/payments.py:84 ``` Each row has the time since the request started, the level, the logger name, the message and the file and line of the log call (project-relative, clickable if [open in editor](the-ui.md#open-in-editor) is configured). ### How it is captured Redline does not add a logging handler or change any logger's level. The first recorder with `capture_logs` wraps the log record factory (`logging.setLogRecordFactory`, keeping whatever factory was installed before), so your own `logging.basicConfig(...)`, `dictConfig(...)` or `basicConfig(force=True)` work exactly as without Redline, before or after it is configured. Each record is filed under whichever request is active in the current `contextvars` context, so concurrent requests and threads do not mix. Outside a request a record costs a single `ContextVar.get()`. Records from Redline's own `redline` loggers are ignored so it can never recurse. Python only creates a record when the logger is enabled for its level, so capture follows **your** logging levels and `log_level` is an additional minimum on top. To capture INFO your loggers must be at INFO: Django's default `LOGGING` and most configured apps are. An app that never configured logging has its root logger at WARNING, so only WARNING and above are captured there (call `logging.basicConfig(level=logging.INFO)` to get INFO too). | Setting | Default | Meaning | |---|---|---| | `capture_logs` | `True` | Master switch | | `log_level` | `"INFO"` | An extra minimum level for stored records, on top of your loggers' own levels. `"WARNING"` is a good production value | | `max_logs_per_trace` | `200` | Cap per request. Extras are counted in `logs_dropped` and the UI says how many were dropped | Messages are formatted, **redacted** and capped at 2,000 characters. Redaction looks for `key=value`, `key: value` and `"key": "value"` pairs whose key matches `redact_keys` (`password=...`, `"token": "..."`) and masks the value; passwords inside URLs (`https://user:password@host`) and secret query-string values are masked too. It is the same key-based rule as everywhere else, so a secret that appears bare in a sentence ("the code is 4821") is **not** masked. See [Security](security.md#logs-and-locals). !!! tip "Logs in the trace list" The **Logs** tab on a request shows only records from that request. To find requests that logged a particular problem, open the request that raised it and follow the linked issue; logs are not searchable across requests (that is a job for your log pipeline). ## Exceptions with locals When a request raises an unhandled exception, the trace's `error` has always held the type, message and traceback. With `capture_locals` (on by default) it also keeps the **project frames** of the traceback together with the local variables in each, which is usually the fastest way to see *why*: ```text OrderError: no stock for sku 'A-77' shop/services.py:58 in reserve item = stock = order = shop/views.py:21 in checkout request = cart = {'A-77': 3, 'B-10': 1} ``` Open the request and choose the **Exception** tab: each frame is expandable, with the source line, the variables, and an open-in-editor link. ### What is kept | Limit | Value | |---|---| | Frames | project code only (library frames are not captured), innermost last, at most 20 | | Locals per frame | at most 30 | | Each value | its `repr`, truncated at 300 characters | | Names starting `__` | skipped | | Unprintable objects | shown as `` | ### What is masked A local whose **name** matches `redact_keys` (`password`, `token`, `api_key`, `session`, `card`, ...) is replaced by `[redacted]`. A local that is a dict or other mapping has its secret-looking **keys** masked before it is printed. This is key-based, so it has the same blind spot as the rest of redaction: a secret held in a variable with an innocent name (`x = request.headers["Authorization"]`), or inside a model's `repr`, is shown as it is. Locals can contain personal data too: an `order` object's `repr` may include a customer's name or email. If that is a concern, turn the feature off and keep the traceback: ```python REDLINE = {"CAPTURE_LOCALS": False} ``` The `production` [preset](configuration.md#presets) does exactly that. The `locals` and `logs` [feature switches](access-control.md#feature-switches) turn the two features off from the access-control side. ### Settings | Setting | Default | |---|---| | `capture_locals` | `True` | ## Cost Logs: one `ContextVar.get()` per record outside a request; inside, building one small object (message formatting, redaction and a callsite lookup). Locals are captured **only when a request raises**, from the traceback, so the happy path pays nothing. ## Correlating your own logs and error reports Redline's recordings, your log files and your error tracker can all point at the same request through the Redline trace id. ```python import logging from redline_core.correlation import TraceIdFilter handler = logging.StreamHandler() handler.addFilter(TraceIdFilter()) # a handler filter sees every record handler.setFormatter(logging.Formatter("%(asctime)s [%(redline_trace_id)s] %(message)s")) logging.getLogger().addHandler(handler) ``` `redline_trace_id` is the id of the request or job being recorded, `-` outside one. The filter never drops a record. `install_log_filter()` adds it to the root logger's existing handlers. Search the id in the UI (`/_redline/#/requests/`). **Sentry.** Without importing anything from Sentry at module level, Redline can tag events that happen inside a recording and add an "Open in Redline" link: ```python import sentry_sdk from redline_core.correlation import chain_before_send sentry_sdk.init( dsn=..., before_send=chain_before_send(None, base_url="https://dev.example.com"), ) ``` The event gets the tag `redline_trace_id` and a `redline` context with `trace_id` and `open_in_redline`. `base_url` defaults to `$REDLINE_PUBLIC_URL`; pass `mount="..."` when the UI is not at `/_redline`. Pass your existing hook as the first argument to keep it. `tag_sentry_scope()` sets the same tag and context on the current scope instead (a no-op when `sentry_sdk` is not installed). Remember that Redline is for development and staging: only link to a UI that exists where the event happens. **OpenTelemetry.** Exported spans (`redline export --send`) carry the attribute `redline.trace_id`, next to the W3C trace id, so a collector can link back to the recording. --- # Working with AI agents Redline is built so a coding agent can find a performance problem, fix it and prove the fix, using recorded data instead of guesses. Everything here is read-only unless stated; the few tools that send load or delete data stay off until the operator turns them on. ## Machine-readable docs | File | What it is | |---|---| | [`/llms.txt`](llms.txt) | Index of every page with a one-line summary ([llmstxt.org](https://llmstxt.org) format) | | [`/llms-full.txt`](llms-full.txt) | All pages in one file, for loading into a context window | | [`/reference/settings.schema.json`](reference/settings.schema.json) | Every setting with its type and default (JSON Schema) | | [`/reference/cli.json`](reference/cli.json) | Every command and flag | They are generated by `scripts/build_llms.py`; CI fails when they are stale. ## Give your agent the instructions ```bash redline agent-skill --write ~/.claude/skills # a Claude skill: .../redline/SKILL.md redline agent-skill --format agents --write . # AGENTS.redline.md to merge into AGENTS.md ``` The text covers how to find problems, fix them and verify, and the rules below. ## MCP server ```bash redline mcp --store .redline/redline.db [--audit .redline/agent-audit.jsonl] ``` It speaks the Model Context Protocol over stdio (line-delimited JSON-RPC) and opens the store read-only. Example client entry: ```json { "mcpServers": { "redline": { "command": "redline", "args": ["mcp", "--store", ".redline/redline.db"] } } } ``` Every tool takes a JSON-schema-checked argument object. Results are bounded in size, and credentials in URLs, tokens, header and cookie values and identity values are never returned (only their names). **Findings and traces** | Tool | Returns | |---|---| | `list_issues` | Findings ranked by sampled impact, each with `why`, callsite and suggestion | | `explain_issue` | One finding in full | | `fix_prompt` | A Markdown brief for fixing one finding, with constraints and how to verify | | `diagnose_preview` | Exactly what `redline diagnose --send` would transmit; never sends | | `list_traces` | Recorded requests, filterable by route, method, status, duration, queries, issues | | `get_trace` | A bounded request summary: timings, issues, slowest spans (no bodies or logs) | | `compare_traces` | Two requests side by side: time by kind, SQL that appeared or vanished | | `list_endpoints` | Per-route latency percentiles, error rate and query counts | | `search_sql` | Normalised SQL statements with counts and timings | | `index_advice` | Index suggestions from the recorded workload (offline) | | `cache_summary`, `external_summary`, `job_summary` | Cache hit rates, outbound call latency, background task outcomes | | `history`, `compare_periods`, `list_releases` | Latency history, before/after comparison of two periods, release markers | | `llm_summary` | Sampled LLM-call tokens and counts per route and model | | `instrumentation_report` | What redline cannot see: inactive integrations, truncated traces, drops | **Load runs** | Tool | Returns | |---|---| | `list_load_runs` | Recent runs with status, knee step, max OK rps and verdict | | `get_load_run` | One run: steps with latency percentiles and errors, the scenario (header, cookie and identity values removed) and its summary | | `load_run_summary` | The analysis: knee, `flows`, `recovery`, `drift`, `identities` (names and counts), `limiting_resource`, `resources` | | `load_run_bottlenecks` | Per step, the queries and routes that slowed most, with callsites | | `load_run_metrics` | CPU, memory, GC, threads and connection-pool numbers per step and the likely limiting resource (`GET api/runs/ID/metrics`) | | `validate_scenario` | Parses a scenario (object or `.json`/`.toml` file in the working directory) and returns errors or a summary; never runs it | | `generate_scenario_from_openapi` | A scenario from an OpenAPI document; writes get weight 0; header values are not returned | | `generate_scenario_from_traces` | A scenario weighted by the traffic recorded in the store | | `generate_scenario_from_stages` | A staged (spike, soak, recovery) scenario from `10:30s,200:20s,10:60s` or a stage list | **Database, SQL and checks** | Tool | Returns | |---|---| | `database_capabilities` | What the plan login may do (`GET api/database/capabilities`). The MCP server holds no database connection, so it answers `supported: false` unless a connection is registered in its process | | `analyze_sql_plan` | Analyses a pasted SQL Server XML plan (operator tree, findings, suggested indexes); nothing is executed and the plan is not echoed back | | `lint_sql`, `scan_sql_source`, `scan_sql_project` | Offline SQL lints for a statement, Python source text, or a directory inside the working directory | | `analyze_source`, `analyze_project` | Static performance review of Python source or a directory | | `doctor` | The setup checks of `redline doctor` for the working directory (`database` and `production` add the permission probe and the production checklist) | | `check_report` | Summary of a saved `redline check compare --json` report | | `check_findings` | Findings new in a saved report, each with a fix brief | | `verify_fix` | gone / still_present / inconclusive from a saved compare report | **State-changing tools (off by default)** | Tool | Needs | What it does | |---|---|---| | `start_load_run` | `--allow-load --load-target URL` | Starts a background load run against the operator's fixed target; one run at a time; scenarios that read local files or import code (`data`, `identities_file`, `metric_sources`) are refused | | `stop_load_run` | `--allow-load` | Asks a running load run to stop gracefully | | `delete_load_run` | `--allow-delete-runs` | Deletes a finished run and its steps | ```bash redline mcp --store .redline/redline.db --allow-load --load-target http://127.0.0.1:8000 ``` Without the flags these tools are neither listed nor callable. The target is fixed by the operator: a `base_url` in an agent's scenario is ignored, so an agent cannot aim load at another host. The server itself still opens the store read-only; a started run is a separate `redline load` process that writes its own results. Bad input produces an error result the model can read; the server keeps running. With `--audit`, each call is appended as a JSONL record containing the tool name, argument *names* and timing, never argument values. The file is created with mode 0600. ## The fix loop ```bash redline fix-prompt ISSUE_ID --store .redline/redline.db > brief.md # evidence + constraints redline check record check.toml # baseline, before editing # ...the agent edits the code... redline check compare check.toml --json report.json redline check verify report.json --kind n_plus_one # exit 0 only when gone ``` `verify` answers `gone`, `still_present` or `inconclusive`. A finding is only `gone` when it was in the baseline, is absent now, responses are equal, and the run had enough samples with complete server metrics. If it says `inconclusive`, collect more samples; do not declare success. See [Refactor check](refactor-check.md#verify-a-fix). ## Reviewing agent-written code in CI ```yaml - run: redline check compare check.toml --json report.json --fail-on slower,changed,broken,budget - run: redline check findings report.json --new-only --json > findings.json # exit 1 if any ``` `findings` lists issues that are new relative to the baseline and includes a fix brief for each, which an agent step can consume. Pair it with the pytest markers (`@pytest.mark.redline(max_queries=…, no_n_plus_one=True)`) and the `redline check ratchet` query-count ratchet so a change cannot quietly add queries. ## AI-assisted diagnosis ```bash redline diagnose ISSUE_ID --store .redline/redline.db # preview only, nothing is sent redline diagnose ISSUE_ID --store .redline/redline.db --send # opted in: really sends ``` Off by default. The default run prints the exact request (destination, model and body) and exits. Sending needs three things together: `--send`, `ai_diagnosis = true` in the settings, and the key in the `REDLINE_AI_API_KEY` environment variable. The destination host is fixed for the provider (`api.anthropic.com`); it cannot be redirected. The body is an allowlist of finding fields (kind, title, evidence, SQL *shape* with literals replaced, file, line, function and one line of source) passed through the redactor. Request and response bodies, logs and LLM prompt text are never part of it. Errors report the HTTP status only, never the key or the provider's response body. Agents must not enable this themselves. ## Rules for agents - Never capture, log or paste prompt or completion text, tokens, passwords or request bodies. - Do not delete traces or run EXPLAIN ANALYZE against a production store. - Do not weaken a test, threshold or budget to make a finding disappear. - Do not push, tag or publish without the owner's approval. - Do not enable `ai_diagnosis` or set `REDLINE_AI_API_KEY`; only the owner opts in. ## Safe deployment recipe Run the app with `read_only = true` and `explain_analyze = false`, point `redline mcp` at a *copy* or read-only mount of the store, and keep `--audit` on. Without `--allow-load` and `--allow-delete-runs` the MCP process cannot write to the store or send traffic at all. --- # LLM-call observability Redline records calls to the Anthropic and OpenAI SDKs as `llm_call` spans, next to the SQL and HTTP spans of the same request, and flags patterns that waste time or money. **Privacy.** Only metadata is stored: provider, model, token counts, status, whether the call streamed, a 16-character hash of the prompt and its length. Prompt text, completions, tool arguments and exception messages are never recorded. ## Turn it on ```python from redline_core.contrib.anthropic import instrument_anthropic from redline_core.contrib.openai import instrument_openai instrument_anthropic() # Messages.create and AsyncMessages.create instrument_openai() # chat.completions.create, sync and async ``` Both return `False` when the SDK is not installed, are idempotent, and leave the SDK's behaviour and exceptions unchanged. Calls made outside a traced request cost one context-variable read. `redline instrumentation` lists them under integrations. **Streaming.** A streamed call is recorded with `stream: true` and no token counts, because usage is only known when the stream ends. Totals therefore undercount when you stream. ## Findings | Kind | Fires when | Default | |---|---|---| | `duplicate_llm_call` | The same model got an identical prompt (same hash) repeatedly in one request | 2 calls | | `serial_llm_calls` | Calls ran back to back with no overlap | 3 calls | | `llm_in_transaction` | A call started while a database transaction was open | always | | `llm_call_loop` | One request made many calls (agent loops, per-item calls) | 8 calls | | `uncached_large_prompt` | A large non-streamed Anthropic prompt used no prompt-cache tokens | 4000 characters | Settings: `llm_duplicate_threshold`, `llm_serial_min`, `llm_loop_calls`, `llm_prompt_cache_chars`. A value of `0` disables that detector. Limits worth knowing: - `serial_llm_calls` is a candidate, not a verdict. A trace shows timing, not whether a later prompt needs an earlier answer. - `duplicate_llm_call` compares hashes of the prompt-bearing arguments (system, messages, tools, input). Model output may legitimately differ between identical prompts. - `uncached_large_prompt` only looks at Anthropic, whose caching is opt-in. OpenAI caches automatically. - Hashes are computed over at most the first two million characters of the arguments. ## Usage summary ```text GET api/llm?window=24h ``` Returns sampled calls, errors, streamed calls, `input_tokens`, `output_tokens`, `cache_read_tokens` and `cache_creation_tokens` per route and model, with totals. Agents get the same data from the `llm_summary` MCP tool. Prices are not included because they change; multiply the token counts by your own rates. Only the newest 300 traces in the window are scanned and counts are labelled sampled. ```python PRICE_PER_MTOK = {"claude-x": (3.0, 15.0)} # your own numbers: (input, output) cost = sum(PRICE_PER_MTOK[r["model"]][0] * r["input_tokens"] / 1e6 + PRICE_PER_MTOK[r["model"]][1] * r["output_tokens"] / 1e6 for r in data["items"] if r["model"] in PRICE_PER_MTOK) ``` --- # Load testing [← Index](index.md) Load testers such as Locust, k6 and Gatling see an application from the outside. They can tell you the p95 doubled at 150 requests per second. They cannot tell you **which query** went from 3 ms to 410 ms. Redline's profiler sees the inside, one request at a time. The load tester joins the two: it drives your app at a controlled rate, tags every request, and then shows, per step of the test, **what got slower inside the server**. ```text Bottlenecks 10 rps 50 rps 100 rps 150 rps growth SELECT ... FROM shop_order ... 3.1 ms 4.0 ms 62 ms 410 ms 132x GET /api/orders 18 ms 24 ms 120 ms 690 ms 38x ``` It ships in `redline-core`. Install the `load` extra (it needs `httpx`): ```bash pip install "redline-core[load] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` The command is `redline`. ## Concepts You can skip this section and use the [quickstart](#quickstart), but the three ideas below decide whether a load test tells you the truth. ### Open versus closed model ```mermaid flowchart LR subgraph closed["Closed model: N users in a loop"] direction LR u1[user] --> s1[send] --> w1[wait for response] --> t1[think] --> u1 end subgraph open["Open model: fixed arrival rate"] direction LR clock(["clock: R requests per second"]) --> s2[send] --> srv[server] clock --> s3[send] --> srv clock --> s4[send] --> srv end ``` A **closed** model runs N virtual users in a loop: send a request, wait for the response, think, send the next. When the server slows down, the users slow down too, so the offered load *falls* exactly when you most need it to hold. The test politely stops hurting the server it is meant to stress. An **open** model sends requests at a fixed arrival **rate**, whether or not earlier ones have finished, the way independent users on the internet behave. When the server slows down, requests pile up, queues grow and latency climbs, which is what happens in production. Redline uses the open model: you choose requests per second, not users. Many internal applications are sized by a fixed number of logged-in users, not by a rate. For that, keep the open model and add **sessions**: an arrival starts one *session* (a flow), the session waits `think_s` between its steps like a person reading a page, and by Little's law the number of sessions in flight is the arrival rate times the session length. 20 arrivals per second with 5 s of think time holds about 100 sessions at once, and the run reports the peak per step ([Sessions and think time](#sessions-and-think-time)). The offered load still does not fall when the server slows. ### Coordinated omission A load generator that waits for each response before sending the next one measures the wrong thing: if one request stalls for two seconds, it silently *omits* the requests it should have sent in that time, and the slow period is under-counted. This is **coordinated omission**, and it makes latency charts look much better than reality. Redline schedules each arrival on a timetable and measures latency from the **scheduled** time, not from when the request was finally sent. If the generator was late, or the connection pool was busy, that waiting counts. Arrivals that cannot even be started because too many requests are already in flight are counted as **dropped** and shown in the results, never hidden. ### The knee Plot achieved throughput and p95 latency against offered load. For a while the server keeps up: latency is flat, throughput follows the target. Then, at some load, it bends: latency shoots up, errors appear, or throughput stops following the target. That bend is the **knee**, and the load just before it is your **maximum healthy rate**. Redline finds the knee for you in a ramp or step test. It is the first complete step where any of these is true: - p95 is more than **2x** the first step's p95; - the error rate is above **1%**; - the achieved rate is below **90%** of the target. The p95 rule compares with the first step, so the first step can only be the knee through errors or a missed target. A step cut short by a stop is reported but never decides the knee. ## Quickstart 1. Start your app (with Redline mounted, so the run can be correlated; see below). 2. Generate a scenario from what Redline already knows: ```bash redline load init --from-traces -o scenario.toml ``` or from an OpenAPI schema: ```bash redline load init --from-openapi http://localhost:8000/openapi.json -o scenario.toml ``` 3. Open `scenario.toml`, check the `base_url` and the request list, and set weights. 4. Run a step test: ```bash redline load scenario.toml --steps 10:100:10 --step-duration 20s ``` That is 10, 20, ... 100 requests per second, 20 seconds each. 5. Read the table, then open the run in the UI (the link is printed at the end as "Open the run in Redline: …") to see the chart and the bottlenecks. The link uses `--ui-url`, else the scenario's `ui_url`, else `mount_path` from your project's Redline config, else `/_redline`; with Django (mounted where your URLconf puts it, often `/redline/`) pass `--ui-url /redline` or set `ui_url` in the scenario. ```text redline load: browse → http://127.0.0.1:8000 run 7c1e...: steps 10 to 100 rps by 10, 20s each step target achieved sent ok err drop p50 p95 p99 max err% 1 10.0 10.0 200 200 0 0 12ms 21ms 38ms 64ms 0.0% 2 20.0 20.0 400 400 0 0 13ms 23ms 41ms 70ms 0.0% ... 7 70.0 69.8 1396 1390 6 0 41ms 190ms 420ms 910ms 0.4% 8 80.0 71.2 1424 1380 44 0 210ms 1.40s 2.10s 3.50s 3.1% total: sent 6420 ok 6370 errors 50 dropped 0 p50 38ms p95 410ms p99 1.80s knee: step 8 – error rate 3.1% > 1% max ok rps: 69.8 verdict: saturated (knee at step 8 (80 rps): error rate 3.1% > 1%) ``` !!! warning "Test an environment you own" A load test is an attack on whatever it points at. Run it against your own local, staging or review environment. Never point it at a production system, a shared dependency or someone else's service. In a shared staging environment, tell the people who use it. ### Correlating with the app Every request carries a header `X-Redline-Run: ;step=`. A Redline-instrumented app turns it into the trace tags `run_id` and `step`, as long as that run is in the app's store and running (or ended less than a minute ago): a made-up header tags nothing, and a run with `--no-store`, or written to another store, does not tag the app's traces. The **bottleneck** analysis joins those tags with the per-query summaries, so the app must be recording the load. Remember [sampling](production.md#sampling): in a profile that keeps 5% of requests you still get enough traces at high rps, but at 5 rps you may get none. Requests tagged with a run that is registered in the app's store and running are always kept (`sampled_by` is `run`), so a low-rate step still produces traces without changing `sample_rate`. The run itself (its steps and latency histograms) is written to the same store the app uses. The default is `.redline/redline.db` in the working directory, and `--store` points elsewhere, so run the command from the app's directory or pass the path. The UI then lists it under **Load**. ### Checking that the app records the run Before the first step, `redline load` can send one harmless request (the scenario's first enabled `GET`, tagged `step=probe`, which the bottleneck analysis ignores) and look for the trace it should have produced. If none appears it says why it usually happens: the app uses a different store than the run, sampling dropped the request, or recording is disabled. - With `--store-url` or `--register-url` the probe is on by default and only warns. - With a file store it is off, so existing runs send no extra request; add `--probe` to turn it on. - `--require-recording` stops the run (status `failed`) instead of warning. - `--no-probe` skips it; `--probe-timeout 10s` waits longer for a slow writer. ### Generator and application on different machines When the generator runs on another host (or the app runs in a container) there is no shared file, and a run written to a local file would tag none of the app's traces. Two options: - **Shared store.** Point both at the same PostgreSQL database: `redline load scenario.toml --store-url postgresql://...` (or set `storage_url` in the project's config, which `redline load` picks up when `--store` is not given). The URL's password is never printed. - **Register over HTTP.** With no shared store, the generator tells the application about the run: `redline load scenario.toml --register-url https://app.example/_redline`. The application must enable `accept_remote_runs` (off by default, and always off while `read_only` is on). The Redline access token is read from `REDLINE_TOKEN` or `--token-file`, never from the command line. The generator checks the application is reachable and accepts the token before the first request, and only runs registered this way can be changed over HTTP, never runs written by a local process. ## Profiles A profile says how the rate changes over time. | Mode | Shape | Parameters | |---|---|---| | `constant` | one step at a fixed rate | `rps`, `duration_s` | | `ramp` | the rate rises (or falls) linearly | `start_rps`, `end_rps`, `duration_s`, `step_duration_s` (default 5 s) | | `steps` | a staircase | `start_rps`, `end_rps`, `step_rps`, `step_duration_s` (default 30 s) | | `stages` | any shape: spike, soak, a pause | `stages`: a list of `{ rps, duration_s }` (`rps = 0` is a pause) | Results are reported **per step**. A ramp is reported in steps too (each at the ramp's rate at the step's midpoint), so the knee finder works on it. Prefer `steps` when looking for a knee: each step is long enough for a stable p95, and "the server held 70 rps and broke at 80" is a sentence you can act on. ### Spikes, soaks and custom shapes `stages` runs an ordered list of `{ rps, duration_s }` stages, each reported as one step: ```toml [profile] stages = [ { rps = 10, duration_s = "1m" }, # normal { rps = 200, duration_s = "30s" }, # the spike { rps = 10, duration_s = "3m" }, # does it recover? ] ``` On the command line: `--stages 10:1m,200:30s,10:3m`. A soak is one long stage (`--stages 40:30m`). Two extra analyses make these shapes useful: - **Recovery.** A step where the rate *falls* never decides the knee (that is recovery, not saturation). Instead the summary reports, for each such step, the p95 before the spike, the peak, and how many seconds after the step began p95 was back within 25% of its level before the spike for three seconds running (`recovered_after_s`, or `null` if it never was). - **Drift.** Any step of 30 s or more is checked for slow growth, comparing its first third with its last: `degrading` when p95 grew by 25% and at least 5 ms with a positive slope, or the error rate climbed by a percentage point; otherwise `stable`. The summary has the slope in ms per minute, and `drift_verdict` is `degrading` if any step is. A leak shows up here long before the knee. `stop_on` ends the run after the first step that breaches a limit, so a test does not keep hammering a server that has already fallen over: ```toml [profile] mode = "steps" start_rps = 10 end_rps = 200 step_rps = 10 step_duration_s = "20s" stop_on = { error_rate = 0.05, p95_ms = 2000 } ``` Arrivals are evenly spaced by default. `poisson = true` (or `--poisson`) uses random inter-arrival times with the same mean, which is closer to independent real users and produces burstier queues. ## Scenario reference A scenario is a **TOML** file (Python 3.11 or newer, or the `tomli` package), a **JSON** file, or a **Python** file that defines `SCENARIO = {...}`. ```toml name = "browse" base_url = "http://127.0.0.1:8000" headers = { Accept = "application/json" } timeout_s = 10 [[requests]] name = "orders" path = "/api/orders/?page={random_int:1:20}" weight = 3 [[requests]] name = "order detail" path = "/api/orders/{random_int:1:500}/" weight = 5 [[requests]] name = "add to cart" method = "POST" path = "/api/cart/" json = { sku = "A-1", qty = 1 } expect_status = [200, 201] [profile] mode = "steps" start_rps = 10 end_rps = 100 step_rps = 10 step_duration_s = "20s" stop_on = { error_rate = 0.05, p95_ms = 2000 } ``` ### Top-level keys | Key | Default | Meaning | |---|---|---| | `name` | file name | Shown in the UI | | `description` | | Free text | | `base_url` | required, here or with `--base-url` | `http://` or `https://` root of the app. Requests use paths only | | `headers` | `{}` | Sent with every request | | `timeout_s` | `10` | Per-request timeout. A timeout is an error | | `requests` | required | A non-empty list. At least one needs `weight > 0` | | `profile` | constant 10 rps for 30 s | See [Profiles](#profiles) | | `workers` | min(CPUs, 8) | Worker **processes** | | `connections` | `64` | Keep-alive connections per worker | | `max_inflight` | `1000` | In-flight cap per worker; arrivals beyond it are counted `dropped` | | `seed` | random | Integer seed for placeholders and request choice, for repeatable runs | | `ui_url` | config `mount_path`, else `/_redline` | Where the Redline UI is mounted (path on `base_url`'s host, or a full URL); only used for the printed link | | `identities`, `identities_file`, `identity_mode` | none | Many users instead of one: see [Identities](#identities) | | `data` | none | CSV / JSON Lines files that fill `{data:source.column}`: see [Data feeds](#data-feeds) | | `auth` | none | A token provider refreshed during the run: see [Token refresh](#token-refresh) | | `flows` | none | Weighted journeys of chained requests: see [Flows](#flows). `requests` may then be empty | Durations accept a number of seconds or strings such as `"20s"`, `"2m"`. ### Request keys | Key | Default | Meaning | |---|---|---| | `name` | method and path | Label in results | | `method` | `GET` | `GET`, `HEAD`, `OPTIONS`, `POST`, `PUT`, `PATCH`, `DELETE` | | `path` | required | Must start with `/`. May contain placeholders | | `weight` | `1` | Relative frequency. `0` keeps the request in the file but never sends it | | `headers` | `{}` | Added to the top-level headers | | `json` | none | A JSON body; sets `Content-Type: application/json` | | `body` | none | A raw string body | | `expect_status` | any status below 400 | A list of acceptable status codes. Anything else counts as an error | | `expect` | none | Rules the response must satisfy: see [Response checks](#response-checks) | | `max_ms` | none | A success slower than this counts as an `assertion` failure | | `extract` | none | Values to read from the response for later steps of a [flow](#flows) | ### Placeholders Rendered separately for every request: | Placeholder | Result | |---|---| | `{random_int:A:B}` | a random integer from A to B, inclusive | | `{random_choice:a\|b\|c}` | one of the listed values | | `{uuid}` | a fresh random UUID (32 hex digits, no dashes) | | `{data:source.column}` | a value from a [data feed](#data-feeds); also works in headers, JSON and raw bodies | Any other `{...}` in a path is an **error**, so an OpenAPI path such as `/orders/{id}` can never be sent by accident. ### Flows Real traffic is journeys: list, open one item from that list, save it. A random detail id often does not exist or is not the caller's, so much of the load turns into cheap 403 and 404 responses. A flow is an ordered list of requests that one arrival runs: ```toml [[flows]] name = "browse" weight = 3 [[flows.steps]] path = "/items" extract = { id = "$.items[0].id" } # a JSON path (shorthand), or ... # extract = { tok = { header = "X-Next" }, n = { regex = "id=(\\d+)", group = 1 } } [[flows.steps]] path = "/items/{var:id}" # {var:name} works in the path, headers, JSON and body expect = [{ json = "$.name" }] ``` One arrival starts one flow, so the open model stays intact. The latency of a flow is measured from its scheduled start to the end of its last step, and each step has its own numbers. A failed step ends the flow and is counted **once** as a flow error, with the class of the failing step (a status code, an exception, `assertion`, or `extract` when a value the next step needs was not in the response). The identity and data row stay the same for the whole flow. The run summary has a `flows` entry (runs, errors, p50/p95/p99, per-step counts and percentiles) that the CLI prints, and the app's traces carry `flow` and `fstep` tags next to `run_id` and `step`, so the bottleneck table gets rows for every step of the journey. Plain requests and flows can be mixed; each arrival picks one by weight. ### Sessions and think time A flow can model a user instead of a burst: ```toml [[flows]] name = "shopper" think_s = [2, 6] # seconds between steps: a number, "3s", or a [min, max] range own_connection = true # each session opens its own connection, like a separate browser [[flows.steps]] path = "/products" [[flows.steps]] path = "/products/{var:id}" ``` `think_s` is picked at random per pause (seeded by the scenario `seed`) and a stop cuts it short. The flow's latency includes the pauses, a step's own latency does not. With `own_connection` the session does not share the worker's keep-alive pool: it connects, sends its steps and closes, so the server sees as many connections as there are sessions. Every step of the run table reports the **peak sessions in flight** (summed over the workers' own peaks), printed by the CLI and in `summary.sessions`. To hold N sessions of length L seconds, use `rps = N / L`. ### Response checks Under load many apps answer `200` with an error body, an empty list or a truncated payload; by default those count as successes. Add `expect` to a request (one rule or a list): | Rule | Passes when | |---|---| | `{ json = "$.items[0].id" }` | the JSON path exists (`exists = false` to require it absent) | | `{ json = "$.status", equals = "ok" }` | the value equals this | | `{ contains = "text" }` / `{ not_contains = "text" }` | the body does / does not contain it | | `{ min_bytes = 200 }` | the body is at least this large | | `{ header = "Content-Type", contains = "json" }` | the header exists (and `equals` / `contains` match) | A failed rule is counted as its own error class, `assertion`, in the error breakdown, and `max_ms` does the same for a response slower than an agreed limit. Failure reasons never include body or header values. ### Several generator hosts (agents) A generator on the machine under test distorts both sides, and one host caps the offered rate. Run `redline load agent` on other hosts and point the controller at them: ```bash # on each generator host (token file mode 0600; use TLS or a private network) redline load agent --listen 0.0.0.0:7700 --token-file agent.token --cert agent.pem --key agent.key # on the controller redline load scenario.toml --steps 100:1000:100 \ --agents https://gen1.internal:7700,https://gen2.internal:7700 \ --agent-token-file agent.token --agent-ca ca.pem ``` The controller computes the step plan once and gives each agent its share of the workers (up to 8 each, never more than the peak rps), numbered globally, so the union of all hosts' arrivals is exactly the planned rate. One shared start time is converted to each agent's clock from a measured offset, and every agent's per-second numbers (counters and latency histograms) stream back and merge exactly like local workers', so steps line up to the second. The controller runs no workers itself unless you also pass `--workers`. Stopping the run (Ctrl-C, `stop_on`) stops the agents; an agent that disappears fails the run with a clear message. What the controller sends is the scenario's requests plus its identities and data rows **inline** (an agent reads no files), so the config, including credentials, crosses the network: use TLS (`--cert`/`--key`, verified with `--agent-ca`) or a private network. An agent needs a token (at least 16 characters), listens on `127.0.0.1` unless told otherwise, refuses `auth.provider` `command` and `python` (use `request`), blocks link-local and metadata targets, and can be limited with `--allow-target URL_PREFIX` (scheme, host and port must match exactly; names are resolved and every address checked, but a name that changes its answer later, DNS rebinding, is not caught: use the allow-list). Each worker also reports its own CPU use. A step where a generator worker was above 90% of a core is marked `generator_limited` (and listed in `summary.generator.limited_steps`): the generator, not the app, may have capped the rate there, so add agents before believing the knee. ### Streams and WebSockets Every request is timed to its **first byte** (headers received) as well as to its **last byte**. The step table's latency is the last byte; first byte is in each step's `ttfb_p50_ms` / `ttfb_p95_ms` and the run summary, and the CLI prints both. A response that streams for a while shows the difference: the first byte is what the user feels. A request can hold a connection open instead of finishing: ```toml [[requests]] name = "live feed" type = "stream" # server-sent events or a chunked response path = "/events" hold_s = 30 # how long to hold it open weight = 1 [[requests]] name = "chat" type = "websocket" # needs: pip install "redline-core[load-websocket]" path = "/ws" messages = ["hello", { type = "ping" }] # sent in order; each reply is timed hold_s = 60 # then keep the connection open this long reply_timeout_s = 5 ``` For these, the latency in the step table is the time to the **first byte** (stream) or to the **handshake** (WebSocket): the hold is not latency. Each step also reports how many were held, events received (a server-sent event, or a chunk for other streams), messages answered, the **highest number open at once** (summed over the workers' own peaks, so exact only when they are balanced), the time to the last byte of a stream and the connect and reply latency of WebSockets. A held stream occupies one of the worker's `connections` and an arrival slot (`max_inflight`): to hold 500 at once with 2 workers set `connections = 300` or more. They cannot carry a request body, and headers (identities, tokens) are sent on the handshake. ### Browser pages Browser-side cost (rendering, bundle size, requests per page) is out of scope: Redline does not drive a browser. To get the *server* side of real page loads grouped like a load run, run a browser automation script (any tool) that adds one header to every request of a page load: ```text X-Redline-Run: ;step=1;page=checkout-17 ``` with a run registered in the app's store (`redline load` registers one; or POST `api/runs/register` with `accept_remote_runs`). The app tags those traces with `page`, and `GET api/runs/{id}/pages` sums them per page load: requests, total server time, queries and the slowest route. ### Identities One set of credentials makes the app see one user thousands of times: per-user caches stay warm and row-level filters always pick the same rows. Give the run many users: ```toml identity_mode = "round_robin" # or "random" (seeded) or "sticky" identities_file = "users.csv" # name, header:X-Api-Key, cookie:session ... [[identities]] name = "alice" headers = { Authorization = "Bearer ${ALICE_TOKEN}" } # ${VAR} reads the environment cookies = { sid = "${ALICE_SID}" } ``` Inline identities come first, then the file's. CSV columns are `name`, `header:` and `cookie:`; a `.jsonl` file holds `{"name", "headers", "cookies"}` objects. A missing environment variable fails the run before any request, naming the variable. Header order: scenario `headers`, then the identity's, then the request's own. `round_robin` cycles through every identity (all workers together visit them in order), `random` picks with the scenario `seed`, and `sticky` gives each worker process one fixed identity (one virtual user per process). Only the identity **name** is ever recorded: as the `identity` tag on the app's traces (filter with `tag=identity:alice`), and as per-identity request counts in the run summary. `GET api/runs/{id}/bottlenecks?identity=alice` splits the bottleneck table to one user. Header and cookie values are masked in the stored run config. ### Data feeds Uniform random identifiers hit rows that do not exist and hit every real row equally, so the page cache and query plans behave nothing like production. ```toml [[data]] name = "orders" file = "orders.csv" # CSV with a header row, or .jsonl pick = "zipf" # "sequential", "random" or "zipf" (first rows hottest) zipf_s = 1.1 # skew for zipf [[requests]] path = "/orders/{data:orders.id}" json = { sku = "{data:orders.sku}" } ``` Relative files resolve against the scenario file. Every reference to one source in a request uses the same row. A missing file or column fails the run before any request. `zipf` and `random` follow the scenario `seed`. `redline load init --from-traces --data-dir DIR` writes the distinct paths seen per endpoint as such files, most used first, instead of one sample path per endpoint. ### Token refresh Short-lived tokens expire mid-run and every request then fails with 401, which looks like a knee. An `auth` block gets a token before the run and refreshes it before it expires, outside the latency numbers: ```toml [auth] provider = "request" # "command", "request" or "python" request = { method = "POST", path = "/login", json = { user = "load", password = "${LOAD_PW}" } } extract = "data.access_token" # dotted path into the JSON response expires_extract = "data.expires_in" # lifetime in seconds (or set ttl_s) refresh_before_s = 30 ``` `command = ["get-token", "--env", "perf"]` runs a program (no shell) and reads its output; `callable = "package.module:function"` calls a Python function returning the token or `(token, ttl_s)`. The token goes in `Authorization: Bearer ...` (`header` and `prefix` change that). Each worker refreshes on its own; refresh calls are never counted in the histograms. If a refresh fails twice, the run stops with an error instead of reporting 401s as server errors. The stored config masks command arguments and request credentials. `auth`, `identities`, `identities_file` and `data` can run a program or read a file, so they are accepted only from a scenario file, never from the UI or `POST api/runs`. ### Authentication Put credentials in `headers`. Do not commit tokens: read them from the environment in a Python scenario. ```python # scenario.py import os SCENARIO = { "name": "authenticated browse", "base_url": "http://127.0.0.1:8000", "headers": {"Authorization": f"Bearer {os.environ['LOAD_TOKEN']}"}, "requests": [{"path": "/api/orders/", "weight": 1}], "profile": {"mode": "constant", "rps": 50, "duration_s": 30}, } ``` ## CLI reference `redline load SCENARIO [options]`. Options override the scenario: | Option | Meaning | |---|---| | `--rps N` | constant rate | | `--ramp A:B` | ramp from A to B rps over `--duration` | | `--stages RPS:DURATION,...` | ordered stages, for example `10:1m,200:30s,10:3m` (spike) or `40:30m` (soak) | | `--agents URL,URL` | run workers on remote `redline load agent` hosts; the controller runs none unless `--workers` is given | | `--agent-token-file PATH`, `--agent-ca PATH` | the agents' token (else `REDLINE_AGENT_TOKEN`) and the CA bundle that verifies their TLS certificates | | `--steps A:B:STEP` | steps from A to B rps, STEP apart, each `--step-duration` | | `--duration 60s` | total duration (default 30 s for constant and ramp) | | `--step-duration 30s` | length of each step | | `--poisson` | Poisson arrivals instead of evenly spaced | | `--workers N` | worker processes | | `--base-url URL` | override the scenario's `base_url` | | `--ui-url PATH\|URL` | where the Redline UI is mounted, for the printed link (overrides the scenario's `ui_url`) | | `--name TEXT` | run name | | `--store PATH` | store to write the run to (default `.redline/redline.db`) | | `--store-url URL` | write the run to a shared PostgreSQL store (`postgresql://...`) | | `--register-url URL` | register the run with the application over HTTP (needs `accept_remote_runs` there) | | `--token-file PATH` | file holding the Redline access token for `--register-url` (else `REDLINE_TOKEN`) | | `--no-store` | do not write to a store | | `--probe`, `--no-probe` | send (or skip) one tagged `GET` before the run to check the app records it. On by default with `--store-url` / `--register-url`, off with a file store | | `--require-recording` | stop the run when the probe request is not recorded (default: warn) | | `--probe-timeout 5s` | how long to wait for the probe trace | | `--json OUT` | also write the results as JSON | | `--fail-p95-ms X` | exit 1 if the run-wide p95 exceeds X ms | | `--fail-error-rate Y` | exit 1 if the error rate exceeds Y (`0.01` or `1%`) | | `--quiet`, `-q` | only print the final table | | `--ui-url URL` | the Redline UI address printed in the "See bottlenecks in the Redline UI at ..." line after the run. Default: the scenario's host plus the `mount_path` setting (from `redline.toml` or `REDLINE_MOUNT_PATH`), else `/_redline` | `--rps`, `--ramp`, `--steps` and `--stages` are mutually exclusive. `redline load init` writes scenarios; see [Generating scenarios](#generating-scenarios). A TOML scenario it writes ends with a commented-out example of the optional keys (`[auth]`, `[[flows]]` with `extract`, `expect`, `max_ms`, `think_s` and `own_connection`): uncomment the lines you need and edit them. Exit codes: `0` ok, `1` a `--fail-*` threshold was breached or the run failed, `2` usage or scenario error, `130` interrupted with Ctrl-C (the partial results are still saved). ### Workers The generator runs as several **processes** (asyncio and httpx in each), not threads, so that the Python GIL in the generator does not cap the rate it can offer or distort the latency it measures. Each worker sends per-second histograms to the parent. All workers follow the same precomputed plan from a shared start time, so step boundaries line up without any messaging. The number of workers never exceeds the target rate. For a high rate, raise `--workers` up to your core count, leaving one for the app if it runs on the same machine. A generator on the same machine competes with the app for CPU; for numbers you trust, run it from another host. ## Reading the results ![A load run: steps, latency chart, the knee and the bottlenecks found under load](assets/screenshots/fastapi-load-light.png){ .rl-shot .rl-only-light } ![A load run: steps, latency chart, the knee and the bottlenecks found under load](assets/screenshots/fastapi-load-dark.png){ .rl-shot .rl-only-dark } ### The step table | Column | Meaning | |---|---| | `target`, `achieved` | the offered rate, and what was actually completed per second | | `sent`, `ok`, `err` | requests started, successful, failed | | `drop` | arrivals that could not start because the in-flight cap was reached. Non-zero means the **generator** or the server's queue was saturated | | `p50`, `p95`, `p99`, `max` | latency, from the *scheduled* time | | `err%` | errors divided by completed requests | An error is a status outside `expect_status`, a timeout, or a connection failure; the final summary breaks them down (`timeout x12, 503 x31`). The verdict is one word: | Verdict | Meaning | |---|---| | `healthy` | no knee in the tested range. Raise the top of the range to find it | | `saturated` | a knee after at least one good step. `max ok rps` is the last good step | | `failing` | the very first step is already the knee. Lower the starting rate | | `no data` | no complete step | ### Resources: which one ran out The knee says when the system stopped keeping up and the bottleneck table says which query slowed; neither says whether the app CPU, the connection pool or memory was the limit. While a run that is registered in the app's store is sending it traffic (and only then), each app worker samples itself once a second: process CPU, resident memory, garbage-collection pauses, threads, and the SQLAlchemy pool (size, checked out, time spent waiting for a connection). Samples are stored with the run and its current step (turn it off with `run_metrics = false`; the `production` preset does). The run summary then carries `resources` (per step, average and maximum of each number) and a verdict in `limiting_resource`, which the CLI prints: ```text limiting resource: step 8: connection pool exhausted (5/5 checked out), wait time 40x the first step ``` The verdict looks at the knee step (else the last one) in this order: **pool** (every connection checked out and requests waiting for one), **cpu** (a worker above 85% of a core), **gc** (pauses of 10% of the time or more), else `unknown`. Memory that grew by 30% over the run is added as a note, never as the limit. `GET api/runs/{id}/metrics` returns the same. Numbers from outside the process (a database or host monitor, a cloud metrics API) come in through a **metric source**: a function you write that returns `{name: number}` for a time range, called once per step after the run: ```toml metric_sources = ["perf_monitors:database"] # package.module:function ``` ```python def database(start_epoch: float, end_epoch: float) -> dict[str, float]: return {"db_cpu_pct": query_my_monitor(start_epoch, end_epoch)} ``` They are stored beside the app's own samples and shown in `resources`. A source that raises is listed under `metric_source_errors`; it never fails the run. Sources are only read from a scenario file (they run your code), and a remote generator posts them to the app with `POST api/runs/{id}/metrics`. Database-side counters (active sessions, waits, blocking) are not sampled by Redline itself: a metric source is the place for them. ### Bottlenecks The **Bottlenecks** table in the UI answers "what got slower". It joins the traces tagged with the run, step by step, with their per-fingerprint and per-route summaries: | Item kind | Compared | |---|---| | `sql` | mean time per execution of each query, by step | | `route` | mean time per request of each endpoint, by step | | `other` | mean time per request that no span covers (the gap between the spans, see [unattributed time](detectors.md#unattributed-time)), by step. Read from the run's 2000 latest requests; absent when every request is fully covered | Each item shows its mean and p95 at every step and a **growth** factor: the last step's mean divided by the first's (floored at 0.01 ms to avoid dividing by nothing). Items are sorted by growth, so the top row is the thing that degraded most as load rose. Click one to open a sample trace, with its callsite. ### What a bottleneck usually means | Pattern | Usually | |---|---| | One SQL statement's time grows 100x | a missing index or a lock; run [EXPLAIN](explain.md) on a sample | | Every statement grows together; routes grow | the database or its pool is saturated. Look for `pool_wait` spans ([Transactions and locks](transactions.md#pool-waits)) | | SQL flat, routes grow | the app itself: CPU, GIL, [blocking in async](async-blocking.md), or a downstream call | | The `other` row grows with the routes | time redline cannot see: CPU, or a client with no span ([wrap it](extending.md#instrumenting-a-client)) | | `dropped` rises with flat server latency | the generator is the limit. More workers, or another machine | | Errors with no matching traces | requests are rejected before the app records them (proxy, worker queue) | ## CI usage `--fail-p95-ms` and `--fail-error-rate` turn a run into a gate. The exit code is `1` on a breach, with the reason printed: ```yaml # .github/workflows/perf.yml (excerpt) - name: Start the app run: | python manage.py migrate python manage.py runserver 8000 & sleep 5 - name: Smoke load test run: | redline load scenario.toml --rps 30 --duration 30s \ --fail-p95-ms 400 --fail-error-rate 1% \ --json load-result.json --no-store - uses: actions/upload-artifact@v4 if: always() with: name: load-result path: load-result.json ``` Notes for stable CI numbers: - Shared CI runners are noisy. Use **generous** thresholds, or compare against a stored baseline rather than an absolute number. Use `constant` at a rate comfortably below the knee: the goal is to catch a regression, not to find capacity. - The gate checks the **whole run**, not each step. - `--json` writes the full per-step results for archiving. `--no-store` skips the SQLite file when there is no UI to view it in. ## Starting a run from the UI With `load_from_ui = True` the **Load** page has a form that starts a run against the app that serves the UI. It is **off by default** (`403 load_disabled`) and needs `redline-core[load]`, and either a file-backed SQLite store or the shared PostgreSQL store (`storage_url`), which the background process reaches through the `REDLINE_STORAGE_URL` environment variable. On a shared store there are no pid files to tell a killed run from a live one, so stopping a run whose process is gone closes it as `failed`. It is also blocked by `read_only` (`403 read_only`) and the `load` feature switch (`404 feature_disabled`), and the `production` preset keeps it off. Turn it on only in environments where load is welcome. See [Security](security.md#load-from-the-ui). **Where the run goes.** The request list can contain only paths (a single leading `/`; no scheme or host), so the form cannot aim the server at somebody else. The target is the `base_url` setting when you set it. Otherwise it is `127.0.0.1` on the port the server is **listening** on (ASGI `scope["server"]`, WSGI `SERVER_PORT`), plus the script root; the `Host` header is never used, so a request cannot aim the run at another service on the machine. When the port is unknown (the app listens on a unix socket), or the app is not reachable on `127.0.0.1` (it listens on one specific interface, or behind a container port mapping), `POST api/runs` answers `400 invalid_body` or the run fails to connect: set `base_url`: ```toml # redline.toml base_url = "http://127.0.0.1:8000" # the application's own address ``` A `base_url` or `workers` key in the request body is ignored. **Limits.** Runs started from the UI are capped more tightly than the CLI: at most one hour, 5 000 requests per second and 200 steps; the body needs a `name`, a non-empty `requests` list, and a `profile` with a `mode` (`constant`, `ramp` or `steps`), a positive `duration_s` and the rates that mode needs. A run goes through the same scenario validation as a file. It runs in a detached `redline load` process, writes into the same store, and is listed with status `running`, then `done`, `stopped` (you stopped it) or `failed`. The run's stored config has secret-looking header values, body keys and URL secrets masked (the raw scenario lives in a mode 0600 file that is deleted when the run ends). The same actions are in the API: `POST api/runs` (`202`), `POST api/runs/{id}/stop`, `DELETE api/runs/{id}` (`409 run_active` while it runs) ([HTTP API](http-api.md#runs)). ## Generating scenarios Writing a scenario by hand is fine for a handful of endpoints; for a real app, generate a starting point and edit it. | Source | Command | Notes | |---|---|---| | **OpenAPI** (FastAPI, Litestar, Django Ninja) | `redline load init --from-openapi URL_OR_FILE` | Path parameters get example values. Operations with required query or header parameters, and all non-GET operations, are written with `weight = 0` so you opt in after reviewing | | **Captured traffic** | `redline load init --from-traces` | Takes the busiest endpoints from your store (`--top`, `--window`), picks a concrete sample path for each, weights GETs by their share of traffic. Bodies are never copied | | **Django URLconf** | `python manage.py redline_scenario [-o FILE] [--base-url URL] [--force]` | Every GET route; routes without parameters get `weight = 1`. A parameterised route (``) is filled with a concrete path from a recent trace of that route, and left out when there is none. The `admin` namespace and Redline's own URLs are skipped. Django Ninja and DRF routes are included. Prints to stdout without `-o` | | **Flask `url_map`** | `flask redline scenario [-o FILE] [--base-url URL] [--force]` | The same rule over the `url_map` (static files and Redline's own routes skipped). Default base URL `http://127.0.0.1:5000` | `redline load init` options: | Option | Meaning | |---|---| | `--from-openapi URL\|FILE` | an OpenAPI 3 or Swagger 2 document | | `--from-traces` | captured traffic in `--store` | | `--store PATH` | for `--from-traces` (default `.redline/redline.db`) | | `--window 24h` | how far back to look | | `--top 10` | endpoints to keep | | `--include-writes` | also include POST/PUT/PATCH/DELETE (written with `weight = 0`) | | `--data-dir DIR` | with `--from-traces`: write each endpoint's distinct paths as CSV here and use them as `zipf` data sources | | `--stages RPS:DURATION,...` | write a stages profile into the scenario | | `--identities-file FILE`, `--identity-mode MODE` | add `identities_file` and `identity_mode` to the scenario | | `--base-url URL` | set `base_url` | | `-o, --out PATH` | output file; `.toml` or `.json`; `-` prints to stdout (default `scenario.toml`) | | `--force` | overwrite an existing file | The generator validates its own output, so a scenario it writes can be run. Write requests are always disabled by default: a load test that POSTs and DELETEs against a real database is something to choose deliberately. ## Limits - It tests **HTTP endpoints over the network**, plus held streams and WebSocket connections (see [Streams and WebSockets](#streams-and-websockets)). It does not drive a browser: see [Browser pages](#browser-pages) for the recipe. - Latency is as measured by the generator, including the network and the generator's own event loop. Distrust sub-millisecond numbers. - Correlated bottlenecks need the app to record the load; with strong sampling, or a store the app is not writing to, the table is empty. - Run records live in the Redline SQLite store and are subject to [history retention](history.md#retention). --- # A full performance test of a multi-user app How the pieces fit together, in the order you would use them. Each step links to the page that has the detail; every key is optional, so start with step 1 and add the rest as you need them. ## 1. Make sure the run lands where the app can see it A load run only fills the bottleneck table when the app tags its traces with the run, which needs the run to exist in the app's store. - Same machine: `redline load scenario.toml --store path/to/redline.db`. - Generator on another host or app in a container: write to the shared PostgreSQL store (`--store-url postgresql://...`) or register over HTTP (`--register-url https://app/_redline`, with `accept_remote_runs` on the app). See [Generator and application on different machines](load-testing.md#generator-and-application-on-different-machines). - Add `--require-recording` to stop early, with the likely causes, when the app does not record the run. - Make the heaviest SQL visible: statements sent through a raw driver cursor are recorded too ([Raw DB-API cursors](integrations.md#raw-db-api-cursors)). ## 2. Offer realistic load | Problem with a flat scenario | Fix | |---|---| | One user repeated thousands of times keeps caches warm | [Identities](load-testing.md#identities) | | Random ids miss real rows and hit every row equally | [Data feeds](load-testing.md#data-feeds) with `pick = "zipf"` | | Tokens expire mid-run and the knee is just 401s | [Token refresh](load-testing.md#token-refresh) | | Detail requests use ids that do not exist | [Flows](load-testing.md#flows) with `extract` and `{var:name}` | | A `200` with an error body counts as a success | [Response checks](load-testing.md#response-checks) | | Real users pause between actions | [Sessions and think time](load-testing.md#sessions-and-think-time) | | Live updates, streams, WebSockets | [Streams and WebSockets](load-testing.md#streams-and-websockets) | `redline load init --from-traces --data-dir data/ --identities-file users.csv` writes a starting scenario with several of these. ## 3. Choose the shape `--steps` finds the knee; `--stages 10:1m,200:30s,10:3m` tests a spike and reports how long p95 took to recover; a long single stage (`--stages 40:30m`) is a soak and reports drift (a leak shows as `degrading`). If the generator saturates a core, steps are marked `generator_limited`: add [agents](load-testing.md#several-generator-hosts-agents) (`redline load agent`) before believing the knee. ## 4. Read the answer 1. The step table and the knee: where it stopped keeping up. 2. **Limiting resource**: pool, CPU, GC, or unknown, from samples the app takes of itself ([Resources](load-testing.md#resources-which-one-ran-out)); add a `metric_sources` function for the database or host. 3. The **bottleneck table**: which query or route grew, per step; flows add a row per step. 4. Flow and step results, recovery, drift, identities, first-byte timing. ## 5. Turn it into a fix - N+1 in raw SQL gets a diff that batches the loop ([N+1 in raw SQL](n-plus-one.md#n1-in-raw-sql-text-and-driver-sql)); apply it, then verify with `redline check verify`. - SQL Server: [permissions and capabilities](database.md#sql-server-permissions-and-capabilities) say which `GRANT` is missing; paste a plan when no login may read plans. - An agent can do all of this through [the MCP tools](agents.md). --- # History and releases [← Index](index.md) Redline keeps individual traces for a few days. That is the right window for debugging a request, and the wrong one for the question you ask after every deploy: **did this release make anything slower?** The **History** page answers it. It keeps small, hourly summaries of every endpoint for 90 days, remembers which release was running, and compares any two releases or time ranges side by side, with a verdict per endpoint and the issues that appeared or went away. ## How it works Three things are stored, all written in the same transaction as the trace itself, and all kept for `history_retention_days` (default 90) regardless of how soon the traces are pruned: | Table | What it holds | |---|---| | **rollups** | per hour, release, route and method: request count, errors, summed duration, a mergeable latency **histogram**, summed queries and query time, issue count | | **releases** | each release name, when it was first and last seen, and how many requests it served | | **issue index** | every issue ever seen: kind, severity, title, route, first and last seen, first and last release, occurrences. It **survives trace pruning** | The latency histogram is log-linear (HDR-style, about 1% relative error from 1 microsecond to an hour). Because histograms merge exactly, p50, p95 and p99 over a week are computed from the hourly rows, not averaged from percentiles (which would be wrong). History reflects **kept** traces. With `sample_rate = 0.1` it is built from a 10% sample (plus every slow request and error), so counts are the sample's, and percentiles are representative. Requests that are ignored or dropped are not included. ## Releases A trace is stamped with a release when it is recorded. Redline resolves the name once, at configure time, from the first of: 1. the `release` setting; 2. the environment variable `REDLINE_RELEASE`; 3. `GIT_SHA`, `SOURCE_VERSION`, `RENDER_GIT_COMMIT` or `HEROKU_SLUG_COMMIT`, which most platforms already set; 4. `git rev-parse --short HEAD` in `project_root`, run once with a one-second timeout; 5. nothing. History still works, grouped as one unnamed release. ```python REDLINE = {"RELEASE": os.environ.get("APP_VERSION")} # or set it in CI ``` Use something that changes on every deploy and is meaningful to you: a git SHA, a version, a build number. The release markers on the timeline are placed where each name is first seen. ## The History page ![The History page with release markers](assets/screenshots/fastapi-history-light.png){ .rl-shot .rl-only-light } ![The History page with release markers](assets/screenshots/fastapi-history-dark.png){ .rl-shot .rl-only-dark } Choose an endpoint (or the whole app) and a window. Four charts share one time axis, with a vertical marker at each release: - **Latency percentiles**: p50, p95 and p99. - **Request count.** - **Error rate.** - **Average queries per request.** Buckets are one hour for windows up to two days, otherwise one day. Only non-empty buckets are drawn, and time is UTC-aligned. The same series is served by `GET api/history` ([HTTP API](http-api.md#get-apihistory)). ## Before and after: comparing periods A period is a **release** or a **time range**: | Form | Example | |---|---| | a release | `release:3f9c2ab` | | a range | `range:1761400000-1761486400` (start and end, epoch seconds) | Pick a baseline (**A**) and the period under test (**B**) and Redline compares them endpoint by endpoint. Each row carries both periods' request count, error rate, p50, p95, p99, average duration and average queries, the p95 change, and a **verdict**: | Verdict | Rule | |---|---| | `regressed` | p95 up **20% or more and 5 ms or more**, or average queries up by 1 or more | | `improved` | the mirror image: p95 down 20% and 5 ms, or average queries down by 1 | | `same` | none of the above | | `new` | the endpoint exists in B only | | `gone` | the endpoint exists in A only | Rows are sorted regressed, new, improved, gone, same, so the problems are on top. The double condition on latency (a relative *and* an absolute change) stops a 0.3 ms endpoint doubling to 0.6 ms from being a headline. Compare two real releases that each served a meaningful amount of traffic; an endpoint with a handful of requests is noise. ### Issues: new, resolved, persisting Below the table, the same two periods' **issues** are diffed: | Group | Meaning | |---|---| | **New** | present in B, not in A. Candidates for "this release introduced it" | | **Resolved** | present in A, gone in B. Did the fix work? | | **Persisting** | present in both, with B's occurrence count | Each links to a sample request while its traces still exist. The issue index itself outlives the traces, so you can still read "N+1 on `/orders/`, first seen in `3f9c2ab`, last seen in `a81d0e4`" months later. ### A typical use 1. Deploy `release B`. Let it serve traffic for an hour or a day. 2. Open **History**, choose A = the previous release, B = the new one. 3. Read the regressed endpoints and the new issues. Open a sample trace for each. For the same comparison on two single requests, use [Compare](the-ui.md#compare-two-requests). For a comparison in your CI pipeline, see the [roadmap](roadmap.md) (v0.3). ## Retention | Setting | Default | Covers | |---|---|---| | `history_retention_days` | `90` | rollups, issue index, releases, load runs | | `max_age_days`, `max_rows` | `7`, `10000` | individual traces (and their `trace_sql`, `trace_ext`, `trace_cache` summaries) | The two are independent: traces can be pruned after a week while the hourly rollups live for 90 days. `0` or `None` for `history_retention_days` keeps history forever. When pruning runs it deletes rollup hours that ended before the cutoff, releases and issue index entries last seen before it, and load runs (with their steps) created before it, but never a run that is still running. **Clear all** and `manage.py redline_clear` delete traces but **keep history**; the API and store can wipe history too (`clear(history=True)`). See [Storage](storage.md#history-tables). ## Upgrading an existing store A store written by 0.1 is migrated in place the first time 0.2 opens it. The new tables are created and **backfilled from the traces still in the file**, in one transaction, so history starts from whatever was there (at most the retained week) rather than from zero. If several workers start at once, the migration runs once. See [Storage](storage.md#the-schema). --- # Django [← Index](index.md) `django-redline` adds Redline to a Django project: one app, one middleware and one URL mount. It supports Django 5.2 (LTS), 6.0 and 6.1 on Python 3.12 and later, under both WSGI and ASGI, with sync and async views. ```python # settings.py INSTALLED_APPS = [..., "django_redline"] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_redline.middleware.RedlineMiddleware", # as high as possible ..., ] # urls.py urlpatterns = [..., path("redline/", include("django_redline.urls"))] ``` Install it as described in [Getting started](getting-started.md#install). There are **no migrations** and no models: Redline never touches your database. ## The pieces | Piece | What it is | |---|---| | `"django_redline"` in `INSTALLED_APPS` | `RedlineConfig.ready()` installs the SQL, cache, template and view hooks, and registers the system checks | | `django_redline.middleware.RedlineMiddleware` | starts and finishes a trace per request; sync and async capable | | `include("django_redline.urls")` | serves the UI at the mount and the [JSON API](http-api.md) under `api/`. The URL namespace is `redline` (`redline:index`, `redline:asset`, `redline:api`) | | `REDLINE = {...}` | optional settings; see the [reference](settings.md) | | `django_redline.span` | re-export of [`redline_core.span`](custom-spans.md) | ## Middleware placement Put `RedlineMiddleware` **near the top**, because the time of everything *below* it is part of the trace and everything above it is not. ```python MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", # "django.middleware.gzip.GZipMiddleware", # keep above Redline if you use it "django_redline.middleware.RedlineMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", ] ``` | Rule | Why | |---|---| | **Below** `GZipMiddleware` | otherwise Redline sees compressed bodies (check `W002`) | | **Above** session, common, CSRF, auth and messages middleware | so their time is in the trace (check `W003`) | | After `SecurityMiddleware` | its redirects need no tracing | The whole stack under Redline appears as a `middleware` span, with the `view` span inside it. ## The URL mount ```python from django.urls import include, path urlpatterns = [ path("redline/", include("django_redline.urls")), ] ``` Any prefix works: the UI uses hash routing and relative URLs. The **trailing slash matters**: `/redline` redirects to `/redline/` through `APPEND_SLASH`. Requests under the mount are **never recorded**; the middleware resolves the mount with `reverse("redline:index")`. If you mount it behind a `path("internal/", ...)` that your auth already protects, you get that protection **in addition to** Redline's own permission check. ## Settings ```python REDLINE = { "SAMPLE_RATE": 1.0, "SLOW_QUERY_MS": 50, "IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"], "PERMISSION": "myproject.redline.can_view", } ``` Every key is a [core setting](settings.md) (case-insensitive) except `PERMISSION` and `STORE`. What Django adds: | Behaviour | Detail | |---|---| | `SAMPLE_RATE` default | `1.0` with `DEBUG = True`, **`0.1` with `DEBUG = False`** | | `STORAGE_PATH` default | `/.redline/redline.db` when `BASE_DIR` is defined | | `PROJECT_ROOT` default | `BASE_DIR`. It decides which stack frames count as your code | | Errors | An unknown key or a bad value raises `ImproperlyConfigured` carrying the core message, and the system check `django_redline.E001` reports it | | Paths | `STORAGE_PATH` and `PROJECT_ROOT` accept a string or a `pathlib.Path` (`BASE_DIR / ".redline" / "redline.db"`) | | `STORE` | Where traces are kept, like FastAPI's `install(store=...)`. See [Custom store](#custom-store) | The runtime (settings, store, recorder, API) is built **lazily on first use**, not in `AppConfig.ready()`, so management commands like `migrate` never create `.redline/`. It is rebuilt when `REDLINE`, `DEBUG` or `BASE_DIR` change through `setting_changed`, which is what makes `override_settings(REDLINE=...)` work in tests. ## Custom store `REDLINE["STORE"]` replaces the default `SQLiteStore.from_settings(settings)` with any object implementing the [`Store` protocol](extending.md#the-store-protocol). It accepts: | Value | Used as | |---|---| | a callable or a class, e.g. `MyStore` | called with the core `Settings`; the result is the store. Rebuilt (and the old one closed) whenever the runtime is rebuilt | | a ready instance | used as-is. It outlives runtime rebuilds (`override_settings` only flushes it) and is closed at process exit | | a dotted path to either, e.g. `"myproject.redline.make_store"` | imported, then as above | ```python # myproject/redline.py from redline_core.storage import SQLiteStore class MirroringStore(SQLiteStore): def __init__(self, settings): super().__init__( settings.storage_path, queue_size=settings.writer_queue_size, max_rows=settings.max_rows, max_age_s=settings.max_age_s, ) def save(self, trace): super().save(trace) send_somewhere_else(trace) # must not block # settings.py REDLINE = {"STORE": "myproject.redline.MirroringStore"} ``` An import error, or a value that does not produce a `Store`, raises `ImproperlyConfigured` (and the system check `django_redline.E001`). ## What 0.2 adds for Django | Feature | Where to read | |---|---| | `transaction.atomic` recorded as `transaction` spans (with `ATOMIC_REQUESTS`), long-transaction and external-call-in-transaction detection | [Transactions and locks](transactions.md) | | DRF serializers timed as `serializer` spans | [Slow serializers](serializers.md) | | Row counts on queries, large and unbounded results, `len(qs)` vs `.count()` / `.exists()` | [Large and unbounded results](result-size.md) | | A sync ORM call inside an `async def` view reported as blocking the event loop | [Blocking in async](async-blocking.md) | | Django's cache framework analysed per key pattern | [Cache efficiency](cache-efficiency.md) | | Strawberry and Graphene resolvers (and `strawberry-django`) | [GraphQL](graphql.md) | | Django Ninja | [Django Ninja](django-ninja.md) | | `manage.py redline_scan` (templates and DRF) | [Static N+1 scan](static-scan.md) | | `manage.py redline_scenario`, then `redline load` | [Load testing](load-testing.md) | | `Server-Timing`, the floating badge (when `DEBUG`), live mode, snapshots | [Server-Timing and the badge](server-timing-badge.md) | | `REDLINE["PRESET"]`, `redline.toml`, `REDLINE_*` | [Configuration](configuration.md) | The badge is `"auto"` by default, which in Django means **on when `DEBUG` is true**. Nothing changes in `MIDDLEWARE` or `urls.py`. ## Access control Django's default access policy is `framework`: the permission check below, and it stays the default under the `production` preset (a preset does not change it). The other policies (`token`, `basic`, IP allow-lists, `read_only`, ...) are available through the same `REDLINE` dict and are described on [Access control](access-control.md). When `ACCESS` is not `"framework"`, `PERMISSION` is not consulted. Every view, page, assets and API, first checks `ALLOWED_HOSTS` (it calls `request.get_host()`, so this holds even without `CommonMiddleware`, a defence against [DNS rebinding](security.md#dns-rebinding)) and then the access gate, with `REDLINE["PERMISSION"]` as the framework hook. Top-level files such as `badge.js` skip `PERMISSION` but not the network rules. | | Default | | |---|---|---| | Who | active superusers: `user.is_active and user.is_superuser` | changed in 0.2 (was staff) | | Anonymous, on the page | redirected to `admin:login` (or `LOGIN_URL` if the admin is not installed), with `?next=` | | | Signed in without access, on the page | `403` plain text | | | On the API | `403` JSON `{"error": {"code": "forbidden", ...}}` | | !!! warning "Changed in 0.2: superusers, not staff" Until 0.1 any active **staff** user could open Redline. Staff status is often given for the admin of a single model, while Redline shows every user's requests (headers, SQL, bodies), so the default now asks for a superuser. To keep the 0.1 rule: ```python REDLINE = {"PERMISSION": "django_redline.conf.staff_permission"} ``` Override it with a callable `(request) -> bool`, or its dotted path: ```python # myproject/redline.py def can_view(request): user = request.user return user.is_active and user.groups.filter(name="performance").exists() ``` ```python REDLINE = {"PERMISSION": "myproject.redline.can_view"} ``` - A string that cannot be imported, or a value that is not callable, raises `ImproperlyConfigured` (and `E001`). - An exception raised **inside** your callable **denies access** (fails closed). - The check needs `request.user`, so keep `AuthenticationMiddleware` in `MIDDLEWARE`. Redline's own middleware does not need it. See [Security](security.md) for the wider picture. ## CSRF The page and `GET` calls need nothing. The mutating calls, `DELETE` (a trace, or all of them) and `POST api/explain`, are protected by Django's own CSRF check, which Redline runs on **every** API request **even if `CsrfViewMiddleware` is not in `MIDDLEWARE`**: - the token must arrive in the CSRF header (`X-CSRFToken`, or whatever `CSRF_HEADER_NAME` says); - on HTTPS Django's Origin and Referer checks also apply; - a failure is a **JSON** `403` with code `csrf_failed`, not Django's HTML page. The served page embeds a fresh token in ``, and the SPA sends it back. Because the token is in the page and not read from a cookie, this works with `CSRF_COOKIE_HTTPONLY = True` and with `CSRF_USE_SESSIONS = True`. Scripts calling the API must log in, keep the session cookie, and send the token. The exception is `ACCESS = "token"`: a request carrying `Authorization: Bearer ` skips Django's CSRF check. The gate's own CSRF rule (`Sec-Fetch-Site: cross-site` or `same-site`, or a mismatched `Origin`, refused with `403 csrf_failed`) applies as well. ## How it hooks in Everything is installed once from `AppConfig.ready()` and is a single `ContextVar.get()` and `None` check when nothing is being recorded. | What | Hook | Span | |---|---|---| | **SQL** | a `connection.execute_wrapper` appended to **every** connection's `execute_wrappers`, through the `connection_created` signal and for connections already open | `sql` | | **Cache** | the backends that `django.core.cache.caches` creates get their public methods wrapped | `cache` | | **Templates** | `django.template.base.Template.render` (top-level templates and `{% include %}`) and the Jinja2 backend | `template` | | **View** | `BaseHandler.make_view_atomic`, called by both the sync and the async handler right before the view | `view` | | **Middleware** | the middleware itself wraps the rest of the stack | `middleware` | Details worth knowing: - Redline's own store is a separate `sqlite3` file, **not a Django connection**, so it can never record itself. Queries run by [EXPLAIN](explain.md) are explicitly suppressed. - **Cache** spans carry `op` (`get`, `set`, `add`, `delete`, `touch`, `incr`, `decr`, `has_key`, `get_or_set`, `get_many`, `set_many`, `delete_many`, `clear`), the `key` (cut at 200 characters, or the first five keys plus a count for the `_many` calls), `hit` (for `get`, `get_many`, `has_key`) and `backend` (`default (LocMemCache)`). A cache backend object you instantiate **yourself**, not through `caches`, is not instrumented. - **Template** spans are named after the template; queries run during rendering nest under them, which is how an N+1 in `{% for item in order.items.all %}` is attributed to the render. - **View** spans are named by the dotted path (`shop.views.order_list`, or the class for class-based views) and carry `{"async": true|false}`. - Queries issued from **library code** (a generic `ListView`, DRF, a lazily rendered `TemplateResponse`) have no project frame in their stack. They are attributed to the **project view** that handled the request, using the view's definition site. When the stack does not pass through the view (a serializer called by a DRF viewset), the view is added as the outermost frame so the [fix suggester](n-plus-one.md#how-the-fix-is-found) can find its queryset. ## What the middleware records | Recorded | Notes | |---|---| | Method, path, **route template** (`/orders//`), view | from `request.resolver_match` after the response | | Request headers, query string | redacted before storage | | Request body | read up front only if it is **not multipart**, has a `Content-Length` above 0 and at most `max_body_bytes`. Otherwise Redline does **not** read it (the view may stream it), and picks up whatever the view itself read | | Response status, headers | `Set-Cookie` values from `response.cookies` are included, then redacted | | Response body | only for non-streaming responses; **streaming and file responses are never consumed**. The size comes from `Content-Length` | | Exceptions | `process_exception` remembers a view's exception for the trace and returns `None`: it **never handles or swallows** it. It becomes the trace's `error` only when the final response is a 5xx: `Http404`, `PermissionDenied`, `BadRequest` and friends turn into 4xx responses and are **not errors** (no `error` on the trace, not kept by `ALWAYS_KEEP_ERRORS`). An exception that escapes the stack is recorded as a 500 and re-raised | | `X-Redline-Run` | becomes `run_id` and `step` tags (kept only for a run that is running in the store) | | `?_redline=profile` (or `1`, `true`, `yes`, `on`) / `X-Redline-Profile: 1` | starts the [profiler](flamegraphs.md); the same values as FastAPI. Honoured with `DEBUG = True`, or when the request carries Redline credentials under `token`/`basic` (a `PERMISSION` cannot run in the middleware) | With `DEBUG = True`, a **kept** response gets an `X-Redline-Trace: ` header so you can find it. It is never sent in production. ## Async views `RedlineMiddleware` declares `sync_capable` and `async_capable`. Django adapts it to the stack automatically: under ASGI with async middleware chain it runs its async path (`__acall__`), under WSGI its sync path. In both, state is carried by `contextvars`. ```python async def summary(request): n = await Order.objects.acount() # recorded, attributed to this line return JsonResponse({"orders": n}) ``` - Async ORM calls (`acount`, `aget`, `async for`) are recorded; they run through the same connection wrapper, via `sync_to_async`, which copies context. - Concurrent async requests do not mix (there is a test for it). - The view span of an async view has `async: true`. ## Django REST Framework DRF views are ordinary Django views, so they are traced like any other. The extra value is in the fix suggester: when a **serializer** reads a relation for every object it serializes, the suggested diff targets the **view's** `queryset` or `get_queryset()`, and the summary says which serializer does it: ```diff class OrderViewSet(viewsets.ModelViewSet): - queryset = Order.objects.all() + queryset = Order.objects.prefetch_related("items") serializer_class = OrderSerializer ``` (Shape only: illustrative, not output copied from a run.) !!! note "How well tested is the DRF support?" The repository's tests exercise this with a small stand-in for `Serializer` and a viewset-shaped class, not with `rest_framework` itself, and the demo shop does not use DRF. The mechanism looks at class names ending in `Serializer` and at the view's `queryset`/`get_queryset`. It should hold for real DRF; it has not been run against it. ## Multiple databases Every connection gets the wrapper, and each SQL span stores its `db_alias` (`default`, `replica`, ...) and `vendor`. EXPLAIN runs on `connections[db_alias]`. If the span's alias no longer exists, or the connection's vendor differs from the recorded one, EXPLAIN answers `501 explain_unavailable`. Vendors other than PostgreSQL, MySQL and SQLite record SQL but cannot be explained. ## System checks `manage.py check` (and `runserver`) run these. For filesystem store paths, the storage check uses effective process permissions: creates/writes/removes its own temporary probe in the nearest existing parent, and opens an existing target for writing without truncating or modifying it. It does not initialize the database. Root may legitimately write through restrictive mode bits; read-only mounts and refused filesystem operations still produce `E002`. | ID | Level | Problem | Fix | |---|---|---|---| | `django_redline.E001` | Error | `REDLINE` is invalid: an unknown key (with a "did you mean"), a bad value, a bad `PERMISSION` | Fix the setting | | `django_redline.E002` | Error | The storage location cannot be created or is not writable | Point `STORAGE_PATH` somewhere writable | | `django_redline.W001` | Warning | `RedlineMiddleware` is not in `MIDDLEWARE`, so nothing is recorded | Add it near the top | | `django_redline.W002` | Warning | `GZipMiddleware` is **after** Redline, so bodies are compressed | Move Redline below it | | `django_redline.W003` | Warning | Redline is listed **after** session, common, CSRF, auth or messages middleware, so their time is not traced | Move Redline above them | | `django_redline.W004` | Warning | `django_redline.urls` is not mounted, so the UI is unreachable | Add the `include()` | | `django_redline.W005` | Warning | `DEBUG` is false and `SAMPLE_RATE` is `1.0` | Lower it, or leave it unset for `0.1` | All are registered under the `compatibility` tag. `E002` and `W005` are only checked when Redline is enabled; the others always run. ## Management commands | Command | Does | |---|---| | `manage.py redline_clear [--noinput]` | Deletes every recorded trace. Asks for confirmation (`Delete all N Redline traces? [y/N]`) unless `--noinput` or `--no-input` | | `manage.py redline_prune [--max-age-days N] [--max-rows N]` | Applies [retention](storage.md#retention) now. Defaults to the `MAX_AGE_DAYS` and `MAX_ROWS` settings. `0` disables that rule for this run (it never deletes everything: that is `redline_clear`). Negative values are an error | | `manage.py redline_scan [PATHS] [--json] [--fail] [--dialect django\|jinja] [--no-drf]` | [Static N+1 scan](static-scan.md): templates that read a relation in a loop, and DRF serializers whose queryset lacks the matching `select_related` / `prefetch_related`. `--fail` exits 1 on findings | | `manage.py redline_scenario [-o FILE] [--base-url URL] [--force]` | Writes a [load-test scenario](load-testing.md#generating-scenarios) from your URLconf (stdout without `-o`) | `redline_clear` and `redline_prune` build the runtime, flush pending writes, and print how many traces they removed. `redline_clear` keeps [history](history.md). Run `redline_prune` from cron if your app is idle for long stretches (the writer prunes as it writes, so an idle app does not prune on its own). ```console $ python manage.py redline_prune --max-age-days 1 Pruned 4120 trace(s); 880 left. ``` ## Under test `override_settings(REDLINE={...})` rebuilds the runtime. To keep test runs from writing a file, use an in-memory store, and set `PROJECT_ROOT` to the code under test so test functions themselves do not count as "your code": ```python REDLINE = { "STORAGE_PATH": ":memory:", "SAMPLE_RATE": 1.0, "PROJECT_ROOT": str(BASE_DIR / "myapp"), } ``` To assert on traces, read the store: ```python from django_redline.runtime import get_runtime rt = get_runtime() rt.store.flush(5.0) trace = rt.store.get(rt.store.list(None, limit=1).items[0]["id"]) assert not [i for i in trace.issues if i.kind == "n_plus_one"] ``` A pytest marker for this (`@pytest.mark.redline(no_n_plus_one=True)`) is planned for [v0.3](roadmap.md). ## Deployment notes - **WSGI (gunicorn, uWSGI)**: the runtime is built lazily in each worker, after the fork, and the store is fork-safe even if something built it before the fork (`--preload`). Each worker writes to the same file; see [Production: process models](production.md#process-models). - **ASGI (uvicorn, daphne, hypercorn)**: nothing special. - **Behind a proxy**: the Django permission uses your session, not the client address, so the FastAPI proxy caveat does not apply. `ALLOWED_HOSTS` and `CSRF_TRUSTED_ORIGINS` must include your host as usual. - **Containers**: `.redline/` must be writable. With a read-only root filesystem point `STORAGE_PATH` at a mounted volume or `/tmp`. ## Troubleshooting | Symptom | Likely cause | |---|---| | `manage.py check` warns `W001` | the middleware is missing | | The UI says 404 at `/redline` | use `/redline/` (trailing slash), or `APPEND_SLASH = False` | | 403 for a superuser | your `PERMISSION` callable returned false or raised (it fails closed). Test it in a shell | | `403 csrf_failed` from a script | send the `X-CSRFToken` header and the session cookie | | No requests appear | path in `IGNORE_PATHS`; `ENABLED` false; `SAMPLE_RATE` below 1 (default `0.1` with `DEBUG = False`) | | Empty callsites | `PROJECT_ROOT` is not an ancestor of your code (set it as a string) | | `ImproperlyConfigured: settings.REDLINE: ... must be a string` | a `Path` in `STORAGE_PATH` or `PROJECT_ROOT`: wrap it in `str()` | | Queries from a thread missing | a bare `threading.Thread` does not carry the trace; use `contextvars.copy_context().run` | --- # Django Ninja [← Index](index.md) [Django Ninja](https://django-ninja.dev) apps are served by `django-redline`; there is no separate package. Install and mount Redline exactly as in [Django](django.md), and your Ninja endpoints are recorded like any other Django view, with two Ninja-specific improvements. ## What you get Ninja registers **one Django view per path** and dispatches to the operation inside it. Left alone, every Ninja request would look like `ninja.operation.view_wrapper` with a route template that is the same for every HTTP method. Redline looks inside: | Trace field | Without the Ninja support | With it | |---|---|---| | `view` | `ninja.operation.view_wrapper` | `shop.api.list_orders`, your endpoint function | | `route` | the Django URL pattern for the path | the same, resolved per operation, so `GET /api/orders/{order_id}` and `DELETE /api/orders/{order_id}` aggregate separately on the [Endpoints](issues-and-endpoints.md#endpoints) page | Nothing is imported unless Ninja is already loaded in the process, so non-Ninja projects pay nothing. ## Setup ```python # settings.py INSTALLED_APPS = [..., "django_redline"] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_redline.middleware.RedlineMiddleware", ..., ] ``` ```python # urls.py from django.urls import include, path from ninja import NinjaAPI api = NinjaAPI() urlpatterns = [ path("api/", api.urls), path("redline/", include("django_redline.urls")), ] ``` Your Ninja routes do not change. Sync and `async def` operations are both supported; the async rules from [Django: async views](django.md#async-views) apply. ## Schemas and serialization Ninja serializes with Pydantic. The `serializer` spans come from [DRF](serializers.md) and from [FastAPI](fastapi.md); Ninja's response building is not hooked separately, so a slow one shows up as time in the `view` span. Wrap the suspect code in a [custom span](custom-spans.md) if you need to isolate it. ## Load testing a Ninja API Ninja publishes an OpenAPI document, so scenarios can be generated from it: ```bash redline load init --from-openapi http://localhost:8000/api/openapi.json -o scenario.toml redline load scenario.toml --steps 10:100:10 --step-duration 20s ``` See [Load testing](load-testing.md#generating-scenarios). ## N+1 in Ninja endpoints The Django fix suggester works unchanged, because Ninja endpoints use the Django ORM: an N+1 inside `list_orders` is reported with a `select_related` or `prefetch_related` diff at the queryset line. See [N+1 detection](n-plus-one.md). --- # FastAPI [← Index](index.md) `fastapi-redline` adds Redline to a FastAPI (or plain Starlette) application with SQLAlchemy. One function, `install()`, does everything. ```python from fastapi import FastAPI from sqlalchemy.ext.asyncio import create_async_engine from fastapi_redline import install app = FastAPI() engine = create_async_engine("sqlite+aiosqlite:///app.db") # access="local": localhost only (unset, Redline answers 404 outside debug mode) install(app, engine=engine, settings={"access": "local"}) # UI at http://localhost:8000/_redline/ ``` Requirements: Python 3.10+, FastAPI 0.110+ (below 1.0), SQLAlchemy 2.x, and `redline-core` at the exact version the adapter pins. Install as shown in [Getting started](getting-started.md#install). Since 0.2 the SQLAlchemy and httpx hooks live in `redline_core.contrib` and are shared with the Flask and Litestar adapters; `fastapi_redline` re-exports them (`instrument_engine`, `instrument_httpx`), so existing imports keep working. ## `install_if_dev()` `install_if_dev(app, **kwargs)` takes the same arguments as `install()` and returns the `Redline` handle, but attaches nothing (and logs a warning) when `REDLINE_ENV`, `APP_ENV`, `ENV`, `ENVIRONMENT`, `FLASK_ENV` or `DJANGO_ENV` is `prod` or `production`; it returns `None` then. `REDLINE_ALLOW_PRODUCTION=1` attaches anyway. It is only in 0.5 and later; on older releases use `install()` behind your own environment check. ## `install()` ```python install( app, engine=None, # Engine | AsyncEngine | [engines] | {"alias": engine} engines=None, # "auto": instrument engines created at runtime settings=None, # dict | redline_core.Settings prefix=None, # default: the mount_path setting, else "/_redline" dependencies=None, # auth dependencies for the UI and API models=None, # Base / registry for fix suggestions (default: auto-discover) store=None, # a custom Store (default: SQLite file at storage_path) ) -> Redline ``` | Argument | Type | Default | Meaning | |---|---|---|---| | `app` | `FastAPI` | required | The application to instrument. Call after it is built, before it starts | | `engine` | `Engine`, `AsyncEngine`, list, or `{alias: engine}` | `None` | Engines to record SQL from and run EXPLAIN on. See [Engines](#engines) | | `settings` | `dict` or `redline_core.Settings` | `None` (defaults) | Any [setting](settings.md); keys are case-insensitive; unknown keys raise `SettingsError` | | `prefix` | `str` or `None` | `None` | Where the UI and API are mounted. `None` means the `mount_path` setting, then `"/_redline"`. Must be a sub-path; `"/"` raises `ValueError` | | `dependencies` | sequence of callables or `Depends(...)` | `None` | Protects the UI and API; a non-empty list implies `access = "framework"`. `None` or `[]` means the `access` policy decides (default `local`: **loopback only**, and only with `app.debug` until `access` is set). See [Access control](#access-control) | | `models` | declarative `Base`, `registry`, mapped class, or an iterable of those | `None` | Where the fix suggester looks for relationships. Default: every registry SQLAlchemy knows | | `store` | a `Store` | `None` | Replace the SQLite store. See [Extending](extending.md#the-store-protocol) | It returns a `Redline` handle (also available as `app.state.redline`) and raises `RuntimeError("Redline is already installed on this app.")` on a second call. ### What it does 1. Builds the settings and **appends a regex to `ignore_paths`** (`^/_redline(/|$)`) so Redline never records itself. 2. Creates the store (`SQLiteStore.from_settings(...)`) and a `SQLAlchemyFixSuggester`, and configures the process-wide recorder. 3. Instruments every engine you passed (registers them for EXPLAIN either way). 4. Mounts the UI and API router under `prefix` and **moves its routes to the front** of the app's route list, so a catch-all route you declared earlier cannot swallow it. 5. Adds the pure-ASGI `RedlineMiddleware`. With `settings={"enabled": False}` steps 3 and 5 are skipped: no SQLAlchemy listeners and no middleware, so a disabled install costs nothing per query (measured: under 1 µs, the same as not installed). The UI still serves the traces already in the store. 6. **Wraps your lifespan**: on shutdown it flushes the pending traces and closes the store. An existing `lifespan=` keeps working and runs first. ### The `Redline` handle | Member | Meaning | |---|---| | `redline.settings` | the effective `Settings` | | `redline.store` | the store (`.count()`, `.flush()`, ...) | | `redline.recorder` | the process recorder | | `redline.api` | the `RedlineAPI` (call `redline.api.dispatch(...)` from a script or test) | | `redline.engines` | the `{alias: engine}` mapping | | `redline.add_engine(engine, alias=None)` | instrument another engine later (only registered for EXPLAIN when disabled); returns its alias | | `redline.close()` | flush and close the store (called by the lifespan wrapper) | ## Engines Redline sees SQL only for engines you give it. SQLAlchemy's cursor-level events fire for both sync and async engines (the listeners go on `engine.sync_engine` for an `AsyncEngine`), so `Session`, `AsyncSession`, `session.execute`, Core and ORM calls are all recorded. === "Async engine" ```python engine = create_async_engine("postgresql+asyncpg://...") install(app, engine=engine) ``` === "Sync engine" ```python engine = create_engine("postgresql+psycopg://...") install(app, engine=engine) ``` === "Several engines" ```python install(app, engine=[async_engine, sync_engine]) install(app, engine={"main": main_engine, "analytics": analytics_engine}) ``` === "Added later" ```python redline = install(app) ... redline.add_engine(late_engine) ``` ### Aliases Every query is stored with a `db_alias`, and EXPLAIN uses it to find the right engine. | You pass | Aliases | |---|---| | one engine | `"default"` | | a dict | its keys | | a list | the first is `"default"`; the others are named after their database file (`.../analytics.db` becomes `analytics`), falling back to `db2`, `db3`, ... | ### Vendors The dialect name maps to a vendor: `postgresql`, `mysql` (also MariaDB) and `sqlite` support EXPLAIN; any other dialect records SQL (vendor `other`) but cannot be explained. !!! note "PRAGMA statements are skipped" SQLite `PRAGMA` statements are not recorded. They are connection housekeeping, not your queries. ### Engines created at runtime (per-user or per-request) Apps that build engines on the fly (for example one per user, with token authentication through `connect_args` or `creator=`) cannot register each one. Opt in to automatic discovery: ```python install(app, engines="auto") # or settings={"instrument_engines": "all"} ``` This sets `instrument_engines="all"`: every SQLAlchemy `Engine` (sync, or the sync engine inside an `AsyncEngine`) that runs a statement inside a recorded request is hooked on its first use, once, under a unique alias (`auto_`). Engines are held weakly, so a disposed per-request engine is garbage collected as usual. Automatically found sync engines can be EXPLAINed; async ones are recorded but not EXPLAINed. Engines you pass as `engine=` keep their own alias. The default stays explicit registration. ## Sync and async endpoints Both work, and both attach queries to the right request. - `async def` endpoints run on the event loop. Each request's trace lives in `contextvars`, so concurrent requests are isolated (there is a test for it). - `def` endpoints run in Starlette's threadpool. Context is copied into the worker thread, so their queries attribute to the right request, also under concurrency. - Work in a bare `threading.Thread` is **not** attributed to any request. For `AsyncSession` the SQL actually runs inside a greenlet, below your `await`. Redline bridges that boundary when it captures the callsite, so the reported line is still **your** `await session.scalars(...)` and not SQLAlchemy's internals. ## What the middleware records `RedlineMiddleware` is a **pure ASGI** middleware, not `BaseHTTPMiddleware`. The latter wraps your app in extra tasks, breaks context propagation for sync endpoints, and buffers streaming responses. | Recorded | Notes | |---|---| | Method, path, **route template** (`/orders/{order_id}`) | Resolved from `scope["route"]` once routing ran. For mounted sub-applications the mount path is prefixed | | Endpoint | Dotted name of the endpoint function (`shop.api.list_orders`) | | Status, headers | The response status and headers | | Request body | **Teed** as your app reads it, so the app sees the untouched `receive`. Kept up to `max_body_bytes` | | Response body | A size-capped copy. A stream is never buffered beyond `max_body_bytes` | | Unhandled exceptions | Recorded with the traceback, then **re-raised untouched** | | Client cancellation | Recorded with status 499 when the client disconnects mid-request | | `X-Redline-Run` | becomes the `run_id` and `step` tags (only for a run that is running in the store) | | `?_redline=profile` / `X-Redline-Profile: 1` | runs the profiler, only with `app.debug` or valid Redline credentials (see [Forcing capture](security.md#forcing-capture)) | What it does **not** do: - **WebSockets and lifespan events** are passed straight through (only `http` scopes are recorded). - **Compressed response bodies are not captured.** A response with a `Content-Encoding` header (for example from `GZipMiddleware` placed *outside* Redline) has no stored body. Order matters: add Redline so it is inside compression if you want bodies. - It finishes the trace **right after the last response chunk is sent**, so background tasks do not inflate latency (and their queries are not in the trace). !!! warning "Middleware order" Starlette runs the middleware added **last** outermost. `install()` calls `add_middleware` when it runs, so middleware you add *after* `install()` wraps Redline and its time is not measured; middleware added *before* is inside and is measured. Call `install()` last for the most complete picture. ## Outbound HTTP (httpx) Opt in, once, at startup: ```python from fastapi_redline import instrument_httpx instrument_httpx() # every httpx.Client / AsyncClient call becomes an http_out span ``` It wraps `httpx.Client.send` and `httpx.AsyncClient.send`, which every request method goes through, so clients created by libraries are covered too. `install()` does not do it for you, so the patch is always an explicit choice. It returns `False` if httpx is not installed, is idempotent, and `uninstrument_httpx()` undoes it. Outside a traced request the wrapper costs one `ContextVar.get()`. Each span is named `GET host/path` and carries `method`, `url` and `status`. **URLs are redacted**: `?api_key=...` is masked. `requests` is covered by [`instrument_requests()`](integrations.md#requests). `aiohttp` is not instrumented. ## New in 0.2 for FastAPI | Feature | Where to read | |---|---| | An event-loop lag monitor that names the blocking call in an `async def` endpoint | [Blocking in async](async-blocking.md) | | `transaction` and `pool_wait` spans from SQLAlchemy | [Transactions and locks](transactions.md) | | Response serialization (`serialize_response`, Pydantic) timed as a `serializer` span | [Slow serializers](serializers.md) | | Row counts, large and unbounded results | [Large and unbounded results](result-size.md) | | `requests`, Redis, asyncpg, psycopg, Marshmallow | [Integrations](integrations.md) | | Strawberry GraphQL | [GraphQL](graphql.md) | | `redline load init --from-openapi` against FastAPI's `/openapi.json` | [Load testing](load-testing.md#generating-scenarios) | | `Server-Timing`, the badge, live mode, snapshots | [Server-Timing and the badge](server-timing-badge.md) | | Presets, `redline.toml`, `REDLINE_*`, token and basic access, read-only | [Configuration](configuration.md), [Access control](access-control.md) | ## Access control !!! danger "The UI exposes your SQL, request bodies and the ability to run EXPLAIN" Treat it as an admin tool. Decide who can reach it before you deploy. ### The default: loopback only, in debug mode With no `dependencies`, the `access` setting decides. **While you have not set it** (in code, `redline.toml` or `REDLINE_ACCESS`), Redline serves its `local` default only when `app.debug` is on (`FastAPI(debug=True)`); otherwise every Redline URL answers `404` and an error is logged at startup. Most apps run under plain `uvicorn` without `debug`, so set it: ```python install(app, engine=engine, settings={"access": "local"}) # your laptop install(app, engine=engine, settings={"access": "token", "token": "..."}) # a server ``` `local` allows a request only when **both** of these hold: - the **client** is loopback: `127.0.0.0/8`, `::1`, IPv4-mapped IPv6 loopback, or Starlette's `TestClient` (a unix-socket peer only with `trust_unix_socket = true`); - the **`Host` header** names loopback: `localhost`, any `*.localhost`, a `127.x.x.x` address or `[::1]`, with any port. This is what stops **DNS rebinding**: a malicious page that points its own domain at `127.0.0.1` reaches your server, but its requests say `Host: evil.example` and are refused. Anyone else gets `403` with `{"error": {"code": "forbidden", "message": ...}}`, and a startup warning is logged: ```text Redline is mounted at /_redline with access='local': only loopback clients addressing localhost are allowed. Set access='token' or 'basic', or pass install(app, dependencies=[...]), before exposing it. ``` !!! warning "Behind a reverse proxy, 'loopback' may be everyone" If nginx or a load balancer forwards to your app over `127.0.0.1`, every request would look like localhost. Redline refuses a loopback peer that carries `X-Forwarded-For`, `X-Real-IP` or `Forwarded` unless it is listed in `trusted_proxies`, but the safe setup is `access = "token"` (or real dependencies) plus `trusted_proxies`. To reach a local server through another name (a hosts-file alias, a tunnel), keep the loopback rules and allow that name explicitly with the `allowed_hosts` setting: ```python install(app, engine=engine, settings={"allowed_hosts": ["devbox"]}) ``` (`loopback_guard(allowed_hosts=[...])` is still exported for use as an explicit dependency.) The `local` policy treats Starlette's `TestClient` as loopback. ### Your own dependency === "Existing auth dependency" ```python from fastapi import Depends install(app, engine=engine, dependencies=[Depends(require_admin_user)]) ``` === "HTTP Basic" ```python import os, secrets from fastapi import Depends, HTTPException from fastapi.security import HTTPBasic, HTTPBasicCredentials basic = HTTPBasic() def redline_auth(creds: HTTPBasicCredentials = Depends(basic)) -> None: ok = secrets.compare_digest(creds.username, "admin") and secrets.compare_digest( creds.password, os.environ["REDLINE_PASSWORD"] ) if not ok: raise HTTPException(401, headers={"WWW-Authenticate": "Basic"}) install(app, engine=engine, dependencies=[Depends(redline_auth)]) ``` === "A bare callable" ```python async def only_staff(request: Request) -> None: if not getattr(request.state, "is_staff", False): raise HTTPException(403) install(app, engine=engine, dependencies=[only_staff]) # wrapped in Depends for you ``` Refuse by **raising** `HTTPException` (the FastAPI way). A dependency that *returns* `False` (`return user.is_admin`) is refused with `403` too, since FastAPI itself would ignore the return value and let the request in; `None` and other values pass. `dependencies=[]` is the same as not passing any (since 0.2: it used to leave the UI open). To open it to everyone on a private network, use a dependency that returns nothing, or `access = "open"` with `REDLINE_ALLOW_OPEN=1`. For tokens, basic auth, `allowed_ips`, `read_only` and the rest, use the [`access` settings](access-control.md); with an explicit policy other than `framework` your dependencies still run, after the gate. The dependencies apply to **everything** under the prefix: the page, assets and the API. An `HTTPException` they raise is answered in Redline's error shape, `{"error": {"code": "unauthorized", "message": "..."}}` for a `401` (`forbidden` for `403`), with its headers (`WWW-Authenticate`) kept, so the UI can show it. See [HTTP API: errors](http-api.md#error-codes). ### CSRF and Origin Every non-`GET` request (`DELETE api/traces...`, `POST api/explain`, login, logout) is always protected by the gate, whatever your dependencies: - a request with `Sec-Fetch-Site: cross-site` or `same-site` is rejected (`403 csrf_failed`); - a request with an `Origin` header must match the request's `Host` (or `X-Forwarded-Host` from a trusted proxy); `Origin: null` is rejected; - a request **without** `Origin` (curl, scripts) is allowed, because a web page cannot forge that, but your dependencies still apply. Browsers always send `Origin` on those methods, so another website cannot drive your Redline through a logged-in browser. This needs no change to the UI. ## Fix suggestions: SQLAlchemy `SQLAlchemyFixSuggester` is registered for you. See [N+1 detection](n-plus-one.md#how-the-fix-is-found) for what it produces. Pass `models=` if your models live in a registry SQLAlchemy cannot discover. SQLModel needs nothing: its tables live in a normal SQLAlchemy registry (or pass `models=SQLModel`). ## EXPLAIN `POST api/explain` runs on the engine the query came from, matched by `db_alias`, with the captured SQL in the **driver's own paramstyle** through `exec_driver_sql`, in a transaction that is always rolled back (and `SET TRANSACTION READ ONLY` on PostgreSQL). - **Async engines** run on the application's event loop, where their connections belong: the loop is captured the first time the API is called. - **Sync engines** run in a threadpool worker. - If the engine behind an alias was never passed to `install()`, EXPLAIN answers `501 explain_unavailable`. ## Running with several workers Each worker process has its own store connection and writer thread, and all write to the **same** SQLite file. SQLite serialises writers (WAL mode, a 10-second busy timeout), so this is intended to work. The store is **fork-safe**: with gunicorn `--preload` the store built by `install()` in the master reopens its connection and starts its own writer in each worker (see [Production: process models](production.md#process-models)). Busy multi-worker deployments have not been load-tested, and each worker prunes independently. For anything beyond a development `--workers 2`, prefer a single worker for the profiler, or per-worker `storage_path`s (use the PID). A shared store for production is planned for [v1.0](roadmap.md). ## Testing your app with Redline installed Starlette's `TestClient` reports its client address as `testclient`, which the loopback check accepts, but it sends `Host: testserver`, which the DNS-rebinding check refuses. Give the client a loopback base URL to open the UI in a test: `TestClient(app, base_url="http://localhost")`. To keep test runs from writing a file, set `storage_path` to `":memory:"`: ```python install(app, engine=engine, settings={"storage_path": ":memory:"}) ``` Or leave Redline out of the app under test, and install it only in your dev entry point. ## Troubleshooting | Symptom | Likely cause | |---|---| | `403 forbidden`: "only reachable from localhost" | you are not on loopback; pass `dependencies` | | `403 forbidden`: "only answers requests addressed to localhost" | the `Host` header is not a loopback name (a hosts-file alias, a tunnel). Use `loopback_guard(allowed_hosts=[...])` | | UI loads, but no requests appear | `install()` ran on a different app object than the one served; or the path is in `ignore_paths` | | Requests appear with no SQL | the engine was not passed to `install()`/`add_engine()` | | Requests have a `route` of `None` and group by raw path | the request matched no route (404), or a catch-all `Mount` swallowed routing | | Callsites are empty | `project_root` is not an ancestor of your code. Set it | | `RuntimeError: Redline is already installed` | `install()` was called twice (an auto-reloader importing twice?) | | N+1 shown with a hint but no diff | the statement could not be located in source. See [confidence](n-plus-one.md#confidence) | ## Wiring an existing application Pass the engine your application's session factory actually uses, after the routers and models are imported and before serving requests. A different engine does not capture those sessions. For an external launcher, set `project_root` to the application's root so source attribution works. Keep the trace store outside source control. ```python from app.main import app from app.db.session import get_engine from fastapi_redline import install, instrument_httpx redline = install(app, engine=get_engine(), settings={ "access": "local", "project_root": "/absolute/path/to/project", }) instrument_httpx() # optional: install() alone does not capture outbound HTTP # If Redis is used, explicitly enable the redis-py integration too: # from redline_core.contrib.redis import instrument_redis # instrument_redis() ``` Use synthetic data and an isolated database for load tests. Missing external/cache spans means the integration may be absent, not necessarily that the app made no calls. SDKs without integrations and separate jobs require explicit instrumentation. Static source analysis complements request capture; its candidates are not measured N+1 defects. ## In-process background tasks Starlette runs a response's `BackgroundTasks` after sending the response. Redline therefore finishes the request trace before those tasks run; their work and latency are not part of the request. To record a task explicitly as its own job trace, schedule it with the helper: ```python from fastapi import BackgroundTasks from fastapi_redline import add_background_task async def send_receipt(order_id: int) -> None: ... @app.post("/orders/{order_id}") async def create_order(order_id: int, background_tasks: BackgroundTasks): add_background_task(background_tasks, send_receipt, order_id) return {"order_id": order_id} ``` `add_background_task(background_tasks, func, *args, **kwargs)` passes the original arguments to the function unchanged. Sync functions still run in Starlette's thread pool, and async functions are awaited. The helper records the function name, job outcome, and safe parent request correlation when called during a traced request. It creates a separate job trace; it does not extend request latency or include the task's work in the request trace. Task arguments and return values are not added to the job recording. Exceptions are recorded as failed jobs and re-raised as Starlette normally handles background task failures. This only covers tasks explicitly scheduled with the helper. It does not instrument task queues, brokers, or other work submitted elsewhere. --- # Flask [← Index](index.md) `flask-redline` is the Flask and SQLAlchemy adapter. It wraps your WSGI app, hooks Flask's own signals for the route template, view and templates, instruments your SQLAlchemy engines and serves the Redline UI from a blueprint inside the same app. It works with plain SQLAlchemy and with **Flask-SQLAlchemy**, with application factories, with `async def` views (Flask's asgiref bridge) and with streaming responses. ## Install ```bash pip install \ "flask-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/flask-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` Python 3.10 or newer, Flask 3.0 or newer (below 4), SQLAlchemy 2.x. Add the `profile` extra to the core requirement for [flamegraphs](flamegraphs.md). See [Getting started](getting-started.md#install) for why the core is named in the same command. ## Mount it ```python from flask import Flask from sqlalchemy import create_engine from flask_redline import Redline app = Flask(__name__) engine = create_engine("sqlite:///app.db") # access="local": localhost only (unset, Redline answers 404 outside debug mode) Redline(app, engine=engine, settings={"access": "local"}) # UI at http://localhost:5000/_redline/ ``` With **Flask-SQLAlchemy** you do not even pass the engine. Its engines, including `SQLALCHEMY_BINDS`, are found and instrumented on the first request, because they may not exist yet when `Redline(app)` runs: ```python db = SQLAlchemy(app) Redline(app) ``` Traces go to their own SQLite file (`.redline/redline.db`), never to your database. ### Application factories ```python redline = Redline(engine=engine) def create_app(): app = Flask(__name__) redline.init_app(app) return app ``` `redline.store`, `.settings`, `.recorder`, `.engines`, `.add_engine(engine, alias=None)` and `.close()` act on the current app (inside an app context) or on the last app that was initialised. The store is flushed and closed at interpreter exit. ## The `Redline` extension ```python Redline( app=None, *, engine=None, # Engine | [engines] | {"alias": engine} engines=None, # "auto": instrument engines created at runtime settings=None, # dict | redline_core.Settings url_prefix=None, # default: the mount_path setting, else "/_redline" permission=None, # callable(request) -> bool; implies access="framework" store=None, # a custom Store; default is the SQLite file ) ``` | Argument | Meaning | |---|---| | `engine` | One engine, a list (the first is the `"default"` alias used by EXPLAIN) or a dict of aliases. Omit it with Flask-SQLAlchemy | | `settings` | A dict of [settings](settings.md) (case-insensitive keys) or a `Settings`. `app.config["REDLINE"]` (a dict) is merged underneath a dict passed here | | `url_prefix` | Where the UI and API live (default: the `mount_path` setting, else `/_redline`). Requests under it are never recorded | | `permission` | Your own access check; implies `access = "framework"`. See [Access control](#access-control) | | `store` | A custom [Store](extending.md#the-store-protocol) | Settings can live in `app.config` too, which is handy with config classes: ```python app.config["REDLINE"] = {"sample_rate": 0.1, "slow_query_ms": 50} Redline(app, engine=engine) ``` The layered configuration (presets, `redline.toml`, `REDLINE_*` environment variables) applies to Flask too; `app.config["REDLINE"]` and `settings=` are the top layer. See [Configuration](configuration.md). ### Several engines ```python Redline(app, engine=[main_engine, analytics_engine]) Redline(app, engine={"main": main_engine, "analytics": analytics_engine}) redline.add_engine(late_engine) # an engine created later ``` The alias is stored on every query so that EXPLAIN runs on the right database. ### Engines created at runtime (per-user or per-request) Apps that build engines on the fly (for example one per user, with token authentication through `connect_args` or `creator=`) cannot register each one. Opt in to automatic discovery: ```python Redline(app, engines="auto") # or settings={"instrument_engines": "all"} ``` This sets `instrument_engines="all"`: every SQLAlchemy `Engine` (sync, or the sync engine inside an `AsyncEngine`) that runs a statement inside a recorded request is hooked on its first use, once, under a unique alias (`auto_`). Engines are held weakly, so a disposed per-request engine is garbage collected as usual. Automatically found sync engines can be EXPLAINed; async ones are recorded but not EXPLAINed. Engines you pass as `engine=` keep their own alias. The default stays explicit registration. ## What is recorded - **Request and response**: method, path, route template (`/orders/`), view dotted name, status, headers, query string and body. Secrets are [redacted](security.md#redaction). - **Bodies are never consumed or buffered without bound.** The request body is copied as the view reads it. Response bodies, including streams, are kept only up to `max_body_bytes`. A `stream_with_context` generator is not read ahead, and the trace ends when the last chunk is sent, so streaming work counts towards the latency. `send_file` and anything served through `wsgi.file_wrapper` is handed back untouched: only its size is recorded. - **SQL** through SQLAlchemy's `before/after_cursor_execute`: statement, bound parameters (redacted), duration, row count, vendor, `db_alias` and the project line that issued the query. - **Spans**: a `view` span around the view function, and a `template` span per `render_template` and `render_template_string`. Queries a template triggers (lazy loading) nest under it. - **Transactions and pool waits**: `transaction` spans from the SQLAlchemy begin, commit and rollback events, and `pool_wait` spans when a connection checkout takes 1 ms or more. See [Transactions and locks](transactions.md). - **Unhandled exceptions** are recorded (Flask's `got_request_exception`) and re-raised or turned into a 500 exactly as before, with [locals](logs-and-exceptions.md#exceptions-with-locals). `abort(404)` and other 4xx `HTTPException`s are client errors, not failures. - **Log records** emitted during the request. See [Logs and exceptions](logs-and-exceptions.md). - **`async def` views** keep the trace: queries and spans created inside the coroutine land in the request's trace. A bare `threading.Thread` is not attributed to any request. - Your own spans: `with redline_core.span("pricing.compute"): ...` ([details](custom-spans.md)). - `X-Redline-Run: ;step=` becomes tags (used by the [load tester](load-testing.md)), for a run that is running in the store. If you put `werkzeug.middleware.proxy_fix.ProxyFix` (or any other WSGI middleware) around the app, wrap it **after** creating `Redline`, so the recorded client address is the real one. Apps mounted under a `SCRIPT_NAME` (`DispatcherMiddleware`) record the full path and route. ## Outbound HTTP and other integrations Nothing is patched unless you ask: ```python from flask_redline import instrument_httpx, instrument_requests instrument_httpx() # every httpx.Client / AsyncClient call becomes an http_out span instrument_requests() # the same for requests.Session.send ``` URLs are redacted (`?api_key=...` is masked). `uninstrument_httpx()` and `uninstrument_requests()` undo it. For Redis, psycopg, asyncpg and Marshmallow see [Integrations](integrations.md). ## Profiling Flamegraphs are opt-in per request: add `?_redline=profile` or the header `X-Redline-Profile: 1` (needs the `profile` extra). They are honoured with `app.debug` or from a request with valid Redline credentials (a client `local` lets in, a token…); see [Forcing capture](security.md#forcing-capture) and [Flamegraphs](flamegraphs.md). ## Endpoints per blueprint Every request served by a blueprint carries the trace tag `blueprint` (the dotted name for nested blueprints, such as `admin.audit`). Apps with many blueprints can read per-blueprint totals instead of one row per route: ```text GET /_redline/api/endpoints?window=24h&group_by=blueprint ``` ```bash flask redline endpoints --group-by blueprint --window 24h # add --json for machine output ``` Each row sums the blueprint's requests (count, p50/p95/p99, average queries, issues) and reports how many routes it spans (`routes`). Requests on routes registered directly on the app are grouped as `(none)`. You can also filter traces by the tag in the UI search. ## Fix suggestions For an N+1, `SQLAlchemyFixSuggester` maps the repeated query to your models and writes a real unified diff with `selectinload(Parent.children)` or `joinedload(Child.parent)`. It works with Flask-SQLAlchemy's `db.session` and `db.Model`. Repeated `text()`/driver SQL without ORM relationships gets a lower-confidence batching hint instead of a diff: use one `IN` query (`bindparam(..., expanding=True)`) or join the child rows into the parent query. See [N+1 detection](n-plus-one.md). ## Server-Timing, the badge and live mode ![The Flask demo shop in Redline: the requests list](assets/screenshots/flask-requests-light.png){ .rl-shot .rl-only-light } ![The Flask demo shop in Redline: the requests list](assets/screenshots/flask-requests-dark.png){ .rl-shot .rl-only-dark } Every recorded response carries a `Server-Timing` header when `server_timing` is on (`"auto"` by default: on in debug mode, off otherwise), HTML pages get the floating badge when `badge` is on (`"auto"`: debug mode), `api/stream` feeds [Live mode](the-ui.md#live-mode) and the snapshot download is served as-is. All of them sit behind the same [access control](access-control.md) and can be switched off with the `sse` and `snapshot` feature switches. See [Server-Timing and the badge](server-timing-badge.md). "Debug mode" is `app.debug`, read per request. `api/stream` holds a worker thread for as long as it is open, so on WSGI servers it closes after about 25 seconds and the UI reconnects with the last `seq`; use a threaded or async worker class if you want live mode under gunicorn. ## Access control The UI exposes your SQL, request bodies and EXPLAIN, so treat it like an admin tool. **Default.** With no `permission`, the [`access` policy](access-control.md) decides, and the default is `local`: only loopback clients (`127.0.0.0/8`, `::1`; a unix-socket peer only with `trust_unix_socket`) that address the server by a loopback name (`Host: localhost`, `127.0.0.1`, `[::1]`, any port; this blocks DNS rebinding) are served, and a warning is logged at startup. **While `access` is not set** (code, `app.config["REDLINE"]`, `redline.toml`, `REDLINE_ACCESS`), that default applies only when `app.debug` is on (`flask --debug run`, `app.run(debug=True)`); otherwise every Redline URL answers `404` and an error is logged at startup. Set `settings={"access": "local"}` on a development machine or `"token"` on a server. Refusals are JSON: `{"error": {"code": "forbidden", "message": "..."}}`. **Your own check.** `permission` is any `callable(request) -> bool`, called with Flask's `request`. Passing it implies `access = "framework"` (unless you set `access` yourself), so it **replaces** the loopback default and the `Host` check becomes yours. The core access check still runs first for `allowed_ips`, `trusted_proxies`, `read_only`, features and CSRF. With an explicit policy such as `token`, `permission` is not used. ```python from flask_login import current_user Redline(app, engine=engine, permission=lambda request: current_user.is_admin) ``` Raise `werkzeug.exceptions.abort(401)` (or any `HTTPException`) inside it to answer with that status. It is rendered as `{"error": {"code": "unauthorized", ...}}`, keeping a `WWW-Authenticate` header. The `allowed_hosts` setting adds accepted host names to the default check (`loopback_guard(allowed_hosts=["devbox"])` is the older spelling). For tokens, basic auth, IP allow-lists, trusted proxies and read-only mode, use the `access` family of settings instead. They behave the same on every framework: see [Access control](access-control.md). **CSRF.** Every non-`GET` request (login and logout included) is refused with `403 csrf_failed` when it carries `Sec-Fetch-Site: cross-site` or `same-site`, or an `Origin` (including `null`) that does not match the request host. Non-browser clients send no `Origin` and are subject only to the access policy. Redline's own responses carry `X-Frame-Options: DENY`. ## EXPLAIN `POST /_redline/api/explain` runs `EXPLAIN` for a recorded SELECT on the engine it came from, inside a transaction that is always rolled back (and `READ ONLY` on PostgreSQL). `EXPLAIN ANALYZE` executes the query, so it is off unless `explain_analyze=True`. See [EXPLAIN](explain.md). ## Command line ```bash flask redline clear [--yes] # delete every recorded trace flask redline prune [--max-age-days N] [--max-rows N] # apply retention now flask redline scan [--json] [--fail] # static N+1 scan of Jinja templates flask redline scenario [-o FILE] [--base-url URL] # write a load-test scenario ``` `scan` runs the Jinja dialect of the [static scan](static-scan.md); `scenario` generates a file for [`redline load`](load-testing.md#generating-scenarios) from your `url_map`. ## Running with several workers Each worker process gets its own writer thread and connection to the same SQLite file in WAL mode. The store is fork-safe, so gunicorn `--preload` works. See [Storage](storage.md#concurrency) and [Production](production.md#process-models). ## Under test Disable recording in your test configuration so tests do not write a trace file: ```python app.config["REDLINE"] = {"enabled": False} ``` With `enabled=False` no WSGI wrapper, hooks or SQLAlchemy listeners are installed. ## Troubleshooting | Symptom | Cause and fix | |---|---| | No requests appear | The path starts with `url_prefix` (never recorded), matches `ignore_paths`, or `sample_rate` dropped it. Check `GET /_redline/api/meta` | | No SQL appears | The engine was not passed and Flask-SQLAlchemy is not set up on the app. Pass `engine=` or call `redline.add_engine()` | | Client address is always `127.0.0.1` behind a proxy | Wrap the app in `ProxyFix` **after** creating `Redline` | | The UI answers 403 `forbidden` | You are not on a loopback address, or used a non-loopback `Host`. Pass `permission=` | | `async def` views lose their queries | Install `flask[async]`. Work in a bare `threading.Thread` is never attributed | A runnable demo with deliberately bad views is in [`examples/flask`](https://github.com/Pythondeveloper6/redline/tree/main/examples/flask). --- # Litestar [← Index](index.md) `litestar-redline` is the Litestar and SQLAlchemy adapter. It is a Litestar plugin: it adds a pure ASGI middleware, hooks Litestar's exception handling, mounts the UI as a `Router` and instruments your SQLAlchemy engines, sync or async. ## Install ```bash pip install \ "litestar-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/litestar-redline" \ "redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core" ``` Python 3.10 or newer, Litestar 2.12 or newer (below 3), SQLAlchemy 2.x. Add the `profile` extra to the core requirement for [flamegraphs](flamegraphs.md). ## Mount it ```python from litestar import Litestar from sqlalchemy.ext.asyncio import create_async_engine from litestar_redline import RedlinePlugin engine = create_async_engine("sqlite+aiosqlite:///app.db") app = Litestar( route_handlers=[...], # access="local": localhost only (unset, Redline answers 404 outside debug mode) plugins=[RedlinePlugin(engine=engine, settings={"access": "local"})], # UI at http://localhost:8000/_redline/ ) ``` Traces go to their own SQLite file (`.redline/redline.db`), never to your database. ## `RedlinePlugin` ```python RedlinePlugin( settings=None, # dict | redline_core.Settings engine=None, # Engine | AsyncEngine | [engines] | {"alias": engine} engines=None, # "auto": instrument engines created at runtime path=None, # default: the mount_path setting, else "/_redline"; never recorded guards=None, # Litestar guards for the UI and API store=None, # a custom Store; default is the SQLite file ) ``` When the app is built the plugin: - adds a pure ASGI middleware (capture, route template, status, bodies, SQL spans); - records exceptions through Litestar's `after_exception` hook; - mounts the UI and JSON API under `path` as a `Router`; - instruments the engines, and **flushes and closes the store on shutdown** (`on_shutdown`; your own lifespan hooks keep working). The plugin object is also the handle: `plugin.recorder`, `plugin.store`, `plugin.settings`, `plugin.add_engine(engine)` for an engine created later and `plugin.close()`. ```python RedlinePlugin(engine=engine, settings={ "sample_rate": 0.1, # keep 10% of requests ... "always_keep_slower_than_ms": 300, # ... plus every slow one and every error "slow_query_ms": 50, }) ``` Presets, `redline.toml` and `REDLINE_*` environment variables apply too; `settings=` is the top layer. `path` defaults to the `mount_path` setting, then `/_redline`. See [Configuration](configuration.md). ### Engines With Litestar's own SQLAlchemy plugin (`advanced-alchemy`) and no `engine=`, that plugin's engines are found and instrumented automatically: ```python from advanced_alchemy.extensions.litestar import SQLAlchemyAsyncConfig, SQLAlchemyPlugin db = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///app.db") app = Litestar([...], plugins=[SQLAlchemyPlugin(config=db), RedlinePlugin()]) ``` Otherwise pass `engine=` yourself. The first engine of a list is the `"default"` alias used by EXPLAIN; others are named after their database file, or pass a dict: ```python RedlinePlugin(engine=[async_engine, sync_engine]) RedlinePlugin(engine={"main": main_engine, "analytics": analytics_engine}) ``` Engines created at runtime (per-user or per-request) are picked up with `RedlinePlugin(engines="auto")`, which sets `instrument_engines="all"`: each engine is hooked on its first use inside a recorded request, under a unique `auto_` alias, and held weakly so disposed engines are collected. Sync engines found this way can be EXPLAINed. See [FastAPI: engines created at runtime](fastapi.md#engines-created-at-runtime-per-user-or-per-request). ## What is recorded - **Request and response**: method, path, route template (`/orders/{order_id}`), handler dotted name (`shop.routes.get_order`, `shop.routes.ShopController.by_sku`), status, headers, query string and body. Secrets are [redacted](security.md#redaction). - **Bodies are never consumed or buffered without bound.** The request body is copied as the app reads it; response bodies, including streams, are kept only up to `max_body_bytes`. - **SQL** through `before/after_cursor_execute`, including through `AsyncSession`: statement, bound parameters (redacted), duration, rows, vendor, `db_alias` and the project line that issued it. - **Transactions and pool waits** as `transaction` and `pool_wait` spans ([details](transactions.md)). - **Event-loop blocking.** A synchronous call inside an `async def` handler stalls the loop for every request. Redline notices and names the call. See [Blocking in async](async-blocking.md). - **Exceptions.** Litestar turns an exception into a response *inside* the middleware, so the plugin registers an `after_exception` hook. A 5xx caused by an exception gets `error` (type, message, traceback and [locals](logs-and-exceptions.md#exceptions-with-locals)); a 4xx `HTTPException` (404, 401, validation) is a client error and is not an error trace. - **Marshmallow `dump`** as a `serializer` span, if you opt in ([Integrations](integrations.md#marshmallow)). Litestar's own DTO and msgspec encoding is not timed separately. - Sync handlers (`sync_to_thread=True`) are attributed to the right request. - Your own spans: `with redline_core.span("pricing.compute"): ...`. - `X-Redline-Run: ;step=` becomes tags (used by the [load tester](load-testing.md)), for a run that is running in the store. Requests that match no route (404) and `405 Method Not Allowed` never reach a route-level middleware, so Litestar does not run Redline for them. ## Outbound HTTP ```python from litestar_redline import instrument_httpx instrument_httpx() # every httpx.Client / AsyncClient call becomes an http_out span ``` Other clients (`requests`), Redis and psycopg are covered in [Integrations](integrations.md). ## Profiling Flamegraphs are opt-in per request: `?_redline=profile` or the header `X-Redline-Profile: 1`, honoured with `Litestar(debug=True)` or from a request with valid Redline credentials (see [Forcing capture](security.md#forcing-capture)). See [Flamegraphs](flamegraphs.md). ## Fix suggestions For an N+1, `SQLAlchemyFixSuggester` maps the repeated query to your models and produces a real unified diff (`selectinload(Parent.children)`, `joinedload(Child.parent)`), exactly as in the [FastAPI adapter](fastapi.md#fix-suggestions-sqlalchemy). ## OpenAPI and load testing Litestar serves an OpenAPI schema, so you can generate a load-test scenario from it: ```bash redline load init --from-openapi http://localhost:8000/schema/openapi.json ``` See [Load testing](load-testing.md#generating-scenarios). ## Server-Timing, the badge and live mode ![The Litestar demo shop in Redline: the requests list](assets/screenshots/litestar-requests-light.png){ .rl-shot .rl-only-light } ![The Litestar demo shop in Redline: the requests list](assets/screenshots/litestar-requests-dark.png){ .rl-shot .rl-only-dark } Every recorded response carries a `Server-Timing` header when `server_timing` is on (`"auto"` by default: on in debug mode, off otherwise), HTML pages get the floating badge when `badge` is on (`"auto"`: debug mode), `api/stream` feeds [Live mode](the-ui.md#live-mode) and the snapshot download is served as-is. All of them sit behind the same [access control](access-control.md) and can be switched off with the `sse` and `snapshot` feature switches. See [Server-Timing and the badge](server-timing-badge.md). "Debug mode" is the Litestar app's `debug` flag. The badge is injected only into small, non-streamed HTML pages (a known `content-length` of at most 2 MiB, or a single body message); anything else passes through untouched. `api/stream` is served on the event loop and closes after five minutes; the UI reconnects with the last `seq`. ## Access control The UI exposes your SQL, request bodies and EXPLAIN, so treat it like an admin tool. **Default.** With no `guards`, the [`access` policy](access-control.md) decides, and the default is `local`: only loopback clients (`127.0.0.0/8`, `::1`; a unix-socket peer only with `trust_unix_socket`) that address the server by a loopback name (`Host: localhost`, `127.0.0.1`, `[::1]`, any port; this blocks DNS rebinding) are served, and a warning is logged at startup. **While `access` is not set** (code, `redline.toml`, `REDLINE_ACCESS`), that default applies only with `Litestar(debug=True)`; otherwise every Redline URL answers `404` and an error is logged. Set `settings={"access": "local"}` on a development machine or `"token"` on a server. Refusals are JSON: `{"error": {"code": "forbidden" | "unauthorized" | ..., "message": "..."}}`. Add other host names with the `allowed_hosts` setting (or `guards=[loopback_guard(allowed_hosts=["devbox"])]`). **Your own guard.** Any Litestar guard. Passing `guards=` implies `access = "framework"` (unless you set `access` yourself), so your guards **replace** the loopback default. The core access check runs first (it still applies `allowed_ips`, `trusted_proxies`, `read_only`, features and CSRF), then your guards: ```python from litestar.exceptions import NotAuthorizedException def require_admin(connection, _handler): if not connection.user or not connection.user.is_admin: raise NotAuthorizedException() RedlinePlugin(engine=engine, guards=[require_admin]) ``` `guards=[]` is the same as not passing any (since 0.2: it used to leave the UI open). For tokens, basic auth, IP allow-lists, trusted proxies and read-only mode, use the `access` family of settings. They behave the same on every framework: see [Access control](access-control.md). With an explicit policy other than `framework`, your `guards` still run after the gate. **CSRF.** Every non-`GET` request to Redline (including login and logout) is refused with `403 csrf_failed` when it carries `Sec-Fetch-Site: cross-site` or `same-site`, or an `Origin` (including `null`) that does not match the request host. This is always on, whatever `guards` you pass. Redline's own responses carry `X-Frame-Options: DENY`. !!! tip "Behind a reverse proxy" A proxy on the same host makes every client look like localhost, so a loopback peer that sends `X-Forwarded-For` (and is not in `trusted_proxies`) is refused under `local`. Use `access = "token"` and `trusted_proxies`. See [Access control](access-control.md#behind-a-reverse-proxy). ## EXPLAIN `POST /_redline/api/explain` runs `EXPLAIN` for a recorded SELECT on the engine it came from, inside a transaction that is always rolled back (`READ ONLY` on PostgreSQL). `EXPLAIN ANALYZE` executes the query, so it is off unless `explain_analyze=True`. See [EXPLAIN](explain.md). ## Troubleshooting | Symptom | Cause and fix | |---|---| | No requests appear | The path starts with `path` (never recorded), matches `ignore_paths`, was sampled out, or is a 404 that matched no route | | No SQL appears | Pass `engine=`, or use `advanced-alchemy`'s plugin so engines are discovered | | The UI answers 403 | Not a loopback client or `Host`. Pass `guards=` or configure [access](access-control.md) | | Handler shows the wrong name | Controllers are named `module.Controller.method`; check `GET api/traces/` for `view` | --- # Integrations [← Index](index.md) Redline records what your framework adapter hooks automatically: the ORM, templates, the cache framework in Django, and so on. Everything else your request does, calling another service, talking to Redis, querying PostgreSQL without an ORM or dumping data through a serializer, is covered by **contrib integrations** in `redline_core.contrib`. They share a few rules: - **Opt-in.** Nothing is patched until you call the `instrument_*` function. They are never imported by `import redline_core`, so unused ones cost nothing. - **Idempotent.** Call each once at startup (twice is harmless). Each has an `uninstrument_*` twin that restores the original. - **Free outside a request.** Outside a traced request each wrapper is one `ContextVar.get()`. - **Redacted.** URLs, keys and parameters pass through the same [redaction](security.md#redaction) as everything else. | Library | Call | Records | Extra | |---|---|---|---| | SQLAlchemy | `instrument_engine(engine)` | `sql`, `transaction`, `pool_wait` spans | `sqlalchemy` | | httpx | `instrument_httpx()` | `http_out` spans | `httpx` | | requests | `instrument_requests()` | `http_out` spans | `requests` | | boto3 | `instrument_boto3()` | `http_out` spans per SDK operation | `boto3` | | redis-py | `instrument_redis()` | `cache` spans | `redis` | | pymongo | `instrument_pymongo()` | `custom` spans per collection call (`client="mongodb"`) | none | | kafka-python | `instrument_kafka()` | `custom` publish spans (`client="kafka"`) | none | | pika | `instrument_pika()` | `custom` publish spans (`client="amqp"`) | none | | Google Cloud Storage | `instrument_google_cloud_storage()` | `custom` upload/download spans (`client="gcs"`) | none | | Azure Blob Storage | `instrument_azure_blob()` | `custom` upload/download/delete spans (`client="azure_blob"`) | none | | asyncpg | `instrument_asyncpg()` | `sql` spans | `asyncpg` | | psycopg 3 | `instrument_psycopg()` | `sql` spans | `psycopg` | | Raw DB-API driver | `instrument_dbapi(module)` | `sql` spans (`source="raw_cursor"`) | any DB-API driver | | Threads and pools | `instrument_threads()` | carries the request into `Thread` and `ThreadPoolExecutor` work; spans get `data["thread"]` | none | | Marshmallow | `instrument_marshmallow()` | `serializer` spans | none | | Strawberry | `RedlineExtension` | `resolver` spans | `strawberry` | | Graphene | `RedlineMiddleware` | `resolver` spans | `graphene` | The extras install the third-party library at a compatible version, for example `pip install "redline-core[redis] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core"`. The adapters re-export `instrument_httpx` (and `instrument_requests` for Flask) so older imports keep working. ## SQLAlchemy ```python from redline_core.contrib.sqlalchemy import instrument_engine instrument_engine(engine) # sync or async engine ``` The FastAPI, Flask and Litestar adapters call this for the engines you pass them. Use it directly when you build an engine Redline does not know about. Beyond statement, parameters, duration and callsite it records: - **`transaction` spans** from the begin, commit and rollback events, with the outcome, the number of queries inside and the number of outbound HTTP calls made while the transaction was open. Empty transactions and control statements such as `SAVEPOINT` are not recorded. See [Transactions and locks](transactions.md). - **`pool_wait` spans** when checking a connection out of the pool takes 1 ms or more, with the pool size and how many connections were already checked out. - The SQLAlchemy [fix suggester](n-plus-one.md) and the EXPLAIN executor (`SQLAlchemyFixSuggester`, `explain_executor_factory`). ## httpx ```python from redline_core.contrib.httpx import instrument_httpx instrument_httpx() # every httpx.Client / AsyncClient call becomes an http_out span ``` A span records method, URL (redacted), status and duration. The span name is `GET host/path`. This feeds the [External calls](external-calls.md) page and the `slow_external`, `duplicate_external` and `retry_storm` detectors. ## requests ```python from redline_core.contrib.requests import instrument_requests instrument_requests() # patches requests.Session.send ``` Same data as httpx. Because `requests` is synchronous, calling it inside an `async def` handler also blocks the event loop; see [Blocking in async](async-blocking.md). ## boto3 ```python from redline_core.contrib.boto3 import instrument_boto3 instrument_boto3() ``` Records one `http_out` span for each botocore client operation. Span names and synthetic URLs contain only the service and operation (for example, `AWS s3 GetObject` and `https://s3.amazonaws.com/__sdk__/GetObject`). Status and duration are recorded; API arguments, response data, bucket and object keys, credentials, presigned URLs, and error messages are not captured. If HTTP-level instrumentation also observes the SDK's network request, both spans may appear: the SDK span measures the whole operation, while the HTTP span measures its network call. `instrument_boto3()` returns `False` when botocore is unavailable. ## Redis ```python from redline_core.contrib.redis import instrument_redis instrument_redis() ``` Wraps `Redis.execute_command` for both the sync client and `redis.asyncio`, and `Pipeline.execute`. Each command becomes a `cache` span with `op` (the command), `key` (capped at 200 characters), `backend` (`redis`) and, for read commands, `hit` (`GET`, `GETEX`, `GETDEL`, `HGET`, `MGET`, `HMGET`, `LINDEX`: a `None` result is a miss). A pipeline is **one** span (`op="pipeline"`); the commands queued on it are not recorded individually, and spans without a key are not included in the [cache statistics](cache-efficiency.md). Django's cache framework (including a Redis cache backend) is already recorded by `django-redline`; use this when you talk to Redis directly, from Flask, FastAPI or Litestar, or from Django code that bypasses `django.core.cache`. ## asyncpg ```python from redline_core.contrib.asyncpg import instrument_asyncpg instrument_asyncpg() ``` For apps that use asyncpg without an ORM. Wraps `Connection.execute`, `fetch`, `fetchrow`, `fetchval` and `executemany`; pool methods delegate to these, so pooled connections are covered. Statements are recorded in asyncpg's `$1` placeholder style. Row counts are filled in where the result exposes them, which enables the [large-result detectors](result-size.md). ## psycopg 3 ```python from redline_core.contrib.psycopg import instrument_psycopg instrument_psycopg() ``` For psycopg 3 used directly, sync or async cursors. The patch is process-wide (a connection argument is accepted and ignored). If you use SQLAlchemy with the psycopg driver you do **not** need this: SQLAlchemy's events already see those queries, and patching both would record each query twice. !!! warning "One path per query" Use exactly one capture path per database driver: the ORM's (Django, SQLAlchemy) *or* the driver-level one (asyncpg, psycopg). If you instrument SQLAlchemy and asyncpg and use SQLAlchemy's asyncpg dialect, every query is recorded twice. ## Raw DB-API cursors SQL that bypasses the engine is recorded too. With an instrumented SQLAlchemy engine, `engine.raw_connection()` called from your code returns a thin proxy: `cursor().execute`, `executemany` and `callproc` become `sql` spans with `source="raw_cursor"`. An `executemany` is one span with a `batch_size`, not one span per row. For a driver used with no engine at all, opt in once at startup: ```python import sqlite3 from redline_core.contrib.dbapi import instrument_dbapi instrument_dbapi(sqlite3) # patches sqlite3.connect; undo with uninstrument_dbapi(sqlite3) ``` Limits: statements run through `connection.connection.cursor()` of a SQLAlchemy `Connection` and connections opened before `instrument_dbapi` was called are not recorded. `redline instrumentation` lists every loaded raw driver (psycopg2, pymysql, MySQLdb, pyodbc, pymssql, oracledb, cx_Oracle) as `dbapi:: active` or `inactive`. Inactive means SQL sent through that driver's own `connect()` is not recorded. `auto_instrument` never wraps a driver, because SQLAlchemy calls the same `connect()` and the SQL would be recorded twice. ## Marshmallow ```python from redline_core.contrib.marshmallow import instrument_marshmallow instrument_marshmallow() ``` Patches `Schema.dump`. Only the **outermost** `dump` becomes a `serializer` span; nested schemas (`fields.Nested`) are part of their parent's time. Feeds the [slow serializer detector](serializers.md). Marshmallow has no extra: the call returns `False` if marshmallow is not installed. ## Data stores, queues and object storage ```python from redline_core.contrib.pymongo import instrument_pymongo from redline_core.contrib.kafka import instrument_kafka from redline_core.contrib.pika import instrument_pika from redline_core.contrib.google_cloud_storage import instrument_google_cloud_storage from redline_core.contrib.azure_blob import instrument_azure_blob ``` These record `custom` spans built with [`instrument_client_method`](extending.md#instrumenting-a-client). Each span has `client`, `op`, `target`, `payload_bytes` and `error` in its data. Every function imports its library only when called and returns `False` if it is not installed, so an app without the library is unaffected. Filters, documents, message keys and bodies, object names, URLs and credentials are never captured, and an error is recorded as its class name. | Integration | What a span covers | Target | Size | |---|---|---|---| | pymongo | `Collection` writes, `find_one`, `count_documents`, `distinct`, `bulk_write`, and each network batch of a `find()` cursor (`op="find"`) | `database.collection` | none | | kafka-python | `KafkaProducer.send` (`op="publish"`). `send` only enqueues, so the span is the time the caller waited, not delivery | topic | value, when bytes | | pika | `BlockingChannel.basic_publish` (`op="publish"`) | `exchange/routing_key` | body | | Google Cloud Storage | `Blob.upload_from_*` and `download_*` | bucket | upload data (`upload_from_string`) and downloaded bytes or text | | Azure Blob Storage | `BlobClient.upload_blob`, `download_blob`, `delete_blob`, sync and `aio`. `download_blob` covers starting the download; the stream is read later | container | upload data | For any other client, wrap it yourself with `instrument_client_method` ([Extending](extending.md#instrumenting-a-client)). `auto_instrument="on"` also instruments these when they are installed; the default `"warn"` lists them if installed and inactive. Asynchronous drivers (motor, aiokafka) are not covered; wrap their coroutine methods with the helper. ## Threads and pools ```python from redline_core.contrib.threads import instrument_threads instrument_threads() ``` Not a client but a gap in what is attributed: SQL, cache and HTTP calls made on a plain `threading.Thread` or a `ThreadPoolExecutor` worker belong to no request, because those threads do not inherit `contextvars`. `instrument_threads()` patches `ThreadPoolExecutor.submit` and `Thread.start` so the work runs in a copy of the request's context. The spans appear under the request, each with the thread's name in `data["thread"]`. It is process-wide, reversible with `uninstrument_threads()`, and never enabled by `auto_instrument`. Work that outlives the request is not recorded. Details and limits: [Work on threads and pools](async-blocking.md#work-on-threads-and-pools). ## GraphQL Strawberry and Graphene resolvers are described on their own page: [GraphQL](graphql.md). ## Writing your own The building blocks are public. `redline_core.record_span` and `redline_core.record_query` add a span to the current request from any code: ```python import time from redline_core import record_span start = time.perf_counter() result = my_client.call() # record_span(kind, name, start, duration_in_seconds, data) record_span("http_out", "POST payments.example/charge", start, time.perf_counter() - start, {"status": 200, "method": "POST"}) ``` For plain timing of your own code, use `redline_core.span` ([Custom spans](custom-spans.md)). For a full integration with its own fix suggestions see [Extending](extending.md). ## Zero-config coverage httpx, requests, Redis and boto3 capture is opt-in, so an installed library can silently go unrecorded. The `auto_instrument` setting (all four adapters apply it when Redline installs) decides what happens: | Value | Behaviour | |---|---| | `"warn"` (default) | Log **one** warning listing installed but uninstrumented integrations and how to enable them. Nothing is patched. | | `"on"` | Instrument every installed supported integration at install time. | | `"off"` | Do nothing. | ```python install(app, settings={"auto_instrument": "on"}) # or REDLINE_AUTO_INSTRUMENT=on ``` Provider libraries are only imported when being instrumented. A failure to instrument one integration is logged and never stops startup. Calling `instrument_httpx()` yourself still works and silences the warning for that integration. ## RQ ```python from redline_core.contrib.rq import instrument_rq integration = instrument_rq(recorder) # web process and worker process # integration.uninstall() restores RQ ``` Install with `pip install "redline-core[rq]"`. Enqueueing inside a traced request stores its trace context in `job.meta["redline"]`; `Job.perform` then records the job (name, id, queue, outcome, SQL and other spans) linked to that request through `parent_trace_id` and the W3C trace id. Arguments and results are not captured. Pass `task_filter=lambda name: ...` to limit which jobs are recorded. ## Dramatiq ```python from redline_core.contrib.dramatiq import instrument_dramatiq instrument_dramatiq(broker, recorder) # in the web process and in the worker process ``` Install with `pip install "redline-core[dramatiq]"`. A middleware carries the trace context in `message.options["redline"]` and records each processed message as a job (the retry count is the attempt). Works with any broker; the tests use `StubBroker`. ## FastAPI and Starlette background tasks `BackgroundTasks.add_task` / `BackgroundTask` run after the response was sent, when the request trace has already been stored. `fastapi_redline.install` records each as its own job (`job.queue = starlette.background`), linked to the request that created it. Other Starlette apps can call `redline_core.contrib.starlette_background.instrument_background_tasks(recorder)`. ## Checking integration coverage Open **Analysis → Recording health** (or `GET api/analysis/health`) to distinguish whether an optional provider is installed, loaded in this process and instrumented. The check never imports providers or enables hooks. An inactive hook means those calls may be missing; an active hook still does not prove calls occurred or cover other workers. HTTPX, requests, Redis and boto3 are explicit opt-ins unless `auto_instrument` is `"on"`; the default `"warn"` logs which ones are installed but inactive. SDK operation spans use a `SDK:` method and a synthetic service URL. Because resource identity and individual retry attempts are deliberately omitted, these spans contribute latency/error/count totals but do not establish duplicate calls or retry storms. This avoids treating reads of different object keys as identical requests. --- # Extending [← Index](index.md) Redline has two extension points, both small `typing.Protocol`s in `redline_core`, and a helper for making any other client visible: | Extension | You write | Use it for | |---|---|---| | [`FixSuggester`](#fixsuggester) | one method, `suggest(issue, spans)` | fix advice for another ORM, a house style, or a framework Redline does not know | | [`Store`](#the-store-protocol) | the storage interface | keeping traces somewhere other than the local SQLite file | | [`instrument_client_method`](#instrumenting-a-client) | one call per client method | spans for a database, queue or storage client Redline has no integration for | All three are **beta** surfaces: signatures may change before 1.0. ## The data you will touch All of it is plain dataclasses in `redline_core.model` (and re-exported from `redline_core`). The public surface and its stability rules are in [API stability](api-stability.md). ```python @dataclass class Span: id: str parent_id: str | None kind: str # sql, cache, http_out, template, middleware, view, custom name: str start_ms: float duration_ms: float callsite: Callsite | None data: dict # kind-specific; for sql: sql, params, fingerprint, # db_alias, vendor, rows, many, explainable @dataclass(frozen=True) class Callsite: file: str # relative to project_root when possible line: int function: str code: str | None # the source line, stripped stack: tuple[Frame, ...] # up to 12 project frames, innermost last # .location -> "file:line" @dataclass class Issue: id: str kind: str # n_plus_one, duplicate_query, slow_query, too_many_queries severity: str # info, warning, critical title: str detail: str span_ids: list[str] fingerprint: str | None callsite: Callsite | None count: int total_ms: float suggestion: Suggestion | None @dataclass class Suggestion: summary: str # "Add .prefetch_related('items') to the Order queryset" code: str | None # a one-line fix diff: str | None # a unified diff, when you could locate the code confidence: str # high, medium, low docs_url: str | None ``` ## FixSuggester ```python from typing import Protocol class FixSuggester(Protocol): def suggest(self, issue: Issue, spans: list[Span]) -> Suggestion | None: ... ``` The detector calls each registered suggester **in order** for every issue. `spans` are the issue's SQL spans (`issue.span_ids` resolved). Return a `Suggestion`, or `None` to pass. - **The first non-`None` result wins.** Order therefore matters. - The built-in `GenericSuggester` (confidence `low`) is always **last**, so you only need to handle the cases you can do better. - **An exception is logged and skipped**: the next suggester runs. A broken suggester never breaks a request. - Suggesters run for **every** issue kind. Return `None` for kinds you do not handle (the Django suggester handles `n_plus_one` and `duplicate_query`; the SQLAlchemy one only `n_plus_one`). - They run on the **request path** when the trace finishes (for kept traces). Keep them fast; parse source files once and cache them. ### A worked example A suggester for a Tortoise-ORM style `prefetch_related`, matching on table name: ```python from redline_core import Issue, Span, Suggestion class TortoiseSuggester: def suggest(self, issue: Issue, spans: list[Span]) -> Suggestion | None: if issue.kind != "n_plus_one" or issue.callsite is None: return None table = _table_of(spans[0].data["fingerprint"]) # your own helper relation = RELATIONS.get(table) # {"orderitem": "Order.items"} if relation is None: return None # let the next suggester try owner, attr = relation.split(".") return Suggestion( summary=f"Prefetch {relation} on the {owner} query.", code=f'{owner}.all().prefetch_related("{attr}")', diff=None, # no source location: hint only confidence="medium", docs_url="https://tortoise.github.io/query.html#prefetching", ) ``` ### Registering it The detector lives on the recorder. Register after Redline is set up. === "FastAPI" ```python redline = install(app, engine=engine) redline.recorder.detector.add_suggester(TortoiseSuggester()) ``` === "Django" ```python # e.g. in an AppConfig.ready() from django_redline.runtime import get_runtime get_runtime().recorder.detector.add_suggester(TortoiseSuggester()) ``` `add_suggester` inserts yours **ahead of the generic fallback but after the adapters' own suggesters**, so the built-in Django or SQLAlchemy advice is tried first and yours only sees what they declined. !!! warning "Django: the runtime is rebuilt when `REDLINE` or `DEBUG` change" `django_redline.runtime` rebuilds the recorder on the `setting_changed` signal (this happens in tests with `override_settings`). A suggester registered on the old recorder does not carry over. Register again after a rebuild, or register from code that runs per runtime. ### Writing a diff A diff is a plain unified diff against the file in the callsite. Build it with `difflib.unified_diff` using `a/` and `b/` headers, as the built-in suggesters do, so the UI's **Copy diff** produces something `git apply` accepts when run from the project root. The file path in `Callsite.file` is relative to `project_root`. Only produce a diff when you are **sure** you found the right expression. A wrong diff is worse than a hint. Use `confidence` honestly: `high` means "relation and line identified". ## Instrumenting a client Time spent in a client Redline cannot see shows up as [unattributed time](detectors.md#unattributed-time) on the request. `instrument_client_method` makes it visible: it wraps one method of a client class (or one object) and records every call as a span with the client name, the operation, a target, the duration, a payload size and, on failure, the exception class. ```python from redline_core import instrument_client_method from redline_core.extending import payload_size restore = instrument_client_method( acme_sdk.Client, # a class (all instances) or one object "put", client="acme", # span data["client"] operation="write", # a string, or a callable (self, args, kwargs) -> str target=lambda self, args, kwargs: args[0], # e.g. the table name payload_bytes=lambda self, args, kwargs: payload_size(args[1]), # request size result_bytes=payload_size, # response size, from the return value ) # restore() puts the original method back ``` | Property | Behaviour | |---|---| | Span | kind `custom` (override with `kind=`), name `acme write orders`, data `client`, `op`, `target`, `payload_bytes`, `error`, and `result_bytes` when given | | Sizes | `payload_size(value)` measures only bytes-like and text values; anything else is `None` rather than serialized to be measured | | Errors | the exception class name only, never its message; the exception is re-raised unchanged | | Safety | a hook that raises is ignored (the call still runs and is recorded); the target is redacted and capped at 200 characters | | Async | coroutine functions are wrapped as coroutines | | Idempotent | wrapping an already wrapped method does nothing; the undo function restores the original and does nothing if another patch replaced yours | | Cost | outside a traced request, one `ContextVar` read per call | Use it on instance methods; static and class methods are not supported. For code you cannot patch, `client_span` is the context-manager form: ```python from redline_core import client_span with client_span("acme", "scan", target="orders") as info: rows = acme_client.scan("orders") info["payload_bytes"] = len(rows) ``` The first-party [pymongo, Kafka, pika, Google Cloud Storage and Azure Blob integrations](integrations.md#data-stores-queues-and-object-storage) are built on this helper. ## The `Store` protocol ```python class Store(Protocol): path: str def save(self, trace: Trace) -> None: ... def get(self, trace_id: str, *, include_profile: bool = True) -> Trace | None: ... def get_profile(self, trace_id: str) -> dict | None: ... def has_profile(self, trace_id: str) -> bool: ... def list(self, filters: Filters | None = None, limit: int = 50, cursor: str | None = None) -> Page: ... def endpoints(self, window: float) -> list[EndpointStats]: ... def issues(self, window: float, kind: str | None = None) -> list[IssueGroup]: ... def delete(self, trace_id: str) -> int: ... def clear(self) -> int: ... def prune(self, max_age_s: float | None = None, max_rows: int | None = None) -> int: ... def count(self) -> int: ... def flush(self, timeout: float | None = None) -> bool: ... def close(self) -> None: ... ``` ### The contract | Method | Obligations | |---|---| | `save` | **Must never block the request.** Enqueue and return; drop and count rather than wait. It is called on the request path, once per kept trace | | `get` | Return the full trace, or `None`. `include_profile=False` must omit the (large) profile | | `list` | Newest first. `filters` carries `q`, `method`, `status`, `min_ms`, `min_queries`, `has_issues`, `route`, `tag`. Return a `Page(items, next_cursor, total)` of `TraceSummary` dicts (`Trace.summary()`). Cursors must stay valid while new rows arrive | | `endpoints` | One `EndpointStats` per `(route or path, method)` in the window; see [the definitions](issues-and-endpoints.md#endpoints). `series` has at most 48 non-empty buckets | | `issues` | Issue groups deduplicated by `Issue.id`, the sample being the latest occurrence | | `delete`, `clear`, `prune` | Return the number of traces deleted. `prune(None, None)` applies the store's own rules; `0` disables a rule for that call (never "delete all"); negative values raise `ValueError` | | `flush` | Block until everything saved so far is durable; `False` on timeout. Called on shutdown | | `close` | Flush and release resources. `save` after `close` should drop | | fork safety | A store built before `fork()` (gunicorn `--preload`) is used in every worker. Do not share sockets, threads or connections across the fork: reopen them in the child (`os.register_at_fork(after_in_child=...)`, or compare `os.getpid()` on use), as `SQLiteStore` does | Useful helpers: `Filters.from_params(...)` parses and validates raw query parameters (raising `FilterError`), `parse_window`, `percentile`, and `encode_cursor` / `decode_cursor` live in `redline_core.storage`. ### Plugging it in === "FastAPI" ```python install(app, engine=engine, store=MyStore()) ``` === "Django" ```python REDLINE = {"STORE": "myproject.redline.MyStore"} # called with the core Settings ``` `STORE` takes a `Store` instance, a callable or class taking the core `Settings`, or the dotted path of either. See [Django: custom store](django.md#custom-store). ### Building on `SQLiteStore` The default store is a good base class: subclass it and override `save` to forward to another system as well, or call `SQLiteStore.from_settings(settings, ...)` and wrap it: ```python from redline_core.storage import SQLiteStore class MirroringStore(SQLiteStore): def save(self, trace): super().save(trace) forward_to_elsewhere(trace.to_dict(include_profile=False)) # must also not block ``` ## Using the core directly Everything the adapters use is public in `redline_core`, so you can instrument something Redline does not cover (a Celery task, a management command, another framework): ```python from redline_core import Recorder, Settings, start_trace, finish_trace, record_query from redline_core.storage import SQLiteStore settings = Settings.from_mapping({"storage_path": ".redline/jobs.db"}) recorder = Recorder(settings, SQLiteStore.from_settings(settings)) builder = recorder.start_trace(method="JOB", path="/jobs/send-email", framework="other") try: ... # your hooks call record_query(...) / record_span(...) recorder.finish_trace(builder, status=200) except Exception as exc: recorder.finish_trace(builder, status=500, error=exc) raise ``` | Function | Purpose | |---|---| | `start_trace(...)` | begin a trace in the current context; pass **unredacted** headers, query and body. Redaction happens at finish | | `finish_trace(builder, status=..., headers=, body=, size=, route=, view=, error=)` | end it; always returns the `Trace`, which is stored if sampling keeps it | | `record_query(sql, params, *, start, duration, db_alias, vendor, rows, many)` | record SQL. `start` is a `time.perf_counter()` reading and `duration` is in **seconds** | | `record_span(kind, name, start, duration, data)` | record any other span, same units | | `current()` | the active `TraceBuilder`, or `None` | | `span(...)` | [custom spans](custom-spans.md) | `recorder.recording(**fields)` is a context manager that starts a trace, finishes it with status 200, or 500 if the block raises, and leaves the result in `recorder.last_trace`, which is handy in tests. !!! note "No public stability promise yet" The adapters use exactly these functions, so they work, but until 1.0 the signatures can change. Pin the version. --- # Configuration [← Index](index.md) Redline has one configuration surface for every framework. The same settings, the same names, the same validation: only the place you write the framework-specific part differs. This page is about *how settings are combined*. The settings themselves are in the [Settings reference](settings.md), and the access-related ones in [Access control](access-control.md). ## Layers and precedence Settings are layered. Each layer overrides the one before it: | # | Layer | Where | Example | |---|---|---|---| | 1 | **Built-in defaults** | `redline_core.conf.Settings` | `sample_rate = 1.0` | | 2 | **Adapter defaults** | the framework adapter | Django: `sample_rate = 0.1` without `DEBUG`, `storage_path` and `project_root` from `BASE_DIR`; `access = "framework"` when the adapter has a native access hook | | 3 | **Preset** | the `preset` setting | `preset = "production"` | | 4 | **Config file** | `redline.toml` or `[tool.redline]` in `pyproject.toml` | `sample_rate = 0.2` | | 5 | **Environment** | `REDLINE_` variables | `REDLINE_SAMPLE_RATE=0.1` | | 6 | **Framework settings** | `REDLINE = {...}`, `app.config["REDLINE"]`, `install(settings=...)`, `RedlinePlugin(settings=...)` | `"SAMPLE_RATE": 0.05` | The last one wins. This lets you keep sensible defaults in a committed file, override them per environment with variables (no code change, no rebuild of the image), and still have the application code say the final word where it must. A **preset** only changes *defaults*: any value set in layers 4 to 6 overrides it. Setting `preset = "production"` and `sample_rate = 0.5` gives you production behaviour with 50% sampling. The `preset` itself is read from the highest layer that sets it (framework, then env, then file, then adapter) and is `dev` if none does. The `features` table is merged key by key across layers rather than replaced. A **native access hook** (Django's superuser check or `PERMISSION`, a non-empty FastAPI `dependencies=` or Litestar `guards=` list, a Flask `permission=`) sets `access = "framework"` at the adapter layer, so any file, env or framework value for `access` wins, but a preset does not: Django with the `production` preset keeps its permission check. See [Access control](access-control.md#framework). When **nothing sets `access`** (FastAPI, Flask, Litestar), the `local` default is served only while the framework is in debug mode; otherwise Redline answers `404` and logs an error at startup. Set `access` in any layer (file, `REDLINE_ACCESS`, code) to choose. See [Access control](access-control.md#policies). !!! tip "See what is in effect" ```bash redline config ``` prints the effective configuration, **where each value came from** (default, adapter, preset, file or `env REDLINE_X`) and any warnings. Secrets are shown as `***`. It sees the file and environment layers only: settings you pass in code (`REDLINE = {...}`, `install(settings=...)`) are not visible to a separate command. The running app's complete view, including the framework layer, is the UI's **Settings** page and `GET api/config`. ## Presets Presets are named bundles of defaults for the three situations most people are in. | Setting | `dev` (default) | `staging` | `production` | |---|---|---|---| | `sample_rate` | `1.0` (keep everything) | `0.25` | `0.05` | | `always_keep_errors` | `True` | `True` | `True` (slow requests are always kept too) | | Request and response bodies | captured | captured | **not** captured | | `capture_locals` | on | **off** | **off** | | `log_level` | `INFO` | `INFO` | `WARNING` | | `access` | `local` (Django: superusers; others: debug mode only until set) | `token` | `token`, **required** | | `read_only` | no | no | **yes** | | `badge` | `auto` (on in debug) | `auto` | **off** | | `server_timing` | `auto` (on in debug) | `auto` | **off** | | `load_from_ui` | off | off | off | | `checks_from_ui` | `auto` | `auto` | off | | `explain_analyze` | off | off | off | | `profile` | `opt_in` | `opt_in` | **off** | Outside `dev` the token must be at least 24 characters, or Redline refuses to start with a message that includes a one-line way to generate one. Choose one: === "Django" ```python # settings.py REDLINE = {"PRESET": "production"} ``` === "FastAPI" ```python install(app, engine=engine, settings={"preset": "production"}) ``` === "Flask" ```python app.config["REDLINE"] = {"preset": "production"} Redline(app, engine=engine) ``` === "Litestar" ```python RedlinePlugin(engine=engine, settings={"preset": "production"}) ``` === "Environment" ```bash REDLINE_PRESET=production ``` The `staging` and `production` presets use `access="token"`, which needs a token (`REDLINE_TOKEN` or `token_file`). Without one Redline raises a `SettingsError` at startup that says how to generate one. See [Access control](access-control.md#production-read-only). The details and reasoning are in [Production](production.md#the-production-preset). ## The config file Redline looks for `redline.toml` in `project_root`, then for a `[tool.redline]` table in `pyproject.toml` there. It never searches parent directories. `project_root` is the framework setting if given, else `REDLINE_PROJECT_ROOT`, else the adapter default (Django: `BASE_DIR`), else the working directory. Set `REDLINE_CONFIG=/path/to/file.toml` to use another file; it must exist. `redline.toml` can be flat, as below, or nest the keys under `[redline]` or `[tool.redline]`. An unknown key in the file is an error naming the file, with a "did you mean" hint. Keys are the setting names, in lower case: ```toml # redline.toml preset = "staging" sample_rate = 0.25 slow_query_ms = 50 ignore_paths = ["/static/", "/favicon.ico", "^/health", "^/metrics"] release = "2026.10.3" # access access = "token" allowed_ips = ["10.20.0.0/16"] trusted_proxies = ["10.0.0.0/8"] [features] replay = false load = false ``` The same content works under `[tool.redline]`: ```toml # pyproject.toml [tool.redline] preset = "staging" sample_rate = 0.25 ``` !!! note "TOML needs Python 3.11 or the `tomli` package" On Python 3.10 without `tomli` the file is **ignored with a warning**, not an error. Run `redline config` to see warnings. !!! danger "Never put secrets in a file you commit" `token`, `basic_users` hashes and similar belong in environment variables or in a `token_file` that is not in version control. A committed `redline.toml` is the place for thresholds and ignore lists. ## Environment variables Every setting has a variable: `REDLINE_` plus the setting name in upper case. Values are parsed by the setting's type. | Type | Written as | Example | |---|---|---| | bool | `1`, `true`, `yes`, `on` / `0`, `false`, `no`, `off` | `REDLINE_ENABLED=0` | | int, float | a number | `REDLINE_SAMPLE_RATE=0.1` | | string | the text, as is (`token` and `secret_key` are kept verbatim) | `REDLINE_ACCESS=token` | | optional (`str`, number or URL) | an empty value, `none` or `null` means unset | `REDLINE_MAX_ROWS=none` | | `badge`, `server_timing` | `auto` or a bool | `REDLINE_BADGE=auto` | | list | a JSON array or comma-separated | `REDLINE_ALLOWED_IPS=10.0.0.0/8,192.168.0.0/16` | | table (`features`, `basic_users`) | a JSON object or `key=value` pairs separated by commas (feature values are bools) | `REDLINE_FEATURES=replay=false,load=false` | Some useful ones: ```bash REDLINE_ENABLED=0 # switch recording off without a deploy REDLINE_PRESET=production REDLINE_ACCESS=token REDLINE_TOKEN=... # from your secret manager REDLINE_SECRET_KEY=... # signs login cookies; needed with several workers REDLINE_RELEASE=$GIT_SHA REDLINE_STORAGE_PATH=/var/lib/myapp/redline.db REDLINE_CONFIG=/etc/myapp/redline.toml REDLINE_ALLOW_OPEN=1 # needed (with access=open) to expose the UI openly ``` Every `REDLINE_` variable must name a setting. A typo such as `REDLINE_SAMPEL_RATE` is a startup error with a "did you mean `REDLINE_SAMPLE_RATE`" hint, never a silent default. The exceptions are `REDLINE_CONFIG`, `REDLINE_ALLOW_OPEN`, `REDLINE_RELEASE` and `REDLINE_TEST_*`. A bad value is reported with the layer it came from. The same "did you mean" error applies to unknown keys in the file and in the framework dict, exactly as in [Settings](settings.md#rules-that-apply-to-every-setting). ## A complete example per framework All four do the same thing: staging preset, 10% sampling, a release name, and a token from the environment. === "Django" ```python # settings.py import os REDLINE = { "PRESET": "staging", "SAMPLE_RATE": 0.1, "RELEASE": os.environ.get("GIT_SHA"), "IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"], # the token itself comes from REDLINE_TOKEN in the environment } ``` === "FastAPI" ```python install(app, engine=engine, settings={ "preset": "staging", "sample_rate": 0.1, "release": os.environ.get("GIT_SHA"), "ignore_paths": ["/static/", "/favicon.ico", "^/health"], }) ``` === "Flask" ```python app.config["REDLINE"] = { "preset": "staging", "sample_rate": 0.1, "release": os.environ.get("GIT_SHA"), "ignore_paths": ["/static/", "/favicon.ico", "^/health"], } Redline(app, engine=engine) ``` === "Litestar" ```python RedlinePlugin(engine=engine, settings={ "preset": "staging", "sample_rate": 0.1, "release": os.environ.get("GIT_SHA"), "ignore_paths": ["/static/", "/favicon.ico", "^/health"], }) ``` ## Checking your setup ```bash redline config # the effective configuration, its sources and any warnings redline doctor # checks: storage writable, UI bundle present, access policy, token, sessions, proxies, retention ``` Run `redline doctor` as a deploy-time check. See the [CLI reference](cli.md). ## Which layer should I use? | You want to... | Use | |---|---| | Set thresholds the whole team shares | `redline.toml` in the repo | | Differ per environment without code changes | `REDLINE_*` variables | | Supply a secret | environment variable or `token_file` | | Pass a Python object (a `Store`, a callable) | the framework settings (it cannot be written in a file) | | Make production safe in one line | `preset = "production"` | --- # Access control [← Index](index.md) The Redline UI shows SQL, request and response bodies, headers, source lines and exception locals. Treat it like a database console. Who may open it is decided by **one policy**, the same for every framework: `redline_core.access.check(request_info)` returns a decision, and each adapter just asks it. Two things always apply, whatever policy you pick: the **CSRF check** on every request that is not a `GET`, `HEAD` or `OPTIONS` (login and logout included) and **`X-Frame-Options: DENY`** on Redline's own responses. The CSRF check refuses `Sec-Fetch-Site: cross-site` **and `same-site`**, and any `Origin` (the literal `null` too) whose host and port differ from the host the request was addressed to; a request with no `Origin` is not a browser and is allowed. It runs after the policy, so outsiders get the policy's refusal first. The order of the checks is: `ui_enabled` (off: `404`), the effective client address (`trusted_proxies`), the network rules, the policy, feature switches and `read_only`, then CSRF. ## Policies Set `access` to one of: | `access` | Who gets in | Typical use | |---|---|---| | `local` (default, see below) | loopback clients using a loopback `Host`, plus anything in `allowed_ips` | your laptop | | `token` | a request with `Authorization: Bearer `, or a browser that logged in with the token | staging, production, a shared server | | `basic` | a user from `basic_users` (`Authorization: Basic`, or the login form) | a small team, behind a proxy that cannot do SSO | | `framework` | the framework's own check: Django superusers or `PERMISSION`, FastAPI `dependencies`, Flask `permission`, Litestar `guards` | you already have an admin login | | `custom` | whatever your `access_check(request_info) -> bool` returns | anything else | | `open` | everyone | **refused** unless `REDLINE_ALLOW_OPEN=1` is also set | The default is `local` for FastAPI, Flask and Litestar. In Django the default is `framework`, meaning active **superusers** (staff in 0.1; see [Django: access control](django.md#access-control)). Passing a native hook (a non-empty FastAPI `dependencies=` or Litestar `guards=` list, a Flask `permission=` callable) switches the default to `framework` for you, unless you set `access` yourself in the file, the environment or the framework settings (a preset does not count). An empty list is the same as no hook. !!! warning "Set `access` explicitly (FastAPI, Flask, Litestar)" While `access` is not set anywhere (code, `redline.toml`, `REDLINE_ACCESS`), Redline serves the `local` default **only when the framework is in debug mode** (`app.debug`, for example `FastAPI(debug=True)`, `flask --debug run` or `Litestar(debug=True)`). Otherwise every Redline URL answers `404` and an error is logged at startup. The reason: a reverse proxy on the same host that adds no `X-Forwarded-For` (`proxy_pass http://127.0.0.1:8000;` with no `proxy_set_header`) makes every visitor a loopback client addressing a loopback `Host`, so `local` would let the whole internet in. Choose: `access = "token"` or `"basic"` on any server, or `access = "local"` on a development machine where you accept that risk. ### Local Only loopback clients (`127.0.0.0/8`, `::1`) that address the server by a loopback name (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`, any port) are served. The `Host` check defeats DNS rebinding: a malicious page cannot make your browser talk to `evil.example`, resolve it to `127.0.0.1`, and read your traces. `allowed_ips` adds client networks, and `allowed_hosts` adds accepted `Host` values (ports are ignored). If a loopback peer sends `X-Forwarded-For`, `X-Real-IP` or `Forwarded` and is **not** in `trusted_proxies`, the request is refused with `403 forbidden`, and `api/config` carries a warning. A reverse proxy running on the same host would otherwise make every visitor look local. Set `trusted_proxies` (see [Network restrictions](#network-restrictions)) or use `token`. A **unix-socket** peer (the app listens on a socket, so there is no client address) is not local: a proxy on the same machine is the usual reason for one. Set `trust_unix_socket = true` if only you can reach that socket. ### Token ```bash REDLINE_ACCESS=token REDLINE_TOKEN=$(openssl rand -hex 32) # or token_file=/run/secrets/redline_token ``` Clients send `Authorization: Bearer `. In a browser, the UI shows a **login screen** when the API answers `401 login_required`; you paste the token once, and Redline sets an HttpOnly, SameSite=Strict cookie (`Secure` when the effective scheme is https, see `cookie_secure`) scoped to its own mount path, valid for `session_ttl_s` (12 hours by default). The token is compared as SHA-256 digests in constant time and is never logged or shown, not even on the Settings page. The page shell and its assets (and `badge.js`) are public because they hold no data; **every `api/` call needs credentials**. Outside the `dev` preset the token must be at least 24 characters, or Redline refuses to start and prints a command to generate one. A `token_file` is read once at startup; keep its permissions to the owner only (`redline doctor` warns otherwise). ```bash curl -H "Authorization: Bearer $REDLINE_TOKEN" https://staging.example.com/_redline/api/meta ``` A failed credential (login body, Bearer or Basic) counts against the client address (an IPv4 address, or the IPv6 /64 it belongs to). After `max_login_attempts` (10) within 300 seconds, further credential attempts from that address answer `429 too_many_requests` with `Retry-After`; a success resets it, and requests carrying a valid session cookie are never limited. The counters are in memory and per process; a full table evicts expired and unblocked entries before blocked ones. For an unknown Basic user name the password is still hashed with the same iteration count as the configured users, so response time does not reveal which names exist. Behind a proxy without `trusted_proxies` all clients share one bucket (`redline doctor` warns). !!! warning "Several worker processes need `secret_key`" Login cookies are signed with `secret_key`. When it is unset each process generates a random key, so a login only works on the worker that issued it and every restart logs everyone out. Set `secret_key` (16 characters or more, for example `REDLINE_SECRET_KEY`) for any multi-worker deployment. Rotating the key, the token or a password revokes all sessions. Logout clears the cookie **and revokes that session** in the process that answered: the cookie is refused there until it would have expired. The revocation list lives in memory, so with several worker processes another worker still accepts a copy of the cookie until it expires (or until you rotate `secret_key`). `cookie_secure` decides the cookie's `Secure` attribute: `"auto"` (default) sets it when the request is https, which includes `X-Forwarded-Proto: https` from a peer in `trusted_proxies`; `true` always sets it (use it when TLS ends at a proxy you have not listed); `false` never does. A refused API call answers `401 login_required` (no credentials) or `401 invalid_credentials` (wrong ones). Both carry a `WWW-Authenticate` header, unless the request has `X-Redline-UI: 1` (the UI and `badge.js` send it) so browsers do not pop up their own dialog. ### Basic ```bash redline hash-password # prompts, prints a PBKDF2-SHA256 hash ``` ```toml # redline.toml access = "basic" [basic_users] alice = "pbkdf2_sha256$..." # the output of redline hash-password ``` Passwords are stored only as hashes: `pbkdf2_sha256$$$`, 600 000 iterations by default (`redline hash-password --iterations N`; 1 000 is the minimum accepted, and `redline doctor` warns below 100 000). A plain password in `basic_users` is rejected at startup. Unknown users still cost a hash computation, so response time does not reveal which users exist. The browser UI shows a username and password form; scripts may send `Authorization: Basic`. Use it behind HTTPS only: basic credentials are sent on every request, and sessions need `secret_key` with several workers, as for tokens. ### Framework Use your application's existing authentication and let Redline defer to it. With no hook configured the request is refused (`403 forbidden`). Each framework exposes its native hook, and passing it implies `access = "framework"`: === "Django" ```python REDLINE = {"ACCESS": "framework", "PERMISSION": "myproject.redline.can_view"} ``` Default: `user.is_active and user.is_superuser` (staff before 0.2). See [Django: access control](django.md#access-control). === "FastAPI" ```python install(app, engine=engine, dependencies=[Depends(require_admin)]) ``` See [FastAPI: access control](fastapi.md#access-control). === "Flask" ```python Redline(app, permission=lambda request: current_user.is_admin) ``` === "Litestar" ```python RedlinePlugin(guards=[require_admin]) ``` ### Custom ```python def can_view(request_info) -> bool: return request_info.headers.get("x-internal-user") in ALLOWED REDLINE = {"ACCESS": "custom", "ACCESS_CHECK": can_view} # or "myproject.redline:can_view" ``` `request_info` has `method`, `path` (relative to the mount), `client_ip` (after `trusted_proxies`), lower-cased `headers`, `cookies`, `host`, `scheme` and `mount`. If your function raises, the error is logged and the request is refused. ### Open `access = "open"` serves the UI to everyone. Without `REDLINE_ALLOW_OPEN=1` in the environment every request is answered `403 open_refused` and an error is logged at startup. With it, Redline serves the UI and logs a warning at startup and then at most once a minute. It exists for sealed environments (a throwaway container, a network you control completely). Do not use it on anything reachable from the internet. ## Network restrictions These apply **in addition to** the policy: | Setting | Effect | |---|---| | `allowed_ips` | IPs and CIDRs (v4 or v6). With `local` it **widens** access: loopback plus these (for example a VPN range `10.8.0.0/16`). With `token`, `basic`, `framework`, `custom` and `open` it **restricts**: when non-empty the client must also be in it, and loopback is not implicit | | `allowed_hosts` | extra `Host` values accepted by `local`'s DNS-rebinding check | | `trusted_proxies` | IPs and CIDRs of reverse proxies. **Only** requests whose TCP peer is in this list have `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Forwarded-Host` believed | `trusted_proxies` matters. If you do not set it, the forwarding headers are ignored, so a client cannot claim to be `127.0.0.1` by sending one. If you do set it, list only the proxies you operate: `X-Forwarded-For` is read from the right, skipping trusted hops, and the first untrusted address is the client. `Forwarded` (RFC 7239) is not parsed. ## Read-only mode `read_only = True` refuses every state-changing `api/` call (anything but `GET`, `HEAD` and `OPTIONS`) with `403 read_only`: deleting traces and runs, `POST api/runs`, stopping a run. Login, logout and `POST api/explain` still work, but an `EXPLAIN` with `analyze: true` is refused with `403 read_only`. Reads, plain EXPLAIN, search and exports still work. The `production` [preset](configuration.md#presets) turns it on. `GET api/meta` reports `access.read_only`, and the UI hides Clear all, ANALYZE and the run controls. ## Feature switches `features` turns individual capabilities off. All default to on. A disabled feature's routes answer `404 feature_disabled`, and the UI hides the matching controls (from `GET api/meta`). Unknown names are an error. | Switch | Turns off | |---|---| | `explain` | `POST api/explain` and the EXPLAIN drawer | | `profile` | `api/traces/{id}/profile`, and the profile is left out of snapshots | | `replay` | the Replay button (replay has no server route; it is a UI feature) | | `snapshot` | `GET api/traces/{id}/snapshot` and the download button | | `load` | the Load page and everything under `api/runs` | | `checks` | the Checks pages and everything under `api/checks` ([Refactor check](refactor-check.md)) | | `logs` | log capture (the trace's `logs` is `[]`) and the Logs tab | | `locals` | exception local variables (not captured, dropped from responses) | | `sse` | `api/stream`; Live mode is hidden | ```toml [features] explain = false replay = false ``` ## Other access settings | Setting | Default | Meaning | |---|---|---| | `ui_enabled` | `True` | If false, every Redline URL answers `404`; Redline **captures but does not serve** the UI or API | | `mount_path` | `None` (then `/_redline`) | Where FastAPI, Flask and Litestar serve the UI when `prefix` / `url_prefix` / `path` is not passed. Django ignores it | | `session_ttl_s` | `43200` | Login cookie lifetime | | `max_login_attempts` | `10` | Failed credential attempts per client IP per 300 seconds | | `secret_key` | `None` | Signs login cookies (see above) | | `base_url` | `None` | Where load runs and refactor checks started from the UI go; see [Load testing](load-testing.md#starting-a-run-from-the-ui) | | `checks_from_ui` | `"auto"` | Whether baseline and compare runs may be started from the UI. `auto` = only in the framework's debug mode; `true`/`false` force it; the `production` preset sets `false`. Every `POST`, `PUT` and `DELETE` under `api/checks` is also refused under `read_only`, and the whole tree answers `404 feature_disabled` when the `checks` feature is off. See [Refactor check](refactor-check.md#settings-and-access) | ## Login and API ![The login screen of a token-protected instance](assets/screenshots/fastapi-login-light.png){ .rl-shot .rl-only-light } ![The login screen of a token-protected instance](assets/screenshots/fastapi-login-dark.png){ .rl-shot .rl-only-dark } | Endpoint | Behaviour | |---|---| | `POST api/login` | body `{"token": "..."}` or `{"username": "...", "password": "..."}` (4 KiB at most); answers `200 {"ok": true, "expires_at": }` and sets the cookie. Never redirects. `400 invalid_json` / `invalid_body`, `401 invalid_credentials`, `429 too_many_requests`; `404` under other policies | | `POST api/logout` | answers `200 {"ok": true}` and clears the cookie, under any policy | | `GET api/config` | `{preset, file, settings, sources, groups, warnings}`: the effective configuration with secrets as `***`, where each value came from, and risky-combination warnings | An unauthenticated request to a `token` or `basic` instance gets `401 login_required`. The UI reacts by showing its login screen. See [HTTP API](http-api.md#authentication-and-csrf). ## Recipes ### Local development Run the app in debug mode and the default `local` policy serves `http://localhost:8000/_redline/` to you and nobody else. Without debug mode (for example a plain `uvicorn main:app`), set it yourself: ```python install(app, engine=engine, settings={"access": "local"}) # or REDLINE_ACCESS=local ``` ### Behind a VPN You run a shared dev or staging box that only VPN users can reach. Add the VPN range: ```toml access = "local" allowed_ips = ["10.8.0.0/16"] allowed_hosts = ["devbox.internal"] ``` Anyone on the VPN can open the UI with no login. If the VPN is wider than the people who should see request bodies, use a token as well. ### Token in staging ```bash REDLINE_PRESET=staging # token access, 25% sampling, no locals REDLINE_TOKEN=... # from your secret store ``` Share the token with the team through your password manager. Rotate it by changing the variable and restarting. ### Production, read-only ```bash REDLINE_PRESET=production REDLINE_TOKEN=... ``` Read-only, token-protected, 5% sampling plus slow requests and errors, no bodies, no locals, no badge. Reach it through your VPN or an SSH tunnel as well; a token is a second lock, not the only one. See [Production](production.md). ### Behind a reverse proxy The proxy terminates TLS and forwards to the app. Without help, every request appears to come from the proxy. Tell Redline which proxy to believe: ```toml access = "token" trusted_proxies = ["10.0.0.0/8"] # your load balancer's network, not "0.0.0.0/0" ``` The proxy must set `X-Forwarded-For` and overwrite any value the client sent. Also set `X-Forwarded-Proto` and `X-Forwarded-Host` (or pass the original `Host`) so the CSRF `Origin` comparison sees the public host name and the login cookie gets `Secure` (or set `cookie_secure = true`). Set `secret_key` when you run several workers. Optionally, restrict `/_redline/` at the proxy to your office or VPN range, so the app's check is the second line of defence: ```nginx location /_redline/ { allow 10.8.0.0/16; deny all; proxy_pass http://app; } ``` ### Kubernetes Do not expose Redline through a public Ingress. Options, safest first: 1. **`kubectl port-forward`**. Reach it from your machine only, with `access = "local"` (set explicitly): ```bash kubectl port-forward deploy/shop 8000:8000 # http://localhost:8000/_redline/ ``` `port-forward` makes the connection arrive from the pod's own loopback side, so the `local` policy lets you in as long as the app is not behind a proxy that adds forwarding headers. If the client address is not loopback, add it to `allowed_ips`. 2. **An internal Ingress or Service** reachable only from the cluster or VPN, with `access = "token"` and `trusted_proxies` set to the ingress controller's pod CIDR. Keep the token in a `Secret`, mounted as `token_file`: ```yaml env: - name: REDLINE_PRESET value: production - name: REDLINE_TOKEN_FILE value: /run/secrets/redline/token volumeMounts: - { name: redline-token, mountPath: /run/secrets/redline, readOnly: true } ``` Remember that the store is a SQLite file **per pod**: use a volume if you want it to survive restarts, and note that each replica has its own data ([Production](production.md#process-models)). ## What to read next [Security](security.md) covers what is stored and the full threat model; [Configuration](configuration.md) covers how these settings are supplied. --- # Production deployment Redline's next release targets production recording across several codebases. Readiness is established for a particular combination of framework, driver, process model, traffic and storage; passing a SQLite unit test does not establish SQL Server or broker-worker behavior. The release must retain its development status until the required deployment checks below have evidence. ## Start with recording and stored-data inspection Use a separate configuration and private storage directory for **each application and environment**. Do not point a profiler store at the application's database. For an initial production canary, make active tools unavailable explicitly: ```toml preset = "production" access = "token" cookie_secure = true token_file = "/run/secrets/redline-token" # Supply REDLINE_SECRET_KEY separately through the deployment secret provider. storage_path = "/var/lib/redline/myapp-production/{role}.db" storage_role = "web" release = "myapp-release-identifier" sample_rate = 0.01 always_keep_errors = true always_keep_slower_than_ms = 500 max_rows = 5000 max_age_days = 2 history_retention_days = 7 writer_queue_size = 64 max_spans_per_trace = 500 max_sql_bytes = 16384 max_span_data_bytes = 8192 max_tag_bytes = 2048 max_trace_bytes = 262144 capture_request_body = false capture_response_body = false capture_sql_params = false capture_locals = false capture_logs = false capture_error_details = false read_only = true profile = "off" badge = false server_timing = false load_from_ui = false checks_from_ui = false analysis_from_ui = false explain_analyze = false [features] explain = false profile = false replay = false replay_writes = false load = false checks = false logs = false locals = false ``` Supply `secret_key` through `REDLINE_SECRET_KEY` or the application's secret provider instead of committing it to a file. Use a randomly generated signing key of at least 32 characters and a strong token of at least 24 characters. Length checks do not verify randomness. Different codebases and environments should have different tokens/signing keys and storage access permissions. A signing key is shared only among workers intentionally serving the same Redline UI. The count/byte controls above match the production preset: queue `64`, span count `500`, SQL text `16384`, span data `8192`, tag value `2048` and completed trace `262144` bytes. The sample, trace/history retention and always-keep rules shown are canary choices. The production preset is a starting point; explicit settings override it. Inspect the resolved configuration with `redline config`, and run `redline doctor` in the deployment's working directory. A configuration file alone is not evidence that the intended workers loaded it. Confirm through the UI's effective configuration and recording health. For Flask, FastAPI and Litestar, pass this settings mapping to the existing adapter. Django maps the same settings from `REDLINE`, with its framework permission policy retained when configured. An explicit native permission hook must authorize the intended operator, not ordinary application users. Authentication details are in [Access control](access-control.md). ## Data minimization and privacy Disabling SQL values withholds bound parameters, normalizes inline literals and removes associated SQL source/fix snippets. This also makes EXPLAIN unavailable for those recordings. `reads_only` is an explicit opt-in, not a privacy boundary: SELECT parameters can contain personal data too. Bodies, locals and logs are separate capture surfaces. Keep all three off for the first production canary. Exception type and structured database codes are useful without treating free-form exception messages as safe. Follow [Security](security.md) for the exact captured surfaces and the current exception-detail controls. Profiles and route rules are pattern matching, not a guarantee that arbitrary clinical notes, identifiers or secrets are absent. Before rollout, use invented sentinel values in the actual application's headers, query strings, routes, SQL, logs and exceptions. Inspect the stored trace, issue data, source snippets and exported snapshot, then scan the disposable store. `redline audit-store` reports bounded key-pattern candidates without printing values; it is not a complete privacy audit and does not prove an existing store is clean. With `capture_error_details = false`, Redline retains error types and structured database codes without formatting exception messages or tracebacks; project exception locals are also disabled. This preserves failure counts while reducing free-text exposure. ## Refuse to attach in production Each adapter has an `install_if_dev` entry point that attaches Redline only when the process does not look like production. It returns `None` (and logs a warning on the `redline` logger) when `REDLINE_ENV`, `APP_ENV`, `ENV`, `ENVIRONMENT`, `FLASK_ENV` or `DJANGO_ENV` is `prod` or `production`, and, for Django, when `DEBUG` is false. `REDLINE_ALLOW_PRODUCTION=1` overrides it (also logged). ```python from fastapi_redline import install_if_dev # flask_redline: install_if_dev(app, ...) install_if_dev(app, engine=engine) from litestar_redline import install_if_dev # returns the plugin, or None plugin = install_if_dev(engine=engine) app = Litestar([...], plugins=[plugin] if plugin else []) # Django: settings.py, then urls.py from django_redline import install_if_dev, urls_if_dev install_if_dev(globals()) # adds the app and middleware urlpatterns += urls_if_dev("redline/") # [] when refused ``` This is a safety net, not access control: it does not replace the `access` settings, and production recording is still configured with the [production presets](#start-with-recording-and-stored-data-inspection). ## Network and operator access Expose the application normally, but place the Redline mount behind the intended operator network/authentication boundary. Use TLS. Configure `trusted_proxies` with the actual proxy peers; do not trust every address for convenience. Set `cookie_secure = true` when the operator entrypoint is always HTTPS and the proxy is configured correctly. `access = "local"` can fail behind a Docker bridge, or accidentally accept a same-host proxy. Use the token/framework policy instead of switching to open access. Test unauthenticated, wrong-token, insufficient-role and cross-origin requests against every worker. Read-only API policy does not govern the application's own endpoints. Replay is a browser request to that application, so disabling `features.replay` is part of recording-only mode. Estimated plans and catalog inspection also contact a database and are separate from reading stored traces; they remain off in the recipe. Load generation, refactor-check runs, source scans, online compilation and actual plans belong in an isolated development environment. ## Storage and process models Use local disk or a local-filesystem Docker named volume with private directory/file permissions. Do not share a writable SQLite file through NFS/SMB or an arbitrary remote filesystem. WAL being available is necessary, but does not prove the underlying volume is safe under multiple containers. A writable store refuses a non-WAL result. Non-development presets refuse an in-repository store unless explicitly overridden. Run `redline doctor` **inside the actual container**, with the same mount and working directory as the app. Its `storage WAL` check creates a throwaway database beside the store and requires `journal_mode=wal` to work; its `filesystem` check warns on Linux mount types commonly used by network/virtual shares. The check does not write to the configured store. The test suite also writes to one file from two independent OS processes, but only your deployment's volumes and process model prove your topology. `{role}`, `{hostname}` and `{pid}` path placeholders help choose separate files. They are not an application namespace automatically added to a shared store. Use an application/environment prefix yourself. Files from unrelated codebases must not be mixed accidentally. | Deployment | Intended storage arrangement | Validation needed | |---|---|---| | One application, one process | One private local file | Retention, shutdown, disk errors and normal traffic | | Several workers on one host | The shared PostgreSQL store, or a local shared file only after a concurrent-writer test, or per-worker files | Contention, busy timeout, pruning, loss and shutdown | | Web and task workers | The shared PostgreSQL store, or explicit web/worker roles with separate files | Worker initialization, fork behavior and correlation | | Several replicas/hosts | The shared PostgreSQL store (`storage_url`), or a private local file per replica | Database reachability and credentials; with files, replica-local inspection and no network-file sharing | | Several independent codebases | Separate processes, settings, credentials and store paths | No cross-application traces or operator access | The SQLite writer starts lazily and has fork/PID handling, but validate the actual gunicorn, uWSGI, ASGI or task-worker start model. Database engines must also follow the database library's fork lifecycle. Redline's storage handling does not make an inherited application connection pool safe. Multiple applications in one interpreter need explicit per-application recorders and integration tests. The default recorder and some integration hooks are process-wide; do not assume that repeatedly calling `configure()` provides application isolation. Queue-independent `job()` accepts an explicit recorder. Initialize Celery instrumentation in the intended worker lifecycle and confirm actual broker delivery, retries and prefork behavior. `extra_stores` provides read-only request/job/profile browsing from existing worker files. It does not combine history, aggregates, live-tail events or mutations. Independent files should use independent trace IDs. Duplicate IDs are marked in request/job listings; inspection, profiles and single-ID deletion are refused rather than choosing another store's evidence. Cross-file reads are not an atomic distributed snapshot. Secondary EXPLAIN/catalog requests are refused because a web process cannot establish the worker's database binding. This is not a distributed store. ### Multi-worker deployments A SQLite file is a single-host store. Several gunicorn/uvicorn workers can write one local file (WAL plus a busy timeout), but their writes queue on one file lock, and as soon as there is more than one host or container each keeps its own traces. For any of these, set `storage_url` to a PostgreSQL database ([Storage: a shared PostgreSQL store](storage.md#a-shared-postgresql-store)): ```bash pip install "redline-core[postgres]" REDLINE_STORAGE_URL=postgresql://redline:...@db.internal:5432/redline ``` Every worker and host then writes the same store, and the UI of any of them shows all traffic. The store opens its connection lazily per process, so gunicorn `--preload` and forked task workers are safe; give it its own database or schema and a role that owns only that. `redline doctor` flags the risky shapes. It reads the worker count from `WEB_CONCURRENCY`, `--workers`/`-w` in `GUNICORN_CMD_ARGS` and `UVICORN_WORKERS` (or `--workers N` when the count lives elsewhere, such as a process manager's command line) and warns when more than one worker would share a SQLite file; it also warns for a SQLite store on a network filesystem. In a deployment pipeline run it with `--strict`, which turns both warnings into failures: ```bash redline doctor --strict --workers 4 ``` ## Capacity and failure behavior Sampling is applied when a recording finishes. Unretained requests still pay the span, fingerprint and callsite cost. A sample rate of 1% is not 1% of the instrumentation overhead. Slow/error keep rules can retain much more than the nominal sample during an incident. The writer queue is bounded and drops/counts traces rather than blocking request code when full. SQL text, span data and tags have separate byte budgets, and the completed serialized trace is checked against `max_trace_bytes` before saving. Budget enforcement may shorten or discard evidence; keep truncation/drop notices visible and inspect preserved failure counts. See [Settings](settings.md#capture-byte-budgets) for defaults and scope. These controls do not establish an absolute process-memory or disk-size ceiling. Active requests, application objects, analysis, serialization and writer batches also consume memory. Measure representative large traces as well as the median request. Retention runs periodically, so a configured row cap is not an instantaneous disk-size guarantee. Measure and monitor: - Application throughput, median/tail latency, CPU and memory with recording disabled and enabled. - Queue drops, writer failures, storage growth and time spent draining at shutdown. - SQL-heavy requests, large results, errors, retries, streaming and concurrent jobs. - Full disk, unwritable directories, SQLite contention and sudden process termination. Use `GET api/meta` recording/drop indicators and the `redline` logger. SQLite's `storage.dropped` includes queue overflow, closed-store loss and failed writer batches; it does not distinguish all those causes. `flush()` signals that queued work was processed, not that every trace persisted successfully: check loss counters and verify expected recordings. Recorder-side capture/sink failures must also be checked in operational logs and independent monitoring. Do not treat sampled endpoint percentiles as an unbiased application SLO. Keep application monitoring independent so a profiler failure cannot hide an application incident. FastAPI/Litestar shutdown hooks and Flask/Django exit hooks flush pending traces. Give the process enough graceful-shutdown time and verify that the hook runs in the deployment. A forced kill can lose queued traces; state the acceptable loss window before rollout. ## Production release gate The complete Compose baseline passed on 2026-10-29 (run `20261029T052447Z-caaef5f7`): 2,120 Python tests, zero failures/errors/skips, plus frontend, demo, docs and packaging checks. Main CI and the actual production topology still require their own evidence; an environment restriction is never a passing assertion. | Area | Confirmed baseline | Still required for the target deployment | |---|---|---| | Capture boundaries | Cycle/Unicode/custom-object/size-limit and safe-fallback tests | Representative memory/latency at intended concurrency and payload sizes | | Privacy and storage loss | Sentinels, effective-write probes, deterministic queue/writer failures and worker shutdown | Actual disk exhaustion, permissions, storage volume and sustained concurrency | | Framework SQL recording | Live Django backend and Flask/FastAPI SQLAlchemy sync/async cases on MySQL, SQL Server and PostgreSQL | Exact deployed backend/driver versions, reconnect behavior and deployment topology | | SQL Server tooling | Live estimated/actual plans, catalogs, compilation nonexecution and setting cleanup | Least-privilege production-like permissions; Django SQL Server EXPLAIN remains unsupported | | Jobs | Redis-delivered Celery prefork success/failure/retry, correlation and shutdown-drain checks | Actual broker/deployment, restart and expected worker concurrency | | Browser | Real Chromium Jobs/detail, SQL checker, privacy and mobile overflow checks | Full accessibility review and target-browser coverage | The Compose baseline uses Python 3.13, Django 5.2 and the driver versions recorded in the run summary. It does not certify all supported versions; the broader matrix runs in main CI. SQL Server's supported container qualification requires native Linux amd64, even if an emulated local run succeeds. Record server/process versions with deployment results. A production recommendation requires evidence for each target deployment: 1. Exact supported Python/framework/driver/queue versions and the process/storage topology. 2. Unit and adapter suites, installed-wheel tests, UI checks and documentation build passing. 3. Live driver tests for failed statements, reconnects, parameter styles and session cleanup; SQL Server plan/compile tests only against an isolated database with appropriate permissions. 4. Broker-worker success/failure/retry, prefork/restart, correlation and graceful shutdown tests. 5. Concurrent writers, retention, backpressure and fault-injection tests under expected traffic (`redline doctor --strict` passing for the storage topology). 6. Sentinel privacy checks across stored traces, issues, callsites, logs and exports. 7. A low-traffic canary with an immediate `enabled = false` rollback and independent monitoring. The [full-stack Compose test project](testing.md) supplies a repeatable baseline for these checks. Its current report must be green; merely adding its test files is not qualification. Validate deployment-specific conditions as well. Once these pass, expand one codebase at a time. Keep active tools disabled on production even when the development demo exercises them. See [Real-world workflows](real-world-workflows.md) for individual feature setup and [Performance](performance.md) for measurement limitations. ## Enforce the recording-only configuration before deployment From **inside the deployment container**, with the same config/environment/working location as the app, run: ```bash redline doctor --production --strict --json ``` `--production` validates the configuration you supplied; it does not switch presets or make an unsafe configuration safe. `--strict` returns nonzero for warnings as well as failures. This gate checks recording-only settings, private persistent storage and retention, authenticated operator access, explicit secure cookies and restricted proxy trust. It keeps provider/auth/storage probes from ordinary `doctor`. Application-defined access hooks remain warnings because a CLI cannot prove their authorization behavior. Use a token-backed configuration for an automated strict gate, or review the hook and its warning explicitly. Never print real token/signing values in deployment logs. If settings are overridden in application code, this CLI cannot see those overrides. Confirm the worker's effective configuration and test its access boundary as well. A successful configuration gate does not validate TLS, real database drivers, disk failure behavior, concurrency or the contents of actual captured data. ## Monitor profiler health independently Poll the protected `GET /api/health` endpoint with your operator credentials. A healthy supported process returns HTTP 200. Degraded, closed, disabled or unavailable recording health returns 503. It reports: - queue depth/capacity and writer-started/alive state; - completed-recording capture/sink failures separately from storage loss; - cumulative dropped items by reason, writer/flush/shutdown failures and written count; - shutdown completion and the serving process PID. Do **not** use this endpoint as the application's load-balancer readiness probe. A profiler problem should alert operators without taking a healthy application out of service. The snapshot does not query the initialized trace database, so it remains useful while SQLite queries are blocked or the connection has closed. It is authenticated, contains no trace payload, storage path or exception message, and uses the same access policy as the other operator endpoints. The UI's Recording health panel shows the same information. Counters are process-local and cumulative, including historical failures; a degraded status can persist after recovery. Monitor counter increases/rates and individual workers, not just the last status response. Unsupported custom health providers are reported as unknown. Queue depth includes markers and lifecycle work; written counts describe write processing rather than an fsync/durability guarantee. Continue independent application monitoring and inspect truncated evidence too. ## Verify graceful shutdown and failure behavior The SQLite writer stops admission before its stop marker. `close(timeout=10)` reports whether shutdown completed. If the deadline expires, queued items may be discarded and counted, while an in-flight batch may still finish later. A live writer retains ownership of its connection until it stops. This improves isolation; it does not make forced kills lossless. Adapters still perform their normal flush/close lifecycle, so size the server's grace period to include both and test it in the actual process topology. Deterministic tests cover full queues, dead writers, injected write failure/recovery, thread-start failure, failed logging and concurrent save/close accounting. Validate actual volume permissions, disk exhaustion, worker restarts and intended concurrency in staging. Read `flush()` success together with loss counters: barrier completion is not proof that every trace persisted. Emergency rollback remains `enabled = false`, followed by normal application restart/reconfiguration; no production traffic generator is enabled by this work. The close timeout bounds admission/queue/join/lock waits. It is not a hard real-time bound on operating-system filesystem calls. Let the process manager enforce the final grace deadline and document the acceptable loss on forced termination. Worker processes without a web endpoint can expose `recorder.operational_health()` and `store.operational_health()` through their existing private metrics/logging integration; the library does not start a monitoring server or aggregate those counters automatically. --- # Upgrading Redline is pre-1.0: the public API may change between minor versions, and every change is listed in the [changelog](changelog.md). The five packages (`redline-core`, `django-redline`, `fastapi-redline`, `flask-redline`, `litestar-redline`) are versioned in lockstep, so upgrade them together. ## Steps 1. Read the [changelog](changelog.md) entries between your version and the target, in particular the *Changed* and *Security* sections. 2. Upgrade the framework package and `redline-core` in the same command: ```bash pip install --pre --upgrade django-redline # or fastapi-redline, flask-redline, litestar-redline ``` 3. Run the configuration check. It loads your settings without changing them and reports anything deprecated or unsafe for recording-only deployments: ```bash redline doctor --production --strict ``` 4. Restart every worker. The recorder is per process; mixed versions against one store work but report their own version in the Meta tab. 5. Open the UI and confirm new traces arrive. ## The trace store The SQLite store migrates itself in place the first time a newer version opens it, in one transaction, so concurrent workers start safely. Older traces stay readable. A store written by a newer version is never opened by an older one; if you must roll back, point the older version at a fresh `store_path` or delete the file. See [Storage](storage.md) and [History and releases](history.md#upgrading-an-existing-store). ## Pre-releases Beta builds are published as pre-releases and need `--pre`. Pin an exact version in production (`django-redline==X.Y.ZaN`) and upgrade deliberately. Anything marked experimental in [API stability](api-stability.md) can change without notice. --- # Operating Redline: its own logs, metrics and health [← Index](index.md) · [Production](production.md) When Redline runs anywhere other than a laptop, you want to know when *it* is unhealthy: dropping traces, failing to write, or misconfigured. This page lists the signals it gives about itself. ## Logs Redline uses the standard library `logging` module and never configures handlers itself; records go wherever your application sends logs. | Logger | What it reports | Typical level | |---|---|---| | `redline` | startup warnings (open access, uninstrumented integrations with `auto_instrument="warn"`, a refused `install_if_dev` in production), writer failures, dropped lifecycle data | `WARNING`, `ERROR` | | `redline.check` | refactor-check runs that could not store a result or read traces | `ERROR` (with traceback) | | `redline.load` | load-test sink failures | `ERROR` (with traceback) | | `redline.scan` | static-scan limits reached | `WARNING` | Messages start with `Redline` (or the command name) and never include captured request data, SQL parameters or credentials: they name the operation and the exception *type*. Debug-level records (catalog reads, executor lookup) are off unless you enable `DEBUG` for `redline`. A JSON log pipeline needs nothing special. With `python-json-logger`, for example: ```python import logging from pythonjsonlogger.json import JsonFormatter handler = logging.StreamHandler() handler.setFormatter(JsonFormatter("%(asctime)s %(levelname)s %(name)s %(message)s")) logging.getLogger("redline").addHandler(handler) logging.getLogger("redline").setLevel(logging.WARNING) ``` To stamp *your application's* log lines with the id of the recording they belong to, add the `TraceIdFilter` from `redline_core.correlation` (see [Logs and exceptions](logs-and-exceptions.md)). ## Metrics `GET {mount}/api/metrics` returns Prometheus text format, behind the same access policy as the rest of the API (so scrape it with the Redline token, or from an allowed network): | Series | Meaning | |---|---| | `redline_writer_queue_depth` / `redline_writer_queue_capacity` | traces waiting for the writer thread, and the bound | | `redline_traces_saved_total` | traces persisted | | `redline_traces_dropped_total{reason=...}` | traces lost: `queue_full`, `write_failure`, `closed`, `capture_failed`, plus rarer reasons (`enqueue_failure`, `lifecycle_write_failure`, `shutdown_timeout`, `writer_unavailable`) when they occur | | `redline_write_failures_total` | writer batches that failed | Suggested alerts: any increase of `redline_traces_dropped_total{reason="write_failure"}` or `redline_write_failures_total` (disk full, permissions, store locked); a sustained queue depth near capacity (the app produces traces faster than the store absorbs them: lower the sample rate). See [HTTP API](http-api.md) for the exact format. ## Health and doctor - `redline doctor` (add `--production` in staging/production) checks the store location, filesystem, WAL, UI bundle, access settings and capture settings from inside the process environment. Run it in the real container. - `GET {mount}/api/meta` reports recording state and drop counters for the UI. - `redline instrumentation --store PATH [--window SECONDS] [--json]` and `GET {mount}/api/instrumentation` (also on the Settings page) show what redline cannot see: installed integrations that are not instrumented, truncated traces, traces without a profile, dropped and failed writes. Counts come from a bounded sample of recent traces. - `redline audit-store` counts possibly unmasked keys in a store without printing values. --- # Full-stack release testing The example projects share [`examples/compose.yaml`](https://github.com/Pythondeveloper6/redline/blob/main/examples/compose.yaml). It provisions disposable PostgreSQL, MySQL, SQL Server and Redis services with health checks, and an image containing all framework adapters, database drivers, Celery and Chromium. From the repository root: ```bash docker compose -f examples/compose.yaml up --build \ --abort-on-container-exit --exit-code-from tests tests ``` The runner executes the complete package suites, including network tests, live database request/transaction/privacy cases, plans and compile checks, a real Redis/prefork worker, and browser tests of the built UI. It also checks demos, docs, lint, package metadata and fresh wheel installation. Integration skips or missing reports fail the run. The MySQL cases (pymysql, aiomysql and asyncmy drivers, EXPLAIN, index advice, killed connections) also run on every push in the lightweight `mysql` CI job against a plain `mysql:8.4` service, without the full Compose stack; a skipped test fails that job. `examples/testing/results/summary.json` must show `qualified: true` for the current run, and the Compose command must exit zero. Results are ignored by Git. Each run keeps separate logs, JUnit reports and actual dependency versions. Browser screenshots support review but do not replace a full accessibility audit or production load testing. Interactive demo services are available through the `demos` profile with host loopback ports 8011–8014 and disposable token authentication. The shops use SQLite; the integration matrix separately exercises real databases. All database credentials/data are test-only. SQL Server's image requires Linux amd64. Microsoft does not support emulation on Apple Silicon; failures there remain failures. Native amd64 CI provides the supported environment. The existing CI trigger remains **main pushes only**, with no PR/manual test trigger and no implicit publishing authorization. See the [complete test-project guide](https://github.com/Pythondeveloper6/redline/blob/main/examples/testing/README.md) for prerequisites, commands, demo URLs, driver coverage, cleanup and current verification limits. A passing Compose baseline is one release gate; validate actual deployment storage, concurrency, drivers, permissions and framework versions as described in [Production](production.md). ## The query-count ratchet A ratchet is a committed file of numbers that may only improve: a pull request that adds queries to an endpoint or a test fails, one that removes queries tightens the file. **Endpoints**, from a [refactor-check suite](refactor-check.md): ```bash redline check ratchet checks/orders.toml --store .redline/check.db --update # create it redline check ratchet checks/orders.toml --store .redline/check.db # CI: fail on regressions redline check ratchet checks/orders.toml --store .redline/check.db --update # after a green run: tighten ``` The file defaults to `.ratchet.json` (`--ratchet-file`). Per request it stores the median query count (needs `--store`, see [server-side metrics](refactor-check.md#server-side-metrics)) and the median latency. Query counts are exact: one more query is a regression. A latency regression needs the median to grow by more than both `--latency-pct` (30) and `--latency-ms` (20); `--no-latency` tracks queries only. Without `--update` nothing is written (and the file must exist); with it, the file is written only when nothing regressed: improvements lower the numbers, new endpoints are added, nothing is ever raised. Keys are sorted, so diffs stay small. A request that is broken (at least half of its calls failed) is reported and fails the run. `--json` and `--markdown` write the verdict; the exit code is `1` on regressions. **Tests**, with the pytest plugin (tests that use the `redline` marker or `--redline-all`): ```bash pytest --redline-ratchet tests/queries.ratchet.json # fail on more queries than recorded pytest --redline-ratchet tests/queries.ratchet.json --redline-ratchet-update # tighten / add, only if the whole session passed ``` Each test is keyed by its node id and records the query count of its busiest request. The same file can hold both the `endpoints` and `tests` sections. --- # Security [← Index](index.md) Redline records the most sensitive thing about your application: what it was asked to do and what it said back. This page is the threat model, what is protected by default, what is **not**, and how to expose the UI safely. To report a vulnerability privately, see `SECURITY.md` in the repository. ## What Redline stores For every kept request, on local disk, in `.redline/redline.db`: | Data | Stored as | Redacted? | |---|---|---| | Request and response **headers** | name and value | values of `redact_headers`, and of any header whose name matches `redact_keys` (`X-Auth-Token`, `X-CSRFToken`, `X-Session-Id`…), are masked | | **Query string** | key and value | values whose key matches `redact_keys` are masked | | **Request body** | text, capped at `max_body_bytes` | JSON, form and multipart keys matching `redact_keys` are masked; multipart files become `[file: name, N bytes]`; any other text (plain, XML, GraphQL, JSON that does not parse) goes through the free-text rule | | **Response body** | text, capped | JSON, form and multipart keys are masked; HTML and other text are **not** scanned (cost); only if `capture_response_body` is on | | **SQL text** and **parameters** | controlled by `capture_sql_params` | `false` withholds values and normalizes literals; `reads_only` retains values only for recognized reads; otherwise configured column/table/profile patterns mask parameters | | **Callsites** | file, line, function and optional **source line** | SQL capture/route restrictions remove associated source and generated fix snippets; other captured source can contain literals | | **Tracebacks** and exception messages | text | the free-text rule (URL passwords, secret query values, `key=value` secrets, JWTs, card numbers), chained exceptions included | | **Exception locals** (project frames: names and `repr` of variables) | text, at most 30 per frame, 300 characters each | variables whose **name** matches `redact_keys` are masked; containers have secret keys masked to a depth of 4, and the whole `repr` goes through the free-text rule (`key=value` pairs, URLs). Values under innocent names are **not** | | **Log records** emitted during the request | level, logger, message (2,000 characters), callsite | the free-text rule: `key=value`, `key: value` and `"key": "value"` pairs whose key matches `redact_keys` are masked, and so are URL passwords and secret query values. Bare secrets in a sentence are not | | **Normalised SQL summaries** (`trace_sql`) | statements with literals replaced by `?` | contains no parameter values | | **Outbound URL and cache key patterns** | digit runs, UUIDs and long hex strings replaced by `*` | cache keys: the part after a session prefix (`django.contrib.sessions.cache`, `session:`, `sess:`) or a secret-looking word (`api_key:`) is masked; URLs as below | | **Release name** | text | no | | **Load-run definitions** | the scenario | secret-looking header values, body keys and URL secrets are masked | | Outbound **URLs** (`http_out`) | URL | the password of `scheme://user:password@host` and query-string values whose key matches `redact_keys` are masked | | The request **path** | text | values of route parameters named like a secret (`token`, `uidb64`, `key`, `signature`, `code`, or matching `redact_keys`); for unmatched routes (404), long token-like segments | | Client address | `REMOTE_ADDR` / ASGI client | no | Everything is JSON in a SQLite file readable by anyone who can read the file. ## Redaction Redaction is **on by default** and cannot be turned off by accident: there is no "disable redaction" switch. It runs on the trace before it is handed to the store, so values recognized by the configured rules are masked before persistence. Unrecognized sensitive data can still reach disk. It is mostly **key-based**: it looks at the *name* of a field (header, query key, JSON key, column, table, route parameter). Free text (log messages, exception messages, tracebacks, text bodies) additionally has JWTs and Luhn-valid card numbers masked by shape. ### Defaults | Where | What is masked | Replaced with | |---|---|---| | Log messages, exception messages and tracebacks, non-JSON request bodies | `key=value`, `key: value`, `"key": "value"` pairs and `value` elements whose key matches `redact_keys`; URL passwords and secret query values inside the text; JWTs; Luhn-valid card numbers (13–19 digits, optionally grouped) | `[redacted]` | | Exception locals | the value of a variable whose name matches `redact_keys`; secret keys of containers (4 levels deep); and the free-text rule over the whole `repr` | `[redacted]` | | Headers | `authorization`, `cookie`, `set-cookie`, `x-api-key`, `proxy-authorization` (case-insensitive), and any header whose name matches `redact_keys` | `[redacted]` | | Query strings, form bodies, multipart fields, JSON bodies (any depth, GraphQL `variables` included) | any key matching `(?i)pass(word)?\|secret\|token\|api[_-]?key\|(?//` → `/reset/[redacted]/[redacted]/`); on unmatched routes, segments of 20+ token characters that mix letters and digits | `[redacted]` | | Multipart file parts | the content | `[file: name, N bytes]` | | Bodies | cut at `max_body_bytes`, **after** masking, so a cut never exposes half a secret | | | Binary bodies | replaced by `` | | The `auth` rule is deliberate: it matches `auth` and `authorization` only as a **whole word**, so `author`, `author_id`, `authenticated`, `authority` and `oauth_provider` stay visible, which would otherwise hide half a blog's data. ### Customising ```python REDLINE = { "REDACT_HEADERS": ["authorization", "cookie", "set-cookie", "x-api-key", "proxy-authorization", "x-internal-token"], "REDACT_KEYS": [ r"(?i)pass(word)?|secret|token|api[_-]?key|(?/`, `/invite//`) | Only parameters named like a secret are masked | Put the path in `ignore_paths`, or avoid secrets in paths | | **Personal data** under ordinary keys (`email`, `name`, `address`, `phone`, `dob`) | They do not all match the default credential pattern | Add reviewed profiles/custom patterns, and keep bodies off in production | | **Bare secrets in text request bodies**, and anything in **HTML or other non-JSON response bodies** | Text request bodies only get the free-text rule (`key=value`, ``, JWTs, cards); response text is not scanned | Turn off `capture_request_body` / `capture_response_body`, or `ignore_paths` | | **Literal values inlined in SQL text** when SQL value capture is enabled | Key masking does not identify arbitrary statement literals | Use bound parameters and `capture_sql_params = false` in production | | **SQL parameters** bound to columns *and* tables whose names look innocent (`settings.value`, `kv.data`) | Matching is on the column and table name | Add patterns, or accept it | | **Bare secrets in exception messages** (`ValueError: bad abc123`) | Only the free-text rule applies (`token=abc123` and `token: abc123` *are* masked) | Do not put secrets in exception messages | | **Source lines** in callsites | They are your code | n/a, but note they land on disk | | **Other headers** that carry secrets under innocent names (`Referer` with a token in the URL, `X-Signature`) | Only the listed names and names matching `redact_keys` are masked | Extend `redact_headers` | | **Multipart field values** under innocent names, and **file names** | Fields are parsed and masked by name; Django and Flask do not read multipart bodies at all, FastAPI and Litestar store the parsed fields (files as `[file: name, N bytes]`) | Turn off request body capture for upload routes with `ignore_paths` | !!! tip "Verify with your own traffic" Send a request containing a fake secret under each field name your app really uses, then open **Request / Response**. The demo does this: `POST /checkout` with `Authorization`, `card_number` and `password` shows all three redacted. ### Logs and locals Two 0.2 features capture more of your application's internals than 0.1 did, so they deserve the same scrutiny as request bodies. - **Log messages** are formatted, redacted for `key=value` pairs, and capped at 2,000 characters. A log line like `Created user alice@example.com with token=abc123` stores the email and masks the token. If your logs carry personal data, raise `log_level`, or set `capture_logs = False`. - **Exception locals** are the values of variables in project frames when a request raised. A model instance's `repr`, a request object, a dict of form data: the value is stored as printed. Names that look secret are masked; **a secret under an innocent name is not**. The `staging` and `production` presets turn `capture_locals` off. The `logs` and `locals` [feature switches](access-control.md#feature-switches) are the access-side counterpart. Neither feature is a place to put secrets, and neither is a reason to log them: redaction is a safety net, not a licence. ### The SQL EXPLAIN consequence Because masked parameter values are what is stored, EXPLAIN of a query filtered on a secret column or table (every query on `django_session`, `authtoken_token`…) runs with `[redacted]` as the value. The plan may differ from the real one. See [EXPLAIN](explain.md#safety). ## Who can open the UI The UI and API expose SQL, bodies, source lines and exception locals, and can run EXPLAIN. Treat access to them as access to a database console with read-only privileges *and* to the traffic. From 0.2 there is **one access policy for every framework**, chosen with the `access` setting: `local`, `token`, `basic`, `framework` (the adapter's native hook), `custom` or `open`. On top of it you can add IP allow-lists, trusted proxies, a `read_only` mode and per-feature switches. The full description, with recipes for a laptop, a VPN, staging, production, a reverse proxy and Kubernetes, is on [Access control](access-control.md). The sections below describe the defaults and the threats. === "Django" **Default: active superusers** (staff before 0.2: staff status is often handed out for one model's admin, and Redline shows every user's requests). The check is `request.user.is_active and request.user.is_superuser`. - An **anonymous** visitor to the page is redirected to the admin login (or `LOGIN_URL`). - A **signed-in non-superuser** (staff included) gets `403`. - The **API** answers `403` JSON `{"error": {"code": "forbidden", ...}}`. Change it with `REDLINE["PERMISSION"]`, a callable `(request) -> bool` or a dotted path to one: ```python # myproject/redline.py def is_performance_team(request): user = request.user return user.is_active and user.groups.filter(name="performance").exists() # settings.py REDLINE = {"PERMISSION": "myproject.redline.is_performance_team"} # the 0.1 rule: "django_redline.conf.staff_permission" ``` The callable is wrapped: an exception in it denies access (it **fails closed**). === "FastAPI, Flask and Litestar" **Default: `local`, loopback only, and only in debug mode until you set `access`.** While `access` is not set anywhere and the app is not in debug mode (`app.debug`), every Redline URL answers `404` and an error is logged at startup: a reverse proxy on the same host that adds no `X-Forwarded-For` would otherwise make every visitor local. Set `access = "local"` to accept that risk on a development machine, or `token`/`basic` on a server. With `local` in force and without `dependencies` (FastAPI), `permission` (Flask) or `guards` (Litestar), a request is served only when **both** hold, and a warning is logged at startup: - the client is loopback (`127.0.0.0/8`, `::1`; a unix-socket peer only with `trust_unix_socket = true`); - the `Host` header names loopback: `localhost`, `*.localhost`, `127.x.x.x` or `[::1]`, with any port. This defeats DNS rebinding (below). A loopback peer that sends `X-Forwarded-For`, `X-Real-IP` or `Forwarded` without being in `trusted_proxies` is refused too (it is almost certainly a reverse proxy on the same host). Pass your own hook (it implies `access = "framework"`; an empty list is no hook), or set `access`, for anything else. `access = "framework"` with no hook attached refuses every request (`403`) in all four adapters: there is nothing to delegate to. A FastAPI dependency should raise `HTTPException` to refuse; one that returns `False` is refused with `403` as well. A refusal is `403` JSON `{"error": {"code": "forbidden", ...}}`. See [FastAPI](fastapi.md#access-control), [Flask](flask.md#access-control) and [Litestar](litestar.md#access-control). ### Cross-site request forgery Reads are `GET`. Every other method (`DELETE` on traces and runs, `POST api/explain`, `POST api/runs`, login and logout) is protected: - **Django** runs Django's own CSRF machinery on every API request (token in the CSRF header, plus the Origin and Referer checks on HTTPS), even if `CsrfViewMiddleware` is not installed, and answers `403 csrf_failed` as JSON. - The shared access gate (all four adapters) rejects `Sec-Fetch-Site: cross-site` **and `same-site`**, and any `Origin` (including `null`) whose host and port differ from the host the request was addressed to, with `403 csrf_failed` in the same JSON shape. This applies whatever access policy you chose. A request with no `Origin` is not a browser and passes. - **Token and basic access** use an HttpOnly, SameSite=Strict session cookie scoped to the mount (`Secure` over https, see `cookie_secure`), so a cross-site request does not carry it. Logging out revokes the session in that process (in memory). - **Replay** sends the recorded request **without your cookies** unless you tick "Send my cookies": the method, path and body were chosen by whoever made the recorded request, and replaying them with your session would be a stored CSRF. ### Forcing capture `?_redline=profile` and `X-Redline-Profile: 1` start the profiler and make Redline keep the trace whatever `sample_rate` says. They are honoured only in framework debug mode or when the request itself carries valid Redline credentials (a Bearer token or Basic credentials, a client the `local` policy lets in, or `access_check`); anyone else could make you profile and store their requests at will. The login cookie is scoped to the mount, so the browser never sends it to application URLs. With `access = "framework"` (a hook that only runs inside Redline's own routes) only debug mode honours them. The `production` preset turns profiling off. `X-Redline-Run` (the load tester's header) and `X-Redline-Check` (the refactor check's) tag a trace only when that run exists in the store and is running (a check also for a minute after it ends). ### DNS rebinding A web page on `evil.example` can re-point its own DNS name at `127.0.0.1`. Your browser then sends that page's requests to your local server, as same-origin requests, so CORS and the CSRF checks do not stop it reading `GET` endpoints. What gives it away is the `Host` header, which still says `evil.example`. - **FastAPI, Flask, Litestar:** the default `local` policy refuses any `Host` that is not a loopback name or address (`403 forbidden`). If you reach the app through a hosts-file alias, allow it explicitly with `allowed_hosts=["devbox"]` in the settings. With your own `dependencies` (real authentication), the attacker's page has no credentials for your host (cookies are bound to `evil.example`), so it is refused too. - **Django:** every Redline view calls `request.get_host()`, so `ALLOWED_HOSTS` is enforced on them even without `CommonMiddleware` (an unknown host gets Django's `400`). With `DEBUG = True` and an empty `ALLOWED_HOSTS`, Django only accepts `localhost`, `127.0.0.1` and `[::1]`. The admin session cookie is not sent to the attacker's host name either. Do not combine `ALLOWED_HOSTS = ["*"]` with a `PERMISSION` that returns `True`. ### Framing The UI page is served with `X-Frame-Options: DENY` by every adapter, so another site cannot frame it and trick a click on **Clear all**. ### Putting it behind a proxy !!! warning "Loopback is not a security boundary behind a proxy" If a reverse proxy forwards to your app on `127.0.0.1`, every request would look local. Redline refuses a loopback peer that carries forwarding headers unless it is a trusted proxy, but a proxy that strips them is not detectable, so use `access = "token"` and set `trusted_proxies` so the real client address is taken from `X-Forwarded-For` **only** when the request comes from your proxy (read from the right, skipping trusted hops). Without `trusted_proxies` Redline ignores that header, so a client cannot spoof its address. See [Access control: behind a reverse proxy](access-control.md#behind-a-reverse-proxy). ### Badge, Server-Timing and CSP - The **floating badge** adds one `
{{ order.customer.name }}{{ order.items.count }}{% for i in order.items.all %}...{% endfor %}