| 1 | # Project Architecture & Guidelines (Django + PostgreSQL + Redis + Celery) |
| 2 | |
| 3 | ## 1. System Architecture |
| 4 | - **Backend Framework**: Django 5.x with WSGI/ASGI (Gunicorn or Uvicorn). |
| 5 | - **Database**: PostgreSQL with connection pooling (PgBouncer or Django 5.1 native pool). |
| 6 | - **Caching & Broker**: Redis for Django cache backend, session store, and Celery task broker. |
| 7 | - **Async Worker Queue**: Celery for asynchronous background job execution. |
| 8 | |
| 9 | ## 2. PostgreSQL Connection Management (Critical) |
| 10 | - Configure Django 5.1+ database connection pool in `settings.py`: |
| 11 | ```python |
| 12 | DATABASES = { |
| 13 | 'default': { |
| 14 | 'ENGINE': 'django.db.backends.postgresql', |
| 15 | 'NAME': env('DB_NAME'), |
| 16 | 'USER': env('DB_USER'), |
| 17 | 'PASSWORD': env('DB_PASSWORD'), |
| 18 | 'HOST': env('DB_HOST'), |
| 19 | 'PORT': env('DB_PORT', default='5432'), |
| 20 | 'OPTIONS': { |
| 21 | 'pool': { |
| 22 | 'min_size': 2, |
| 23 | 'max_size': 10, |
| 24 | 'timeout': 10, |
| 25 | }, |
| 26 | }, |
| 27 | 'CONN_MAX_AGE': 0, # Must be 0 when using native pooling or PgBouncer |
| 28 | } |
| 29 | } |
| 30 | ``` |
| 31 | - If deploying behind PgBouncer in `transaction` mode: |
| 32 | - Disable server-side cursors: `'DISABLE_SERVER_SIDE_CURSORS': True`. |
| 33 | - Set `CONN_MAX_AGE = 0` to prevent persistent connections from conflicting with the external pooler. |
| 34 | |
| 35 | ## 3. Redis & Celery Best Practices |
| 36 | - Configure thread safety and broker connection limits: |
| 37 | ```python |
| 38 | CELERY_BROKER_URL = env('REDIS_URL') |
| 39 | CELERY_RESULT_BACKEND = env('REDIS_URL') |
| 40 | CELERY_RESULT_BACKEND_THREAD_SAFE = True |
| 41 | CELERY_TASK_ACKS_LATE = True |
| 42 | CELERY_WORKER_PREFETCH_MULTIPLIER = 1 |
| 43 | ``` |
| 44 | - Use `django-redis` with `BlockingConnectionPool` to prevent unbounded Redis socket creation under heavy load: |
| 45 | ```python |
| 46 | CACHES = { |
| 47 | 'default': { |
| 48 | 'BACKEND': 'django_redis.cache.RedisCache', |
| 49 | 'LOCATION': env('REDIS_URL'), |
| 50 | 'OPTIONS': { |
| 51 | 'CLIENT_CLASS': 'django_redis.client.DefaultClient', |
| 52 | 'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool', |
| 53 | 'CONNECTION_POOL_CLASS_KWARGS': {'max_connections': 50, 'timeout': 20}, |
| 54 | }, |
| 55 | } |
| 56 | } |
| 57 | ``` |
| 58 | |
| 59 | ## 4. Background Job & Task Rules |
| 60 | - All Celery tasks MUST be idempotent. Network glitches can cause worker retries. |
| 61 | - Separate CPU-heavy queues from fast I/O queues (e.g., `high-priority`, `default`, `analytics`). |
| 62 | - Pass record IDs (primary keys) to Celery tasks instead of serialized model instances to prevent stale data race conditions. |
| 63 | |
| 64 | ## 5. Common Pitfalls to Avoid |
| 65 | - ❌ Calculating connection pool without worker count: Total connections = `(Gunicorn Workers × DB Pool) + (Celery Workers × Concurrency)`. Ensure this is within PostgreSQL `max_connections`. |
| 66 | - ❌ Unindexed Foreign Keys: Always ensure database models define `db_index=True` on filtered columns. |
| 67 | - ❌ Blocking the HTTP Request Loop: Offload any third-party API calls, email dispatches, or heavy reporting to Celery. |
| 68 | |
| 69 | ## 6. Testing Conventions |
| 70 | - Use `pytest` + `pytest-django` with `--reuse-db` for fast local iteration; drop `--reuse-db` in CI to catch migration drift. |
| 71 | - Use `factory_boy` for model factories instead of fixtures — fixtures rot as schemas evolve, factories don't. |
| 72 | - Test Celery tasks synchronously with `CELERY_TASK_ALWAYS_EAGER = True` in the test settings module, and assert idempotency by calling the task twice. |
| 73 | - Cover connection-pool-sensitive code paths (long transactions, `CONN_MAX_AGE` interactions) with integration tests against a real Postgres instance, not SQLite. |
| 74 | |
| 75 | ## 7. Git Workflow & PR Conventions |
| 76 | - Conventional Commits (`feat:`, `fix:`, `refactor:`) with the Django app name in scope, e.g. `fix(billing): correct Stripe webhook idempotency key`. |
| 77 | - Every migration file ships in the same PR as the model change that generated it — never a follow-up PR. |
| 78 | - Run `python manage.py makemigrations --check --dry-run` in CI to block unmigrated model changes from merging. |
| 79 | - Require `pytest` and `ruff check .` green before merge; squash-merge to keep `main` bisectable. |