Skip to content
Silver 4 min read · Aggregation 2 practice problems ↓

percentile_approx

Medians and 95th percentiles describe data better than averages, but an exact percentile on billions of rows needs them all sorted in one place. percentile_approx gives an almost exact answer with a tiny fraction of the work. This lesson shows how, and what the accuracy setting buys.

Step 1 · PySpark functions · Silver · Smarter aggregates, lesson 2 of 2

Read first: groupBy + agg (skip if you know it)

In plain words first

To find the median height in a stadium exactly, you would line up every person by height and find the middle one. To get very close, you can ask each section for a short summary of their heights and combine the summaries. You may be off by a centimetre, but you never had to line up 50,000 people.

percentile_approx is the summary method: small notes per partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →, merged together, accurate to within a margin you choose.

Why not exact?

An exact percentile needs every value of a group sorted in one place. Unlike sum or count, it cannot be pre-aggregated per partition. On a group with a billion rows that is a lot of memory and a slow sort. An approximate sketch stores a small summary of the distribution instead, and two sketches can be merged, so it works like any other partial aggregationaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →.

Step by step

For /api, the 10 latencies sorted are 12, 15, 18, 22, 25, 31, 40, 55, 90, 400.

StatisticValueComment
Average70.8 msPulled up by the 400 ms outlier
Median (p50)25 msHalf the requests are faster than this
p9090 ms9 in 10 requests are faster than this

Latency is the classic case for percentiles: the average describes no real request, while p50 and p90 describe what users experience.

Run the example

PySparkSpark SQL

Input: latency

endpointms
/api12
/api15
/api18
/api22
/api25
/api31
/api40
/api55
/api90
/api400
/web80
/web95
/web120
from pyspark.sql import functions as F
result = latency.groupBy("endpoint").agg(
    F.round(F.avg("ms"), 1).alias("avg_ms"),
    F.percentile_approx("ms", 0.5).alias("p50"),
    F.percentile_approx("ms", 0.9).alias("p90"),
)
SELECT endpoint,
       ROUND(AVG(ms), 1)                AS avg_ms,
       percentile_approx(ms, 0.5)       AS p50,
       percentile_approx(ms, 0.9)       AS p90
FROM latency
GROUP BY endpoint

The playground computes exact nearest-rank values on small data. Real Spark returns an actual value from the data within the error bound, which on small groups is usually exact too.

The accuracy argument

  • The third argument, default 10,000, controls the sketch size. The relative error of the rank is roughly 1 / accuracy: with 10,000, the returned value's rank is within about 0.01% of the requested one.
  • Higher accuracy means more memory per group and a slower merge. With millions of groups, lowering it (for example to 1,000) can matter.
  • Pass a list of percentages to get several in one pass: percentile_approx("ms", [0.5, 0.9, 0.99]) returns an arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more →.

Related functions

FunctionExact?Notes
percentile_approx / approx_percentileNoScales; returns a value from the data
medianExact (3.4+)Convenient; needs all values of a group
percentile(col, p)ExactInterpolates between values, so may return a value not in the data
DataFrame.approxQuantileNoWhole-DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more →, not per group; returns Python values to the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more →

Common mistakes

  • Reporting average latency — Outliers dominate. Report p50, p90 and p99.
  • Using exact percentile on huge groups — Memory-heavy and slow; percentile_approx was designed for this.
  • Expecting interpolation — percentile_approx returns an actual value from the data, unlike percentile.

Key takeaways

  • Exact percentiles need all of a group's values together; approximate ones merge sketches.
  • Relative rank error is about 1 / accuracy (default 10,000).
  • Pass a list to compute several percentiles in one pass.
  • percentile_approx returns real values; percentile interpolates.

Interview prep

THE QUESTION

"Compute p95 latency per endpoint per minute over a year of logs."

Group by endpoint and the minute (date_trunc), aggregate with percentile_approx(ms, 0.95). Explain why approximate: an exact percentile cannot be pre-aggregated, while sketches merge across partitions. Mention the accuracy knob for memory if there are millions of groups.

Avoid: sorting all latencies per group. That cannot scale to a year of logs; sketches can.

Follow-ups · answer out loud, then open

Follow-up"What does the accuracy parameter control?"
The default is 10,000. The relative error is about 1/accuracy, so higher accuracy means more memory per group and a more precise result. For dashboards the default is usually enough.
Scenario"You want p50, p90 and p99 per endpoint. Do you need three aggregations?"
No. Pass an array of percentages: F.percentile_approx("ms", [0.5, 0.9, 0.99]) returns an array, from one sketch. Then pick the elements.
Trap"The average of daily p95 values is the monthly p95."
Percentiles do not average. Compute the monthly p95 from the raw data, or merge sketches if your system stores them.

Check yourself

3 questions

Why can percentile_approx be pre-aggregated per partition while an exact percentile cannot?

Show the answer

Sketches summarise the distribution and can be merged. Each partition builds a sketch, and sketches merge, so only small summaries are shuffled.

What does raising the accuracy argument do?

Show the answer

Reduces error but uses more memory. A bigger sketch gives a smaller rank error at the cost of memory and merge time.

Which may return a value that does not appear in the data?

Show the answer

percentile. percentile interpolates between neighbouring values.

Practise this

Problems that use percentile_approx, graded on hidden tests

Keep going

Up next · new module: Arrays and nested data · 4 min read
explode
Turn each array element into its own row, and the rows explode silently drops.

Related lessons

Previous: max_by / min_by

Primary sources: functions.percentile_approx · functions.median