The user wants a "fallback service for third-party dependencies with stubs".
This means I need to design and implement a system in code (likely TypeScript or Python, but I'll stick to a general robust pattern, probably TypeScript/Node.js as it's common for enterprise patterns) that handles the failure of external services (APIs, databases) gracefully by falling back to a "stub" or "mock" implementation.
Core Concepts:
Interface/Contract: The calling code shouldn't know or care if it's talking to the real service or the stub. Dependency Injection (DI) is key here.
The Real Service: The actual third-party client (e.g., Stripe, SendGrid).
The Stub Service: A simplified, local implementation that returns hardcoded data or performs basic logic without external calls.
The Fallback Service (The Wrapper): This is the entry point. It tries the real service, catches errors, and delegates to the stub if necessary (or based on configuration).
Configuration: A way to toggle "offline mode" or strict vs. lenient modes.
Architecture Options:
Option A: Decorator Pattern. The Fallback Service wraps the Real Service. If the Real throws, it calls the Stub. This is transparent to the app.
Option B: Factory/Strategy Pattern. A factory checks config/health and decides which instance (Real or Stub) to return at startup.
Option C: Middleware/Proxy. Intercept calls at a lower level.
Decision: Option A (Decorator/Wrapper) is usually best for "Fallback" specifically because it handles runtime errors. If the API is flaky, you want to catch the exception at the moment and return a stub value. Option B is good for "Maintenance Mode", but Option A covers both.
Language Choice:
TypeScript provides clear interfaces, making this pattern very explicit and readable.
Step-by-Step Implementation Plan:
Define the Interface: Create a standard contract (e.g., IPaymentService).
Implement Real Service: A class calling an external API.
Implement Stub Service: A class returning static data.
Implement Fallback Service: The wrapper that tries Real, catches errors, and returns Stub.
Configuration/Context: How to enable/disable this (e.g., env variables).
Usage Example: How to wire it all together.
Refining the "Fallback" Logic:
Should it always try the real one first?
Scenario 1: API is down. -> Real throws -> Catch -> Return Stub.
Scenario 2: We are in dev mode. -> Don't even try Real -> Return Stub immediately (saves time/cost).
Use a specific domain example, like an EmailService or WeatherService, to make it concrete. Let's go with a NotificationService (common third-party dependency like Twilio/SendGrid).
Add error logging.
Add latency simulation to the stub (optional but cool).
Make it generic if possible, but concrete is usually better for tutorials. I'll stick to concrete but mention the generic capability.
Self-Correction during drafting:
Simply catching any error might be dangerous. Some errors (like Auth errors) shouldn't fall back to a stub because the stub implies "success" (usually). If the API key is wrong, falling back to a stub might hide the configuration bug.
Refinement: I should distinguish between "Network/Availability Errors" (503, Timeout) and "Logic/Auth Errors" (401, 400). For this example, I'll keep it simple but add a comment about filtering errors.
Let's stick to TypeScript for strong typing, as it demonstrates the "Contract" aspect best.
Final Output Structure:
Concept Overview: Explain the Strategy/Decorator pattern.
The Interface: Define what the service does.
Implementations: Real vs. Stub.
The Fallback Wrapper: The core logic.
Wiring it up: Dependency Injection / Factory.
Let's write the code.
Step 1: InterfaceINotificationService
Step 2: RealTwilioClient (mocked)
Step 3: StubConsoleNotificationService (logs to console instead of sending SMS)
Step 4: FallbackResilientNotificationService
This looks solid. I will produce the response based on this plan.
Creating a fallback service is a classic application of the Strategy Pattern combined with the Decorator Pattern.
The goal is to define a common interface (Contract). The application interacts with this interface without knowing whether it is talking to the live third-party API or a local stub. A "Fallback" wrapper decides which one to use at runtime based on availability or configuration.
Here is a robust implementation in TypeScript.
1. The Architecture
Contract (Interface): Defines the shape of the data and methods.
Live Service: The real implementation calling the 3rd party API.
Stub Service: A mock implementation returning hardcoded data or logic.
Fallback Service: A wrapper that attempts the Live Service first and catches errors to route to the Stub Service.
2. The Implementation
Let's imagine we are integrating with a Weather API.
Step 1: Define the Contract
First, we define what our service does. This ensures our Stub and Live Service are interchangeable.
typescript
// types.ts
export interface WeatherData {
temperature: number;
condition: string;
isReliable: boolean; // To track if data is real or stubbed
}
export interface IWeatherService {
getWeather(city: string): Promise<WeatherData>;
}
Step 2: The Concrete Implementations
The Real Service (Third-Party)
This class interacts with the actual external world. It throws errors if the network is down or the API key is invalid.
typescript
// services/LiveWeatherService.ts
import { IWeatherService, WeatherData } from './types';
export class LiveWeatherService implements IWeatherService {
async getWeather(city: string): Promise<WeatherData> {
console.log(`[Live] Fetching real data for ${city}...`);
// Simulate a network call
const response = await fetch(`https://api.example.com/weather?city=${city}`);
if (!response.ok) {
throw new Error(`API Failed with status ${response.status}`);
}
const data = await response.json();
return {
temperature: data.temp,
condition: data.condition,
isReliable: true
};
}
}
The Stub Service (Fallback)
This class mimics the behavior of the real service but returns static data instantly. It never throws network errors.
This is the core component. It acts as a circuit breaker. It tries the primary service, and if an error occurs, it gracefully degrades to the stub.
typescript
// services/FallbackWeatherService.ts
import { IWeatherService, WeatherData } from './types';
export class FallbackWeatherService implements IWeatherService {
private primaryService: IWeatherService;
private stubService: IWeatherService;
constructor(primary: IWeatherService, stub: IWeatherService) {
this.primaryService = primary;
this.stubService = stub;
}
async getWeather(city: string): Promise<WeatherData> {
try {
// 1. Try the real service
return await this.primaryService.getWeather(city);
} catch (error) {
// 2. Log the failure (important for monitoring)
console.error(`[Fallback] Primary service failed. Switching to stub. Error: ${(error as Error).message}`);
// 3. Fallback to the stub
return await this.stubService.getWeather(city);
}
}
}
3. Wiring it Up (Dependency Injection)
You can now use a Factory function or a DI container to instantiate the service. This keeps your application logic clean.
typescript
// main.ts
import { LiveWeatherService } from './services/LiveWeatherService';
import { StubWeatherService } from './services/StubWeatherService';
import { FallbackWeatherService } from './services/FallbackWeatherService';
// Factory Pattern
function createWeatherService(): FallbackWeatherService {
const live = new LiveWeatherService();
const stub = new StubWeatherService();
// You could also add logic here:
// e.g., if (process.env.NODE_ENV === 'test') return stub;
return new FallbackWeatherService(live, stub);
}
// --- Usage ---
async function runApp() {
const weatherService = createWeatherService();
// The app doesn't know or care if it's using Live or Stub data
const forecast = await weatherService.getWeather("London");
if (forecast.isReliable) {
console.log(`Real Forecast: ${forecast.temperature}°C`);
} else {
console.log(`System in Degraded Mode: ${forecast.temperature}°C`);
}
}
runApp();
4. Advanced: Configurable Stubs (Modes)
Sometimes you want the Stub to run explicitly (e.g., in a demo environment or CI pipeline) without waiting for the Live service to fail.
You can extend the Factory to handle "Offline Modes":
typescript
function createWeatherService(mode: 'live' | 'stub' | 'auto' = 'auto') {
const live = new LiveWeatherService();
const stub = new StubWeatherService();
if (mode === 'live') return live;
if (mode === 'stub') return stub;
// 'auto' uses the fallback wrapper
return new FallbackWeatherService(live, stub);
}
// usage
const service = createWeatherService(process.env.SERVICE_MODE as any || 'auto');
Summary of Benefits
Resilience: Your application won't crash if the third-party API is down.
Development Speed: Frontend/Backend devs can work offline using the Stub.
Testing: You can inject the StubWeatherService into unit tests to avoid hitting real APIs (saving money and flakiness).