Skip to main content

Django Custom Middleware

Create Django middleware for request logging, rate limiting, tenant identification, response headers, and performance monitoring.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Create custom Django middleware for multi-tenant SaaS API. I need middleware that handles request auditing, rate limiting, tenant resolution, and security hardening. Build: 1) A request logging middleware that captures: request method, path, user (if authenticated), IP address (respecting X-Forwarded-For from Nginx reverse proxy with Cloudflare in front), request body size, response status code, and response time in milliseconds. Log in structured JSON format to Python logging to stdout (picked up by container log driver). 2) A rate limiting middleware using Redis with sliding window algorithm — limit authenticated users to 1000 requests per minute and anonymous users to 60 requests per minute. Return 429 with Retry-After header. Exclude health check endpoints and webhook receivers from rate limiting. 3) A subdomain-based multi-tenancy middleware that identifies the tenant from subdomain (acme.app.com → tenant=acme) and sets request.tenant for downstream use. Reject requests with invalid tenants with 404. 4) A security headers middleware adding: X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, Content-Security-Policy for API-only (strict default-src none), and Permissions-Policy. 5) A performance monitoring middleware that emits metrics to StatsD (sent to Datadog) for p50/p95/p99 response times grouped by endpoint pattern (not exact URL to avoid cardinality explosion). 6) Proper middleware ordering in MIDDLEWARE setting with explanation of why order matters. 7) Unit tests for each middleware using Django test client and RequestFactory.

What this prompt does

This prompt generates a set of custom Django middleware for a [project_type], covering the cross-cutting concerns named in [middleware_purpose]. It builds request logging that captures method, path, authenticated user, client IP (respecting X-Forwarded-For from [proxy_setup]), request body size, response status, and response time in milliseconds, written in [log_format] to [log_destination].

It also produces a rate limiter backed by [rate_limit_backend] that caps authenticated users at [auth_rate_limit] and anonymous users at [anon_rate_limit], returns 429 with a Retry-After header, and skips [rate_limit_exclusions]. A [tenant_strategy] multi-tenancy middleware resolves the tenant from [tenant_identifier], sets request.tenant for downstream use, and rejects invalid tenants with a 404. A security-headers middleware adds X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, a CSP tuned for [csp_policy], and Permissions-Policy, while a performance monitor emits p50/p95/p99 metrics to [metrics_backend] grouped by endpoint pattern to avoid cardinality explosion. Crucially, it explains MIDDLEWARE ordering and ships unit tests per middleware.

When to use it

  • You need request auditing logged consistently across every endpoint
  • You want rate limiting that distinguishes authenticated from anonymous traffic
  • You're building multi-tenant routing and need tenant resolved early in the stack
  • You want security headers applied globally rather than per-view
  • You need latency percentiles per endpoint without blowing up metric cardinality
  • You want middleware that ships with RequestFactory and test-client unit tests
  • You're inheriting a project and want these concerns centralized instead of scattered across views

Example output

The AI returns several middleware classes, each as its own code block, plus a MIDDLEWARE list showing the correct order with comments explaining why each sits where it does. Expect a 429 response example with a Retry-After header, a CSP header string for [csp_policy], a structured [log_format] log line, and unit tests using Django's test client and RequestFactory for each component so you can verify behavior before wiring them in. The ordering comments in the MIDDLEWARE list double as documentation for the next engineer who touches the stack.

Pro tips

  • Be precise about [proxy_setup] so X-Forwarded-For parsing picks the right client IP and isn't spoofable behind your real proxy chain
  • Set [auth_rate_limit] and [anon_rate_limit] to genuinely different values — anonymous traffic usually warrants a much tighter cap
  • List [rate_limit_exclusions] carefully so health checks and webhook receivers never get throttled
  • Keep performance metrics grouped by endpoint pattern, not exact URL, or [metrics_backend] cardinality will explode
  • Pay attention to the ordering explanation — tenant resolution must run before anything that reads request.tenant
  • Apply security headers in the response phase so they cover error responses too, not just successful ones
  • Exclude [rate_limit_exclusions] before counting a request so a health-check probe never consumes a rate-limit token
  • If the CSP feels too permissive, re-prompt with the exact sources you allow for [csp_policy]

Frequently Asked Questions

Why does the prompt insist on explaining middleware ordering?
Because order genuinely matters in Django's MIDDLEWARE stack. Tenant resolution must run before any middleware that reads `request.tenant`, and security headers should wrap the final response, so the prompt asks for an explicit ordering rationale to prevent subtle bugs.
How does the rate limiter tell authenticated and anonymous users apart?
It applies `[auth_rate_limit]` to logged-in users and the tighter `[anon_rate_limit]` to anonymous traffic, storing counters in `[rate_limit_backend]`. When a limit is hit it returns a 429 response with a Retry-After header so clients know when to retry.
Does it correctly get the real client IP behind a proxy?
Yes. The logging middleware respects X-Forwarded-For based on your `[proxy_setup]`, so it extracts the originating client IP rather than the proxy's address. Configure the proxy chain accurately, since a misconfigured trust setting can let clients spoof their IP.
Will the performance middleware overload my metrics backend?
It's designed to avoid that by grouping p50/p95/p99 timings by endpoint pattern rather than exact URL. Tracking exact URLs would create a separate metric per ID and cause a cardinality explosion in `[metrics_backend]`, which this approach prevents.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Django & Flask Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support