Optimize
Performance, scaling, and reliability work for Django apps that are already live.
Best for teams with a working stack who want stronger uptime and smoother deploys.
Optimize guides are for a site that already runs and needs to be faster, cheaper, safer to release, or easier to operate. Most follow the same loop: measure, change one thing, and measure again.
They are grouped by the part of the stack they improve. Start where your measurements point, which for most Django sites is the database, then caching, then the app server.
Topics in Optimize
Grouped by guide type, then difficulty
Narrow the list by experience level or stack, then work through the matching guides in recommended order.
Foundations guides
Learn the concepts, tradeoffs, and prerequisites before you change production infrastructure.
A good app deploy can still fail if the database migration step is unsafe. That is the real problem behind many Django migration deployment issues in production.
A lot of Django apps reach production with local-development assumptions still in place: DEBUG=True, weak host validation, secrets in .env files with broad permissions, Gunicorn...
A production Django deployment needs a reliable way to answer a simple question: is this instance safe to keep running and safe to receive traffic?
A default Django project does not give you a production-safe logging setup.
Many Django teams start with a manual deployment process over SSH. That is normal: log into a Linux server, pull code, install dependencies, run migrations, collect static files...
Choose what to cache in a Django app: HTTP caching, per-view and fragment caches, low-level caching, invalidation, stampede protection, and hit rates.
Use feature flags in Django to separate deploys from releases: flag types, a simple flag model, django-waffle, gradual rollouts, kill switches, and cleanup.
Estimate CPU, memory, and database capacity for Django: measure per-request costs, calculate worker counts, plan headroom, load test, and scale.
Prepare Django to run on multiple servers behind a load balancer: shared sessions, media, caches, migrations, scheduled jobs, health checks, and deploys.
Write a practical disaster recovery plan for Django: RPO and RTO targets, failure scenarios, point-in-time recovery, runbooks, access, and drills.
Tasks guides
Follow actionable deployment and operations guides you can work through step by step.
Local logs are not enough once a Django app is in production. Exceptions can happen after deploys, during background jobs, or only under real user traffic patterns.
Set up external uptime monitoring for Django: what to check, health endpoints, keyword and SSL checks, heartbeats for jobs, and alert routing.
Keep a Django server patched automatically: unattended-upgrades on Ubuntu and Debian or dnf-automatic on RHEL, security-only origins, service restarts, reboot windows, exclusions for PostgreSQL, and monitoring.
Add a swap file to a 1-2 GB Django server so pip installs, migrations, and traffic spikes do not trigger the OOM killer: sizing, fstab, swappiness, Docker and cloud caveats, and when swap is the wrong fix.
Create custom 404, 500, 403, and 400 pages for a Django site in production: templates and handler views, a 500 page that cannot fail, static assets that load, Nginx error pages for when Django is down, and testing them with DEBUG off.
Detect Django scheduled jobs that fail or silently stop running: heartbeat (dead man's switch) monitoring with Healthchecks.io, Cronitor, or your own endpoint, pinging start and success from management commands, Celery Beat, and Kubernetes CronJobs.
Use django-dbbackup to back up the Django database and media to S3 or other storage on a schedule: configuration, compression and GPG encryption, cleanup, restores with dbrestore and mediarestore, and its limits compared with native tools.
Stop bot signups and contact-form spam in Django: add Cloudflare Turnstile with server-side verification, honeypot fields and timing checks, rate limits, email confirmation, and how to keep forms accessible and private.
Catch expiring HTTPS certificates before users do: check expiry from outside with uptime monitors, Prometheus blackbox exporter, or a scheduled script, cover every domain and certificate path, alert at 21 and 7 days, and verify that renewal actually reloads Nginx.
Publish /.well-known/security.txt from Django with contact, expiry, policy, and encryption fields, set up a vulnerability disclosure policy and intake mailbox, triage reports, and avoid common mistakes like expired files and unmonitored addresses.
A manual Django deployment often looks simple at first: SSH into a server, pull code, install dependencies, run migrations, collect static files, restart Gunicorn, and hope the...
Django and Gunicorn log rotation becomes a production issue as soon as your app writes request logs, error logs, or application logs to disk for more than a few days.
A Django app is only recoverable if its PostgreSQL data is recoverable. In production, that means more than occasionally running pg_dump.
Find and fix N+1 queries in Django: detect them in tests and logs, use select_related, prefetch_related, Prefetch objects, and annotations correctly.
Use CONN_MAX_AGE and CONN_HEALTH_CHECKS correctly: when persistent connections help, connection math, idle timeouts, ASGI caveats, and measuring gains.
Compress Django responses and static files correctly: Nginx gzip settings, precompressed static assets, Brotli support, BREACH caveats, and checks.
Shrink and speed up Django Docker images: slim base images, multi-stage builds, layer ordering, BuildKit cache mounts, .dockerignore, and measurement.
Protect Django login, API, and expensive endpoints with Nginx limit_req: zones, burst and nodelay, 429 responses, real client IPs, and dry runs.
Back up Django uploads reliably: MEDIA_ROOT with restic, S3 versioning and replication, consistency with database backups, retention, and restores.
Cache Django static files for a year without stale assets: manifest hashing, immutable Cache-Control headers in Nginx and WhiteNoise, CDNs, and deploy order.
Keep Django and its dependencies current safely: Dependabot or Renovate, pip-audit in CI, grouped updates, test gates, and urgent security releases.
Choose and tune Django's session backend for production: database, cached_db, cache, or signed cookies; cookie security flags; expiry; write frequency; and cleaning up expired sessions.
Enable pg_stat_statements for a Django app, rank queries by total time, trace them back to ORM code, confirm plans with EXPLAIN ANALYZE, and fix them with indexes and better querysets.
Serve a Django site over HTTP/2 and HTTP/3 (QUIC) with Nginx: version-specific directives, Alt-Svc, UDP 443, keeping HTTP/1.1 to Gunicorn, verifying with curl, and what actually gets faster.
Stop slow Celery tasks from delaying urgent ones in Django: define queues, route tasks with CELERY_TASK_ROUTES, run dedicated workers per queue with their own concurrency and limits, and monitor queue depth.
Stop runaway queries from exhausting Django workers: set statement_timeout per connection or role, give migrations and Celery different limits, handle QueryCanceled errors, and work with PgBouncer.
Rotate Django's SECRET_KEY without breaking sessions and password reset links: what the key signs, SECRET_KEY_FALLBACKS, a staged rollout, leak response, and third-party libraries that use the key.
Block brute-force attacks on Django login and admin pages with fail2ban: log failed logins with the real client IP, write a filter and jail, ban at the firewall, and combine with app-level rate limiting.
Cut the cost of running Django in production: measure before resizing, right-size servers and databases, trim idle environments, control egress, NAT, logs, and backups, and commit only to steady usage.
Put a Django site into maintenance mode safely: an Nginx flag file returning 503 with Retry-After, a static maintenance page, staff IP bypass, health checks, and when to avoid maintenance windows.
Decide which Redis data must survive restarts in a Django stack: AOF versus RDB for Celery queues and sessions, no persistence for caches, fork memory, Docker volumes, and verifying recovery.
Centralise Django, Gunicorn, Celery, and Nginx logs in Grafana Loki: structured JSON logging, Grafana Alloy collecting from journald and files, low-cardinality labels, LogQL queries, and retention.
Run Flower to monitor Celery in a Django deployment: enable task events, run Flower under systemd bound to localhost, protect it with authentication behind Nginx, persist state, and export Prometheus metrics.
Use Django template fragment caching in production: the cache tag with vary-on keys, per-user and per-language fragments, cached template loaders, invalidation with make_template_fragment_key, and avoiding stale or leaked content.
Control how browsers and CDNs cache Django responses: cache_control and never_cache decorators, public versus private, max-age versus s-maxage, Vary headers from sessions and cookies, ETags, and safe defaults for logged-in pages.
Make Django REST Framework APIs faster in production: eliminate N+1 queries with select_related and prefetch_related, slim serializers, paginate everything, cache expensive endpoints, use values() for read-heavy lists, and measure with profiling.
Speed up large Django data loads and updates: bulk_create and bulk_update with batch_size, update() with F expressions, update_conflicts for upserts, transactions, disabling per-row signals, COPY for very large imports, and what bulk methods skip.
Serve fast, right-sized images from a Django app: generate thumbnails in background tasks, use WebP and AVIF, responsive srcset, CDN or image service resizing, cache headers for media, and avoid resizing images inside web requests.
Switch Django to structured JSON logs for production: configure python-json-logger or structlog, include request ID, user, and timing fields, keep Gunicorn and Celery logs consistent, avoid logging secrets, and query logs in Loki, CloudWatch, or Datadog.
Correlate Django logs per request with a request ID: accept or generate X-Request-ID at Nginx or the load balancer, store it in a contextvar, add it to every log line and Sentry event, return it to clients, and pass it to Celery tasks and outbound calls.
Record who changed what and when in a Django app: compare django-simple-history, django-auditlog, and pghistory triggers, capture the acting user and request ID, protect audit tables from tampering, plan retention, and keep audit writes fast.
Instrument a Django app with Datadog APM: install ddtrace, run Gunicorn under ddtrace-run, configure service, env, and version tags, trace Celery, PostgreSQL, and Redis, correlate logs with traces, and control cost with sampling.
Ship Django, Gunicorn, and Celery logs to Amazon CloudWatch Logs: the awslogs driver on ECS, the CloudWatch agent on EC2, JSON logs for Logs Insights queries, retention settings, metric filters and alarms, and controlling ingestion cost.
Defend a Django site against abusive bots, scrapers, and credential stuffing with a web application firewall: Cloudflare or AWS WAF managed rules, rate-based rules, bot challenges on login and signup, protecting APIs, and avoiding false positives.
Protect Django logins from password guessing with django-axes: install the backend and middleware, choose lockout parameters by user and IP, get real client IPs behind proxies, store attempts in cache or database, and unlock users safely.
Upgrade Django password hashing to Argon2id: install argon2-cffi, put Argon2PasswordHasher first, let existing hashes upgrade on login, wrap old hashes to upgrade everyone now, tune memory and time cost, and size servers for login load.
Scan Django container images with Trivy for vulnerable OS packages and Python dependencies: run it locally and in CI, fail builds on fixable critical issues, ignore false positives with expiry, rebuild on new base images, and scan running registries.
Make Django Docker builds fast in CI and locally: order layers so dependencies cache, BuildKit cache mounts for pip and uv, registry-backed cache for CI, .dockerignore, and multi-stage builds that compile once.
Configure Nginx TLS for a Django site to earn an SSL Labs A+: TLS 1.2 and 1.3 only, modern ciphers, HSTS with Django settings, OCSP stapling, session settings, certificate chain, and verifying with SSL Labs and testssl.sh.
Export large datasets from Django as CSV without timeouts or memory spikes: StreamingHttpResponse with iterator(), values_list to skip model instances, Nginx buffering, background exports to object storage for very large files, and Excel compatibility.
Upgrade a production Django app to a newer Python version safely: check Django and dependency support, run tests on both versions in CI, rebuild virtualenvs or images, upgrade Celery workers together, deploy gradually, and roll back cleanly.
Deliver Django configuration on Kubernetes: ConfigMaps for non-secret settings, Secrets for credentials, envFrom versus mounted files, rolling pods when values change, encryption at rest, and syncing from external secret managers.
Respond to a leaked Django SECRET_KEY, database password, or API key: assess exposure, rotate in the right order, use SECRET_KEY_FALLBACKS only when appropriate, invalidate sessions and tokens, purge Git history, and prevent the next leak.
Pick Redis maxmemory and maxmemory-policy settings for Django workloads: allkeys-lru or allkeys-lfu for caches, noeviction for Celery brokers and locks, volatile policies for mixed use, and how to split instances so evictions never drop queued tasks or sessions.
Decide which indexes a Django app needs: find slow queries, index foreign keys and filter and ordering columns, use composite, partial, covering, and expression indexes with Meta.indexes, remove unused indexes, and add them without locking production tables.
Read PostgreSQL query plans for Django ORM queries with QuerySet.explain(analyze=True, buffers=True): spot sequential scans, bad row estimates, sorts, and nested loops, run EXPLAIN safely on production, and turn plans into indexes and queryset fixes.
Implement data retention in Django: delete old logs, task results, sessions, and events in small batches with primary key ranges, avoid long locks and replica lag, handle cascades, schedule cleanup with Celery or cron, and consider partitioning for big tables.
Cut bandwidth and server work with HTTP conditional requests in Django: ConditionalGetMiddleware, the condition, etag, and last_modified decorators, cheap ETag functions, 304 Not Modified responses for APIs, and how ETags interact with CDNs and compression.
Make Django templates render faster in production: confirm the cached template loader is active, avoid disabling it with custom loaders or APP_DIRS mistakes, reduce expensive template work, use fragment caching, and measure template time per view.
Turn on PostgreSQL slow query logging for a Django app: set log_min_duration_statement, add auto_explain for plans, tag queries with application_name and SQL comments to find the view that sent them, and ship logs to your log platform without flooding it.
Configure Celery retries for Django tasks: autoretry_for with retry_backoff and jitter, manual self.retry with countdown, max_retries and retry_backoff_max, which exceptions to retry, idempotency, and dead-letter handling for tasks that keep failing.
Expose Celery metrics to Prometheus for a Django app: run celery-exporter for task counts, failures, runtimes, and queue lengths, enable task events, build Grafana panels, and alert on growing queues, rising failures, and missing workers.
Add application-level rate limiting to Django views with django-ratelimit: protect login, signup, password reset, and search, key limits by IP, user, or field, use a shared Redis cache, get the real client IP behind proxies, and return helpful 429 responses.
Set up Django REST Framework throttling that works in production: shared Redis cache, AnonRateThrottle and UserRateThrottle defaults, ScopedRateThrottle per endpoint, correct client IPs behind proxies with NUM_PROXIES, Retry-After headers, and custom throttles per API key.
Build reliable webhook endpoints in Django: verify signatures, store the raw event first, return 2xx quickly, process asynchronously with Celery, deduplicate by event ID, handle out-of-order delivery, and replay failed events safely.
Undo a Django migration safely in production: migrate an app back to a previous migration, understand which operations are reversible, handle data loss from reverting added columns and data migrations, roll back code and schema in the right order, and prefer forward fixes.
Rotate PostgreSQL or MySQL credentials used by a Django app without outages: use two database roles or dual passwords, update secrets in the right order, restart web, Celery, and cron processes, handle PgBouncer, and automate rotation with Secrets Manager.
Encrypt PostgreSQL dumps and media backups for a Django app: use age or GPG for client-side encryption, restic or pgBackRest built-in encryption, server-side encryption with KMS on S3, manage and store keys separately, and test restores with decryption.
Protect a Django deployment from voluntary disruptions on Kubernetes: add PodDisruptionBudgets for web and Celery, spread replicas across nodes and zones, set graceful termination and preStop delays, and avoid budgets that block node drains forever.
Size Kubernetes resources for Django web and Celery pods: measure real usage, set memory requests near the working set and limits above peaks, avoid CPU throttling with sensible CPU limits, match Gunicorn workers to CPU requests, and use VPA recommendations.
Make collectstatic to S3 or other object storage fast: skip unchanged files, use storage backends that compare hashes, collect locally then sync with the AWS CLI, skip post-processing where safe, and run it once per release in CI instead of on every server.
Decide what to purge from Cloudflare or another CDN after deploying Django: rely on hashed static file names, purge cached HTML by URL or tag, automate purges from CI with an API token, avoid purge-everything, and keep old assets available during rollouts.
Use orjson to make Django and Django REST Framework JSON serialization faster: an orjson renderer and parser for DRF, an ORJSONResponse for plain views, handling of datetimes, Decimals, and UUIDs, and when JSON encoding is actually your bottleneck.
Control Sentry volume and cost for Django: keep error sample_rate at 1.0, set traces_sample_rate or a traces_sampler that keeps slow and critical transactions, drop health checks and noisy errors with before_send, and use rate limits and spike protection.
Cut log volume from Django, Gunicorn, Nginx, and Celery without losing what matters: set sane log levels per logger, drop health check and static access logs, deduplicate access logging, sample high-volume info logs, and route debug detail to short retention.
Prove your Django backups work by restoring them regularly: automate a restore into a scratch database, measure restore time against your RTO, verify row counts and run Django checks and smoke tests, test point-in-time recovery, and record the results.
Configure Cloudflare WAF custom rules, rate limiting, and managed rulesets for Django: protect /admin and login views, challenge bad bots, skip rules for webhooks and uploads, avoid blocking legitimate API clients, and verify the real client IP at the origin.
A standard Django deploy often causes a brief outage because the old app process stops before the new one is fully ready.
Manual server creation is one of the fastest ways to introduce deployment drift into a Django environment.
A failed Django release can break more than page requests. It can also break background workers, scheduled jobs, static asset loading, startup commands, or database compatibility.
Pre-release load testing answers a practical deployment question: will this Django release survive real traffic on your actual production stack.
If you want to optimize Gunicorn workers for Django, the main production risk is getting concurrency wrong.
Enable Django's native psycopg 3 connection pool: sizing per process, CONN_MAX_AGE rules, health checks, Gunicorn and ASGI behavior, and PgBouncer.
Use Nginx proxy_cache in front of Django safely: cache zones, bypassing logged-in users, respecting Cache-Control, stale serving, and purging.
Expose Django metrics to Prometheus, handle Gunicorn multiprocess mode, add database and host exporters, build Grafana panels, and alert on what matters.
Run blue-green deployments for Django with Nginx: two release environments, smoke tests, instant traffic switching, migration rules, and fast rollback.
Add PostgreSQL read replicas to Django: multi-database settings, routers, replication lag and read-your-writes, transactions, migrations, and tests.
Tune Celery workers for Django workloads: pool types, concurrency, prefetch multiplier, acks_late, time and memory limits, and dedicated queues.
Change large PostgreSQL tables from Django migrations without outages: lock_timeout, concurrent indexes, NOT VALID constraints, and batched backfills.
Add distributed tracing to Django with OpenTelemetry: instrument Django, PostgreSQL, Redis, and Celery, initialize safely under Gunicorn, and sample.
Find why Django endpoints are slow in production: sample live Gunicorn workers with py-spy, record flame graphs, and dump stuck workers safely.
Design Django Celery tasks that can run twice without harm: enqueue on commit, idempotency keys and unique constraints, row locks, external API idempotency, and bounded retries with backoff.
Add a Content Security Policy to Django: Django 6 built-in CSP settings or django-csp, nonces for inline scripts, report-only rollout, collecting violation reports, and handling third-party scripts.
Set up point-in-time recovery for a Django PostgreSQL database with pgBackRest: WAL archiving, full and incremental backups, restoring to a timestamp before a bad migration, and managed-service PITR.
Upgrade the PostgreSQL behind a Django app to a new major version: check Django and psycopg support, choose dump and restore, pg_upgrade, or logical replication, then analyze, verify, and roll back safely.
Keep Django tables fast and small with autovacuum tuning: find dead tuples and bloat, set per-table thresholds for hot tables in migrations, raise cost limits, and remove blockers like long transactions.
Release Django changes to a small share of traffic first: run stable and canary versions side by side, split traffic in Nginx or a load balancer, compare errors and latency per version, and promote or roll back.
Add PostgreSQL indexes to large tables in a live Django app without blocking writes: AddIndexConcurrently in non-atomic migrations, handling failed concurrent builds, finding missing indexes, and removing unused ones safely.
Cache Django HTML at Cloudflare’s edge safely: Cache Rules for anonymous pages, bypassing cache when session or CSRF cookies exist, respecting origin Cache-Control, purging on deploy or content change, and avoiding cached private pages.
Decide when async views improve a production Django app: concurrent external API calls, streaming, and long-polling benefit, while ORM-heavy views usually do not. Measure, avoid blocking calls, and run async code under ASGI correctly.
Paginate large Django tables without slow OFFSET and COUNT queries: keyset (cursor) pagination on an indexed column, DRF CursorPagination, avoiding exact counts, admin tips, and when page numbers are still fine.
Tune PostgreSQL configuration for a Django app: shared_buffers, effective_cache_size, work_mem, max_connections with pooling, random_page_cost on SSDs, checkpoints and WAL, autovacuum, and statement timeouts, with safe starting values by server size.
Use PostgreSQL declarative partitioning for very large Django tables such as events, logs, and audit trails: range partitions by time, creating them with migrations or pg_partman, primary key constraints, ORM behaviour, and dropping old data instantly.
Run Django search on PostgreSQL full-text search in production: a stored SearchVectorField with a GIN index, weights and ranking, language configurations, trigram similarity for typos, keeping vectors updated, and when to move to a search engine.
Make Django processes start faster: measure import time with python -X importtime, defer heavy imports, avoid database queries at import, trim INSTALLED_APPS, and why startup matters for serverless, autoscaling, deploys, and management commands.
Decide whether to enable Gunicorn preload_app for Django: memory savings from copy-on-write, faster worker boot, fail-fast startup, the database and client connections you must close after fork, and why reloads need a full restart.
Use Gunicorn gevent workers for Django apps that spend time waiting on external APIs: worker_connections, monkey patching, psycopg and database connection limits, CPU-bound pitfalls, and comparing gevent with threads and ASGI.
Tune Nginx for a Django backend: worker_processes and worker_connections, client keepalive_timeout, upstream keepalive connection pools to Gunicorn or Uvicorn, proxy buffering, and file descriptor limits, with when each setting matters.
Give a Django staging environment realistic data without exposing customers: copy production, anonymise personal fields with a management command or tooling, subset large tables, disable outbound email and payments, and automate refreshes.
Keep a Django app running through database failures: managed Multi-AZ PostgreSQL, Patroni or CloudNativePG for self-hosted clusters, connection endpoints that follow the primary, CONN_HEALTH_CHECKS and retries, and testing failover.
Migrate a Django PostgreSQL database to a new server, provider, or major version with seconds of downtime: logical replication publications and subscriptions, schema copy, sequence sync, cutover steps, and verification.
Scale Django Channels beyond one process: the Redis channel layer and its capacity settings, running several Daphne or Uvicorn instances behind a load balancer, sticky sessions, connection limits, group fan-out costs, and graceful reconnects during deploys.
Autoscale Django web pods on Kubernetes with the Horizontal Pod Autoscaler: accurate CPU requests, scaling on CPU or requests per second, min and max replicas, scale-down stabilisation, database connection limits, and testing under load.
Configure Kubernetes liveness, readiness, and startup probes for Django: separate cheap liveness and dependency-aware readiness endpoints, ALLOWED_HOSTS and HTTPS redirects, timeouts and thresholds, and avoiding restart storms during database outages.
Shut down Django web servers and Celery workers without dropping requests or tasks: how Gunicorn, Uvicorn, and Celery handle SIGTERM, graceful timeouts, Docker stop_grace_period, Kubernetes preStop and terminationGracePeriodSeconds, and PID 1 pitfalls.
Cache Django ORM queries automatically with django-cachalot or django-cacheops: how invalidation works, when it speeds up read-heavy apps, which tables to exclude, multi-process and raw SQL pitfalls, and how to measure hit rates before trusting it in production.
Stop cache stampedes (dogpile effects) in Django when a popular cache key expires and hundreds of requests recompute it at once: use locks, stale-while-revalidate, jittered timeouts, background refresh, and probabilistic early expiration.
Speed up Django JSONField lookups on PostgreSQL: choose GinIndex with jsonb_ops or jsonb_path_ops for containment queries, add expression B-tree indexes for specific keys, write queries that can use them, and build the indexes concurrently.
Measure and remove PostgreSQL table and index bloat in a Django database without long locks: estimate bloat, understand why VACUUM FULL blocks the app, run pg_repack on large tables, reindex concurrently, and prevent bloat from returning.
Lower the memory footprint of Django processes: measure RSS per Gunicorn and Celery worker, trim imports and INSTALLED_APPS, stream large querysets and responses, recycle workers with max-requests, try jemalloc, and size worker counts to fit the server.
Configure ECS service auto scaling for Django web and Celery services: target tracking on CPU or ALB requests per target, step scaling on SQS or custom queue metrics, sensible min and max tasks, cooldowns, database connection limits, and graceful shutdown.
Plan a multi-region Django deployment: decide between active-passive and active-active, route users with latency or geo DNS, place PostgreSQL primaries and read replicas, handle sessions, caches, Celery, and media per region, and test regional failover.
Control how fast Celery tasks run in a Django app: per-worker rate_limit on tasks, why it is not global, global limits with a Redis token bucket or dedicated queues and concurrency, handling third-party API 429 responses, and protecting the database from task floods.
Stop losing or duplicating side effects when Django saves data and enqueues Celery tasks: compare transaction.on_commit with a transactional outbox table, write outbox rows atomically, relay them with a worker using SKIP LOCKED, and make consumers idempotent.
Accept large uploads in Django without timeouts or memory spikes: upload directly to S3 with multipart presigned URLs, use the tus resumable protocol, tune Nginx and Django upload limits, process files in Celery, and validate files after upload.
Squash long Django migration histories without breaking deployed environments: run squashmigrations, keep replaced migrations until every database has applied them, handle RunPython and elidable operations, update dependencies, and remove old files in a later release.
Backfill or transform millions of rows in Django without long locks or failed deploys: move heavy data changes out of schema migrations, batch updates by primary key, run them as resumable management commands or Celery jobs, and keep code compatible during the backfill.
Rename a Django model field or column without breaking running code during rolling deploys: use db_column to rename in Python only, or expand and contract with a new column, dual writes, backfill, and removal across several releases.
Drop a Django model field and its database column safely during rolling deploys: stop using the field in code first, remove it from Django’s state with SeparateDatabaseAndState, drop the column in a later release, and handle NOT NULL columns and dependent indexes.
Convert a Django AutoField primary key to BigAutoField before it overflows: estimate time to exhaustion, avoid the table-rewriting ALTER on big tables, add a new bigint column with triggers, backfill, swap keys and foreign keys, and handle sequences.
Lock down network access for Django on Kubernetes: default-deny ingress and egress, allow the ingress controller to reach web pods, let web and Celery reach PostgreSQL, Redis, and DNS, permit required external APIs, and test policies without breaking the app.
Make Kubernetes rolling updates of Django truly zero-downtime: configure maxSurge and maxUnavailable, readiness probes that reflect real readiness, preStop delays for endpoint propagation, Gunicorn graceful shutdown, backward-compatible migrations, and minReadySeconds.
Avoid connection exhaustion when Django runs on Lambda, Cloud Run, Vercel, or autoscaling containers: use pooled endpoints (RDS Proxy, Neon, Supabase pooler, PgBouncer), set CONN_MAX_AGE and server-side cursor options correctly, and cap concurrency per instance.
Add always-on continuous profiling to Django and Celery with Grafana Pyroscope: install the Python SDK or use eBPF, tag profiles by view and task, read flame graphs to find hot code paths, compare releases, and keep overhead low in production.