From 244c3348c1674c145f476cf988bf3b26d3f7231e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Jan 2026 16:32:36 +0000 Subject: [PATCH] docs: Add Phase 6 documentation for Cloudflare deployment - Create comprehensive CLOUDFLARE_DEPLOYMENT.md with step-by-step guide - Create TROUBLESHOOTING.md covering common issues and solutions - Update README.md with quick deploy section and documentation links - Mark Phase 6 tasks as completed in migration plan --- CLOUDFLARE_MIGRATION_PLAN.md | 8 +- README.md | 24 +- docs/CLOUDFLARE_DEPLOYMENT.md | 507 +++++++++++++++++++++++++++ docs/TROUBLESHOOTING.md | 638 ++++++++++++++++++++++++++++++++++ 4 files changed, 1172 insertions(+), 5 deletions(-) create mode 100644 docs/CLOUDFLARE_DEPLOYMENT.md create mode 100644 docs/TROUBLESHOOTING.md diff --git a/CLOUDFLARE_MIGRATION_PLAN.md b/CLOUDFLARE_MIGRATION_PLAN.md index db4661d..b4b8b92 100644 --- a/CLOUDFLARE_MIGRATION_PLAN.md +++ b/CLOUDFLARE_MIGRATION_PLAN.md @@ -645,10 +645,10 @@ Step-by-step deployment guide including: - [ ] 5.5 Test deployment pipeline (user action required) ### Phase 6: Documentation -- [ ] 6.1 Update `README.md` with Cloudflare info -- [ ] 6.2 Create `CLOUDFLARE_DEPLOYMENT.md` -- [ ] 6.3 Update `.env.example` -- [ ] 6.4 Create troubleshooting guide +- [x] 6.1 Update `README.md` with Cloudflare info +- [x] 6.2 Create `CLOUDFLARE_DEPLOYMENT.md` +- [x] 6.3 Update `.env.example` +- [x] 6.4 Create troubleshooting guide --- diff --git a/README.md b/README.md index aff984b..d8d7b58 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,29 @@ This application is designed to be deployed on **Cloudflare** infrastructure: | **MCP Server** | Cloudflare Containers | Clinical decision support tools | | **Database** | Neon/Supabase + Hyperdrive | PostgreSQL with connection pooling | -See [CLOUDFLARE_MIGRATION_PLAN.md](./CLOUDFLARE_MIGRATION_PLAN.md) for deployment instructions. +### Quick Deploy + +```bash +# Install Wrangler CLI +npm install -g wrangler + +# Login to Cloudflare +wrangler login + +# Deploy frontend +cd frontend && npm run build +wrangler pages deploy dist --project-name=renalguard-frontend + +# Set up secrets +./scripts/setup-cloudflare-secrets.sh +``` + +### Documentation + +- **[CLOUDFLARE_DEPLOYMENT.md](./docs/CLOUDFLARE_DEPLOYMENT.md)** - Complete step-by-step deployment guide +- **[CLOUDFLARE_MIGRATION_PLAN.md](./CLOUDFLARE_MIGRATION_PLAN.md)** - Migration architecture and planning +- **[DATABASE_SETUP.md](./docs/DATABASE_SETUP.md)** - Neon/Supabase database configuration +- **[CICD_SETUP.md](./docs/CICD_SETUP.md)** - GitHub Actions CI/CD pipeline setup --- diff --git a/docs/CLOUDFLARE_DEPLOYMENT.md b/docs/CLOUDFLARE_DEPLOYMENT.md new file mode 100644 index 0000000..1cd415b --- /dev/null +++ b/docs/CLOUDFLARE_DEPLOYMENT.md @@ -0,0 +1,507 @@ +# RENALGUARD AI - Cloudflare Deployment Guide + +This guide provides step-by-step instructions for deploying RENALGUARD AI to Cloudflare infrastructure. + +## Table of Contents + +1. [Prerequisites](#prerequisites) +2. [Account Setup](#account-setup) +3. [Database Setup (Neon)](#database-setup-neon) +4. [Cloudflare Hyperdrive Setup](#cloudflare-hyperdrive-setup) +5. [Frontend Deployment (Pages)](#frontend-deployment-pages) +6. [Backend Deployment (Containers)](#backend-deployment-containers) +7. [MCP Server Deployment](#mcp-server-deployment) +8. [Environment Variables](#environment-variables) +9. [Domain Configuration](#domain-configuration) +10. [Verification](#verification) +11. [Troubleshooting](#troubleshooting) + +--- + +## Prerequisites + +Before starting, ensure you have: + +- **Node.js 20+** installed locally +- **Docker** installed for local container builds +- **Git** for version control +- **Wrangler CLI** installed: `npm install -g wrangler` +- A **Cloudflare account** (free tier available) +- A **Neon account** for PostgreSQL (free tier available) +- An **Anthropic API key** for Claude AI features + +--- + +## Account Setup + +### 1. Create Cloudflare Account + +1. Go to [cloudflare.com](https://cloudflare.com) and sign up +2. Verify your email address +3. Navigate to **Workers & Pages** in the dashboard +4. Note your **Account ID** from the right sidebar + +### 2. Create Cloudflare API Token + +1. Go to **My Profile** > **API Tokens** +2. Click **Create Token** +3. Use the **Edit Cloudflare Workers** template +4. Add permissions: + - **Account** > **Cloudflare Pages** > **Edit** + - **Account** > **Workers Scripts** > **Edit** + - **Zone** > **Zone** > **Read** (if using custom domain) +5. Save the token securely + +### 3. Create Neon Account + +1. Go to [neon.tech](https://neon.tech) and sign up +2. Create a new project named `renalguard-production` +3. Select a region close to your expected user base +4. Note the connection string from the dashboard + +--- + +## Database Setup (Neon) + +### 1. Create Database + +Neon automatically creates a default database. You can use it or create a new one: + +```sql +-- Optional: Create dedicated database +CREATE DATABASE renalguard; +``` + +### 2. Get Connection String + +From the Neon dashboard, copy your connection string: + +``` +postgresql://USER:PASSWORD@ep-xxx-yyy.us-east-1.aws.neon.tech/neondb?sslmode=require +``` + +### 3. Run Database Migrations + +```bash +# Clone the repository +git clone +cd renalguard + +# Set database URL +export DATABASE_URL="postgresql://USER:PASSWORD@ep-xxx.neon.tech/neondb?sslmode=require" + +# Install dependencies +cd backend +npm install + +# Run migrations +npm run migrate +# Or manually: node runMigration.js +``` + +### 4. Seed Initial Data (Optional) + +```bash +# Populate with demo patients +curl -X POST http://localhost:3000/api/init/populate +``` + +--- + +## Cloudflare Hyperdrive Setup + +Hyperdrive accelerates database connections from Cloudflare edge locations. + +### 1. Install Wrangler + +```bash +npm install -g wrangler + +# Authenticate with Cloudflare +wrangler login +``` + +### 2. Create Hyperdrive Configuration + +```bash +wrangler hyperdrive create renalguard-db \ + --connection-string="postgresql://USER:PASSWORD@ep-xxx.neon.tech/neondb?sslmode=require" +``` + +### 3. Note the Hyperdrive ID + +The command will output a Hyperdrive ID like `abc123-def456-...`. Save this for later use. + +--- + +## Frontend Deployment (Pages) + +### 1. Create Cloudflare Pages Project + +```bash +cd frontend + +# Create the project (first time only) +wrangler pages project create renalguard-frontend + +# Or via dashboard: +# Workers & Pages > Create application > Pages > Connect to Git +``` + +### 2. Configure Build Settings + +In the Cloudflare dashboard or `wrangler.toml`: + +| Setting | Value | +|---------|-------| +| Build command | `npm run build` | +| Build output directory | `dist` | +| Root directory | `frontend` | +| Node.js version | `20` | + +### 3. Set Environment Variables + +In the Cloudflare Pages dashboard > Settings > Environment variables: + +``` +VITE_API_URL = https://renalguard-backend..cloudflare.dev +``` + +### 4. Deploy + +```bash +cd frontend + +# Build locally +npm run build + +# Deploy to Cloudflare Pages +wrangler pages deploy dist --project-name=renalguard-frontend +``` + +### 5. Verify Deployment + +Your frontend will be available at: +- Production: `https://renalguard-frontend.pages.dev` +- Preview: `https://.renalguard-frontend.pages.dev` + +--- + +## Backend Deployment (Containers) + +### 1. Build Docker Image + +```bash +# From project root +docker build -t renalguard-backend:latest -f Dockerfile . +``` + +### 2. Push to Cloudflare Container Registry + +```bash +# Login to Cloudflare registry +docker login registry.cloudflare.com \ + --username \ + --password + +# Tag the image +docker tag renalguard-backend:latest \ + registry.cloudflare.com//renalguard-backend:latest + +# Push the image +docker push registry.cloudflare.com//renalguard-backend:latest +``` + +### 3. Deploy Container + +Currently, Cloudflare Containers deployment is done via the dashboard or API: + +1. Go to **Workers & Pages** > **Containers** +2. Click **Create Container** +3. Select your pushed image +4. Configure: + - Memory: 512 Mi + - CPU: 0.5 + - Port: 3000 +5. Add environment variables (see below) +6. Deploy + +### 4. Configure Container Environment + +Set these environment variables in the container settings: + +``` +NODE_ENV = production +PORT = 3000 +DATABASE_URL = +ANTHROPIC_API_KEY = +MCP_SERVER_URL = https://renalguard-mcp-server..cloudflare.dev +CORS_ORIGIN = https://renalguard-frontend.pages.dev +``` + +--- + +## MCP Server Deployment + +### 1. Build MCP Server Image + +```bash +cd mcp-server +docker build -t renalguard-mcp-server:latest . +``` + +### 2. Push to Registry + +```bash +docker tag renalguard-mcp-server:latest \ + registry.cloudflare.com//renalguard-mcp-server:latest + +docker push registry.cloudflare.com//renalguard-mcp-server:latest +``` + +### 3. Deploy Container + +1. Go to **Workers & Pages** > **Containers** +2. Create new container with the MCP server image +3. Configure: + - Memory: 256 Mi + - CPU: 0.25 + - Port: 3001 + - **Internal only** (not publicly accessible) +4. Add environment variables: + +``` +NODE_ENV = production +MCP_SERVER_PORT = 3001 +DATABASE_URL = +``` + +--- + +## Environment Variables + +### Required Secrets + +Set these in the Cloudflare dashboard or via Wrangler: + +```bash +# Database +wrangler pages secret put DATABASE_URL --project-name=renalguard-frontend +# Enter: postgresql://... or hyperdrive://... + +# AI Service +wrangler pages secret put ANTHROPIC_API_KEY --project-name=renalguard-frontend +# Enter: sk-ant-api03-... + +# Neon API (for MCP server) +wrangler pages secret put NEON_API_KEY --project-name=renalguard-frontend +# Enter: napi_... +``` + +### Using the Setup Script + +Alternatively, use the provided setup script: + +```bash +# First, create backend/.dev.vars with your credentials +cp backend/.dev.vars.example backend/.dev.vars +# Edit backend/.dev.vars with your values + +# Source the variables +source backend/.dev.vars + +# Run the setup script +./scripts/setup-cloudflare-secrets.sh +``` + +### Complete Environment Variable Reference + +| Variable | Service | Required | Description | +|----------|---------|----------|-------------| +| `DATABASE_URL` | Backend, MCP | Yes | PostgreSQL connection string | +| `ANTHROPIC_API_KEY` | Backend | Yes | Claude AI API key | +| `NEON_API_KEY` | MCP Server | No | Neon management API key | +| `MCP_SERVER_URL` | Backend | Yes | URL to MCP server | +| `CORS_ORIGIN` | Backend | Yes | Allowed frontend origins | +| `VITE_API_URL` | Frontend | Yes | Backend API URL | +| `STRIPE_SECRET_KEY` | Backend | No | Stripe payments | +| `RESEND_API_KEY` | Backend | No | Email notifications | +| `UPSTASH_REDIS_REST_URL` | Backend | No | Redis caching | + +--- + +## Domain Configuration + +### Custom Domain for Pages + +1. Go to **Pages** > **renalguard-frontend** > **Custom domains** +2. Click **Set up a custom domain** +3. Enter your domain (e.g., `app.renalguard.com`) +4. Add the provided DNS records to your domain registrar: + - CNAME: `app` -> `renalguard-frontend.pages.dev` + +### Custom Domain for Containers + +1. Go to **Workers & Pages** > **Containers** > **Your container** +2. Navigate to **Custom domains** +3. Add your domain (e.g., `api.renalguard.com`) + +--- + +## Verification + +### 1. Test Frontend + +```bash +# Visit your Pages URL +curl -I https://renalguard-frontend.pages.dev +# Should return 200 OK +``` + +### 2. Test Backend API + +```bash +# Health check +curl https://renalguard-backend..cloudflare.dev/health +# Should return: {"status":"ok","timestamp":"..."} + +# API endpoint +curl https://renalguard-backend..cloudflare.dev/api/patients +``` + +### 3. Test Database Connection + +```bash +# Via backend health endpoint with database check +curl https://renalguard-backend..cloudflare.dev/health?db=true +``` + +### 4. Test MCP Server + +The MCP server should be accessible only from the backend container: + +```bash +# From backend container logs, verify MCP connection +# Look for: "Connected to MCP server successfully" +``` + +--- + +## Troubleshooting + +### Common Issues + +#### 1. Database Connection Fails + +**Symptoms**: Backend logs show "ECONNREFUSED" or "timeout" + +**Solutions**: +- Verify DATABASE_URL is correct +- Check Neon project is active (not suspended) +- Ensure Hyperdrive is configured correctly +- Try direct connection first, then Hyperdrive + +```bash +# Test direct connection +psql "postgresql://USER:PASS@ep-xxx.neon.tech/neondb?sslmode=require" +``` + +#### 2. CORS Errors + +**Symptoms**: Browser console shows "Access-Control-Allow-Origin" errors + +**Solutions**: +- Update CORS_ORIGIN to match your frontend URL exactly +- Include both http and https if needed +- For multiple origins, use comma-separated values + +``` +CORS_ORIGIN=https://renalguard-frontend.pages.dev,https://app.renalguard.com +``` + +#### 3. Container Won't Start + +**Symptoms**: Container status shows "Failed" or "CrashLoopBackOff" + +**Solutions**: +- Check container logs in Cloudflare dashboard +- Verify all required environment variables are set +- Ensure Docker image builds successfully locally +- Check memory/CPU limits are sufficient + +```bash +# Test locally first +docker run -e NODE_ENV=production -e PORT=3000 renalguard-backend:latest +``` + +#### 4. Frontend Can't Reach Backend + +**Symptoms**: API calls fail with network errors + +**Solutions**: +- Verify VITE_API_URL is set correctly during build +- Check backend container is running and healthy +- Verify CORS is configured correctly +- Check backend URL includes protocol (https://) + +#### 5. Anthropic API Errors + +**Symptoms**: AI features return 401 or "invalid API key" + +**Solutions**: +- Verify ANTHROPIC_API_KEY is set correctly +- Check API key hasn't expired +- Ensure key has correct permissions +- Check Anthropic API status + +#### 6. Slow Database Queries + +**Symptoms**: Requests timeout or take >5 seconds + +**Solutions**: +- Enable Hyperdrive for connection pooling +- Check Neon compute is scaled appropriately +- Add database indexes for slow queries +- Consider upgrading Neon plan + +### Useful Commands + +```bash +# View Wrangler logs +wrangler pages deployment tail --project-name=renalguard-frontend + +# List Pages deployments +wrangler pages deployment list --project-name=renalguard-frontend + +# Rollback to previous deployment +wrangler pages deployment rollback --project-name=renalguard-frontend + +# Check Hyperdrive status +wrangler hyperdrive get renalguard-db + +# Test secret is set +wrangler pages secret list --project-name=renalguard-frontend +``` + +### Getting Help + +- **Cloudflare Status**: [cloudflarestatus.com](https://www.cloudflarestatus.com) +- **Neon Status**: [neonstatus.com](https://neonstatus.com) +- **Cloudflare Community**: [community.cloudflare.com](https://community.cloudflare.com) +- **Wrangler Docs**: [developers.cloudflare.com/workers/wrangler](https://developers.cloudflare.com/workers/wrangler) + +--- + +## Next Steps + +After successful deployment: + +1. **Configure monitoring**: Set up Cloudflare Analytics +2. **Enable caching**: Configure Cloudflare CDN caching rules +3. **Set up alerts**: Configure health check alerts +4. **Enable backups**: Ensure Neon automatic backups are enabled +5. **Review security**: Enable Cloudflare WAF if needed + +--- + +*Last Updated: January 2026* diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000..a4a1815 --- /dev/null +++ b/docs/TROUBLESHOOTING.md @@ -0,0 +1,638 @@ +# RENALGUARD AI - Troubleshooting Guide + +This guide covers common issues and solutions for both local development and Cloudflare deployment. + +## Table of Contents + +1. [Local Development Issues](#local-development-issues) +2. [Docker Issues](#docker-issues) +3. [Database Issues](#database-issues) +4. [Cloudflare Deployment Issues](#cloudflare-deployment-issues) +5. [AI/Anthropic Issues](#aianthropic-issues) +6. [MCP Server Issues](#mcp-server-issues) +7. [Frontend Issues](#frontend-issues) +8. [Email/Notification Issues](#emailnotification-issues) + +--- + +## Local Development Issues + +### Application Won't Start + +**Symptom**: `npm run dev` fails or backend crashes immediately + +**Check 1: Node.js version** +```bash +node --version +# Should be v20.x or higher +``` + +**Check 2: Dependencies installed** +```bash +cd backend && npm install +cd ../frontend && npm install +cd ../mcp-server && npm install +``` + +**Check 3: Environment variables** +```bash +# Ensure .env file exists +cat .env + +# Required variables: +# - DATABASE_URL +# - ANTHROPIC_API_KEY (for AI features) +``` + +### Port Already in Use + +**Symptom**: `EADDRINUSE: address already in use :::3000` + +**Solution**: +```bash +# Find and kill the process using the port +lsof -i :3000 +kill -9 + +# Or use a different port +PORT=3001 npm run dev +``` + +### TypeScript Compilation Errors + +**Symptom**: Build fails with type errors + +**Solution**: +```bash +# Clean and rebuild +rm -rf dist node_modules/.cache +npm run build + +# Check TypeScript version +npx tsc --version +# Should match package.json version +``` + +--- + +## Docker Issues + +### Docker Compose Won't Start + +**Symptom**: `docker-compose up` fails + +**Check 1: Docker is running** +```bash +docker info +# Should show system information +``` + +**Check 2: Ports available** +```bash +# Check if ports 3000, 3001, 5432, 8080 are free +lsof -i :3000 -i :3001 -i :5432 -i :8080 +``` + +**Check 3: Clean restart** +```bash +docker-compose down -v +docker-compose up --build +``` + +### Container Health Check Fails + +**Symptom**: Container shows "unhealthy" status + +**Diagnosis**: +```bash +# Check container logs +docker-compose logs backend +docker-compose logs mcp-server + +# Check health status +docker inspect --format='{{json .State.Health}}' healthcare-backend +``` + +**Common Causes**: +- Database not ready yet (wait for postgres to be healthy first) +- Missing environment variables +- Port binding issues inside container + +### Out of Disk Space + +**Symptom**: `no space left on device` + +**Solution**: +```bash +# Clean Docker resources +docker system prune -a --volumes + +# Remove specific images +docker image prune -a +``` + +### Build Fails with Network Issues + +**Symptom**: `npm install` fails inside Docker with network errors + +**Solution**: +```bash +# Use --network=host during build +docker build --network=host -t renalguard-backend . + +# Or configure Docker DNS +# Add to /etc/docker/daemon.json: +# {"dns": ["8.8.8.8", "8.8.4.4"]} +``` + +--- + +## Database Issues + +### Cannot Connect to Database + +**Symptom**: `ECONNREFUSED 127.0.0.1:5432` or connection timeout + +**Check 1: Database is running** +```bash +# For Docker +docker-compose ps postgres +# Should show "Up" status + +# For Neon +# Check neon.tech dashboard for project status +``` + +**Check 2: Connection string format** +```bash +# Local Docker: +DATABASE_URL=postgresql://healthcare_user:healthcare_pass@localhost:5432/healthcare_ai_db + +# Neon (requires SSL): +DATABASE_URL=postgresql://user:pass@ep-xxx.neon.tech/dbname?sslmode=require +``` + +**Check 3: Network connectivity** +```bash +# Test connection +psql "$DATABASE_URL" + +# Or via Node.js +node -e "require('pg').Pool({connectionString: process.env.DATABASE_URL}).query('SELECT 1')" +``` + +### Migrations Fail + +**Symptom**: `relation does not exist` or migration errors + +**Solution**: +```bash +# Run migrations in order +cd backend +node runMigration.js + +# Check migration status +psql "$DATABASE_URL" -c "SELECT * FROM schema_migrations ORDER BY version;" + +# Reset and rerun (DESTRUCTIVE) +psql "$DATABASE_URL" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" +node runMigration.js +``` + +### Slow Queries + +**Symptom**: API requests timeout or take >5 seconds + +**Diagnosis**: +```bash +# Check slow queries in Neon dashboard +# Or enable query logging locally + +# Add to PostgreSQL: +# log_min_duration_statement = 1000 +``` + +**Solutions**: +- Add missing indexes (check EXPLAIN ANALYZE output) +- Use Hyperdrive for Cloudflare deployment +- Upgrade Neon compute size + +### Neon Database Suspended + +**Symptom**: Connection works initially then fails + +**Cause**: Neon suspends inactive databases on free tier + +**Solution**: +- Enable "Scale to zero" with longer timeout +- Upgrade to paid plan for always-on compute +- Implement connection retry logic + +--- + +## Cloudflare Deployment Issues + +### Pages Deployment Fails + +**Symptom**: Wrangler deploy fails or build errors + +**Check 1: Build locally first** +```bash +cd frontend +npm run build +# Should complete without errors +``` + +**Check 2: Correct output directory** +```bash +# Verify dist folder exists and contains index.html +ls frontend/dist/index.html +``` + +**Check 3: Wrangler authentication** +```bash +wrangler whoami +# Should show your account + +# Re-authenticate if needed +wrangler login +``` + +### Container Won't Start + +**Symptom**: Container shows "Failed" in Cloudflare dashboard + +**Diagnosis**: +- Check container logs in Cloudflare dashboard +- Review environment variables are set correctly +- Verify image was pushed successfully + +**Common Issues**: +```bash +# Missing env vars - container won't start without required config +# Check these are set: +# - DATABASE_URL +# - NODE_ENV +# - PORT + +# Image not found - verify push succeeded +docker images | grep renalguard +``` + +### CORS Errors + +**Symptom**: Browser console shows `Access-Control-Allow-Origin` errors + +**Solution**: + +1. Check CORS_ORIGIN environment variable: +```bash +# Must match exactly (including protocol) +CORS_ORIGIN=https://renalguard-frontend.pages.dev +``` + +2. For multiple origins: +```bash +CORS_ORIGIN=https://renalguard-frontend.pages.dev,https://app.renalguard.com +``` + +3. Verify backend CORS middleware: +```javascript +// backend/src/index.ts should have: +app.use(cors({ + origin: process.env.CORS_ORIGIN?.split(','), + credentials: true +})); +``` + +### Hyperdrive Connection Issues + +**Symptom**: Database works locally but fails in Cloudflare + +**Check 1: Hyperdrive is configured** +```bash +wrangler hyperdrive list +# Should show renalguard-db +``` + +**Check 2: Connection string format** +```bash +# Direct connection (for testing): +DATABASE_URL=postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require + +# Hyperdrive connection (for production): +DATABASE_URL=hyperdrive://renalguard-db +``` + +**Check 3: Hyperdrive caching** +```bash +# Disable caching for debugging +wrangler hyperdrive update renalguard-db --caching=disabled +``` + +### SSL/TLS Certificate Issues + +**Symptom**: `SSL_ERROR_HANDSHAKE_FAILURE` or certificate errors + +**For Custom Domains**: +1. Verify DNS is properly configured +2. Wait for SSL certificate provisioning (up to 24 hours) +3. Check Cloudflare SSL/TLS settings (Full or Full (Strict)) + +--- + +## AI/Anthropic Issues + +### API Key Invalid + +**Symptom**: `401 Unauthorized` or `Invalid API key` + +**Solutions**: +```bash +# Verify key format +echo $ANTHROPIC_API_KEY | head -c 20 +# Should start with: sk-ant-api03- + +# Check key is set in environment +grep ANTHROPIC_API_KEY .env + +# For Cloudflare, verify secret is set +wrangler pages secret list --project-name=renalguard-frontend +``` + +### Rate Limiting + +**Symptom**: `429 Too Many Requests` + +**Solutions**: +- Implement exponential backoff (already in code) +- Reduce concurrent AI requests +- Upgrade Anthropic API tier +- Cache AI responses where appropriate + +### Timeout Errors + +**Symptom**: AI requests timeout after 30 seconds + +**Solutions**: +```javascript +// Increase timeout in doctorAgent.ts +const AI_TIMEOUT = 60000; // 60 seconds + +// Or use streaming responses for long operations +``` + +### Claude Overloaded + +**Symptom**: `503 Service Unavailable` or `overloaded_error` + +**Solution**: The application already implements retry logic: +- First retry after 2 seconds +- Second retry after 4 seconds +- Third retry after 8 seconds + +If persists, check [Anthropic Status](https://status.anthropic.com) + +--- + +## MCP Server Issues + +### MCP Server Not Responding + +**Symptom**: Backend can't connect to MCP server + +**Check 1: MCP server is running** +```bash +# Docker +docker-compose ps mcp-server +# Should show "Up" status + +# Check logs +docker-compose logs mcp-server +``` + +**Check 2: Correct URL configured** +```bash +# For Docker: +MCP_SERVER_URL=http://mcp-server:3001 + +# For local development: +MCP_SERVER_URL=http://localhost:3001 +``` + +**Check 3: Network connectivity** +```bash +# From backend container +docker-compose exec backend wget -qO- http://mcp-server:3001/health +``` + +### MCP Tools Not Available + +**Symptom**: "Tool not found" errors + +**Diagnosis**: +```bash +# Check MCP server logs for tool registration +docker-compose logs mcp-server | grep "Registered tool" +``` + +**Solution**: Ensure MCP server builds successfully: +```bash +cd mcp-server +npm run build +ls dist/tools/ +# Should list all tool files +``` + +### Database Queries Fail in MCP + +**Symptom**: MCP tools return database errors + +**Check**: MCP server has correct database configuration: +```bash +# In docker-compose.yml, mcp-server should have: +environment: + DB_HOST: postgres + DB_PORT: 5432 + DB_NAME: healthcare_ai_db + DB_USER: healthcare_user + DB_PASSWORD: healthcare_pass +``` + +--- + +## Frontend Issues + +### Blank Page After Deployment + +**Symptom**: Frontend loads but shows blank white page + +**Check 1: Browser console for errors** +- Open Developer Tools > Console +- Look for JavaScript errors + +**Check 2: API URL configured correctly** +```bash +# During build, VITE_API_URL must be set +VITE_API_URL=https://renalguard-backend.example.com npm run build +``` + +**Check 3: SPA routing configured** +```bash +# Ensure _redirects file exists +cat frontend/public/_redirects +# Should contain: /* /index.html 200 +``` + +### API Requests Fail + +**Symptom**: Network errors or 404 on API calls + +**Check 1: VITE_API_URL is correct** +```bash +# In browser console: +console.log(import.meta.env.VITE_API_URL) +# Should show your backend URL +``` + +**Check 2: Backend is accessible** +```bash +curl -I https://your-backend-url/health +# Should return 200 OK +``` + +### Build Fails + +**Symptom**: Vite build errors + +**Common Issues**: +```bash +# TypeScript errors +npm run build 2>&1 | grep error + +# Out of memory +NODE_OPTIONS=--max-old-space-size=4096 npm run build + +# Clear cache +rm -rf node_modules/.vite +npm run build +``` + +--- + +## Email/Notification Issues + +### Emails Not Sending + +**Symptom**: Test emails fail or notifications don't arrive + +**Check 1: SMTP configuration** +```bash +# Verify Resend API key is set +echo $RESEND_API_KEY | head -c 10 +# Should start with: re_ +``` + +**Check 2: Test email sending** +```bash +curl -X POST http://localhost:3000/api/settings/email/test \ + -H "Content-Type: application/json" \ + -d '{"to": "test@example.com"}' +``` + +**Check 3: Email service logs** +- Check Resend dashboard for delivery status +- Look for bounces or spam blocks + +### Notification Queue Backlog + +**Symptom**: Notifications delayed or not processing + +**Diagnosis**: +```bash +# Check pending notifications +curl http://localhost:3000/api/notifications/stats +``` + +**Solution**: +- Restart notification service +- Check for database connection issues +- Increase notification processing frequency + +--- + +## Useful Debugging Commands + +### Docker + +```bash +# View all logs +docker-compose logs -f + +# View specific service logs +docker-compose logs -f backend + +# Shell into container +docker-compose exec backend sh + +# Check container resources +docker stats +``` + +### Database + +```bash +# Connect to database +docker-compose exec postgres psql -U healthcare_user -d healthcare_ai_db + +# Check table sizes +SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) +FROM pg_catalog.pg_statio_user_tables +ORDER BY pg_total_relation_size(relid) DESC; + +# Check active connections +SELECT * FROM pg_stat_activity WHERE datname = 'healthcare_ai_db'; +``` + +### Cloudflare + +```bash +# View deployment logs +wrangler pages deployment tail --project-name=renalguard-frontend + +# List secrets +wrangler pages secret list --project-name=renalguard-frontend + +# Rollback deployment +wrangler pages deployment rollback --project-name=renalguard-frontend +``` + +### Network + +```bash +# Test backend connectivity +curl -v https://backend-url/health + +# Test with detailed timing +curl -w "@curl-format.txt" -o /dev/null -s https://backend-url/api/patients +``` + +--- + +## Getting Help + +If issues persist: + +1. **Check Logs**: Always review logs first +2. **Search Issues**: Check GitHub issues for similar problems +3. **Documentation**: Review relevant docs +4. **Community**: Ask on Cloudflare Community or Stack Overflow +5. **File Issue**: Create a GitHub issue with: + - Error messages + - Steps to reproduce + - Environment details + - Relevant logs + +--- + +*Last Updated: January 2026*