views:

491

answers:

5

I am looking for an algorithm that determines percentiles for live data capture.

For example, consider the development of a server application.

The server might have response times as follows: 17 ms 33 ms 52 ms 60 ms 55 ms etc.

It is useful to report the 90th percentile response time, 80th percentile response time, etc.

The naive algorithm is to insert each response time into a list. When statistics are requested, sort the list and get the values at the proper positions.

Memory usages scales linearly with the number of requests.

Is there an algorithm that yields "approximate" percentile statistics given limited memory usage? For example, let's say I want to solve this problem in a way that I process millions of requests but only want to use say one kilobyte of memory for percentile tracking (discarding the tracking for old requests is not an option since the percentiles are supposed to be for all requests).

Also require that there is no a priori knowledge of the distribution. For example, I do not want to specify any ranges of buckets ahead of time.

+7  A: 

If you want to keep the memory usage constant as you get more and more data, then you're going to have to resample that data somehow. That implies that you must apply some sort of rebinning scheme. You can wait until you acquire a certain amount of raw inputs before beginning the rebinning, but you cannot avoid it entirely.

So your question is really asking "what's the best way of dynamically binning my data"? There are lots of approaches, but if you want to minimise your assumptions about the range or distribution of values you may receive, then a simple approach is to average over buckets of fixed size k, with logarithmically distributed widths. For example, lets say you want to hold 1000 values in memory at any one time. Pick a size for k, say 100. Pick your minimum resolution, say 1ms. Then

  • The first bucket deals with values between 0-1ms (width=1ms)
  • Second bucket: 1-3ms (w=2ms)
  • Third bucket: 3-7ms (w=4ms)
  • Fourth bucket: 7-15ms (w=8ms)
  • ...
  • Tenth bucket: 511-1023ms (w=512ms)

This type of log-scaled approach is similar to the chunking systems used in hash table algorithms, used by some filesystems and memory allocation algorithms. It works well when your data has a large dynamic range.

As new values come in, you can choose how you want to resample, depending on your requirements. For example, you could track a moving average, use a first-in-first-out, or some other more sophisticated method. See the Kademlia algorithm for one approach (used by Bittorrent).

Ultimately, rebinning must lose you some information. Your choices regarding the binning will determine the specifics of what information is lost. Another way of saying this is that the constant size memory store implies a trade-off between dynamic range and the sampling fidelity; how you make that trade-off is up to you, but like any sampling problem, there's no getting around this basic fact.

If you're really interested in the pros and cons, then no answer on this forum can hope to be sufficient. You should look into sampling theory. There's a huge amount of research on this topic available.

For what it's worth, I suspect that your server times will have a relatively small dynamic range, so a more relaxed scaling to allow higher sampling of common values may provide more accurate results.

Edit: To answer your comment, here's an example of a simple binning algorithm.

  • You store 1000 values, in 10 bins. Each bin therefore holds 100 values. Assume each bin is implemented as a dynamic array (a 'list', in Perl or Python terms).
  • When a new value comes in:

    • Determine which bin it should be stored in, based on the bin limits you've chosen.
    • If the bin is not full, append the value to the bin list.
    • If the bin is full, remove the value at the top of the bin list, and append the new value to the bottom of the bin list. This means old values are thrown away over time.
  • To find the 90th percentile, sort bin 10. The 90th percentile is the first value in the sorted list (element 900/1000).

If you don't like throwing away old values, then you can implement some alternative scheme to use instead. For example, when a bin becomes full (reaches 100 values, in my example), you could take the average of the oldest 50 elements (i.e. the first 50 in the list), discard those elements, and then append the new average element to the bin, leaving you with a bin of 51 elements that now has space to hold 49 new values. This is a simple example of rebinning.

Another example of rebinning is downsampling; throwing away every 5th value in a sorted list, for example.

I hope this concrete example helps. The key point to take away is that there are lots of ways of achieving a constant memory aging algorithm; only you can decide what is satisfactory given your requirements.

ire_and_curses
Thank you for your good insights, but I can't glean enough from this to actually do an implementation. The links you gave don't mention percentiles or "rebinning". You wouldn't happen to know of any references which are dedicated to the topic at hand?
binarycoder
@binarycoder: I've added an example to my answer to try and make what I'm saying a little more concrete. Hope it helps.
ire_and_curses
+1  A: 

