Class AnomalyDetector

java.lang.Object
com.nmontytskyi.monitoring.detector.AnomalyDetector

public class AnomalyDetector extends Object
Statistical anomaly detector based on the Z-score method.

Determines whether a current metric value is anomalous relative to its own historical norm. Unlike hard thresholds (e.g. response_time > 1000ms), this approach adapts to the actual norm of each service:

  • Service A with a baseline of 800ms → anomaly above ~1200ms
  • Service B with a baseline of 50ms → anomaly above ~130ms

Algorithm (Z-score):

   μ (mean)               = sum(values) / n
   σ (standard deviation) = sqrt(sum((xi - μ)²) / n)
   Z                      = (currentValue - μ) / σ
 

A value is considered anomalous when |Z| > threshold. The standard threshold is 3.0 (three-sigma rule): under a normal distribution only 0.3% of values fall outside this range.

At least 10 historical measurements are required for a reliable calculation. When there is insufficient data, AnomalyDetector.AnomalyResult.insufficient() is returned.

  • Field Details

    • DEFAULT_THRESHOLD

      public static final double DEFAULT_THRESHOLD
      Default Z-score threshold (three-sigma rule).
      See Also:
    • MIN_SAMPLE_SIZE

      public static final int MIN_SAMPLE_SIZE
      Minimum number of historical values required for a reliable calculation.
      See Also:
  • Constructor Details

    • AnomalyDetector

      public AnomalyDetector()
      Creates a detector with the default threshold of 3.0.
    • AnomalyDetector

      public AnomalyDetector(double threshold)
      Creates a detector with a custom Z-score threshold.
      Parameters:
      threshold - deviation threshold; recommended values: 2.0 (sensitive), 3.0 (standard)
      Throws:
      IllegalArgumentException - if the threshold is not positive
  • Method Details

    • analyze

      public AnomalyDetector.AnomalyResult analyze(double currentValue, List<Double> historicalValues)
      Analyses the current value against a set of historical measurements.
      Parameters:
      currentValue - current metric value (e.g. response time in ms)
      historicalValues - list of previous measurements of the same metric; must not include currentValue
      Returns:
      analysis result containing the Z-score and anomaly flag