Skip to content

Troubleshooting Guide

Common issues and solutions for Noumaris development and deployment.

Quick Diagnosis

SymptomLikely CauseSection
"Connection refused" to databasePort mismatch or Docker not runningDatabase Issues
"Keycloak not running"Wrong port or container not startedKeycloak Issues
WebSocket connection dropsAuth failure or rate limitWebSocket Issues
Frontend stuck on "initializing"AuthContext error or CORSFrontend Issues
"Port already in use"Conflicting servicePort Conflicts
npm/poetry install failsDependency conflictBuild Issues

Database Issues

Connection Refused

Symptoms:

sqlalchemy.exc.OperationalError: could not connect to server: Connection refused

Causes & Fixes:

  1. Docker not running

    bash
    # Check if containers are running
    docker ps
    
    # Start Docker services
    docker-compose up -d
  2. Wrong 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!
  3. Container not ready - Wait 30 seconds after docker-compose up

    bash
    # 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:

  1. 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 head
  2. Corrupted 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"
  3. 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 it

Fix:

sql
-- 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 first

Slow Queries

Diagnosis:

sql
-- 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 refused

Fixes:

  1. 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:8081
  2. Container not started

    bash
    docker-compose up -d keycloak
    
    # Wait 30-60 seconds for startup
    docker-compose logs -f keycloak
    # Look for "Started" message
  3. Container crashed

    bash
    docker-compose ps
    # If status is "Exit 1", check logs
    docker-compose logs keycloak

JWT Validation Fails

Symptoms:

fastapi.HTTPException: Could not validate credentials

Causes & Fixes:

  1. Expired token - Frontend token expired (default 30 min)

    • Fix: Refresh the page or logout/login
  2. Wrong realm - Token issued for different realm

    bash
    # Check backend/.env
    KEYCLOAK_REALM=noumaris
    
    # Check frontend .env.localhost
    VITE_KEYCLOAK_REALM=noumaris
  3. Keycloak 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:

  1. Theme not built

    bash
    cd frontend
    npm run build-keycloak-theme
  2. Theme 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 keycloak
  3. Theme 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.py to create demo users

WebSocket Issues

Connection Fails

Symptoms:

WebSocket connection to 'ws://localhost:8000/transcribe' failed

Causes & Fixes:

  1. Missing or expired token

    javascript
    // Token must be passed as query parameter
    const ws = new WebSocket(`ws://localhost:8000/transcribe?token=${token}`);
  2. Token format wrong

    javascript
    // ✅ CORRECT
    ws://localhost:8000/transcribe?token=eyJhbGciOiJSUzI1NiIsInR5cCI6...
    
    // ❌ WRONG - includes "Bearer "
    ws://localhost:8000/transcribe?token=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6...
  3. 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:

  1. 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
  2. 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
  3. 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:

bash
# 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.log

Fixes:

  1. Audio not streaming - Check browser DevTools console
  2. Deepgram API key invalid - Verify key in backend/.env
  3. Microphone permissions - Grant in browser
  4. Silent audio - Speak into microphone

Frontend Issues

Auth Stuck on "initializing"

Symptoms:

  • Frontend loads but stays on loading screen forever
  • AuthContext authStatus never changes from 'initializing'

Fixes:

  1. Clear localStorage

    javascript
    // Browser DevTools → Console
    localStorage.clear();
    location.reload();
  2. CORS issue - Backend rejects frontend requests

    • Check browser DevTools → Network tab for CORS errors
    • Verify backend CORS settings allow http://localhost:5173
  3. Keycloak not accessible

    bash
    # Test Keycloak URL
    curl http://localhost:8081/realms/noumaris/.well-known/openid-configuration

API Calls Return 401 Unauthorized

Symptoms:

GET http://localhost:8000/templates 401 (Unauthorized)

Fixes:

  1. Token not in headers

    • Check Network tab → Headers
    • Should have: Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6...
  2. Token expired

    • JWT tokens expire after 30 minutes
    • Refresh page to get new token
    • Or implement automatic token refresh
  3. 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 superadmin role
  • Institution admin endpoints require institution_admin role
  • 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 policy

Fix:

  • Backend CORS settings in main.py should include http://localhost:5173
  • Restart backend after changing CORS config

Components Not Re-rendering

Symptoms:

  • Update made, but UI doesn't reflect change

Fixes:

  1. React Query cache stale

    javascript
    // Invalidate query after mutation
    queryClient.invalidateQueries(['templates']);
  2. 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 tree

Fixes:

  1. Version conflicts

    bash
    # Delete lock file and node_modules
    rm package-lock.json
    rm -rf node_modules
    
    # Reinstall
    npm install
  2. Node version mismatch

    bash
    # Check version
    node --version
    # Should be v18 or higher
    
    # Install correct version
    brew install node@18
  3. Cache corrupted

    bash
    npm cache clean --force
    npm install

poetry install Fails

Symptoms:

SolverProblemError: Because package-a depends on package-b...

Fixes:

  1. Lock file out of sync

    bash
    cd backend
    rm poetry.lock
    poetry install
  2. Python version mismatch

    bash
    # Check version
    python3 --version
    # Should be 3.11+
    
    # Tell Poetry to use specific Python
    poetry env use python3.11
    poetry install
  3. Dependency conflict

    • Check pyproject.toml for version constraints
    • May need to update or pin specific versions

Docker Build Fails

Symptoms:

ERROR [builder] failed to solve: process "/bin/sh -c pip install..." did not complete successfully

Fixes:

  1. Context size too large

    bash
    # Add to .dockerignore
    node_modules
    __pycache__
    .venv
    *.pyc
  2. Base image unavailable

    bash
    # Pull image manually
    docker pull python:3.11-slim
  3. Build 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 :::8000

Diagnosis:

bash
# Find process using port (macOS/Linux)
lsof -i :5173
lsof -i :8000

# Kill process
kill -9 PID

Common 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:

bash
# Change frontend port
npm run localhost -- --port 5174

# Change backend port
PORT=8001 python -m uvicorn src.noumaris_backend.api.main:app --reload

Performance Issues

Slow API Responses

Diagnosis:

  1. Check FastAPI logs for slow endpoints
  2. Use /docs to test endpoint directly
  3. 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:

  1. Code splitting

    javascript
    const Page = lazy(() => import('./Page'));
  2. Optimize images - Use WebP, lazy loading

  3. Reduce bundle size

    bash
    # Analyze bundle
    npm run build
    npx vite-bundle-visualizer

High Memory Usage

Backend:

bash
# Check Python process memory
ps aux | grep python

# Optimize database connection pool
# In main.py, reduce pool size

Frontend:

bash
# Check for memory leaks
# Browser DevTools → Memory → Take heap snapshot

Common Error Messages

"alembic.util.exc.CommandError: Target database is not up to date"

Meaning: Database schema doesn't match current code

Fix:

bash
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 /docs for 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 def for async endpoints
  • Don't mix sync/async incorrectly

Getting Help

If issue persists:

  1. Check logs

    • Backend: Console output
    • Frontend: Browser DevTools console
    • Docker: docker-compose logs -f
  2. Search documentation

  3. Enable debug mode

    python
    # Backend main.py
    app = FastAPI(debug=True)
  4. Minimal reproduction

    • Isolate the issue
    • Test with curl or Postman
    • Check if issue exists on fresh setup

Next Steps

Internal documentation for Noumaris platform