FastAPI backend with advanced caching and performance optimization for the IPL Cricket Dashboard.
- 🚀 Advanced Caching: Redis + Memory caching with intelligent TTL strategies
- ⚡ Performance Optimized: Connection pooling, query optimization, response compression
- 📊 Neo4j Integration: Efficient graph database queries with caching layers
- 🔍 Monitoring: Built-in performance monitoring and cache analytics
- 🛡️ Production Ready: Health checks, error handling, and scalable architecture
-
Install dependencies:
cd backend pip install -r requirements.txt -
Set up environment:
cp example.env .env # Edit .env with your Neo4j and Redis credentials -
Start the API:
uvicorn backend_api:app --reload --host 0.0.0.0 --port 8000
# From project root
docker-compose up -dThis starts:
- FastAPI backend on port 8000
- Redis cache on port 6379
- Auto-reload for development
GET /api/overview- Database overview statisticsGET /api/seasons- Season statisticsGET /api/venues- Venue performance data
GET /api/batsmen/top- Top batsmen leaderboardGET /api/bowlers/top- Top bowlers leaderboardGET /api/players/{name}/stats- Individual player statisticsGET /api/team/{name}/stats- Team performance data
GET /api/search?q={query}- Search players, teams, venuesGET /api/players/all- Complete player database
GET /health- Health check with cache statusGET /api/cache/stats- Cache performance metricsPOST /api/cache/clear- Clear all caches (dev/debug)
- Redis Cache: Distributed caching (30min - 4hr TTL)
- Memory Cache: Application-level caching (5-30min TTL)
- Query Cache: Database result caching (5min TTL)
- Overview/Historical: 1-4 hours (changes infrequently)
- Player/Team Stats: 15-30 minutes (moderate updates)
- Search Results: 5 minutes (dynamic content)
- Live Data: No cache (real-time requirements)
Execute these commands in Neo4j Browser for optimal performance:
CREATE INDEX player_name_index IF NOT EXISTS FOR (p:Player) ON (p.name);
CREATE INDEX team_name_index IF NOT EXISTS FOR (t:Team) ON (t.name);
CREATE INDEX match_season_index IF NOT EXISTS FOR (m:Match) ON (m.season);
CREATE INDEX match_venue_index IF NOT EXISTS FOR (m:Match) ON (m.venue);See neo4j_optimization.cypher for complete indexing strategy.
- Max Pool Size: 50 connections
- Connection Timeout: 60 seconds
- Retry Strategy: Exponential backoff with jitter
- Connection Lifetime: 1 hour
NEO4J_URI- Neo4j connection URINEO4J_USERNAME- Neo4j usernameNEO4J_PASSWORD- Neo4j password
REDIS_URL- Redis connection URLENABLE_REDIS- Enable/disable Redis cachingCACHE_TTL- Default cache TTL in seconds
WORKERS- Number of Uvicorn workersMAX_POOL_SIZE- Neo4j connection pool sizeREQUEST_TIMEOUT- API request timeout
See example.env.production for complete production configuration.
- Cache Hit Rates: Memory, Redis, and database cache performance
- Response Times: API endpoint performance tracking
- Error Rates: Success/failure monitoring by endpoint
- Resource Usage: Connection pool and memory utilization
curl http://localhost:8000/api/cache/stats
curl http://localhost:8000/health- Copy
example.env.productionto.env - Configure Neo4j and Redis connection strings
- Set appropriate cache TTL values for your use case
- Configure CORS origins for your frontend domains
- Workers: Set to 2x CPU cores for optimal throughput
- Memory: Allocate 512MB+ for Redis cache
- Connections: Tune Neo4j pool size based on concurrent load
- TTL: Adjust cache expiration based on data freshness requirements
The /health endpoint provides comprehensive system status:
- Database connectivity
- Cache system status
- Performance metrics
- Error rates
- Add route function with
@cache_response()decorator - Define appropriate TTL for the data type
- Add to API documentation
- Test cache behavior with different TTL values
- Use
@cache_response(ttl=seconds)for automatic caching - Access cache stats via
/api/cache/stats - Clear cache during development with
/api/cache/clear
- Use read transactions for better performance
- Implement query result caching for expensive operations
- Monitor query performance with Neo4j query logs
- Follow indexing guidelines in
neo4j_optimization.cypher
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │────│ FastAPI │────│ Neo4j DB │
│ (Nuxt.js) │ │ Backend │ │ (Graph DB) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
┌─────────────────┐
│ Redis Cache │
│ (Memory Store) │
└─────────────────┘
Data Flow:
- Frontend requests data from FastAPI
- FastAPI checks Redis cache first
- On cache miss, queries Neo4j database
- Results cached in Redis + memory
- Response compressed and sent to frontend
- Frontend caches in localStorage with stale-while-revalidate
This project is licensed under the MIT License - see the LICENSE file for details.