Home/Docs/auto-learning
AL

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.

87 tests>94% coverageZero ML depsPluggable storage

How It Works#

The learning cycle runs in four stages:

1. Record

Every endpoint call is captured as an EndpointPattern — method, path, status, duration, timestamp.

2. Aggregate

PatternRegistry groups calls by endpoint and computes p50/p95/p99 latency, error rate, and call frequency.

3. Detect

AnomalyDetector uses z-score and percentile analysis to flag latency spikes, error surges, frequency shifts, and unknown endpoints.

4. Tune

ConfigTuner adjusts timeoutMs, maxRetries, circuitBreakerThreshold, and bulkheadMaxConcurrent based on detected anomalies.

Configuration#

All options are optional — the defaults work for most backends.

PropTypeDescription
feedbackIntervalMsnumberHow often the learning cycle runs (ms).
anomaly.latencyStdDevThresholdnumberZ-score threshold for latency spike detection.
anomaly.errorRateThresholdnumberError rate fraction that triggers an anomaly (0.10 = 10%).
tuner.cooldownMsnumberMinimum time between config adjustments.
storageStorageAdapterPluggable persistence layer.
observabilityObservabilityAdapterPluggable 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.

resilience.service.ts
@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.

PropTypeDescription
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.

learning.service.ts
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);