|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the "Elastic License |
| 4 | + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side |
| 5 | + * Public License v 1"; you may not use this file except in compliance with, at |
| 6 | + * your election, the "Elastic License 2.0", the "GNU Affero General Public |
| 7 | + * License v3.0 only", or the "Server Side Public License, v 1". |
| 8 | + */ |
| 9 | + |
| 10 | +package org.elasticsearch.common.metrics; |
| 11 | + |
| 12 | +import static java.lang.Math.exp; |
| 13 | +import static java.lang.Math.expm1; |
| 14 | + |
| 15 | +/** |
| 16 | + * Implements a version of an exponentially weighted moving rate (EWMR). This is a calculation over a finite time series of increments to |
| 17 | + * some sort of gauge or counter which gives a value for the rate at which the gauge is being incremented where the weight given to an |
| 18 | + * increment decreases exponentially with how long ago it happened. |
| 19 | + * |
| 20 | + * <p>Definitions: The <i>rate</i> of increase of the gauge or counter over an interval is the sum of the increments which occurred during |
| 21 | + * the interval, divided by the length of the interval. The <i>weighted</i> rate of increase is the sum of the increments with each |
| 22 | + * multiplied by a weight which is a function of how long ago it happened, divided by the integral of the weight function over the interval. |
| 23 | + * The <i>exponentially</i> weighted rate is the weighted rate when the weight function is given by {@code exp(-1.0 * lambda * time)} where |
| 24 | + * {@code lambda} is a constant and {@code time} specifies how long ago the increment happened. A <i>moving</i> rate is simply a rate |
| 25 | + * calculated for an every-growing series of increments (typically by updating the previous rate rather than recalculating from scratch). |
| 26 | + * |
| 27 | + * <p>This class is thread-safe. |
| 28 | + */ |
| 29 | +public class ExponentiallyWeightedMovingRate { |
| 30 | + |
| 31 | + // The maths behind this is explained in section 2 of this document: https://github.com/user-attachments/files/19166625/ewma.pdf |
| 32 | + |
| 33 | + // This implementation uses synchronization to provide thread safety. The synchronized code is all non-blocking, and just performs a |
| 34 | + // fixed small number of floating point operations plus some memory reads and writes. If they take somewhere in the region of 10ns each, |
| 35 | + // we can do up to tens of millions of QPS before the lock risks becoming a bottleneck. |
| 36 | + |
| 37 | + private final double lambda; |
| 38 | + private final long startTimeInMillis; |
| 39 | + private double rate; |
| 40 | + long lastTimeInMillis; |
| 41 | + |
| 42 | + /** |
| 43 | + * Constructor. |
| 44 | + * |
| 45 | + * @param lambda A parameter which dictates how quickly the average "forgets" older increments. The weight given to an increment which |
| 46 | + * happened a time {@code timeAgo} milliseconds ago will be proportional to {@code exp(-1.0 * lambda * timeAgo)}. The half-life |
| 47 | + * (measured in milliseconds) is related to this parameter by the equation {@code exp(-1.0 * lambda * halfLife)} = 0.5}, so |
| 48 | + * {@code lambda = log(2.0) / halfLife)}. This may be zero, but must not be negative. |
| 49 | + * @param startTimeInMillis The time, in milliseconds since the epoch, to consider the start time for the rate calculation. This must be |
| 50 | + * greater than zero. |
| 51 | + */ |
| 52 | + public ExponentiallyWeightedMovingRate(double lambda, long startTimeInMillis) { |
| 53 | + if (lambda < 0.0) { |
| 54 | + throw new IllegalArgumentException("lambda must be non-negative but was " + lambda); |
| 55 | + } |
| 56 | + if (startTimeInMillis <= 0.0) { |
| 57 | + throw new IllegalArgumentException("lambda must be non-negative but was " + startTimeInMillis); |
| 58 | + } |
| 59 | + synchronized (this) { |
| 60 | + this.lambda = lambda; |
| 61 | + this.rate = Double.NaN; // should never be used |
| 62 | + this.startTimeInMillis = startTimeInMillis; |
| 63 | + this.lastTimeInMillis = 0; // after an increment, this must be positive, so a zero value indicates we're waiting for the first |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Returns the EWMR at the given time, in millis since the epoch. |
| 69 | + * |
| 70 | + * <p>If there have been no increments yet, this returns zero. |
| 71 | + * |
| 72 | + * <p>Otherwise, we require the time to be no earlier than the time of the previous increment, i.e. the value of {@code timeInMillis} |
| 73 | + * for this call must not be less than the value of {@code timeInMillis} for the last call to {@link #addIncrement}. If this is not the |
| 74 | + * case, the method behaves as if it had that minimum value. |
| 75 | + */ |
| 76 | + public double getRate(long timeInMillis) { |
| 77 | + synchronized (this) { |
| 78 | + if (lastTimeInMillis == 0) { // indicates that no increment has happened yet |
| 79 | + return 0.0; |
| 80 | + } else if (timeInMillis <= lastTimeInMillis) { |
| 81 | + return rate; |
| 82 | + } else { |
| 83 | + // This is the formula for R(t) given in subsection 2.6 of the document referenced above: |
| 84 | + return expHelper(lastTimeInMillis - startTimeInMillis) * exp(-1.0 * lambda * (timeInMillis - lastTimeInMillis)) * rate |
| 85 | + / expHelper(timeInMillis - startTimeInMillis); |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Given the EWMR {@code currentRate} at time {@code currentTimeMillis} and the EWMR {@code oldRate} at time {@code oldTimeMillis}, |
| 92 | + * returns the EWMR that would be calculated at {@code currentTimeMillis} if the start time was {@code oldTimeMillis} rather than the |
| 93 | + * {@code startTimeMillis} passed to the parameter. This rate incorporates all the increments that contributed to {@code currentRate} |
| 94 | + * but not to {@code oldRate}. The increments that contributed to {@code oldRate} are effectively 'forgotten'. All times are in millis |
| 95 | + * since the epoch. |
| 96 | + * |
| 97 | + * <p>Normally, {@code currentTimeMillis} should be after {@code oldTimeMillis}. If it is not, this method returns zero. |
| 98 | + * |
| 99 | + * <p>Note that this method does <i>not</i> depend on any of the increments made to this {@link ExponentiallyWeightedMovingRate} |
| 100 | + * instance, or on its {@code startTimeMillis}. It is only non-static because it uses this instance's {@code lambda}. |
| 101 | + */ |
| 102 | + public double calculateRateSince(long currentTimeMillis, double currentRate, long oldTimeMillis, double oldRate) { |
| 103 | + if (currentTimeMillis <= oldTimeMillis) { |
| 104 | + return 0.0; |
| 105 | + } |
| 106 | + // This is the formula for R'(t, T) given in subsection 2.7 of the document referenced above: |
| 107 | + return (expHelper(currentTimeMillis - startTimeInMillis) * currentRate - expHelper(oldTimeMillis - startTimeInMillis) * exp( |
| 108 | + -1.0 * lambda * (currentTimeMillis - oldTimeMillis) |
| 109 | + ) * oldRate) / expHelper(currentTimeMillis - oldTimeMillis); |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Updates the rate to reflect that the gauge has been incremented by an amount {@code increment} at a time {@code timeInMillis} in |
| 114 | + * milliseconds since the epoch. |
| 115 | + * |
| 116 | + * <p>If this is the first increment, we require it to occur after the start time for the rate calculation, i.e. the value of |
| 117 | + * {@code timeInMillis} must be greater than {@code startTimeInMillis} passed to the constructor. If this is not the case, the method |
| 118 | + * behaves as if {@code timeInMillis} is {@code startTimeInMillis + 1} to prevent a division by zero error. |
| 119 | + * |
| 120 | + * <p>If this is not the first increment, we require it not to occur before the previous increment, i.e. the value of |
| 121 | + * {@code timeInMillis} for this call must be greater than or equal to the value for the previous call. If this is not the case, the |
| 122 | + * method behaves as if this call's {@code timeInMillis} is the same as the previous call's. |
| 123 | + */ |
| 124 | + public void addIncrement(double increment, long timeInMillis) { |
| 125 | + synchronized (this) { |
| 126 | + if (lastTimeInMillis == 0) { // indicates that this is the first increment |
| 127 | + if (timeInMillis <= startTimeInMillis) { |
| 128 | + timeInMillis = startTimeInMillis + 1; |
| 129 | + } |
| 130 | + // This is the formula for R(t_1) given in subsection 2.6 of the document referenced above: |
| 131 | + rate = increment / expHelper(timeInMillis - startTimeInMillis); |
| 132 | + } else { |
| 133 | + if (timeInMillis < lastTimeInMillis) { |
| 134 | + timeInMillis = lastTimeInMillis; |
| 135 | + } |
| 136 | + // This is the formula for R(t_j+1) given in subsection 2.6 of the document referenced above: |
| 137 | + rate += (increment - expHelper(timeInMillis - lastTimeInMillis) * rate) / expHelper(timeInMillis - startTimeInMillis); |
| 138 | + } |
| 139 | + lastTimeInMillis = timeInMillis; |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Returns something mathematically equivalent to {@code (1.0 - exp(-1.0 * lambda * time)) / lambda}, using an implementation which |
| 145 | + * should not be subject to numerical instability when {@code lambda * time} is small. Returns {@code time} when {@code lambda = 0}, |
| 146 | + * which is the correct limit. |
| 147 | + */ |
| 148 | + private double expHelper(double time) { |
| 149 | + // This is the function E(lambda, t) defined in subsection 2.6 of the document referenced above, and the calculation follows the |
| 150 | + // principles discussed there: |
| 151 | + assert time >= 0.0; |
| 152 | + double lambdaTime = lambda * time; |
| 153 | + if (lambdaTime >= 1.0e-2) { |
| 154 | + // The direct calculation should be fine here: |
| 155 | + return (1.0 - exp(-1.0 * lambdaTime)) / lambda; |
| 156 | + } else if (lambdaTime >= 1.0e-10) { |
| 157 | + // Avoid taking the small difference of two similar quantities by using expm1 here: |
| 158 | + return -1.0 * expm1(-1.0 * lambdaTime) / lambda; |
| 159 | + } else { |
| 160 | + // Approximate exp(-1.0 * lambdaTime) = 1.0 - lambdaTime + 0.5 * lambdaTime * lambdaTime here (also works for lambda = 0): |
| 161 | + return time * (1.0 - 0.5 * lambdaTime); |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments