跳到正文
DEV Community· Ashutosh Sahu·· 6 小時前AI 評分45

大規模計算延遲百分位數

Calculating percentiles at scale

AI 導讀

團隊為提升分析儀錶板計算 API 延遲百分位數的效率,提出按時間桶預先彙總延遲分佈,再合併直方圖計算近似值。直方圖採用 1000ms 分桶,目標是讓結果與實際值偏差控制在 5% 內;方案亦會減少部分難以高效支援的篩選條件。

正文

Some times ago, We designed an analytics dashboard with lots of analytical aggregated information, most of which we didn't know why was needed there.

We had a bunch of Third Party APIs, and based on the requests, their responses and timings used to differ. It was decided that all the requests will be logged in our database for analytics purpose, along with their latencies, the dashboard will have a dedicated section to show the p50, p95, and p99 latencies. Any unusual spikes in latency would be noticed and alerted accordingly.

Before moving forward, let me tell you the tech stack:

  • MSSQL for database
  • Node.js for backend

That's all we need to know.

The mistake

Initially, we tried to calculate the percentiles directly from the raw request logs stored in the database, expecting that simple queries and basic indexing would be enough.

Then came the api integrations, some of these APIs had either extremely high latencies like going upto 40 seconds, some of them required us to poll repeatedly until a certain condition was met. Irrespective of all these, we continued to log them directly in the database. we had a timeout threshold of 60 seconds which means no request will go beyond this point in time.

Our dashboard had filters - date range with minute level granularity, endpoint selection, query params selection, response status, and other important values, and by default, we were showing the latency over the week, with none of the other filters applied.

It didn't take longer to realize that querying raw logs for percentiles was becoming increasingly inefficient and slow, especially as the volume of data grew and the variability in request latencies widened. In the test environment, with limited data, the dashboard APIs started taking more than 26s to return with the default filters.

Trying the fix

We had to launch it, so we didn't had enough time to properly look at the problem. Still we went through couple of iterations:

  • First, we were calculating percentiles after fetching all the records in node. we moved it to calculating percentiles directly in the database using SQL queries.
  • for filters, we created individual indexes and composite indexes on the columns that were frequently used together.
  • In the final iteration, asking claude, we found that our SQL query was calculating p50, p95 and p99 separately, it suggested changes that helped us calculate all in a single pass, bringing down the query execution time significantly.

Finally, the dashboard loaded faster within 5-6 seconds with default filters. However, changing date filters to months, still caused us to wait long and get a timeout eventually. Challenge accepted.

Pre-computing percentiles

The first thing come to my mind was using timeseries or similar kind of db extensions that auto pre-compute and store the percentiles for different time intervals. For now 1m and 1hr buckets would be enough. Then based on time range I just need to do some average or median of these pre-computed percentiles to get an approximate result.

There was a problem, It's not a postgres db. So what, we can build around tables by ourselves and manage them just like timeseries extensions do, by creating and maintaining pre-aggregated tables for different time intervals and updating them as new data comes in.

Only mistake was that I didn't touched the percentile math at all. Thankfully, I went to brainstorm the idea first with claude.

Percentiles are not additive, they don't work like count, sum, avg, min/max where you can combine pre-aggregated values to get the overall result. A percentile is a rank position in a sorted distribution. If a minute bucket has 10 requests, but another minute bucket has 100 requests, simply averaging the percentiles of these buckets will not reflect the true percentile of the combined 110 requests. The distribution of values within each bucket matters, and ignoring it leads to incorrect results.

