# 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
---
{ .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 }
{ .rl-shot .rl-only-light }
{ .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"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "Timeline"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "Issues"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "EXPLAIN"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "Flamegraph"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "Endpoints"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "Redaction"
{ .rl-shot .rl-only-light }
{ .rl-shot .rl-only-dark }
=== "FastAPI N+1"
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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.
{ .rl-shot .rl-only-light }
{ .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.
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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.
{ .rl-shot .rl-only-light }
{ .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
{ .rl-shot .rl-only-light }
{ .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 `***`.
{ .rl-shot .rl-only-light }
{ .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 `