Skip to main content

Troubleshooting

This document provides guidance for diagnosing and resolving common issues that may arise when working with FF-API-External.

Table of Contents

Common Issues

API Connection Issues

Issue: Unable to connect to the API

Symptoms:

  • HTTP 502 Bad Gateway error
  • Network timeout errors
  • "Connection refused" errors

Possible Causes:

  1. The API service is not running
  2. Firewall blocking connection
  3. Incorrect port configuration
  4. DNS resolution issues
  5. Load balancer issues

Solutions:

  1. Check if the API service is running:

    ps aux | grep gunicorn  # If using Gunicorn
    ps aux | grep uwsgi # If using uWSGI
  2. Verify firewall rules:

    sudo iptables -L  # Linux
  3. Verify the API is listening on the expected port:

    netstat -tulpn | grep 8080  # Assuming port 8080
  4. Check Nginx/Apache configuration:

    nginx -t  # Test Nginx configuration
    apache2ctl configtest # Test Apache configuration
  5. Check logs for error messages:

    tail -f /var/log/nginx/error.log
    tail -f /var/log/apache2/error.log
    tail -f /path/to/application/log

Issue: CORS Issues

Symptoms:

  • Browser console showing CORS errors
  • API working with direct tools like Postman but not with web applications

Solutions:

  1. Verify CORS configuration in the application:

    # Specific CORS setting
    @app.route('/api/endpoint', methods=['GET'])
    @cross_origin()
    def api_endpoint():
    # Implementation
  2. Configure CORS with more specific settings:

    cors = CORS(app, resources={
    r"/api/*": {
    "origins": ["https://trusted-domain.com"],
    "methods": ["GET", "POST"],
    "allow_headers": ["Content-Type", "Authorization"]
    }
    })

Database Connection Issues

Issue: Unable to connect to MySQL

Symptoms:

  • API returns 500 errors
  • Logs showing MySQL connection errors

Possible Causes:

  1. Incorrect database credentials
  2. MySQL server not running
  3. Network/firewall issues
  4. Exceeded connection limits

Solutions:

  1. Verify database credentials in .env file
  2. Ensure MySQL server is running:
    sudo systemctl status mysql
  3. Check if you can connect to MySQL manually:
    mysql -h hostname -u username -p
  4. Check the MySQL error log:
    tail -f /var/log/mysql/error.log
  5. Verify connection limits:
    SHOW VARIABLES LIKE 'max_connections';
    SHOW STATUS LIKE 'Threads_connected';

Issue: Unable to connect to MongoDB

Symptoms:

  • API returns 500 errors
  • Logs showing MongoDB connection errors

Solutions:

  1. Verify MongoDB connection string in .env file
  2. Ensure MongoDB server is running
  3. Check if MongoDB certificates are correctly placed
  4. Try connecting to MongoDB manually:
    mongo "mongodb+srv://host/database" --username user --password password
  5. Check MongoDB logs for errors

Third-Party Service Issues

Issue: API Key or Authentication Issues

Symptoms:

  • 401 or 403 errors when accessing third-party services
  • Messages about invalid API keys or authentication

Solutions:

  1. Verify API keys in .env file
  2. Check if API keys have expired or been revoked
  3. Ensure API keys have the necessary permissions
  4. Check if you've reached API rate limits
  5. Verify that the third-party service is operational

Issue: Rate Limiting

Symptoms:

  • 429 Too Many Requests errors
  • Sudden failure of previously working endpoints

Solutions:

  1. Implement caching for frequently accessed data
  2. Reduce the frequency of API calls
  3. Implement exponential backoff and retry strategies
  4. Consider upgrading to a higher API tier if available
  5. Distribute requests across multiple API keys if possible

Performance Issues

Issue: Slow API Response Times

Symptoms:

  • API calls taking longer than expected to complete
  • Timeout errors

Possible Causes:

  1. Inefficient database queries
  2. Resource constraints (CPU, memory)
  3. Third-party service delays
  4. Network latency
  5. Lack of caching

