Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Redline

fastapi-redline

The FastAPI + SQLAlchemy adapter for Redline: a request profiler and backend analyzer. Every request becomes a trace with a span timeline, the SQL it ran, N+1 and duplicate-query detection with concrete fix diffs, one-click EXPLAIN, optional flamegraphs, and a fast web UI served from your own app.

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/

Traces are stored in their own SQLite file (.redline/redline.db), never in your database.

Install

pip install --pre fastapi-redline

Published packages are available on PyPI. This checkout describes development v0.4; installed behavior depends on the released version. Docs: https://pythondeveloper6.github.io/redline/.

For flamegraphs install the adapter's profile extra: pip install --pre "fastapi-redline[profile]".

Python 3.10+, FastAPI 0.110+, SQLAlchemy 2.x.

install()

install(
    app,
    engine=None,          # Engine | AsyncEngine | [engines] | {"alias": engine}
    settings=None,        # dict | redline_core.Settings
    prefix=None,          # default: the mount_path setting, else "/_redline"
    dependencies=None,    # auth dependencies for the UI + API (see below)
    models=None,          # Base / registry for fix suggestions (default: auto-discover)
    store=None,           # custom Store (default: SQLite file at storage_path)
) -> Redline

What it does:

  • configures the recorder and the store, and flushes and closes the store on shutdown (it wraps your lifespan; an existing lifespan= keeps working);
  • adds a pure ASGI middleware (not BaseHTTPMiddleware);
  • instruments the engines;
  • mounts the UI and JSON API under prefix (ahead of any catch-all route you declared).

Call it after your app is built, before it starts. settings takes any Redline setting with case-insensitive keys:

install(app, 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,
})

Multiple engines

The first engine of a list is the "default" db alias; others are named after their database file, or pass a dict. The alias is stored on each query so EXPLAIN runs on the right engine.

install(app, engine=[async_engine, sync_engine])
install(app, engine={"main": main_engine, "analytics": analytics_engine})
redline = install(app)
redline.add_engine(late_engine)            # instrument an engine created later

SQLModel

Nothing to do: SQLModel tables live in a regular SQLAlchemy registry, which the fix suggester discovers (or pass models=SQLModel).

What is recorded

  • Request / response: method, path, route template (/orders/{order_id}), endpoint dotted name, status, headers, query string and body. Secrets are redacted by the core (Authorization, cookies, password/token/card keys...).
  • Bodies are never consumed or buffered unboundedly. 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: statement, bound params (redacted), duration, rowcount, vendor, executemany, db_alias, and the project line that issued the query, also through AsyncSession (the greenlet boundary is bridged).
  • Unhandled exceptions are recorded and re-raised untouched.
  • Spans from def endpoints running in Starlette's threadpool attach to the right request (context is copied to the worker thread; tested under concurrency).
  • The trace is finished when the last response chunk is sent, so background tasks do not inflate latency. Work that starts a bare threading.Thread is not attributed to any request.
  • Your own spans: with redline_core.span("pricing.compute"): ... (also async with and as a decorator).
  • X-Redline-Run: <id>;step=<n> becomes tags (used by the load tester).
  • X-Redline-Check: <id>;req=<i>;n=<k> becomes tags (used by redline check, only for a check run that exists in the store).

Outbound HTTP (httpx)

Opt-in, once at startup:

from fastapi_redline import instrument_httpx

instrument_httpx()   # every httpx.Client / AsyncClient call becomes an http_out span

URLs are redacted (?api_key=... is masked). Use uninstrument_httpx() to undo it.

Profiling

Flamegraphs are opt-in per request: add ?_redline=profile or the header X-Redline-Profile: 1 (needs the [profile] extra). They are recorded with pyinstrument in async mode, so concurrent requests do not pollute each other.

Fix suggestions

For an N+1, SQLAlchemyFixSuggester maps the repeated query back to your models and tells you how to eager-load it:

Repeated query Suggestion
child table filtered by its foreign key selectinload(Parent.children)
parent looked up by primary key, once per row joinedload(Child.parent)
association (secondary) table filtered by the parent selectinload(Parent.tags)

It then walks the call stack to find the select(Parent) or session.query(Parent) in your source and produces a real unified diff:

-        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()

plus the from sqlalchemy.orm import selectinload line when it is missing. When the statement cannot be located (it lives in another module, or is built dynamically) you get the one-line code hint with lower confidence instead. Both the lazy-load form (order.items) and explicit per-row queries are recognised.

Access control

The UI exposes your SQL, request bodies and EXPLAIN, so treat it like an admin tool.

