@shockmouse/recommendations
v1.0.1
Published
A robust, type-safe recommendation engine for managing product recommendations with sophisticated fallback handling, telemetry, and rate limiting.
Readme
Recommendation Engine SDK
A robust, type-safe recommendation engine for managing product recommendations with sophisticated fallback handling, telemetry, and rate limiting.
Features
- 🎯 Priority-based recommendation sets
- 🔄 Intelligent fallback chains
- ⚡️ Built-in caching with TTL support
- 🛡️ Rate limiting protection
- 📊 Telemetry and error tracking
- 🎨 Context-aware display conditions
- ✅ Full TypeScript support
- ⏱️ Timeout protection
- 🔍 Batch evaluation
Installation
npm install @occollective/recommendationsQuick Start
import { createEngine } from '@shockmouse/recommendations';
// Create a configured engine instance
const engine = createEngine({
maxTimeout: 2000, // 2 seconds
maxFallbackDepth: 3,
cache: {
ttl: 5 * 60 * 1000, // 5 minutes
maxSize: 1000,
},
rateLimiting: {
windowMs: 60000, // 1 minute
maxRequests: 100,
},
});
// Define a recommendation set
engine.define(
'holiday-sale',
[
{ id: 'bundle-1', name: 'Holiday Bundle', price: 99.99 },
{ id: 'gift-1', name: 'Gift Set', price: 49.99 },
],
async (context) => {
// Custom display logic
return isHolidaySeason() && hasStock();
},
{
priority: 2,
location: 'home-page',
fallbackProducts: [
{ id: 'regular-1', name: 'Standard Option', price: 29.99 },
],
}
);
// Get recommendations for a location
const recommendations = await engine.getForLocation('home-page', {
userId: 'user-123',
region: 'US',
});Advanced Usage
Fallback Chains
Create sophisticated fallback chains for reliable recommendation delivery:
// Primary recommendation set
engine.define(
'premium-members',
premiumProducts,
async (context) => isPremiumMember(context),
{
priority: 3,
location: 'product-page',
fallback: 'personalized', // Falls back to personalized recommendations
}
);
// Secondary recommendation set
engine.define(
'personalized',
personalizedProducts,
async (context) => hasPersonalizationData(context),
{
priority: 2,
location: 'product-page',
fallback: 'default', // Falls back to default recommendations
}
);
// Default recommendation set
engine.define('default', defaultProducts, async () => true, {
priority: 1,
location: 'product-page',
fallbackProducts: safeDefaultProducts, // Final fallback
});Telemetry Integration
The engine provides comprehensive telemetry tracking:
const engine = createEngine({
telemetry: {
trackEvent: (name, properties) => {
analytics.track(name, properties);
},
trackError: (error, context) => {
errorReporting.captureException(error, { extra: context });
},
trackTiming: (name, durationMs, properties) => {
metrics.recordTiming(name, durationMs, properties);
},
},
});Rate Limiting
Protect your recommendation engine from overuse:
const engine = createEngine({
rateLimiting: {
windowMs: 60000, // 1 minute window
maxRequests: 100, // Max requests per window
},
});Batch Processing
The engine automatically processes recommendations in batches to prevent blocking:
// These will be evaluated in batches of 3
engine.define('set1', products1, condition1, { location: 'home' });
engine.define('set2', products2, condition2, { location: 'home' });
engine.define('set3', products3, condition3, { location: 'home' });
engine.define('set4', products4, condition4, { location: 'home' });
engine.define('set5', products5, condition5, { location: 'home' });Type Safety
The engine provides comprehensive TypeScript types:
import type {
Product,
RecommendationSet,
RecommendationOptions,
EngineOptions,
} from '@occollective/recommendations';
interface CustomProduct extends Product {
category: string;
inStock: boolean;
}
const options: RecommendationOptions = {
priority: 2,
location: 'category-page',
fallbackProducts: defaultProducts,
};Error Handling
The engine includes built-in error handling and timeout protection:
try {
const recommendations = await engine.get('holiday-sale', context);
} catch (error) {
if (error instanceof RecommendationError) {
switch (error.code) {
case ErrorCodes.RATE_LIMIT_EXCEEDED:
// Handle rate limiting
break;
case ErrorCodes.EVALUATION_TIMEOUT:
// Handle timeout
break;
case ErrorCodes.FALLBACK_DEPTH_EXCEEDED:
// Handle excessive fallback chain
break;
}
}
}Performance Optimization
Caching Strategy
The engine implements intelligent caching:
const engine = createEngine({
cache: {
ttl: 5 * 60 * 1000, // Cache for 5 minutes
maxSize: 1000, // Prevent memory leaks
},
});Efficient Context Usage
Optimize your display conditions:
engine.define(
'efficient-set',
products,
async (context) => {
// ✅ Good: Cache expensive operations
const userSegment = await getUserSegmentCached(context.userId);
return userSegment === 'target';
},
options
);Best Practices
- Fallback Chains: Keep fallback depth reasonable (recommended max: 3-5 levels)
- Timeouts: Set appropriate timeouts based on your display condition complexity
- Caching: Use TTL values that balance freshness with performance
- Rate Limiting: Configure limits based on your infrastructure capacity
- Error Handling: Always handle potential errors, especially in production
- Telemetry: Implement comprehensive tracking for monitoring and debugging
License
MIT License - see the LICENSE file for details.
