Production Lifecycle, S3, WAF & Scaling Architecture
Operating Django reliably in containerized production environments—whether on Kubernetes, Cloud PaaS (Fly.io, AWS ECS), or Docker Compose—requires more than simply putting an application server inside a container.
True production readiness spans the entire software lifecycle: CI validation, zero-downtime database migrations, edge WAF filtering, object storage offloading, database connection multiplexing, canary rollouts, and graceful container drainage.
This guide provides the complete architectural blueprint and operational handbook for deploying Django with Hurricane across three distinct infrastructure tiers.
1. The Complete Django Production Lifecycle
Phase 1: CI/CD Pipeline Governance
Before any Docker image is built or deployed to staging or production, enforce strict automated quality gates in your CI runner (GitHub Actions / GitLab CI):
- Django Production Security Check:Validates critical settings:
python manage.py check --deployDEBUG=False,SECRET_KEYsecurity, cookieSECUREflags, andALLOWED_HOSTS. - Backward-Compatible Migration Linting:Uses
python manage.py lintmigrations --git-commit-id origin/maindjango-migration-linterto block backward-incompatible DDL statements (like non-nullable columns without defaults or unindexed foreign keys). - Container Image Build & Security Scanning: Build the Docker container using a multi-stage Dockerfile and scan for CVEs via Trivy or Grype before pushing to your container registry.
Phase 2: Pre-Rollout Orchestration (Migrations & Assets)
Database Schema Migrations: The Single-Runner Principle
In multi-pod Kubernetes or autoscaling environments, never let multiple pods apply migrations simultaneously.
- Kubernetes / GitOps: Run migrations in a dedicated single-instance Kubernetes
Jobor Helmpre-upgradehook:python manage.py migrate --noinput - Application Pods: Start Hurricane with
--check-migrations(read-only verification). Pods query PostgreSQL, verify that required schema versions are present, and hold the/startupprobe non-ready until the migration Job finishes. - Docker Compose / Single-Instance: Use
--check-migrations-applyto safely auto-migrate before opening HTTP ports.
Static Assets: Pre-Deploy S3 Upload
For production deployments using S3/CloudFront:
- Execute
collectstaticinside your CI/CD pipeline or deployment job:python manage.py collectstatic --noinput - Upload assets directly to S3 with immutable cache headers (
Cache-Control: max-age=31536000, public, immutable).
Phase 3: Rollout & Traffic Routing
When new Hurricane pods start:
- Liveness & Startup Gate: Kubelet queries
/startupon port 8001. Hurricane verifies database reachability and checks schema version. - Readiness Probe Activation: Once startup passes,
/readymonitors worker thread pool availability and queue backlog depth. - Traffic Shift: Ingress (or AWS ALB) only routes user traffic to the pod once
/readyreturnsHTTP 200.
Phase 4: Post-Rollout, Drain & Graceful Termination
When a pod is retired during a rolling update or autoscaling scale-down:
- The Ingress Race Condition: When Kubelet sends a termination signal, Kubernetes updates endpoint objects asynchronously. Ingress controllers may take 1–3 seconds to stop routing new requests to the terminating pod.
- The Solution (Kubernetes
preStopHook): Add a 5-second sleep in the containerlifecycle.preStophook:This ensures Ingress removes the pod from endpoints before Hurricane receiveslifecycle: preStop: exec: command: ["/bin/sh", "-c", "sleep 5"]SIGTERM. - Graceful Socket Draining: Upon receiving
SIGTERM, Granian stops accepting new TCP connections and gives in-flight Django requests up to--graceful-timeout(default: 30s) to complete cleanly.
2. Edge Defense-in-Depth: WAF + Ingress + Hurricane
Modern production architectures rely on defense-in-depth. No single security layer is foolproof.
Why Both WAF and In-Pod Protection Are Essential:
- WAF Bypasses & Origin Probes: Attackers scanning cloud IP ranges frequently hit your Load Balancer's public IP directly, bypassing Cloudflare rules entirely. Hurricane's Fast-404 acts as an unbreachable last line of defense.
- Private Clouds & Compliance: In air-gapped VPCs, on-premise clusters, or European sovereign environments where external third-party WAFs cannot be used, Hurricane provides native edge security out-of-the-box.
- Real Client IP Forwarding: Ensure your edge proxy passes the authentic client IP and configure Hurricane to trust it:
In Django settings:
python manage.py serve --rate-limit-proxy-header="X-Forwarded-For"settings.pySECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True
3. Asset Architecture at Scale: S3 vs. In-Pod Serving
| Strategy | Recommended Use Case | Mechanism | Pros & Trade-offs |
|---|---|---|---|
| S3 + CloudFront CDN | Enterprise / High-Traffic Production | django-storages + boto3 | Maximum scalability, zero pod bandwidth usage. Requires AWS IAM & S3 setup. |
| In-Pod Hurricane Streaming | Staging, PR Reviews, Docker Compose | python manage.py serve --static --media | Zero-configuration, Nginx-grade sendfile speed (<20µs), no S3 bucket required. |
| S3 Direct Pre-Signed Uploads | Large Media Uploads (> 5MB) | Browser uploads directly to S3 via pre-signed URL | Eliminates large file streaming through Python/Django workers entirely. |
The Enterprise Pre-Signed Upload Pattern
Streaming 50 MB video or PDF uploads through Django worker threads ties up server memory and database connections.
In production, use Direct S3 Pre-Signed POST URLs:
- The frontend requests an upload signature from Django (
/api/uploads/sign/). - Django validates user permissions and generates a temporary S3 pre-signed URL with restrictive file type and size constraints.
- The browser uploads the raw binary file directly to S3 bucket.
- On completion, the browser sends the S3 object key to Django to store in the database.
- Result: Zero memory overhead on Django pods.
4. Database Scaling & Connection Pooling (PgBouncer)
When scaling Django horizontally in Kubernetes, managing PostgreSQL connections is the single most critical stability factor.
The CONN_MAX_AGE Trap in Horizontal Pod Autoscaling (HPA)
- In standard Django,
CONN_MAX_AGE=60holds database connections open across requests. - The Problem: If Hurricane runs with
--workers=16across 20 autoscaling pods, your pods can open: $$\text{20 pods} \times \text{16 workers} = \text{320 persistent connections}$$ - PostgreSQL defaults to
max_connections = 100(or 500 on large RDS instances). When HPA scales up during a traffic spike, Django immediately exhausts the connection pool withFATAL: remaining connection slots are reserved for non-replication superuser connections.
The Solution: Transaction-Level Pooling with PgBouncer
Always place PgBouncer or AWS RDS Proxy between Hurricane and PostgreSQL:
Recommended Django Settings with PgBouncer:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "production_db",
"USER": "django_user",
"PASSWORD": os.environ["DATABASE_PASSWORD"],
"HOST": os.environ.get("PGBOUNCER_HOST", "pgbouncer.internal"),
"PORT": 6432,
# Close connection after every transaction so PgBouncer can reuse it immediately:
"CONN_MAX_AGE": 0,
}
}
5. Three Production Architecture Blueprints
Blueprint 1: Enterprise Multi-AZ Kubernetes (EKS / GKE)
For high-concurrency, mission-critical applications:
- Traffic Layer: Cloudflare WAF ➔ AWS ALB ➔ Ingress-Nginx.
- App Layer: Hurricane ASGI/WSGI across multi-AZ pods with Horizontal Pod Autoscaler (HPA).
- Data Layer: AWS RDS Aurora PostgreSQL behind RDS Proxy / PgBouncer.
- Assets: AWS S3 behind CloudFront CDN.
apiVersion: apps/v1
kind: Deployment
metadata:
name: django-hurricane-prod
namespace: production
spec:
replicas: 4
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 0
template:
metadata:
labels:
app: django-hurricane
spec:
terminationGracePeriodSeconds: 35
containers:
- name: django
image: 123456789012.dkr.ecr.eu-central-1.amazonaws.com/myapp:2.0.0
command:
- python
- manage.py
- serve
- --port=8000
- --probe-port=8001
- --check-migrations
- --fast-404=auto
- --rate-limit=20/s
- --rate-limit-burst=50
- --rate-limit-proxy-header=X-Forwarded-For
ports:
- name: http
containerPort: 8000
- name: probes
containerPort: 8001
resources:
requests:
cpu: "500m"
memory: "512Mi"
limits:
cpu: "2000m"
memory: "1536Mi"
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 5"]
startupProbe:
httpGet:
path: /startup
port: probes
failureThreshold: 30
periodSeconds: 2
livenessProbe:
httpGet:
path: /alive
port: probes
periodSeconds: 10
timeoutSeconds: 2
readinessProbe:
httpGet:
path: /ready
port: probes
periodSeconds: 2
timeoutSeconds: 2
Blueprint 2: Cloud PaaS (Fly.io / AWS ECS Fargate)
For teams seeking zero-ops container hosting without managing Kubernetes:
app = "my-django-production"
primary_region = "fra"
[http_service]
internal_port = 8000
force_https = true
auto_stop_machines = false
auto_start_machines = true
min_machines_running = 2
[[http_service.checks]]
interval = "10s"
timeout = "2s"
grace_period = "5s"
method = "GET"
path = "/alive"
[[http_service.checks]]
interval = "5s"
timeout = "2s"
method = "GET"
path = "/ready"
[deploy]
release_command = "python manage.py migrate --noinput"
In your Dockerfile:
CMD ["python", "manage.py", "serve", "--port=8000", "--probe-port=8000", "--static"]
Blueprint 3: Zero-Nginx Standalone Docker Compose
For single VPS instances (Hetzner, DigitalOcean, EC2), staging servers, or development:
version: "3.9"
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: myapp
POSTGRES_USER: django
POSTGRES_PASSWORD: secretpassword
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U django"]
interval: 5s
timeout: 3s
retries: 5
web:
build: .
command: >
python manage.py serve
--port=8000
--static
--media
--check-migrations-apply
ports:
- "8000:8000"
environment:
DATABASE_URL: postgres://django:secretpassword@db:5432/myapp
HURRICANE_FAST_404: "auto"
HURRICANE_RATE_LIMIT: "true"
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8001/alive')"]
interval: 10s
timeout: 2s
retries: 3
restart: always
volumes:
postgres_data:
6. Automated Rollback & Canary Strategy
To prevent faulty releases from impacting users, combine Hurricane's health probes with progressive delivery tools like Argo Rollouts or Ingress Canary Headers:
Automated Rollback Metrics to Watch:
Configure Prometheus alerts to trigger automated deployment rollbacks if any of these conditions occur within 5 minutes of release:
rate(hurricane_http_requests_total{status=~"5.."}[2m]) / rate(hurricane_http_requests_total[2m]) > 0.01(Error rate > 1%)histogram_quantile(0.95, rate(hurricane_http_request_duration_seconds_bucket[2m])) > 0.500(P95 latency > 500ms)hurricane_readiness_state == 0(Readiness failure or queue backlog saturation)
