auto-learning
v0.2.0@backendkit-labs/auto-learning
Self-tuning backend intelligence — learns, detects anomalies, auto-adjusts.
Overview#
@backendkit-labs/auto-learning observes your backend in production and continuously tunes its resilience configuration. Every endpoint call is recorded as a pattern; a periodic feedback loop analyzes those patterns, detects anomalies, and emits an updated TunableConfig that your circuit breaker, bulkhead, and HTTP client can consume immediately.
How It Works#
The learning cycle runs in four stages:
Every endpoint call is captured as an EndpointPattern — method, path, status, duration, timestamp.
PatternRegistry groups calls by endpoint and computes p50/p95/p99 latency, error rate, and call frequency.
AnomalyDetector uses z-score and percentile analysis to flag latency spikes, error surges, frequency shifts, and unknown endpoints.
ConfigTuner adjusts timeoutMs, maxRetries, circuitBreakerThreshold, and bulkheadMaxConcurrent based on detected anomalies.
Configuration#
All options are optional — the defaults work for most backends.
| Prop | Type | Description |
|---|---|---|
| feedbackIntervalMs | number | How often the learning cycle runs (ms). |
| anomaly.latencyStdDevThreshold | number | Z-score threshold for latency spike detection. |
| anomaly.errorRateThreshold | number | Error rate fraction that triggers an anomaly (0.10 = 10%). |
| tuner.cooldownMs | number | Minimum time between config adjustments. |
| storage | StorageAdapter | Pluggable persistence layer. |
| observability | ObservabilityAdapter | Pluggable logging and metrics. |
NestJS Integration#
AutoLearningModule.forRoot() registers the core instance as a singleton. The @AutoLearn() decorator marks controllers or methods for automatic pattern recording via an interceptor — no manual recordPattern() calls needed.
@Injectable() export class ResilienceService implements OnModuleInit { constructor( @Inject(AUTO_LEARNING_INSTANCE) private readonly learner: AutoLearningCore, ) {} onModuleInit() { this.learner.onConfigChange((config) => { this.circuitBreaker.setThreshold(config.circuitBreakerThreshold); this.bulkhead.setMaxConcurrent(config.bulkheadMaxConcurrent); }); } }
Storage Adapters#
The default InMemoryStorage loses data on restart — suitable for development. For production, implement StorageAdapter backed by Redis or SQL.
| Prop | Type | Description |
|---|---|---|
| savePattern(pattern) | Promise<Result> | Persist an endpoint pattern observation. |
| getAggregates() | Promise<Result> | Load aggregated statistics per endpoint. |
| saveConfig(config) | Promise<Result> | Persist the latest tuned configuration. |
| loadConfig() | Promise<Result> | Load the last saved configuration on startup. |
| prune(olderThan) | Promise<Result> | Remove patterns older than the given date. |
Examples#
From basic to production-grade — copy and adapt.
import { AutoLearningCore } from '@backendkit-labs/auto-learning'; const learner = AutoLearningCore.create(); learner.recordPattern({ method: 'POST', path: '/api/payments', statusCode: 200, durationMs: 145, timestamp: new Date(), }); learner.onConfigChange((config) => { circuitBreaker.setThreshold(config.circuitBreakerThreshold); bulkhead.setMaxConcurrent(config.bulkheadMaxConcurrent); httpClient.setTimeout(config.timeoutMs); }); learner.startFeedbackLoop(60_000);