Use a dynamic array T[] of large integers or something where T[n] counts the numer of times the response time was n milliseconds. If you really are doing statistics on a server application then possibly 250 ms response times are your absolute limit anyway. So your 1 KB holds one 32 bits integer for every ms between 0 and 250, and you have some room to spare for an overflow bin. If you want something with more bins, go with 8 bit numbers for 1000 bins, and the moment a counter would overflow (i.e. 256th request at that response time) you shift the bits in all bins down by 1. (effectively halving the value in all bins). This means you disregard all bins that capture less than 1/127th of the delays that the most visited bin catches.

If you really, really need a set of specific bins I'd suggest using the first day of requests to come up with a reasonable fixed set of bins. Anything dynamic would be quite dangerous in a live, performance sensitive application. If you choose that path you'd better know what your doing, or one day you're going to get called out of bed to explain why your statistics tracker is suddenly eating 90% CPU and 75% memory on the production server.

As for additional statistics: For mean and variance there are some nice recursive algorithms that take up very little memory. These two statistics can be usefull enough in themselves for a lot of distributions because the central limit theorem states that distributions that that arise from a sufficiently large number of independent variables approach the normal distribution (which is fully defined by mean and variance) you can use one of the normality tests on the last N (where N sufficiently large but constrained by your memory requirements) to monitor wether the assumption of normality still holds.

jilles de wit
<If you really are doing statistics on a server application> I am interesting in collecting more kinds of statistics, not just response times. It is not always easy to determine proper bounds. So, I'm looking for a general-purpose solution. Thanks.
binarycoder
+2  A: 

I believe there are many good approximate algorithms for this problem. A good first-cut approach is to simply use a fixed-size array (say 1K worth of data). Fix some probability p. For each request, with probability p, write its response time into the array (replacing the oldest time in there). Since the array is a subsampling of the live stream and since subsampling preserves the distribution, doing the statistics on that array will give you an approximation of the statistics of the full, live stream.

This approach has several advantages: it requires no a-priori information, and it's easy to code. You can build it quickly and experimentally determine, for your particular server, at what point growing the buffer has only a negligible effect on the answer. That is the point where the approximation is sufficiently precise.

If you find that you need too much memory to give you statistics that are precise enough, then you'll have to dig further. Good keywords are: "stream computing", "stream statistics", and of course "percentiles". You can also try "ire and curses"'s approach.

redtuna
I dunno. This replacement algorithm would seem to clearly introduce bias against old data. This is why I'd really appreciate a proper mathematical argument as to the robustness of any solution.
binarycoder
If the live data is taken from some distribution D, then a subsampling -any subsampling- will also derive from D. If the live data instead is not taken from some distribution, then a list of percentiles might not be the most enlightening thing to look for.
redtuna
Keywords are helpful.. Searching for "quantile" and "stream" bring up all kinds of research on this subject! All of techniques seem a lot more involved than any of the algorithms suggested here. Which is why I'm hesitant to mark anything as "the answer".
binarycoder
I am accepting this as the "best" answer. But to do an unbiased "reservoir sampling" p must be reservoirSize/totalSamplesSoFar. Also, the element to evict must be chosen at random (not the oldest).
binarycoder
+3  A: 

I've just published a blog post on this topic. The basic idea is to reduce the requirement for an exact calculation in favor of "95% percent of responses take 500ms-600ms or less" (for all exact percentiles of 500ms-600ms)

You may use any number of buckets of any arbitrary size (e.g. 0ms-50ms,50ms-100ms, ... just anything that fits your usecase). Normally, it shouldn't be a problem to but all requests that exceed a certain response time (e.g. 5 seconds for a web application) in the last bucket (i.e. > 5000ms).

For each newly captured response time, you simply increment a counter for the bucket it falls into. To estimate the n-th percentile, all that's needed is summing up counters until the sum exceeds n percent of the total.

This approach only requires 8 byte per bucket, allowing to track 128 buckets with 1K of memory. More than sufficient for analysing response times of a web application using a granularity of 50ms).

As an example, here is a Google Chart I've created from 1 hour of captured data (using 60 counters with 200ms per bucket):

response times

Nice, isn't it? :) Read more on my blog.

sfussenegger
Although some applications will need a more sophisticated bucketing algorithm, that sure is a really cool way to display percentile data!
binarycoder
I've just changed the colors of the chart (was http://j.mp/kj6sW) and the result is even cooler. Now it's quite easy to get approximate percentiles for the last 60 minutes of the application's responses. Might be that some applications need exact data. For most web applications (and similar severs) it should be perfectly sufficient though.
sfussenegger
A: 

Try the simple algorithm defined in the paper “Sequential Procedure for Simultaneous Estimation of Several Percentiles” (Raatikainen). It’s fast, requires 2*m+3 markers (for m percentiles) and tends to an accurate approximation quickly.