Default. With no dependencies, the access setting decides (default local, served only in debug mode until you set access): only loopback clients (127.0.0.0/8, ::1; unix sockets 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. Refusals, and HTTPExceptions from your own dependencies, are JSON {"error": {"code": "forbidden" | "unauthorized" | ..., "message"}}. Add other host names with the allowed_hosts setting. Passing dependencies= implies access="framework". A loopback peer sending X-Forwarded-For without being in trusted_proxies is refused; behind a reverse proxy use access="token" and trusted_proxies. Tokens, basic auth, allowed_ips and read_only are described in the access control docs.

Your existing auth dependency:

from fastapi import Depends

install(app, engine=engine, dependencies=[Depends(require_admin_user)])

HTTP Basic:

import 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)])

(dependencies=[] is the same as passing none. A dependency that returns False is refused with 403; raising HTTPException is the normal way.)

CSRF. The mutating endpoints (DELETE traces, POST explain) reject browser requests whose Origin does not match the request host, Origin: null, and Sec-Fetch-Site: cross-site. Browsers always send Origin on those methods, so another website cannot drive your Redline through a logged-in browser. Non-browser clients (curl, scripts) send no Origin and are only subject to your auth dependencies.

EXPLAIN

POST /_redline/api/explain runs EXPLAIN for a recorded SELECT on the engine it came from (matched by db_alias) inside a transaction that is always rolled back (and READ ONLY on PostgreSQL). The captured SQL is in the driver's paramstyle and goes through exec_driver_sql. Async engines run on the application's event loop. EXPLAIN ANALYZE executes the query, so it is off unless explain_analyze=True.

Development

uv sync --all-packages
cd packages/fastapi-redline && uv run pytest

A runnable demo with deliberately bad endpoints lives in examples/fastapi.

v0.4 real-world workflows

The next release adds:

  • Handled SQL failures with vendor/SQLSTATE/native-code classification, raw rowcounts, failed-attempt counts and stable issue groups, even when the application returns HTTP 200.
  • SQL Server estimated plans, guarded actual-plan collection and catalog candidates; explicit engine ownership, optional all-engine observation and observed session-state evidence.
  • Offline redline check-sql for supported raw-SQL Python shapes, JSON/JUnit reports, baselines, explicit compile checks and schema snapshots. Static checks are conservative.
  • Generic background jobs, stages, row outcomes, retries and optional Celery signals; a Jobs page and commit-before-failure evidence for investigating partial job completion.
  • SQL value policies, privacy profiles, route rules, request/user correlation and redaction preview.
  • Bounded capture, failure-safe observation, storage auditing, read-only worker-store browsing, and explicit sanitized OTLP summary export.

Use these to investigate a caught database error, a migration that broke raw SQL, a worker that committed before failing, an N+1 endpoint, or a performance refactor whose responses must remain equivalent. The UI exposes SQL evidence, jobs, offline SQL checks and privacy preview alongside the existing timelines, plans, profiles and refactor reports.

For production choose the record-and-inspect preset, private storage and authenticated access. Replay, load/refactor runs, source analysis and database plan execution are disabled by default there. Live MySQL/SQL Server drivers, broker/prefork behavior and the intended filesystem/deployment must be qualified before rollout; fixture tests do not establish compatibility with every codebase.

See the detailed workflow guide, production guide and feature catalog.

Please test Redline on a real development or staging project and open an issue for bugs or feature requests. Include framework/database/driver versions and a small sanitized reproduction. Never post credentials or private recordings; follow the security policy for vulnerabilities.

License

MIT

Metadata

Release files for fastapi-redline 0.4.0a1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-redline 0.4.0a1
File Size Uploaded Provenance Actions
fastapi_redline-0.4.0a1.tar.gz 40.8 kB With provenance Details for fastapi_redline-0.4.0a1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-redline 0.4.0a1
File Interpreter ABI Platform Actions
fastapi_redline-0.4.0a1-py3-none-any.whl Python 3 none any Details for fastapi_redline-0.4.0a1-py3-none-any.whl

Total release size: 64.9 kB

Release files / fastapi_redline-0.4.0a1.tar.gz

Download URL fastapi_redline-0.4.0a1.tar.gz
Size 40.8 kB
Tags Source
SHA-256 checksum
How to use checksums
efcab2ad808a6188496dc78b7af7d865ed1c1999689fd9d580cc146c347cc860
BLAKE2b-256 checksum
How to use checksums
e9f727432987a49479c5fe44fd471d43357968e7539dc88449d6d888a5214d2d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Release files / fastapi_redline-0.4.0a1-py3-none-any.whl

Download URL fastapi_redline-0.4.0a1-py3-none-any.whl
Size 24.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c0feef435cf5d1338ad5bf9ea19f9769e72f57627654eaa0b8794fe1aa9e2207
BLAKE2b-256 checksum
How to use checksums
5f9f4634154340d70f67d72e679c4cb77c42af7c10d97e6de48b8c8782923251
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Security for fastapi-redline 0.4.0a1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_redline-0.4.0a1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page