Spaces:
Paused
Paused
File size: 6,372 Bytes
9f4dea0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | # 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.
|