chain-rdeveloper portal
build

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:

  1. Verify PostgreSQL is running:

    ``bash sudo systemctl status postgresql # or for Docker docker ps | grep postgres ``

  2. Check connection string:

    ``bash # Test connection psql "postgresql://user:password@localhost:5432/chainr" ``

  3. Verify database exists:

    ``sql \l -- List databases CREATE DATABASE chainr; -- If missing ``

  4. 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:

  1. Check current migration state:

    ``bash alembic current ``

  2. View migration history:

    ``bash alembic history ``

  3. Fix migration conflicts:

    ```bash # Mark migration as applied (dangerous!) alembic stamp head

    # Or rollback and reapply alembic downgrade -1 alembic upgrade head ```

  4. Reset database (development only): ``bash # Drop and recreate database dropdb chainr createdb chainr alembic upgrade head ``

Authentication Issues

JWT Token Errors

Symptoms:

  • Invalid token or Token expired errors

  • Users unable to access protected endpoints

Solutions:

  1. Verify JWT secret key:

    ``bash # Check environment variable echo $JWT_SECRET_KEY ``

  2. 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 ``

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

  1. Check email configuration:

    ``bash # Verify SMTP settings echo $SMTP_SERVER echo $SMTP_PORT ``

  2. Test email sending:

    ``python # Test email service from app.services.email import EmailService email_svc = EmailService() email_svc.send_test_email("test@example.com") ``

  3. 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 Large errors

Solutions:

  1. Check file size limits:

    ``nginx # nginx.conf client_max_body_size 100M; ``

  2. Verify upload permissions:

    ``bash # Check upload directory ls -la /app/uploads/ # Fix permissions chown -R app:app /app/uploads/ chmod 755 /app/uploads/ ``

  3. Check disk space: ``bash df -h du -sh /app/uploads/ ``

File Processing Errors

Symptoms:

  • Documents fail to process

  • AI analysis timeouts

Solutions:

  1. Check file type support:

    ``python # Verify supported MIME types ALLOWED_TYPES = ['application/pdf', 'text/plain', ...] ``

  2. Monitor processing queues:

    ``bash # Check Redis queues redis-cli LLEN document_processing_queue ``

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

  1. Check service health:

    ``bash curl http://localhost:8000/health curl http://localhost:8001/health ``

  2. Review service logs:

    ``bash docker logs svc-core docker logs svc-auth ``

  3. Check resource usage:

    ``bash docker stats # Check memory/CPU limits ``

  4. Restart failing services: ``bash docker-compose restart svc-core ``

CORS Errors

Symptoms:

  • Browser console shows CORS errors

  • API calls blocked by browser

Solutions:

  1. Check CORS configuration:

    ``python # FastAPI CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ``

  2. Verify frontend configuration:

    ``javascript // Frontend API calls const response = await fetch("/api/projects", { credentials: "include", // Include cookies }); ``

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

  1. 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; ```

  2. Verify caching:

    ``bash # Check Redis cache hit rate redis-cli INFO stats | grep keyspace ``

  3. Profile application:

    ``python # Use py-spy for profiling py-spy top --pid $(pgrep uvicorn) ``

  4. Check resource limits: ``bash # Docker resource usage docker stats # System resources htop ``

Memory Leaks

Symptoms:

  • Gradual memory increase

  • Out of memory errors

Solutions:

  1. Monitor memory usage:

    ``bash # Check process memory ps aux --sort=-%mem | head ``

  2. Profile memory usage:

    ```python # Use memoryprofiler from memoryprofiler import profile

    @profile def memoryintensivefunction(): # Code to profile pass ```

  3. 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 refused between services

Solutions:

  1. Check Docker networking:

    ``bash docker network ls docker network inspect chainr_default ``

  2. Verify service names:

    ``yaml # docker-compose.yml services: svc-core: # Correct service name svc-auth: # Correct service name ``

  3. Test inter-service communication: ``bash # From core container docker exec svc-core curl http://svc-auth:3000/health ``

DNS Resolution Issues

Symptoms:

  • Name resolution failure

  • Services can't reach external APIs

Solutions:

  1. Check DNS configuration:

    ``bash cat /etc/resolv.conf ``

  2. Test DNS resolution:

    ``bash nslookup api.openai.com ``

  3. Check network connectivity: ``bash ping 8.8.8.8 curl https://httpbin.org/ip ``

Deployment Issues

Container Startup Failures

Symptoms:

  • Containers fail to start

  • CrashLoopBackOff status

Solutions:

  1. Check container logs:

    ``bash docker logs <container_name> ``

  2. Verify environment variables:

    ``bash docker exec <container> env | grep -E "(DATABASE|REDIS|JWT)" ``

  3. Check dependencies:

    ``bash # Ensure dependent services are healthy docker ps ``

  4. 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:

  1. Check build logs:

    ``bash docker build --no-cache -t chainr/core . ``

  2. Verify requirements files:

    ``bash # Check if files exist and are valid cat requirements.txt pip install --dry-run -r requirements.txt ``

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

  1. Check Prometheus targets:

    ``bash curl http://localhost:9090/api/v1/targets ``

  2. Verify metrics endpoints:

    ``bash curl http://localhost:8000/metrics ``

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

  1. Tune alert thresholds:

    ```yaml # Adjust alert rules

    • alert: HighErrorRate expr: rate(errors_total[5m]) > 0.1 # Adjust threshold for: 10m # Increase duration

    ```

  2. Implement alert grouping:

    ``yaml # Group related alerts group_by: ["service", "severity"] ``

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

  1. Check environment file:

    ``bash # Verify .env file exists ls -la .env cat .env ``

  2. Start dependencies:

    ``bash # Start PostgreSQL and Redis docker-compose up -d db redis ``

  3. Run migrations:

    ``bash # Apply database migrations alembic upgrade head ``

  4. 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:

  1. Configure Python interpreter:

    ``json // .vscode/settings.json { "python.defaultInterpreterPath": "./venv/bin/python" } ``

  2. Install development dependencies:

    ``bash pip install -r requirements-dev.txt ``

  3. Update IDE extensions:

    • Python extension

    • Pylance

    • Docker extension

Emergency Procedures

Service Outage Response

  1. Assess impact and notify stakeholders

  2. Check monitoring dashboards

  3. Review recent deployments

  4. Scale resources if needed

  5. Implement temporary workarounds

  6. Restore service and investigate root cause

  7. Document incident and prevention measures

Data Recovery

  1. Assess data loss scope

  2. Check backup availability

  3. Restore from backup if needed

  4. Verify data integrity

  5. Communicate with affected users

  6. Implement prevention measures

Security Incident Response

  1. Isolate affected systems

  2. Preserve evidence for investigation

  3. Notify relevant parties

  4. Contain the breach

  5. Recover systems

  6. Conduct post-mortem analysis

Remember to document all issues and solutions to build a knowledge base for faster resolution of future problems.