How sisovin/redis-cache-aside-pattern works
Main Components
• Application Entry Point: Represented by src/app.js, this is the starting point where Express (or similar) is configured.
• Services: Include two key services:
• Cache Service (src/services/cacheService.js): Implements logic to read from, write to, and invalidate the cache.
• Database Service (src/services/dbService.js): Handles database interactions.
• Middleware: Show middleware such as cacheMiddleware (for handling auto-caching logic) and errorHandler. These act as interceptors in the request processing pipeline.
• Models: Illustrate the data model layer (src/models/userModel.js and src/models/productModel.js) that define the schema or ORM definitions.
• Utilities: Represent helper modules like logger (src/utils/logger.js) for logging cache hits/misses and eviction (src/utils/eviction.js) for LRU and TTL based cache eviction policies.
• Configuration Files: Include config components (src/config/cache.js for cache client setup, src/config/database.js for DB connection, and src/config/constants.js for common constants). These modules encapsulate important environmental and connection details.
• External Components: Outside the application, indicate the primary PostgreSQL database and a caching system (Redis or Memcached). Optionally, include Docker containers if using docker-compose.yml.
Relationships and Data Flow
• The API Routes hand off the request to the appropriate Controllers.
• Controllers coordinate the interaction between the Cache Service and Database Service:
• On a cache hit, data is retrieved from the cache.
• On a cache miss, the Database Service is queried; the response is then cached.
• Middleware, such as cacheMiddleware, intercepts requests to automate caching logic.
• Logger and eviction utilities capture ongoing cache performance and manage cache lifecycle.
Architectural Patterns and Design Principles
• Separation of Concerns: Different directories clearly indicate layers responsible for configuration, business logic, data access, utilities, and presentation.
• Middleware Chaining: Represent how errors and caching behaviors are centrally handled through middleware.
• Testing Components: Optionally include a segment for testing (unit and integration) that assures the reliability of cache hits/misses.