A high-performance, production-ready workout training application built with FastAPI, featuring comprehensive optimizations for scalability, security, and user experience.
- Async Database Operations: Implemented async SQLAlchemy for better concurrency
- Redis Caching: Intelligent caching for frequently accessed data
- Connection Pooling: Optimized database connection management
- Gzip Compression: Reduced response sizes for better network performance
- Rate Limiting: Protected against abuse with configurable limits
- JWT Authentication: Secure token-based authentication
- Password Hashing: Bcrypt for secure password storage
- Security Headers: Comprehensive security headers middleware
- Input Validation: Pydantic models for robust data validation
- CORS Configuration: Proper cross-origin resource sharing setup
- Structured Logging: JSON-formatted logs with correlation IDs
- Prometheus Metrics: Request counts, latency, and custom metrics
- Health Checks: Application and database health monitoring
- Request Tracking: Full request/response logging with performance metrics
- Docker Multi-stage Build: Optimized container images
- Database Migrations: Alembic for schema version control
- Environment Configuration: Centralized settings management
- Error Handling: Comprehensive error handling and recovery
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Nginx Proxy β β FastAPI App β β PostgreSQL β
β (Load Bal.) βββββΊβ (API Server) βββββΊβ (Database) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
β β β
βΌ βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Redis Cache β β Prometheus β β Grafana β
β (Session/Data)β β (Monitoring) β β (Dashboard) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
- Backend: FastAPI 0.104.1
- Database: PostgreSQL 15 + SQLAlchemy 2.0
- Cache: Redis 7
- Authentication: JWT + Passlib
- Monitoring: Prometheus + Grafana
- Containerization: Docker + Docker Compose
- Logging: Structlog
- Testing: Pytest
- Docker & Docker Compose
- Python 3.11+ (for local development)
- Git
-
Clone the repository
git clone <repository-url> cd backend-python
-
Create environment file
cp .env.example .env # Edit .env with your configuration
-
Start the application stack
docker-compose up -d
-
Access the application
- API: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Grafana: http://localhost:3000 (admin/admin)
- Prometheus: http://localhost:9090
-
Create virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
export DATABASE_URL="sqlite:///./smart_force.db" export SECRET_KEY="your-secret-key" export DEBUG=true
-
Initialize database
alembic upgrade head
-
Run the application
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
Variable | Description | Default |
---|---|---|
DATABASE_URL |
Database connection string | sqlite:///./smart_force.db |
SECRET_KEY |
JWT secret key | your-secret-key-here |
REDIS_URL |
Redis connection string | None |
ENVIRONMENT |
Environment (dev/prod) | development |
DEBUG |
Debug mode | False |
RATE_LIMIT_PER_MINUTE |
API rate limit | 60 |
The application supports both SQLite (development) and PostgreSQL (production):
# Development
DATABASE_URL=sqlite:///./smart_force.db
# Production
DATABASE_URL=postgresql://user:password@localhost/smartforce_db
POST /api/v1/auth/login
- User loginPOST /api/v1/auth/register
- User registrationPOST /api/v1/auth/refresh
- Refresh token
GET /api/v1/trainings/{id}
- Get training by IDPOST /api/v1/trainings/
- Create new trainingPUT /api/v1/trainings/{id}
- Update trainingDELETE /api/v1/trainings/{id}
- Delete trainingGET /api/v1/users/{id}/trainings
- Get user trainingsGET /api/v1/professors/{id}/trainings
- Get professor trainings
GET /health
- Health checkGET /metrics
- Prometheus metrics
Application logs are structured and include:
- Request correlation IDs
- Performance metrics
- Error tracking
- User activity
Prometheus metrics include:
- HTTP request counts
- Response latency
- Error rates
- Cache hit/miss ratios
Grafana dashboards provide:
- Real-time application metrics
- Database performance
- User activity analytics
- Error rate monitoring
# Run all tests
pytest
# Run with coverage
pytest --cov=app
# Run specific test file
pytest tests/test_training.py
-
Update environment variables
export ENVIRONMENT=production export DATABASE_URL=postgresql://... export SECRET_KEY=your-secure-secret-key
-
Build and deploy
docker-compose -f docker-compose.prod.yml up -d
-
Run database migrations
docker-compose exec app alembic upgrade head
The application is designed to scale horizontally:
# Scale the application
docker-compose up -d --scale app=3
# Use a load balancer (nginx) for distribution
- Authentication: JWT-based authentication with refresh tokens
- Authorization: Role-based access control
- Input Validation: Comprehensive data validation
- Rate Limiting: Protection against abuse
- Security Headers: XSS, CSRF, and other security protections
- Password Security: Bcrypt hashing with salt
- User Data: 1 hour cache
- Training Data: 30 minutes cache
- Exercise Data: 2 hours cache
- API Responses: Intelligent cache invalidation
- Connection Pooling: 20 connections with 30 overflow
- Query Optimization: Indexed foreign keys
- Async Operations: Non-blocking database calls
- Pagination: Efficient data retrieval
- Compression: Gzip compression for responses
- Rate Limiting: Configurable per-endpoint limits
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the documentation at
/docs
- Review the health endpoint at
/health
- Complete workout training application
- JWT authentication
- Redis caching
- Prometheus monitoring
- Docker deployment
- Comprehensive API documentation