Spaces:
Paused

miracle / docs /deployment.md
dushyantsingh0
backend stabilization
9f4dea0
|
Raw History Blame Contribute Delete
6.37 kB
# Deployment Guide
Nexus uses a 3-tier deployment strategy: Hugging Face Spaces as primary, Railway as failover, and Docker Compose for local parity.
---
## Docker image
The `Dockerfile` is a four-stage build:
| Stage | Base | Output |
|---|---|---|
| `frontend-build` | `node:20-slim` | Compiled React assets (`dist/`) |
| `python-base` | `python:3.11-slim` | System deps + pip packages from `requirements.txt` |
| `ai-layer` | `python-base` | AI/ML packages from `requirements-ai.txt` |
| `production` | `ai-layer` | Final image: copied frontend assets, Gunicorn entry |
**Build the production image:**
```bash
docker build --target production -t nexus:latest .
```
**Run locally:**
```bash
docker run -p 8000:7860 \
--env-file .env \
nexus:latest
```
The container exposes port **7860** (Hugging Face Spaces convention). The `run_prod.sh` script handles internal service startup.
---
## Production startup (`scripts/run_prod.sh`)
The script runs inside the container as the entry point:
1. **Start local Redis** β€” `redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru` (ephemeral, pub/sub only)
2. **Run Alembic migrations** β€” `alembic upgrade head` (guarded by a file lock so only one instance runs migrations)
3. **Start ARQ Regular Worker** β€” background process
4. **Start ARQ Heavy Worker** β€” background process
5. **Start Gunicorn** β€” 4 uvicorn workers, 120 s timeout, port 7860
6. **Monitor loop** β€” checks worker PIDs every 30 s, restarts crashed workers
---
## Tier 1 β€” Hugging Face Spaces
The primary production environment. HF Spaces reads the `README.md` frontmatter and builds the Docker image automatically on push.
**Frontmatter (do not remove from README.md):**
```yaml
---
title: Nexus
emoji: πŸš€
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 7860
pinned: false
---
```
**Required Secrets** (set in Space Settings β†’ Repository secrets):
| Secret | Value |
|---|---|
| `DATABASE_URL` | Supabase or Neon async connection string |
| `ARQ_REDIS_URL` | Upstash Redis URL |
| `CACHE_REDIS_URL` | Upstash Redis URL |
| `SECRET_KEY` | Random 32+ char string |
| `ANTHROPIC_API_KEY` | Anthropic API key |
`LOCAL_REDIS_URL` defaults to `redis://localhost:6379` β€” the container starts its own Redis, so no secret needed.
**Deployment steps:**
1. Push to `main` branch.
2. HF Spaces detects the push, runs `docker build --target production`.
3. The new container replaces the old one with zero-downtime (HF Spaces handles health checks).
**URLs:**
- Customer portal: `https://3scerror404-nexus.hf.space/`
- Internal portal: `https://3scerror404-nexus.hf.space/internal/`
- API docs: `https://3scerror404-nexus.hf.space/docs`
---
## Tier 2 β€” Railway (failover)
`railway.json` at the repo root configures auto-detection:
```json
{
"build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile", "target": "production" },
"deploy": { "startCommand": "bash scripts/run_prod.sh", "healthcheckPath": "/api/v1/system/health/" }
}
```
**Setup:**
1. Create a new Railway project and connect this GitHub repo.
2. Railway detects `railway.json` and builds automatically.
3. Set environment variables in the Railway dashboard (same set as HF Spaces secrets above).
4. Add a custom domain or use the `.railway.app` subdomain.
**Switching traffic:** Update your DNS CNAME or load-balancer origin to point at Railway when HF Spaces is unavailable.
---
## Tier 3 β€” Local Docker (development parity)
```bash
# Windows one-click
./scripts/start_local.bat
# Unix / WSL
docker compose -f compose.example.yml up --build
```
The compose file starts:
- `api` β€” the production Docker image with source mounted for hot reload
- `redis` β€” Redis 7 Alpine
- `ollama` β€” Ollama with `nomic-embed-text` pre-pulled
Ports:
| Service | Port |
|---|---|
| API | 8000 |
| Redis | 6379 |
| Ollama | 11434 |
---
## Frontend build
The frontend is compiled as static assets and served by FastAPI:
```bash
cd frontend
npm install
npm run build --workspaces # builds both customer and internal apps
```
Output directories:
- `frontend/apps/customer/dist/` β†’ served at `/`
- `frontend/apps/internal/dist/` β†’ served at `/internal/`
FastAPI mounts these with `StaticFiles`. In Docker, the `frontend-build` stage compiles the assets and the `production` stage copies them into place.
---
## Database (PostgreSQL + pgvector)
**Cloud options:**
- [Supabase](https://supabase.com) β€” free tier, pgvector enabled by default
- [Neon](https://neon.tech) β€” serverless Postgres, enable pgvector in the dashboard
- Self-hosted PostgreSQL 15+ with `CREATE EXTENSION vector;`
**Connection string format:**
```
postgresql+asyncpg://user:password@host:5432/dbname?ssl=require
```
Always run migrations before starting the app:
```bash
alembic upgrade head
```
---
## Redis
**Cloud options:**
- [Upstash](https://upstash.com) β€” HTTP-compatible Redis, use for `ARQ_REDIS_URL` and `CACHE_REDIS_URL`
- Self-hosted Redis 7+
Note: `LOCAL_REDIS_URL` (pub/sub) requires a real persistent TCP Redis, not Upstash's HTTP API. In production on HF Spaces and Railway, the container runs its own Redis for this role.
---
## Scaling considerations
- **Horizontal API scaling**: Gunicorn workers are stateless. Scale by adding more container replicas behind a load balancer. Session state is in PostgreSQL + Redis, not in-process.
- **Worker scaling**: Run additional `HeavyWorkerSettings` or `RegularWorkerSettings` instances β€” ARQ deduplicates jobs via the Redis latch in `tasks/system.py`.
- **Database connections**: The API pool is capped at 70 connections per instance (`AsyncAdaptedQueuePool`). If running multiple replicas, use PgBouncer in transaction mode to prevent connection exhaustion.
- **Vector index**: pgvector HNSW index is in-memory at query time. For large corpora (>1M vectors), increase `hnsw.ef_search` and consider dedicating a read replica for semantic search.
---
## Health check
`GET /api/v1/system/health/` returns HTTP 200 when the DB, Redis, and ARQ queue are reachable. Configure your load balancer or platform to use this endpoint with a 5 s timeout and 3-failure threshold before marking unhealthy.
---
## Render (alternate)
`render.yaml` is included for one-click Render.com deployment. It mirrors the Railway setup. Set the same environment variables in the Render dashboard.