Troubleshooting Guide
Common issues and solutions for Noumaris development and deployment.
Quick Diagnosis
| Symptom | Likely Cause | Section |
|---|---|---|
| "Connection refused" to database | Port mismatch or Docker not running | Database Issues |
| "Keycloak not running" | Wrong port or container not started | Keycloak Issues |
| WebSocket connection drops | Auth failure or rate limit | WebSocket Issues |
| Frontend stuck on "initializing" | AuthContext error or CORS | Frontend Issues |
| "Port already in use" | Conflicting service | Port Conflicts |
| npm/poetry install fails | Dependency conflict | Build Issues |
Database Issues
Connection Refused
Symptoms:
sqlalchemy.exc.OperationalError: could not connect to server: Connection refusedCauses & Fixes:
Docker not running
bash# Check if containers are running docker ps # Start Docker services docker-compose up -dWrong port - Local PostgreSQL uses 5433 (not 5432)
bash# Check DATABASE_URL in backend/.env DATABASE_URL=postgresql://medical_user:password123@localhost:5433/medical_db # ^^^^ Important!Container not ready - Wait 30 seconds after
docker-compose upbash# Check container health docker-compose ps # View logs docker-compose logs postgres
Migration Failures
Symptoms:
alembic.util.exc.CommandError: Can't locate revision identified by 'abc123'Fixes:
Out-of-sync migrations - Database has different version than code
bash# Check current version alembic current # View history alembic history # Downgrade to head, then upgrade alembic downgrade base alembic upgrade headCorrupted migration - Auto-generated migration is wrong
bash# Delete the bad migration file rm backend/alembic/versions/bad_migration_file.py # Recreate alembic revision --autogenerate -m "description"Database is ahead of code - Pulled older code after migrations
bash# Downgrade to match code alembic downgrade abc123 # Revision in your code
Can't Drop Table
Symptoms:
ERROR: cannot drop table users because other objects depend on itFix:
-- Connect to database
docker exec -it noumaris-postgres psql -U medical_user -d medical_db
-- Drop with cascade (careful!)
DROP TABLE users CASCADE;
-- Or fix migration to drop foreign keys firstSlow Queries
Diagnosis:
-- Enable query logging (psql)
ALTER DATABASE medical_db SET log_statement = 'all';
-- View slow queries
SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;Fixes:
- Add indexes to frequently queried columns
- Use
select_related()in SQLAlchemy to avoid N+1 queries - Optimize joins and filters
Keycloak Issues
Keycloak Not Running
Symptoms:
requests.exceptions.ConnectionError: Failed to establish a new connection: [Errno 61] Connection refusedFixes:
Check port - Keycloak runs on 8081 (not 8080)
bash# Verify in backend/.env and frontend/.env.localhost KEYCLOAK_URL=http://localhost:8081 VITE_KEYCLOAK_URL=http://localhost:8081Container not started
bashdocker-compose up -d keycloak # Wait 30-60 seconds for startup docker-compose logs -f keycloak # Look for "Started" messageContainer crashed
bashdocker-compose ps # If status is "Exit 1", check logs docker-compose logs keycloak
JWT Validation Fails
Symptoms:
fastapi.HTTPException: Could not validate credentialsCauses & Fixes:
Expired token - Frontend token expired (default 30 min)
- Fix: Refresh the page or logout/login
Wrong realm - Token issued for different realm
bash# Check backend/.env KEYCLOAK_REALM=noumaris # Check frontend .env.localhost VITE_KEYCLOAK_REALM=noumarisKeycloak configuration mismatch
bash# Re-apply Terraform config cd terraform/keycloak terraform apply
Custom Theme Not Loading
Symptoms:
- Keycloak login page shows default theme, not custom Noumaris theme
Fixes:
Theme not built
bashcd frontend npm run build-keycloak-themeTheme not deployed to Keycloak
bash# Copy JAR to Keycloak container docker cp frontend/dist_keycloak/keycloak-theme-for-kc-22-to-25.jar noumaris-keycloak:/opt/bitnami/keycloak/providers/ # Restart Keycloak docker-compose restart keycloakTheme not selected in realm settings
- Admin Console → noumaris realm → Realm Settings → Themes
- Set "Login Theme" to "noumaris"
- Or re-apply Terraform with
login_theme=noumaris
Can't Create Users
Symptoms:
KeyError: 'User already exists'Fix:
- Use Keycloak Admin Console to check if user exists
- Delete user and try again
- Or use
seed_db.pyto create demo users
WebSocket Issues
Connection Fails
Symptoms:
WebSocket connection to 'ws://localhost:8000/transcribe' failedCauses & Fixes:
Missing or expired token
javascript// Token must be passed as query parameter const ws = new WebSocket(`ws://localhost:8000/transcribe?token=${token}`);Token format wrong
javascript// ✅ CORRECT ws://localhost:8000/transcribe?token=eyJhbGciOiJSUzI1NiIsInR5cCI6... // ❌ WRONG - includes "Bearer " ws://localhost:8000/transcribe?token=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6...Backend not running
bash# Check if backend is up curl http://localhost:8000/health
Connection Drops During Transcription
Symptoms:
- WebSocket connects, then closes after a few seconds
Causes & Fixes:
Rate limit exceeded - Max 3 concurrent connections per user
bash# Check backend logs ERROR: Rate limit exceeded for user_id: 123- Fix: Close other transcription sessions
Deepgram timeout
bash# Backend logs show ERROR: Deepgram connection failed: timeout- Fix: Check Deepgram API key in backend/.env
- Verify internet connection
- Check Deepgram status page
Invalid audio format
- Deepgram expects specific audio encoding
- Check browser microphone permissions
- Verify audio stream is being sent
No Transcript Received
Symptoms:
- WebSocket connected, but no interim/final messages
Diagnosis:
# Check backend logs for connection ID
grep "WebSocket /transcribe connected" backend.log
# Note the connection ID (UUID)
# Filter logs by connection ID
grep "abc-123-def" backend.logFixes:
- Audio not streaming - Check browser DevTools console
- Deepgram API key invalid - Verify key in backend/.env
- Microphone permissions - Grant in browser
- Silent audio - Speak into microphone
Frontend Issues
Auth Stuck on "initializing"
Symptoms:
- Frontend loads but stays on loading screen forever
- AuthContext
authStatusnever changes from'initializing'
Fixes:
Clear localStorage
javascript// Browser DevTools → Console localStorage.clear(); location.reload();CORS issue - Backend rejects frontend requests
- Check browser DevTools → Network tab for CORS errors
- Verify backend CORS settings allow
http://localhost:5173
Keycloak not accessible
bash# Test Keycloak URL curl http://localhost:8081/realms/noumaris/.well-known/openid-configuration- Should return JSON configuration
- If fails, check Keycloak Issues
API Calls Return 401 Unauthorized
Symptoms:
GET http://localhost:8000/templates 401 (Unauthorized)Fixes:
Token not in headers
- Check Network tab → Headers
- Should have:
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6...
Token expired
- JWT tokens expire after 30 minutes
- Refresh page to get new token
- Or implement automatic token refresh
User role missing
- User might not have required role in Keycloak
- Admin Console → Users → [user] → Role Mappings
API Calls Return 403 Forbidden
Symptoms:
POST http://localhost:8000/admin/institutions 403 (Forbidden)Cause: User lacks required role for endpoint
Fix:
- Superadmin endpoints require
superadminrole - Institution admin endpoints require
institution_adminrole - Check Keycloak user role assignments
CORS Errors
Symptoms:
Access to fetch at 'http://localhost:8000/health' from origin 'http://localhost:5173' has been blocked by CORS policyFix:
- Backend CORS settings in
main.pyshould includehttp://localhost:5173 - Restart backend after changing CORS config
Components Not Re-rendering
Symptoms:
- Update made, but UI doesn't reflect change
Fixes:
React Query cache stale
javascript// Invalidate query after mutation queryClient.invalidateQueries(['templates']);Missing dependencies in useEffect
javascript// Add all dependencies useEffect(() => { // ... }, [dependency1, dependency2]); // Don't omit dependencies
Build & Dependency Issues
npm install Fails
Symptoms:
npm ERR! ERESOLVE unable to resolve dependency treeFixes:
Version conflicts
bash# Delete lock file and node_modules rm package-lock.json rm -rf node_modules # Reinstall npm installNode version mismatch
bash# Check version node --version # Should be v18 or higher # Install correct version brew install node@18Cache corrupted
bashnpm cache clean --force npm install
poetry install Fails
Symptoms:
SolverProblemError: Because package-a depends on package-b...Fixes:
Lock file out of sync
bashcd backend rm poetry.lock poetry installPython version mismatch
bash# Check version python3 --version # Should be 3.11+ # Tell Poetry to use specific Python poetry env use python3.11 poetry installDependency conflict
- Check
pyproject.tomlfor version constraints - May need to update or pin specific versions
- Check
Docker Build Fails
Symptoms:
ERROR [builder] failed to solve: process "/bin/sh -c pip install..." did not complete successfullyFixes:
Context size too large
bash# Add to .dockerignore node_modules __pycache__ .venv *.pycBase image unavailable
bash# Pull image manually docker pull python:3.11-slimBuild cache corrupted
bash# Build without cache docker build --no-cache -t image-name .
Port Conflicts
Port Already in Use
Symptoms:
Error: listen EADDRINUSE: address already in use :::5173
Error: listen EADDRINUSE: address already in use :::8000Diagnosis:
# Find process using port (macOS/Linux)
lsof -i :5173
lsof -i :8000
# Kill process
kill -9 PIDCommon Port Users:
- 5173: Frontend (Vite) - Sometimes old Vite process hangs
- 8000: Backend (Uvicorn) - Old Python process
- 5433: PostgreSQL - Another PostgreSQL instance
- 8081: Keycloak - Old Keycloak container
Permanent Fix:
# Change frontend port
npm run localhost -- --port 5174
# Change backend port
PORT=8001 python -m uvicorn src.noumaris_backend.api.main:app --reloadPerformance Issues
Slow API Responses
Diagnosis:
- Check FastAPI logs for slow endpoints
- Use
/docsto test endpoint directly - Check database query time
Fixes:
- Add database indexes
- Use
select_related()/joinedload()for relationships - Implement caching with React Query
- Optimize N+1 queries
Slow Frontend Load
Fixes:
Code splitting
javascriptconst Page = lazy(() => import('./Page'));Optimize images - Use WebP, lazy loading
Reduce bundle size
bash# Analyze bundle npm run build npx vite-bundle-visualizer
High Memory Usage
Backend:
# Check Python process memory
ps aux | grep python
# Optimize database connection pool
# In main.py, reduce pool sizeFrontend:
# Check for memory leaks
# Browser DevTools → Memory → Take heap snapshotCommon Error Messages
"alembic.util.exc.CommandError: Target database is not up to date"
Meaning: Database schema doesn't match current code
Fix:
alembic upgrade head"pydantic.error_wrappers.ValidationError"
Meaning: API request data doesn't match Pydantic model
Fix:
- Check API request payload matches expected schema
- View
/docsfor correct schema
"KeyError: 'access_token'"
Meaning: Keycloak response missing access token
Fix:
- Check Keycloak configuration
- Verify client is configured correctly
- Check if token refresh is needed
"RuntimeError: Event loop is closed"
Meaning: Async operation attempted after loop closed
Fix:
- Ensure using
async deffor async endpoints - Don't mix sync/async incorrectly
Getting Help
If issue persists:
Check logs
- Backend: Console output
- Frontend: Browser DevTools console
- Docker:
docker-compose logs -f
Search documentation
Enable debug mode
python# Backend main.py app = FastAPI(debug=True)Minimal reproduction
- Isolate the issue
- Test with curl or Postman
- Check if issue exists on fresh setup
Next Steps
- Development Guide - Development workflows
- Deployment Guide - Deployment procedures
- Commands Reference - Quick command lookup