Skip to content

Add blog post: TopK per partition with enable_window_topn - #219

Open
Inf1mum wants to merge 5 commits into
apache:mainfrom
Inf1mum:blog/topk-per-partition
Open

Inf1mum wants to merge 5 commits into
apache:mainfrom
Inf1mum:blog/topk-per-partition

Conversation

@Inf1mum

@Inf1mum Inf1mum commented Nov 13, 2026 •

Copy link
Copy Markdown

Rendered version: https://inf1mum.github.io/datafusion-site/blog/2026/11/13/topk-per-partition/ — GitHub Pages preview built from this branch with the ASF-Pelican build (same approach as the preview in #203).

Add a self-contained blog post about the "TopK per partition" optimization for window functions (PartitionedTopKExec / datafusion.optimizer.enable_window_topn), as requested in apache/datafusion#27233: apache/datafusion#27233

About the post

The post expands the draft section written for the DataFusion 55 release post (the draft in the issue, by Andrew Lamb, who also wrote the request) into a full informative post following the "low-key DataFusion pitch" pattern of the Dynamic Filters and Sort Pushdown posts. Structure:

  • The "top N per group" use case (including the h2o/db-benchmark query-8 shape)
  • Background: the default plan sorts the entire input, O(N log N) time and O(N) memory
  • How to use it in DataFusion 55: SET datafusion.optimizer.enable_window_topn = true, before/after EXPLAIN output, which queries the WindowTopN rule applies to, and how to turn it off
  • How it works: per-partition bounded heaps, shared RowConverter/MemoryReservation, ROW_NUMBER vs RANK retention semantics, emission order
  • Benchmarks with the verified numbers from the introducing PR (#21479), including the honest high-cardinality regression cliff and why the feature is behind a flag
  • Status and roadmap: ROW_NUMBER + RANK in 55, DENSE_RANK on main (#23869), the open enable-by-default EPIC (#24608 / #27197) — stated accurately as of today
  • Remaining work, acknowledgements, and references

Coordination / credits

Per the issue's note that blog posts help raise author visibility: the post credits SubhamSinghal (feature implementation), 2010YOUY01 and kosiew (reviews), jayzhan211 (memory optimizations), saadtajwar, stuhood, viirya, and zhuqi-lucas (further contributions), and Andrew Lamb (draft section this post grew out of), with links to their GitHub profiles.

Facts and validation

  • All technical claims, the benchmark table, and version status are taken from the issue, the linked draft, the 55.0.0 source (datafusion/physical-optimizer/src/window_topn.rs, datafusion/physical-plan/src/sorts/partitioned_topk.rs, config.rs), the window_topn.slt sqllogictest EXPLAIN output, and the linked PRs — no invented numbers. The "enable by default" work is described as in-flight (the PR is still open at the time of writing).
  • Front matter and structure mirror recent posts in this repo (e.g. 2026-07-20-sort-pushdown.md, 2026-10-24-point-queries.md).
  • Local validation: the post was validated with a standalone Pelican build (processed 1 article, HTML renders title, tables, and code blocks correctly), and the typos check passes. The front matter is identical in shape to sibling posts, and CI's pelican build will be the authoritative check.

Review

Review would be most valuable from the feature authors, in particular SubhamSinghal (https://github.com/SubhamSinghal), jayzhan211 (https://github.com/jayzhan211), and alamb (https://github.com/alamb), to check that the technical description and benchmark framing match their intent.

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Inf1mum plese review this and rework it / remove unecessary content . It should be in your words, not a LLM generated post

DataSourceExec
```

This plan:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please expand here with an explanation of how this operator works? This is not enough detail to follow I don't think

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed - the walkthrough now goes stage by stage: SortExec does a blocking, spill-capable sort of all N rows because the window needs each partition contiguous and ordered; BoundedWindowAggExec walks the sorted stream and numbers every row (it holds state only for the open partition, but touches all N); the filter then keeps rn <= K and throws the rest away.

Also folded in the concrete ratio (10M rows / 1K partitions / K=3 → 3K survivors, 0.03%), and moved "How It Works" before the usage section so the new operator is explained before it appears in the second EXPLAIN.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done -- the How It Works section now opens with a plain-language description: the operator keeps the top K rows per distinct partition key in a hash map of bounded heaps, reads the unsorted input once, and evicts everything else. The Rust-level detail is gone; the section links to the source instead.

operator works, and reports the measured performance — including the cases
where it is *not* a good fit.

This post grew out of a draft section [@alamb] wrote for the [DataFusion

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is irrelevant detail

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut. The intro now runs one example only (top five products per category), so this listing of other use cases is gone.

@alamb
alamb marked this pull request as draft November 13, 2026 19:44
SET datafusion.optimizer.enable_window_topn = false;
```

## How It Works

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would put this into beginning

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved up. The point that the operator emits rows already grouped and ordered -- all the window function needs -- is now in the first paragraph of How It Works, and the dedicated emission-order subsection is gone.

| --------------------------------- | ------: | -------: | ----------- |
| 100 partitions (100K rows each) | 43 ms | 174 ms | **4.0x** |
| 1K partitions (10K rows each) | 71 ms | 146 ms | **2.1x** |
| 10K partitions (1K rows each) | 619 ms | 128 ms | **0.2x** (regression) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would be good to come up with golden partition num number and also the reason why regression happens

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured this on a released build (55.2.0, exact h2o group-by Q8 shape, 10M rows, K=2, min of 4 runs) — two things turned up:

  • The published table predates #23096 (shared encoder/reservation), which is already in the 55.0.0 changelog — so the 10K-partition regression doesn't reproduce on released 55.x: the rewrite is ~5.6x faster there. The old numbers are real for the #21479-era build, so the post keeps them labeled "as measured in #21479" and adds a fresh sweep.
  • On 55.2.0 the crossover sits between ~50K and ~60K partitions — roughly 150–200 rows per partition at K=2. The reason the regression happens beyond that: the enabled-plan cost grows linearly with P (~5–6 µs per distinct partition key — a hash probe into P heap states per row, one heap + hash-map entry per key, an O(P log P) emit sort), while the sort it replaces stays roughly flat in P. And unlike SortExec, PartitionedTopKExec has no spill path (memory is O(K×P×row_size)), so it can't degrade gracefully the way the sort does. The window operator on top adds its own ~4 µs/partition on top of that.

Reworking the section now with the fresh table and fixing the "follow-up work on main" sentence.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need to try and detail the history of the development -- i recommend dropping this section entirely and just presenting the numbers in the next section "Performance Improvement"

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The results now state it plainly: up to about 10,000 partitions the new plan is 4-7x faster; above 50,000 it gets worse, because every distinct partition key adds a heap and a hash-map entry, so very high-cardinality keys cost more than the sort they replace. I kept the measured 50,000 crossover from this sweep rather than picking a rounder number.

What: restructure and expand the Top N per group post per review remarks.
Why: alamb asked for a fuller explanation of the default plan (L105) and
flagged the draft-provenance paragraph as irrelevant detail (L56);
comphead asked to move the mechanism section before the usage section (L166).
How: expanded the three-stage default-plan walkthrough with per-stage
mechanics (blocking spill-capable sort, bounded window numbering, filter
selectivity); deleted the provenance paragraph and its now-unused link def;
moved How It Works (with its subsections) directly after the default-plan
section so the operator is explained before it appears in the second
EXPLAIN output.
What: rework the benchmark section — keep the original table labeled as
pre-#23096, add a fresh partition sweep on DataFusion 55.2.0, and correct
the follow-up-work sentence.
Why: comphead asked for a golden partition number and the reason for the
regression; on released 55.x the 10K-partition regression does not
reproduce because #23096 is already in the 55.0.0 changelog, so the old
'follow-up work on the main branch' claim was wrong.
How: new sweep table (h2o group-by Q8 shape, 10M rows, K=2, min of 4 runs,
crossover between ~50K and ~60K partitions ≈ 150-200 rows/partition), the
two regression mechanisms (linear per-partition overhead vs flat sort
baseline; no spill path in PartitionedTopKExec + window-operator
per-partition cost), one-line trade-off summary.
@Inf1mum
Inf1mum requested review from alamb and comphead November 15, 2026 18:43
@comphead

Copy link
Copy Markdown
Contributor

Thanks @Inf1mum appreciate if you can provide a rendered version link, so we can go though it, please check earlier blogposts how to gen the link

What: rewrite the prose in a plain first-person voice, cut redundant
passages, and keep all technical facts, config names, code blocks,
tables, and the heading structure unchanged.
Why: alamb asked for the post to be reworked and written in the
author's own words rather than as an LLM-generated post.
How: deleted the roadmap-style intro paragraph and the pattern-section
bullet list that repeated the intro examples; merged the duplicated
trade-off paragraphs in the benchmarks section into one; folded the
'if you try this' paragraph into the Get Involved list; replaced
formulaic connective phrasing with shorter sentences; wrote the
benchmark-intro sentence in first person (I re-ran the same shape on
55.2.0). Diff: 62 insertions, 79 deletions in one file.

Signed-off-by: Inf1mum <vadimlazuk5@gmail.com>
@Inf1mum

Inf1mum commented Nov 16, 2026

Copy link
Copy Markdown
Author

Both items, done in 5bcf8cd:

  1. Prose rewritten in a plain first-person voice. Deleted the roadmap-style intro paragraph and the pattern-section bullet list that repeated the intro examples; merged the two duplicated trade-off paragraphs in the benchmarks section into one; folded the "if you try this" paragraph into the Get Involved list; replaced the formulaic connective phrasing with shorter, direct sentences ("The plan is correct, but every stage does work on rows the filter later throws away:", "I re-ran the same shape on DataFusion 55.2.0: ..."). All config names, code blocks, tables, and the heading structure are unchanged — 62 insertions, 79 deletions in one file.

  2. Rendered version: https://inf1mum.github.io/datafusion-site/blog/2026/11/13/topk-per-partition/ — generated the way the 55.0.0 post preview did it: the branch is built with the ASF-Pelican build and deployed to GitHub Pages on the fork, so the preview URL matches the production URL shape. The link is also in the PR description now.

Ready for re-review.

@comphead

Copy link
Copy Markdown
Contributor

thanks, rendered version is much easier to read and follow

@Inf1mum

Inf1mum commented Nov 17, 2026

Copy link
Copy Markdown
Author

Thanks @comphead — glad it reads better now. Left the prose in the same register for the remaining sections; happy to adjust anything else that stands out.

@alamb
alamb marked this pull request as ready for review November 20, 2026 18:32

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @Inf1mum -- I wrote up quite a bit of feedback, hopefully it is helpful. It will likely take some time to implement but I think this blog will be much better for it

cc @SubhamSinghal as you were the primary author so I suspect you may be interested in this post too


*[Vadim Lazuk](https://github.com/Inf1mum)*

"Find the top N rows within each group" is one of the most common shapes in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in the intro of the article, you have only a few words to "hook" the reader so I think we should make this as concise as possible. For example, do we need to have all three examples? I think one makes the point

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also I am not sure I would call it "the most common shapes" -- maybe a "common shape" ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done -- the intro keeps only the top-five-products example; the latest-events and highest-paid variants are cut.

to compute the window function, and then throwing almost all of the sorted
output away. DataFusion 55 recognizes the pattern: with
[datafusion.optimizer.enable_window_topn] enabled, the full sort is replaced
by a new `PartitionedTopKExec` operator that keeps only the top N rows per

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe link to the operator documentation here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done -- the flag name in the intro links to the configuration documentation, and the operator and rule names link to their source files.

) WHERE rn <= 5;
```

Until recently, DataFusion evaluated this query by sorting the *entire* input

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could make this paragraph a more concise (it is the intro) by removing the detail on how to enable and the operator name - the main point of this paragraph I think is that DataFusion now has a specialized operator for this kind fo query and that it goes XXX times faster (we should figure out what XXX is and include that).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done -- the intro paragraph now makes exactly that point: DataFusion has a specialized operator for this pattern, and the same query runs up to 6.8x faster in the benchmarks below. The enable instructions moved to a short Using It section.


The query above computes the top five rows per `category`. The same shape
covers the latest events per device, the highest-paid employees per
department, and many other screens and reports. It is also query 8 of the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does "screen" mean in this context? I don't think the query 8 / db-benchmark reference is super releavant here and can be cut . The fact that the query is in benchmarks shouldn't be a surprise given the post claims it is a common query pattern

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and to be clear, I am asking what screen means because I think you could remove it and make this more concise)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut. The db-benchmark query-8 reference now appears once, in the performance section, simply as the source of the benchmark query; the intro no longer mentions it.

[h2o group-by benchmark]: https://github.com/h2oai/db-benchmark
[#13586]: https://github.com/apache/datafusion/issues/13586

What matters for the optimizer is the ratio: the filter keeps a *small, fixed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

THis paragraph feels out of place / too early -- you haven't introduced sorting or sort based plans yet and this is some sort of analysis of that plan

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved. That analysis now lives in its own short section, The Default Plan Sorts Everything, right after the sort-based plan is first shown -- three one-line bullets and one concrete sentence (10 million rows sorted to keep 3,000).

| 10,000 | 1,000 | 159 ms | 885 ms | 0.18x (5.6x faster) |
| 20,000 | 500 | 205 ms | 791 ms | 0.26x (3.9x faster) |
| 50,000 | 200 | 416 ms | 500 ms | 0.83x (≈ parity) |
| 60,000 | ~167 | 454 ms | 289 ms | 1.57x (regression) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would personally summarize this as "above 50,000 partitions performance gets worse"

Although I thought this was fixed in datafusion 56 ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used almost your wording: "above 50,000 partitions performance gets worse." On 56: the 56.0.0 changelog lists PartitionedTopK work (#25730, #25968) but nothing identified as fixing this regression, so the post reports the measured 55.2.0 crossover -- I left a marked question in the post; do you recall which change fixed it?

per partition** at `K = 2`. Past that the rewrite loses ground for two
reasons:

- **Per-partition overhead grows linearly with P.** Every row probes the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this analysis and below important to the story (aka that this is a good operator)?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut to what serves the story: two sentences that say why high-cardinality keys get worse and why that keeps the feature opt-in. The memory analysis below it is deleted.


## Status and Roadmap

As of DataFusion 55.0.0:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

List should be updated to be "as of 56"

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated -- the status list now reads "As of DataFusion 56.0.0 (released November 2026)", with each item dated to 56 or 57.

`datafusion.optimizer.enable_window_topn`.
- `DENSE_RANK` support has landed on the main branch
([#23869]) and is expected in an upcoming release.
- The optimization is **not yet enabled by default**. Work to flip the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this ticket is now fixed -- so the optimization will be enabled in 57 by default.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated -- the status section now says the optimization will be enabled by default in DataFusion 57, citing #27197 (merged after the 56.0.0 branch cut) and the closed EPIC #24608.


- [Further "per partition" top-k optimizations][#24060] — the umbrella for
the next round of improvements.
- [Support filters with embedded projections][#21596] — widen the set of

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think just the umbrella item (which links to the other tickets) is adequate

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done -- Remaining Work is now just the #24060 umbrella issue, which links to the individual tickets.

@alamb

alamb commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Hi @Inf1mum -- I am wondering if you will have time to address this feedback?

@alamb

alamb commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

I realize with the level of contribution across projects you may not have the time to help push this one throuh

Screenshot 2026-11-25 at 10 08 21 AM

@Inf1mum

Inf1mum commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks for the nudge @alamb -- and no worries about the timing question. The revision is pushed as one commit on the branch (2,496 to 1,638 words).

What changed: the window expression is explained in plain words first, with one worked example; K, N, and P are defined up front and the complexity change is stated once; internals like RowConverter are replaced by links to the source; the results section presents the numbers only; status is updated to off by default in 56, on by default in 57.

Two open points are marked as HTML comments in the post for you: (1) the diagram you offered to help with; (2) whether the above-50,000-partition regression is fixed in 56 -- the 56.0.0 changelog lists PartitionedTopK work but nothing identified as this fix, so the post reports the measured 55.2.0 crossover for now.

Rendered version, rebuilt from the new head: https://inf1mum.github.io/datafusion-site/blog/2026/11/13/topk-per-partition/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants