Skip to main content
Pre-release

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

Redline

django-redline

A modern request profiler for Django: SQL timelines, N+1 detection with ready-to-apply select_related/prefetch_related diffs, one-click EXPLAIN, flamegraphs and a fast web UI. It is async-correct (WSGI and ASGI, sync and async views). It does not touch your database: traces live in their own SQLite file.

It replaces django-silk. Redline stores redacted data rather than plaintext secrets, never writes to your app DB or records itself, supports async, groups N+1s, and adds EXPLAIN and flamegraphs.

Status: 0.5.0b1, beta. Built on redline-core.

Install

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

# 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",
    ...
]

# urls.py
from django.urls import include, path

urlpatterns = [
    ...,
    path("redline/", include("django_redline.urls")),
]

Run your app, make some requests and open /redline/ as a superuser.

What you get

  • Requests: every request with method, route template (/orders/<int:pk>/), view, status, duration, query count and issue badges. Filter, search and live polling.

  • Request detail: a waterfall of the span tree (middleware, then view, then SQL / cache / template spans, plus your own span()s), SQL grouped by fingerprint with the project file:line that ran it, redacted headers and bodies, and the traceback of unhandled exceptions.

  • Issues: N+1s, duplicate queries, slow queries and query budgets, deduplicated across requests.

  • The Django fix suggester maps the repeated SQL back to your models and relations, then finds the queryset in your source and writes the patch:

    --- a/shop/views.py
    +++ b/shop/views.py
    @@ -32,5 +32,5 @@
     def order_list(request):
    -    orders = Order.objects.select_related("customer").order_by("-id")[:30]
    +    orders = Order.objects.select_related("customer").prefetch_related("items").order_by("-id")[:30]
    
    Situation Suggestion
    reverse FK (order.items.all()) prefetch_related("items")
    forward FK / 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") / prefetch_related("products")
    nested loops (for item in order.items.all(): item.product) prefetch_related("items__product") on the outer queryset
    GenericRelation / GenericForeignKey prefetch_related(...) (GFK: low confidence)
    the relation is filtered per row (order.items.filter(...)) a Prefetch(..., queryset=..., to_attr=...) hint
    loop in a template, generic ListView (model = Order) diff on the render() queryset / adds queryset = ... to the view
    DRF serializer reading a relation targets the view's queryset / get_queryset()

    The fix is inserted before ordering and slicing, replaces a bare .all(), or extends an existing prefetch_related(...). When the queryset cannot be located you get a code hint with lower confidence.

  • EXPLAIN on any captured SELECT, run on connections[alias] inside a transaction that is always rolled back (and READ ONLY on PostgreSQL). Plans are analysed for full scans, temp sorts and spills, with CREATE INDEX suggestions. Works on SQLite, PostgreSQL and MySQL.

  • Flamegraphs: add ?_redline=profile to any URL (or send X-Redline-Profile: 1) to profile that request with pyinstrument (needs the profile extra).

  • Load-test correlation: an X-Redline-Run: <id>;step=<n> request header tags the trace.

  • Refactor-check correlation: X-Redline-Check: <id>;req=<i>;n=<k> (sent by redline check) tags the trace, only for a check run that exists in the store.

Settings

Everything is optional. REDLINE keys are case-insensitive, and unknown keys fail the system check with a "did you mean" hint.

REDLINE = {
    "ENABLED": True,
    "SAMPLE_RATE": 1.0,               # default 1.0 with DEBUG=True, 0.1 with DEBUG=False
    "ALWAYS_KEEP_SLOWER_THAN_MS": 500,
    "ALWAYS_KEEP_ERRORS": True,
    "IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"],  # "^" = regex
    "STORAGE_PATH": BASE_DIR / ".redline/redline.db",  # the default; str or pathlib.Path
    "N_PLUS_ONE_THRESHOLD": 5,
    "SLOW_QUERY_MS": 100,
    "TOO_MANY_QUERIES": 50,
    "PROFILE": "opt_in",              # off | opt_in | sampled | all
    "EXPLAIN_ANALYZE": False,         # ANALYZE executes the query: off by default
    "MAX_ROWS": 10_000, "MAX_AGE_DAYS": 7,  # 0 or None disables a retention rule
    "MAX_SPANS_PER_TRACE": 2_000,     # beyond it spans are counted, not stored
    "PERMISSION": "myproject.redline.can_view",   # Django-only, see below
    "STORE": "myproject.redline.make_store",      # Django-only: a custom Store (optional)
}

