Skip to content

Repository files navigation

Defensive Cache - Node.js Application

A Node.js application demonstrating defensive caching patterns with Redis. This application shows how to implement fallback caching strategies when external services fail.

🚀 Features

  • Defensive Caching: Automatically falls back to cached data when external services fail
  • Redis Integration: Uses Redis for fast, persistent caching

📋 Prerequisites

  • Docker
  • Docker Compose

🏃‍♂️ Quick Start

Development Mode (with Hot Reload)

  1. Start the application:

    docker-compose up --build
  2. Access the application:

  3. Test Commands

    # Test the endpoint multiple times to see caching behavior
    for i in {1..10}; do
      echo "Request $i:"
      curl -s http://localhost:3000/api/recommendations | jq .
      echo "---"
      sleep 1
    done

🏗️ Project Structure

src/
├── index.ts                    # Main application entry point
├── routes/                     # API route definitions
│   ├── index.ts               # Route aggregator
│   └── recommendation.ts      # Recommendation endpoints
├── services/                   # Business logic
│   └── list-recommendations.ts # Recommendation service with defensive caching
└── infra/                     # Infrastructure layer
    └── cache/                 # Caching infrastructure
        ├── cache-provider.ts  # Cache abstraction layer
        └── redis.ts          # Redis client configuration

Recommendations

  • GET /api/recommendations - Get recommendations with defensive caching
    • Success Response (200): Returns recommendations from external service or cache
    • Fallback: Automatically uses cached data if external service fails
    • Error Response (500): Only if both external service and cache fail

🛡️ Defensive Caching Strategy

The application implements a defensive caching pattern:

  1. Primary: Attempt to fetch data from external service
  2. Cache on Success: Store successful responses in Redis cache
  3. Fallback on Failure: If external service fails, return cached data
  4. Graceful Degradation: Only return error if both sources fail
  5. Use cases:
    • E-commerce recommendations page: we have a page with recommendations that are fetched from an external service, but this service is not always available, so we want to show the recommendations even if the external service fails.

Example Flow:

External Service Request → Success → Cache Data → Return Response
                    ↓
                Failure → Check Cache → Return Cached Data
                                    ↓
                                No Cache → Return Error

🎯 Testing the Defensive Cache

The application includes a simulated external service that randomly fails (50% chance). This allows you to test the defensive caching behavior:

  1. First Request: May succeed or fail randomly
  2. Subsequent Requests: If first succeeded, cache will be populated
  3. Failed Requests: Will automatically fall back to cached data
  4. Cache Miss: Only returns error if both external service and cache fail

👨‍💻 Author

Arlen Vasconcelos

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages