Skip to main content
Pre-release

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

Redline

litestar-redline

The Litestar + 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 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 are stored in their own SQLite file (.redline/redline.db), never in your database.

Install

pip install --pre litestar-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 "litestar-redline[profile]".

Python 3.10+, Litestar 2.12+ (< 3), SQLAlchemy 2.x.

RedlinePlugin

RedlinePlugin(
    settings=None,    # dict | redline_core.Settings
    engine=None,      # Engine | AsyncEngine | [engines] | {"alias": engine}
    path=None,        # default: the mount_path setting, else "/_redline"; never recorded
    guards=None,      # Litestar guards for the UI + API (see "Access control")
    store=None,       # custom Store (default: SQLite file at storage_path)
)

What it does when the app is built:

  • adds a pure ASGI middleware (capture, route template, status, bodies, SQL spans);
  • records exceptions through Litestar's after_exception hook (see below);
  • mounts the UI and JSON API under path as a Litestar Router;
  • instruments the engines, and flushes and closes the store on shutdown (on_shutdown; your own lifespan hooks keep working).

settings takes any Redline setting with case-insensitive keys:

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,
})

The plugin object is also the handle: plugin.recorder, plugin.store, plugin.settings, plugin.add_engine(engine) for an engine created later, plugin.close().

Engines

With Litestar's own SQLAlchemy plugin (advanced-alchemy) and no engine=, the plugin's engine(s) are found and instrumented automatically:

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" db alias (used by EXPLAIN); others are named after their database file, or pass a dict:

RedlinePlugin(engine=[async_engine, sync_engine])
RedlinePlugin(engine={"main": main_engine, "analytics": analytics_engine})

What is recorded

  • Request / 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 by the core.
  • 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.
  • 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, locals); a 4xx HTTPException (404, 401, validation) is a client error and is not an error trace.
  • Sync handlers (sync_to_thread=True) are attributed to the right request.
  • Your own spans: with redline_core.span("pricing.compute"): ....
  • 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).

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.

Profiling

Flamegraphs are opt-in per request: ?_redline=profile or the header X-Redline-Profile: 1 (needs the [profile] extra).

Outbound HTTP (httpx)

from litestar_redline import instrument_httpx

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

Fix suggestions

For an N+1, SQLAlchemyFixSuggester maps the repeated query back to your models and produces a real unified diff (selectinload(Parent.children), joinedload(Child.parent)), exactly as in the FastAPI adapter.

Access control

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

Default. With no guards, 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 are JSON {"error": {"code": "forbidden" | "unauthorized" | ..., "message"}}. Use the allowed_hosts setting to allow another host name. Passing guards= 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. See the access control docs.

Your own guard (any Litestar guard; it replaces the loopback default):

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 passing none.

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 or same-site. This is always on, whatever guards you pass.

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 (READ ONLY on PostgreSQL). EXPLAIN ANALYZE executes the query, so it is off unless explain_analyze=True.

Development

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

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 litestar-redline 0.5.0b1

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

Source distribution (sdist)

Source distribution for litestar-redline 0.5.0b1
File Size Uploaded Provenance Actions
litestar_redline-0.5.0b1.tar.gz 39.4 kB With provenance Details for litestar_redline-0.5.0b1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for litestar-redline 0.5.0b1
File Interpreter ABI Platform Actions
litestar_redline-0.5.0b1-py3-none-any.whl Python 3 none any Details for litestar_redline-0.5.0b1-py3-none-any.whl

Total release size: 62.0 kB

Release files / litestar_redline-0.5.0b1.tar.gz

Download URL litestar_redline-0.5.0b1.tar.gz
Size 39.4 kB
Tags Source
SHA-256 checksum
How to use checksums
171286770829ae65728697c0315c63682e9670d0e6adae4a190e61eead964b9a
BLAKE2b-256 checksum
How to use checksums
8af1c5c4cf6efff3b9bf13b1dff08bb2eccf4b48c58a59a47bb5682558df15ea
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 Nov 13, 2026.

Transparency log

Release files / litestar_redline-0.5.0b1-py3-none-any.whl

Download URL litestar_redline-0.5.0b1-py3-none-any.whl
Size 22.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ae4cbcd7166505fd415f8374935cc50929bfe23a8a53bb35701971e1ad035ec8
BLAKE2b-256 checksum
How to use checksums
11af84db726b6b01c64d4265094af4fc5004b95f8af340034b4ef804a7355a48
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 Nov 13, 2026.

Transparency log

Security for litestar-redline 0.5.0b1

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 litestar_redline-0.5.0b1.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 Nov 13, 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