Deciding tradeoffs and considerations

  1. We don't want exactly accurate percentiles, if we can get appproximate results which are deviating within 5% of the actual value, thats fine. what it means?

    • if the p95 is 100ms, getting a result between 95ms and 105ms is acceptable.
    • if the p95 is 55s, getting a result between 52.2s and 57.7s is acceptable. This would seem huge, but for high-latency operations, a 5% deviation is tolerable and still provides meaningful insights preventing false alerts.
  2. We are ok with reducing some filters, which are hard to support efficiently at scale, as long as the core insights and critical metrics remain accurate and actionable.

  3. We don't want to remove minute level granularity in the date range filters, simply because we are lazy to redesign the date component to allow user to select finer intervals.

  4. It's still a MVP and we don't want to move the data to a separate BI system or introduce complex ETL pipelines at this stage. We aim to keep the solution simple and maintainable within the existing infrastructure.

The approach for efficiently calculating percentiles

The key idea is to pre calculate the counts and distributions of the values within time buckets along with filters.

Instead of storing individual request times, we can store a histogram of latencies for each minute or hour bucket. Each histogram will capture the distribution of latencies within that time interval. When a query comes in for a larger time range, we can merge the histograms of the relevant buckets and then calculate approximate percentiles from the combined histogram. This allows us to efficiently compute percentiles over large datasets without scanning every individual record. Don't worry, I will explain it with example later on.

Our requests usaully have latencies in range of 5s to 1m, after which they get a timeout. we decided to use 1000ms buckets for the histograms, which gives us a good balance between accuracy and storage efficiency. we reduced down these filters:

  • response code - we only care about successful requests, any 4xx or higher status usually returns very early. not contributing to the percentiles.
  • user and other high cardinality attributes, because they are not suitable for histograms.

after this, we are left with the 3 filters and fixed 30×2×3=180 values. still high but manageable, if it's skewed.

so now we have 2 tables representing histograms over time buckets of 1m and 1h, looking like this:

time filter_1 filter_2 filter_3 b0_1s b1_2s b2_3s ... b59_60s total
2026-12-01 12:00 Abc a true 0 0 22 ... 0 590
2026-12-01 12:01 Def b false 1 0 18 ... 0 483

so now we have count of requests that fall under each latency bucket and filter.

calculating percentiles for the date range 12:00 to 12:01, with the filter combination filter_1 = Abc, filter_2 = a, filter_3 = true looks like this:

  • merge the histograms for the relevant time buckets (12:00 and 12:01) for each filter combination.
  • sum the counts for each latency bucket and the total column across the rows from 12:00 to 12:01 that matches the filter combination.
  • results:

b2_3s=22+18=40b3_4s=18+39=57b4_5s=0+48=48…b35_36s=78+29=107total=40+57+48+107=252

  • calculate percentile range:

p50=0.5×252=126p90=0.9×252=226.8

  • That means p50 is the 126th request in the sorted order of latencies, and p90 is the 227th request.
  • commulative count of requests by latency bucket:

b2_3s+b3_4s=40+57=97b2_3s+b3_4s+b4_5s=40+57+48=145

  • so p50 lies somewhere in b4_5s time range:

126−97=29

  • so the 126th request lies 29 requests into the b4_5s bucket.
  • b4_5s has 48 requests in total, assuming they are evenly distributed into the b4_5s bucket. so the p50 latency is approximately:

2948×1000ms≈604ms 4s+604ms≈4.604s

Even if it's not perfectly uniform distribution, with this bucket range, the maximum error will be within 1s range, while we accepted the error at around 2.2s in our tradeoffs. so practically, we can increase the bucket size to 2s for better storage efficiency without significantly affecting the accuracy.

The math looks terrible here, lot's of operations, but this is still significantly more efficient than sorting all individual request latencies, especially at scale.
We can do this all computation directly in SQL using queries too, saving a lot of memory and processing time compared to fetching and sorting all individual request latencies.

Scaling further

  • We can improve storage and computation by increasing the bucket size.
  • We also can add another level of aggregation, such as daily or weekly histograms, to further reduce storage and computation requirements for larger date range queries.
  • We can improve the date range filters by restricting to 5minute granularity, which reduces the number of time buckets we need to process.

Note: AI is only used to format the Katex(Latex math) in this document because Dev.to Latex support is terrible

來源:DEV Community · dev.to