Solutions:

  1. Profile API endpoints to identify bottlenecks:

    import time

    start_time = time.time()
    # Operation to profile
    end_time = time.time()
    print(f"Operation took {end_time - start_time} seconds")
  2. Optimize database queries:

    • Add indexes to frequently queried fields
    • Use query projections to return only necessary fields
    • Implement pagination for large result sets
  3. Implement caching for expensive operations:

    # Simple in-memory cache
    cache = {}

    def get_data(key):
    if key in cache:
    return cache[key]

    # Expensive operation to get data
    data = expensive_operation()

    cache[key] = data
    return data
  4. Monitor resource usage:

    htop  # CPU and memory usage
    iostat -x 1 # Disk I/O
    iftop # Network I/O
  5. Increase server resources if necessary

Security Issues

Issue: Unusual API Access Patterns

Symptoms:

  • Sudden increase in API traffic
  • Access attempts from suspicious IP addresses
  • Unusual endpoint access patterns

Solutions:

  1. Review access logs to identify suspicious patterns
  2. Implement rate limiting based on IP address or API key
  3. Consider implementing IP whitelisting for sensitive endpoints
  4. Review authentication mechanisms
  5. Enable more detailed logging for security events

Debugging Techniques

Log Analysis

The application uses Python's logging module for logging:

import logging

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

To enable more detailed logging for debugging:

logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

Common log locations:

  • Application logs: Configured in the application
  • Nginx logs: /var/log/nginx/access.log and /var/log/nginx/error.log
  • Apache logs: /var/log/apache2/access.log and /var/log/apache2/error.log
  • MySQL logs: /var/log/mysql/error.log
  • MongoDB logs: Configured in MongoDB configuration

API Testing

Use tools like Postman, curl, or httpie to test API endpoints:

# Using curl
curl -X GET "https://api.example.com/api/v1/endpoint" \
-H "Authorization: Bearer your_token" \
-H "Content-Type: application/json"

# Using httpie
http GET "https://api.example.com/api/v1/endpoint" \
Authorization:"Bearer your_token" \
Content-Type:"application/json"

For testing with request data:

# Using curl
curl -X POST "https://api.example.com/api/v1/endpoint" \
-H "Authorization: Bearer your_token" \
-H "Content-Type: application/json" \
-d '{"key": "value"}'

# Using httpie
http POST "https://api.example.com/api/v1/endpoint" \
Authorization:"Bearer your_token" \
key=value

Database Debugging

MySQL Debugging

Connect to MySQL and query data:

mysql -h hostname -u username -p

# Once connected
USE database_name;
SHOW TABLES;
DESCRIBE table_name;
SELECT * FROM table_name LIMIT 10;

Check for slow queries:

SHOW PROCESSLIST;

MongoDB Debugging

Connect to MongoDB and query data:

mongo "mongodb+srv://host/database" --username user --password password

# Once connected
use database_name
show collections
db.collection_name.find().limit(10)

Check for MongoDB performance:

db.currentOp()
db.serverStatus()

Common Error Codes

HTTP StatusMeaningCommon Causes
400Bad RequestInvalid input parameters, malformed request
401UnauthorizedMissing or invalid authentication token
403ForbiddenValid authentication but insufficient permissions
404Not FoundResource or endpoint doesn't exist
405Method Not AllowedUsing an unsupported HTTP method for the endpoint
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error, exception in code
502Bad GatewayProxy or gateway issue, API server not running
503Service UnavailableServer overloaded or under maintenance
504Gateway TimeoutTimeout when the gateway server waited for the API server

Support Resources

If you're experiencing issues not covered in this troubleshooting guide, consider the following resources:

  1. Check the application logs for detailed error information
  2. Review the documentation for the specific endpoint or feature
  3. Check for known issues in the issue tracker
  4. Consult with the development team
  5. For third-party service issues, consult their respective documentation and support resources

For urgent production issues, follow the incident response procedure:

  1. Identify the severity and impact
  2. Communicate the issue to the appropriate team members
  3. Investigate using the debugging techniques described above
  4. Apply temporary mitigations if possible
  5. Implement and test a permanent fix
  6. Document the incident and resolution