This release is a pre-release and may not be stable for production use.
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.2.0a1, alpha. Built onredline-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 querysetGenericRelation/GenericForeignKeyprefetch_related(...)(GFK: low confidence)the relation is filtered per row ( order.items.filter(...))a Prefetch(..., queryset=..., to_attr=...)hintloop in a template, generic ListView(model = Order)diff on the render()queryset / addsqueryset = ...to the viewDRF 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 existingprefetch_related(...). When the queryset cannot be located you get a code hint with lower confidence. -
EXPLAIN on any captured
SELECT, run onconnections[alias]inside a transaction that is always rolled back (andREAD ONLYon PostgreSQL). Plans are analysed for full scans, temp sorts and spills, withCREATE INDEXsuggestions. Works on SQLite, PostgreSQL and MySQL. -
Flamegraphs: add
?_redline=profileto any URL (or sendX-Redline-Profile: 1) to profile that request with pyinstrument (needs theprofileextra). -
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 byredline 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 withREDLINE["PERMISSION"], a callable(request) -> boolor its dotted path. Anonymous visitors to the page are redirected to the admin login. The API answers403JSON. Redline's views also enforceALLOWED_HOSTS(against DNS rebinding) and the page sendsX-Frame-Options: DENY. - CSRF: the JSON API runs Django's own CSRF check on every request, even without
CsrfViewMiddleware. Mutating calls (DELETEtraces,POST api/explain) need the token in the CSRF header (X-CSRFTokenby default). On HTTPS the Origin/Referer checks also apply. The page embeds a fresh token in<meta name="redline-csrf">, so this also works withCSRF_COOKIE_HTTPONLY/CSRF_USE_SESSIONS. Failures are a JSON403csrf_failed. - Redaction:
Authorization,Cookie,Set-Cookie,X-Api-Keyheaders 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 E001invalid REDLINEE002storage not writable W001middleware missing W002GZipMiddlewareinside RedlineW003Redline listed after middleware it should time W004URLs not mounted W005DEBUG=FalsewithSAMPLE_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_wrapperon every connection. Cache spans come from wrapping the backends thatcachescreates. Template spans come fromTemplate.render, and the view span fromBaseHandler.make_view_atomic. - Each hook is a single
ContextVarlookup 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-sqlfor 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.4.0a1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_redline-0.4.0a1.tar.gz | 77.9 kB | With provenance | Details for django_redline-0.4.0a1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_redline-0.4.0a1-py3-none-any.whl | Python 3 | none | any | Details for django_redline-0.4.0a1-py3-none-any.whl |
Total release size: 135.7 kB
Release files / django_redline-0.4.0a1.tar.gz
| Download URL | django_redline-0.4.0a1.tar.gz |
|---|---|
| Size | 77.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e016ee0f2044654874000b2ce90f9c13d9b6cd3ad2bf1faeb9b2c17f967845dd
|
|
BLAKE2b-256 checksum How to use checksums |
5c83ad330acd3c152fa5ea261bf01153356d0711fe58023d19fde3964a38ade3
|
| 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 logRelease files / django_redline-0.4.0a1-py3-none-any.whl
| Download URL | django_redline-0.4.0a1-py3-none-any.whl |
|---|---|
| Size | 57.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ef396d08a3df3854d34282991a0c1c749b9c65d7fa03594f6ec1aa9fa4aa57ed
|
|
BLAKE2b-256 checksum How to use checksums |
b40877fd9a378b1768f8eb9a678ab4f679261bd1247d9e6c1d1757b52b9d9e66
|
| 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 logSecurity for django-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.
Attestation for django_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 logA 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.