The full list is in the settings reference of the docs (redline_core.conf.Settings). PROJECT_ROOT defaults to BASE_DIR. It decides which stack frames count as "your code".

Security

  • Access: superusers only by default (user.is_active and user.is_superuser; staff before 0.2). Override it with REDLINE["PERMISSION"], a callable (request) -> bool or its dotted path. Anonymous visitors to the page are redirected to the admin login. The API answers 403 JSON. Redline's views also enforce ALLOWED_HOSTS (against DNS rebinding) and the page sends X-Frame-Options: DENY.
  • CSRF: the JSON API runs Django's own CSRF check on every request, even without CsrfViewMiddleware. Mutating calls (DELETE traces, POST api/explain) need the token in the CSRF header (X-CSRFToken by default). On HTTPS the Origin/Referer checks also apply. The page embeds a fresh token in <meta name="redline-csrf">, so this also works with CSRF_COOKIE_HTTPONLY / CSRF_USE_SESSIONS. Failures are a JSON 403 csrf_failed.
  • Redaction: Authorization, Cookie, Set-Cookie, X-Api-Key headers and password/token/secret-like keys in query strings, bodies and SQL params are masked before anything is stored.
  • Requests to Redline's own URLs are never recorded. Its storage is a separate SQLite file, never a Django connection.

Your own spans

from django_redline import span

@span("pricing.compute")
def compute(order): ...

with span("render-pdf", pages=3):
    ...

Operations

  • manage.py redline_clear [--noinput] deletes every trace.

  • manage.py redline_prune [--max-age-days N] [--max-rows N] applies retention now. The writer also prunes as it goes.

  • System checks (manage.py check):

    ID Problem
    E001 invalid REDLINE
    E002 storage not writable
    W001 middleware missing
    W002 GZipMiddleware inside Redline
    W003 Redline listed after middleware it should time
    W004 URLs not mounted
    W005 DEBUG=False with SAMPLE_RATE=1.0
  • Writes happen on a background thread through a bounded queue. Under overload, traces are dropped and counted rather than slowing requests.

How it hooks in

  • The middleware is sync and async capable. SQL goes through connection.execute_wrapper on every connection. Cache spans come from wrapping the backends that caches creates. Template spans come from Template.render, and the view span from BaseHandler.make_view_atomic.
  • Each hook is a single ContextVar lookup when nothing is being recorded.
  • Queries run from library code (generic views, DRF, lazily rendered TemplateResponses) are attributed to the project view that handled the request.

Supports Django 5.2, 6.0 and 6.1 on Python 3.12+. A runnable demo is in examples/django.

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 django-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 django-redline 0.5.0b1
File Size Uploaded Provenance Actions
django_redline-0.5.0b1.tar.gz 80.3 kB With provenance Details for django_redline-0.5.0b1.tar.gz

Built distribution (wheel)

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

Total release size: 139.5 kB

Release files / django_redline-0.5.0b1.tar.gz

Download URL django_redline-0.5.0b1.tar.gz
Size 80.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e46429dea56b55711a94e9ec3df30a288acb481bdf0af1753bb39d6c81bdc67c
BLAKE2b-256 checksum
How to use checksums
ee386a7ce31700ef417d9b6b4e5426ad17a783d122b9b430037608ebfd995199
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 / django_redline-0.5.0b1-py3-none-any.whl

Download URL django_redline-0.5.0b1-py3-none-any.whl
Size 59.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3b339b7db83f648b63bb1363a22250cb28905dc656d03faa9c0ea195ccb5799e
BLAKE2b-256 checksum
How to use checksums
5b36edc8d897c47980af5a0cb8c868c89b25aab5cc23a197a30590675e7afbce
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 django-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 django_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