Common Issues & Solutions
Overview
This document outlines frequently encountered issues in the Chainr platform and their solutions.
Database Issues
Connection Refused
Symptoms:
Services fail to start with database connection errors
psycopg2.OperationalError: could not connect to server
Solutions:
Verify PostgreSQL is running:
``
bash sudo systemctl status postgresql # or for Docker docker ps | grep postgres``Check connection string:
``
bash # Test connection psql "postgresql://user:password@localhost:5432/chainr"``Verify database exists:
``
sql \l -- List databases CREATE DATABASE chainr; -- If missing``Check firewall settings: ``
bash sudo ufw status # Allow PostgreSQL port sudo ufw allow 5432``
Migration Failures
Symptoms:
Alembic migration errors
alembic.util.exc.CommandError
Solutions:
Check current migration state:
``
bash alembic current``View migration history:
``
bash alembic history``Fix migration conflicts:
```bash # Mark migration as applied (dangerous!) alembic stamp head
# Or rollback and reapply alembic downgrade -1 alembic upgrade head ```
Reset database (development only): ``
bash # Drop and recreate database dropdb chainr createdb chainr alembic upgrade head``
Authentication Issues
JWT Token Errors
Symptoms:
Invalid tokenorToken expirederrorsUsers unable to access protected endpoints
Solutions:
Verify JWT secret key:
``
bash # Check environment variable echo $JWT_SECRET_KEY``Check token expiration:
``
python # Decode token to check expiration import jwt decoded = jwt.decode(token, options={"verify_signature": False}) print(decoded['exp']) # Check expiration timestamp``Sync system clocks: ``
bash # Check system time date # Sync with NTP sudo ntpdate pool.ntp.org``
Password Reset Issues
Symptoms:
Password reset emails not received
Invalid reset token errors
Solutions:
Check email configuration:
``
bash # Verify SMTP settings echo $SMTP_SERVER echo $SMTP_PORT``Test email sending:
``
python # Test email service from app.services.email import EmailService email_svc = EmailService() email_svc.send_test_email("test@example.com")``Check token validity:
Reset tokens expire in 1 hour
Ensure user clicks link within time limit
Check for token tampering
File Upload Issues
Upload Failures
Symptoms:
Files fail to upload
413 Request Entity Too Largeerrors
Solutions:
Check file size limits:
``
nginx # nginx.conf client_max_body_size 100M;``Verify upload permissions:
``
bash # Check upload directory ls -la /app/uploads/ # Fix permissions chown -R app:app /app/uploads/ chmod 755 /app/uploads/``Check disk space: ``
bash df -h du -sh /app/uploads/``
File Processing Errors
Symptoms:
Documents fail to process
AI analysis timeouts
Solutions:
Check file type support:
``
python # Verify supported MIME types ALLOWED_TYPES = ['application/pdf', 'text/plain', ...]``Monitor processing queues:
``
bash # Check Redis queues redis-cli LLEN document_processing_queue``Scale processing workers: ``
bash # Increase worker count docker-compose up --scale svc-ai=3``
API Issues
502 Bad Gateway
Symptoms:
Intermittent API failures
Services show as unhealthy
Solutions:
Check service health:
``
bash curl http://localhost:8000/health curl http://localhost:8001/health``Review service logs:
``
bash docker logs svc-core docker logs svc-auth``Check resource usage:
``
bash docker stats # Check memory/CPU limits``Restart failing services: ``
bash docker-compose restart svc-core``
CORS Errors
Symptoms:
Browser console shows CORS errors
API calls blocked by browser
Solutions:
Check CORS configuration:
``
python # FastAPI CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )``Verify frontend configuration:
``
javascript // Frontend API calls const response = await fetch("/api/projects", { credentials: "include", // Include cookies });``Check nginx proxy headers: ``
nginx location /api/ { proxy_pass http://backend; proxy_set_header Origin $http_origin; }``
Performance Issues
Slow Response Times
Symptoms:
API responses take >2 seconds
Frontend feels sluggish
Solutions:
Check database query performance:
```sql -- Enable query logging SET logstatement = 'all'; SET logduration = 'on';
-- Find slow queries SELECT * FROM pgstatstatements ORDER BY total_time DESC; ```
Verify caching:
``
bash # Check Redis cache hit rate redis-cli INFO stats | grep keyspace``Profile application:
``
python # Use py-spy for profiling py-spy top --pid $(pgrep uvicorn)``Check resource limits: ``
bash # Docker resource usage docker stats # System resources htop``
Memory Leaks
Symptoms:
Gradual memory increase
Out of memory errors
Solutions:
Monitor memory usage:
``
bash # Check process memory ps aux --sort=-%mem | head``Profile memory usage:
```python # Use memoryprofiler from memoryprofiler import profile
@profile def memoryintensivefunction(): # Code to profile pass ```
Check for object leaks: ``
python # SQLAlchemy session leaks # Ensure sessions are properly closed async with AsyncSession() as session: # Use session pass``
Networking Issues
Service Discovery Failures
Symptoms:
Services can't communicate
Connection refusedbetween services
Solutions:
Check Docker networking:
``
bash docker network ls docker network inspect chainr_default``Verify service names:
``
yaml # docker-compose.yml services: svc-core: # Correct service name svc-auth: # Correct service name``Test inter-service communication: ``
bash # From core container docker exec svc-core curl http://svc-auth:3000/health``
DNS Resolution Issues
Symptoms:
Name resolution failureServices can't reach external APIs
Solutions:
Check DNS configuration:
``
bash cat /etc/resolv.conf``Test DNS resolution:
``
bash nslookup api.openai.com``Check network connectivity: ``
bash ping 8.8.8.8 curl https://httpbin.org/ip``
Deployment Issues
Container Startup Failures
Symptoms:
Containers fail to start
CrashLoopBackOffstatus
Solutions:
Check container logs:
``
bash docker logs <container_name>``Verify environment variables:
``
bash docker exec <container> env | grep -E "(DATABASE|REDIS|JWT)"``Check dependencies:
``
bash # Ensure dependent services are healthy docker ps``Validate configuration: ``
bash # Test configuration loading docker exec <container> python -c "from app.config import settings; print(settings)"``
Build Failures
Symptoms:
Docker build fails
Missing dependencies
Solutions:
Check build logs:
``
bash docker build --no-cache -t chainr/core .``Verify requirements files:
``
bash # Check if files exist and are valid cat requirements.txt pip install --dry-run -r requirements.txt``Clear build cache: ``
bash docker system prune -f docker build --no-cache .``
Monitoring & Alerting Issues
Missing Metrics
Symptoms:
Prometheus shows no data
Grafana dashboards empty
Solutions:
Check Prometheus targets:
``
bash curl http://localhost:9090/api/v1/targets``Verify metrics endpoints:
``
bash curl http://localhost:8000/metrics``Check service discovery: ```yaml # prometheus.yml scrape_configs:
jobname: "chainr-core" staticconfigs:
targets: ["svc-core:8080"]
```
Alert Fatigue
Symptoms:
Too many false positive alerts
Important alerts ignored
Solutions:
Tune alert thresholds:
```yaml # Adjust alert rules
alert: HighErrorRate expr: rate(errors_total[5m]) > 0.1 # Adjust threshold for: 10m # Increase duration
```
Implement alert grouping:
``
yaml # Group related alerts group_by: ["service", "severity"]``Set up alert routing: ```yaml # Route alerts by severity routes:
match: severity: critical receiver: "pagerduty"
match: severity: warning receiver: "slack"
```
Development Environment Issues
Local Setup Problems
Symptoms:
Services fail to start locally
Database connection issues
Solutions:
Check environment file:
``
bash # Verify .env file exists ls -la .env cat .env``Start dependencies:
``
bash # Start PostgreSQL and Redis docker-compose up -d db redis``Run migrations:
``
bash # Apply database migrations alembic upgrade head``Check port conflicts: ``
bash # Check if ports are in use lsof -i :8000 lsof -i :5432``
IDE Configuration Issues
Symptoms:
Linting errors
Import resolution failures
Solutions:
Configure Python interpreter:
``
json // .vscode/settings.json { "python.defaultInterpreterPath": "./venv/bin/python" }``Install development dependencies:
``
bash pip install -r requirements-dev.txt``Update IDE extensions:
Python extension
Pylance
Docker extension
Emergency Procedures
Service Outage Response
Assess impact and notify stakeholders
Check monitoring dashboards
Review recent deployments
Scale resources if needed
Implement temporary workarounds
Restore service and investigate root cause
Document incident and prevention measures
Data Recovery
Assess data loss scope
Check backup availability
Restore from backup if needed
Verify data integrity
Communicate with affected users
Implement prevention measures
Security Incident Response
Isolate affected systems
Preserve evidence for investigation
Notify relevant parties
Contain the breach
Recover systems
Conduct post-mortem analysis
Remember to document all issues and solutions to build a knowledge base for faster resolution of future problems.