Windows in PySpark

Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:50 on Thursday. Tess's order-status board says the first week of June had 68 orders. The store took 40. Nothing is broken: the daily files in landing/orders/ send an order again every time its status changes, and the 3 June batch arrived twice. Nora: "One row per order, the latest. You wrote it in SQL in Module 2. Now write it in PySpark."

You'll learn to

  • Build a window with Window.partitionBy().orderBy() and use it with .over()
  • Keep the latest row per key, and the top N per group
  • Add lag, running totals and moving averages with explicit frames
  • Explain how Spark runs a window, and which frames are expensive

Learn

Keep every row, and look at its neighbours

A groupBy squeezes each group into one row. Sometimes you need every row kept, with a value from its neighbours beside it: its number among its order's versions, or yesterday's revenue next to today's. That is a window function, and Module 2 wrote it in SQL with OVER (PARTITION BY ... ORDER BY ...).

In PySpark you build the window once, as an object, then attach it to a function with .over(w):

from pyspark.sql import Window
w = Window.partitionBy('order_id').orderBy(F.desc('updated_at'))
drops.withColumn('rn', F.row_number().over(w))

The functions you know are all in F: row_number, rank, dense_rank, lag, lead, and sum, avg, count, min and max used with .over(w).

Module 2's SQL, and its PySpark twin

SQL (Module 2)PySpark
ROWNUMBER() OVER (PARTITION BY orderid ORDER BY updatedat DESC)F.rownumber().over(Window.partitionBy("orderid").orderBy(F.desc("updatedat")))
WHERE rn = 1, in an outer query, because a window cannot go in WHERE.filter(F.col("rn") == 1) straight after the withColumn
LAG(revenue) OVER (ORDER BY day)F.lag("revenue").over(Window.orderBy("day"))
SUM(revenue) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)F.sum("revenue").over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow))
AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)F.avg("revenue").over(w.rowsBetween(-2, 0))

Number the versions, keep the newest

The daily drops hold 68 rows for 40 orders. An order appears on the day it was placed and again each day its status changed, and the 3 June batch came twice. The board needs one row per order: its latest version.

The pattern is Module 2's. Partition by order_id, order newest first, number the rows with row_number, keep number 1. Add a tie-breaker to the orderBy, so the choice never depends on luck. Here two rows with the same updated_at are exact copies from the retry file, so any column works, but say it on purpose.

Why not dropDuplicates(['order_id'])? It keeps an arbitrary row per key, whichever a partition sees first: fine for exact copies, wrong whenever versions differ.

Order 1013, from three rows to one

Three landed rows of order 1013 meet in one window partition, are sorted newest first, are numbered 1 to 3, and only number 1, the shipped version, is kept.

  1. Three rows land. Order 1013 was placed on 3 June and shipped on 4 June. The 3 June row arrived twice, because that batch was retried.

  2. Partition and sort. partitionBy("order_id") puts all three rows in one window partition. orderBy sorts them newest first: the shipped version on top, the two placed copies tied below it.

  3. Number them. row_number gives 1, 2 and 3, and never repeats a number. The two copies tie on updated_at and on status, so which one is 2 is luck: harmless here, because they are identical.

  4. Keep rn = 1. One row survives: shipped. One filter removed the copy and the old version together.

Watch the right-hand box: one window partition, sorted, numbered, then filtered.

One row per order: the latest

from pyspark.sql import SparkSession, Window, functions as F

spark = SparkSession.builder.getOrCreate()
drops = spark.read.csv("landing/orders/*.csv", header=True, inferSchema=True)

w = Window.partitionBy("order_id").orderBy(F.col("updated_at").desc(), F.col("status"))
ranked = drops.withColumn("rn", F.row_number().over(w))
latest = ranked.filter(F.col("rn") == 1).drop("rn")

print("rows landed:", drops.count())
print("orders:", latest.count())
for r in ranked.filter(F.col("order_id") == 1013).orderBy("rn").collect():
    print(r["rn"], r["status"], r["updated_at"])

The last three lines print order 1013's rows with their numbers, as in the walkthrough.

Remember: the latest row per key is row_number over the key, newest first, with a tie-breaker. Keep 1, then drop the helper column.

How Spark runs a window

A window needs two things from the rows below it, and the planner adds both:

  1. All rows of a key in one task. A shuffle by the partitionBy columns: Exchange hashpartitioning(order_id, 200).
  2. Sorted. Each task sorts its rows by the partition columns, then by the orderBy columns.

Then the Window operator walks the sorted rows one key at a time. It copies that key's rows into a buffer: the first 4,096 rows go into a plain in-memory array, and beyond that into a sorter that spills to disk when memory runs out. It computes each row's value, emits the rows, clears the buffer, and moves to the next key.

So a window's memory is set by its largest key, not by the table.

The physical plan of the dedup window

A plan tree: a filter on rn, over a Window operator, over a sort by order_id, updated_at and status, over an exchange hash-partitioned by order_id, over the CSV scan.

Read it bottom up: the scan, the shuffle by order_id, the sort, then the window, then the filter on rn.

Inside one window task

Five steps down: rows arrive hashed by key, are sorted, one key is buffered at a time with 4,096 rows in memory before a spillable sorter takes over, the frame computes each value, and rows are emitted.

Order 1013 has three rows and never leaves memory. A bot account with 30 million events of about 120 bytes each needs 3.6 GB for its one window partition, in one task, so it spills while 199 tasks sit idle.

Top N per group, and what ties do

Tess's next question: the top 2 products by revenue in each category. It is the same shape. Partition by the group, order by the measure descending, keep rn <= 2.

The three ranking functions differ only on ties:

  • row_number gives every row a different number, so ties are broken by whatever comes next in orderBy (add a column that makes it deterministic).
  • rank gives tied rows the same number and then skips: 1, 2, 2, 4.
  • dense_rank gives tied rows the same number and does not skip: 1, 2, 2, 3.

Pick on purpose. "Exactly two products per category" is row_number; "everyone who shares second place" is rank or dense_rank.

Top 2 products per category, and a tie

from pyspark.sql import SparkSession, Window, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
products = spark.read.csv("data/products.csv", header=True, inferSchema=True)

lines = items.withColumn("line_amount", F.col("qty") * F.col("unit_price"))
per_product = (
    lines.groupBy("product_id").agg(F.round(F.sum("line_amount"), 2).alias("revenue"))
    .join(products.select("product_id", "name", "category"), "product_id")
)
w = Window.partitionBy("category").orderBy(F.desc("revenue"), "product_id")
top2 = per_product.withColumn("rn", F.row_number().over(w)).filter(F.col("rn") <= 2)
for r in top2.filter(F.col("category").isin("Electronics", "Sports")).orderBy("category", "rn").collect():
    print(r["category"], r["rn"], r["name"], r["revenue"])

by_price = Window.orderBy(F.desc("price"))
ranked = products.select(
    "product_id", "name", "price",
    F.row_number().over(Window.orderBy(F.desc("price"), "product_id")).alias("row_number"),
    F.rank().over(by_price).alias("rank"),
    F.dense_rank().over(by_price).alias("dense_rank"),
)
for r in ranked.filter(F.col("price").between(20, 25)).orderBy(F.desc("price"), "product_id").collect():
    print(r["name"], r["price"], r["row_number"], r["rank"], r["dense_rank"])

The first loop prints the top two of two categories; the second prints three products around a price tie.

Two products at $24.99

productpricerownumberrankdenserank
Desk Lamp (104)24.99111111
Cookbook (111)24.99121111
Canvas Tote (114)22.00131312

row_number split the tie by product_id because the window says so. rank skipped 12; dense_rank did not. A filter like rank <= 11 returns 12 products, not 11.

Looking back a row: lag and running totals

Now the other half of Module 2: questions that look across rows in time order, over Window.orderBy('day') on a small table of daily revenue.

  • Change since yesterday: F.col('revenue') - F.lag('revenue').over(w). The first day has no yesterday, so it gets null.
  • Running total: F.sum('revenue') over a frame from the first row to the current row.
  • 3-day moving average: F.avg('revenue') over rowsBetween(-2, 0), the current row and the two before it.

The rows a function sees for one row are its frame. Always write the frame with rowsBetween. Without one, a window with an orderBy uses a range frame, which treats rows with the same orderBy value as one block: the SQL default from Module 2.

A frame slides over customer 3's orders

Customer 3's four orders in time order; at each step the current row moves down one, the frame grows from the first row to the current one, and the running total and the previous amount are filled in.

  1. Row 1. The window is Window.partitionBy("customer_id").orderBy("order_ts"). The frame holds only this row: running total $177.55. lag looks one row back and finds nothing, so it gives null.

  2. Row 2. The frame now holds rows 1 and 2: running total $297.55. lag brings back the previous amount, $177.55.

  3. Row 3. Three rows in the frame: $646.52. A 3-row moving average, rowsBetween(-2, 0), would use exactly these three rows.

  4. Row 4. The frame covers the whole partition: $701.30, customer 3's total. The next customer starts a new partition, and the frame starts again.

Each step moves the amber row down by one; the teal rows above it are the rest of its running frame.

Daily revenue with change, running total and moving average

from pyspark.sql import SparkSession, Window, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)

lines = items.withColumn("line_amount", F.col("qty") * F.col("unit_price"))
daily = (
    lines.join(orders.filter(F.col("status") != "cancelled"), "order_id")
    .groupBy(F.to_date("order_ts").alias("day"))
    .agg(F.round(F.sum("line_amount"), 2).alias("revenue"))
)
w = Window.orderBy("day")
trend = (
    daily
    .withColumn("change", F.round(F.col("revenue") - F.lag("revenue").over(w), 2))
    .withColumn("running", F.round(F.sum("revenue").over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow)), 2))
    .withColumn("avg_3d", F.round(F.avg("revenue").over(w.rowsBetween(-2, 0)), 2))
)
for r in trend.orderBy("day").limit(6).collect():
    print(r["day"], r["revenue"], r["change"], r["running"], r["avg_3d"])

The same three functions, on 14 days of revenue instead of one customer's orders.

Slide a frame over ordered rows

Rows ordered by day with a highlighted frame that slides down one row at a time, showing which rows a running total or a three-row moving average adds up.

Pick sum or lag, turn PARTITION BY on and off, and step through the rows: the outlined rows are the ones each value comes from.

The frame that costs n squared

Spark picks a frame implementation from the frame you write, and their costs differ:

  • Whole partition (no orderBy, or unbounded on both sides): computed once per key, then copied to every row.
  • Running (unboundedPreceding to currentRow): one pass; each row adds itself to the running total.
  • Sliding (rowsBetween(-2, 0)): rows enter and leave a small buffer, and the aggregate is recomputed over it, so the cost is n times the frame size.
  • To the end (currentRow to unboundedFollowing): Spark's own source calls this frame "a very expensive operator to use, O(n * (n - 1) /2)", because it recomputes the aggregate after every row.

For a 1,000,000-row partition, the last one is about 500 billion row visits.

Work per frame for one partition of n = 1,000,000 rows

FrameSpark's frame classRow visits
no orderBy, or unbounded both waysUnboundedWindowFunctionFrameabout n: 1,000,000
unboundedPreceding to currentRowUnboundedPrecedingWindowFunctionFramen: 1,000,000
rowsBetween(-2, 0)SlidingWindowFunctionFramen times the frame size: 3,000,000
currentRow to unboundedFollowingUnboundedFollowingWindowFunctionFramen(n-1)/2: 499,999,500,000

lag and lead use their own offset frames and only look one row away. The quadratic frame is invisible on 14 daily rows and takes hours on a million-row key.

Remaining revenue, the slow way and the fast way

from pyspark.sql import SparkSession, Window, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
daily = (
    items.join(orders.filter(F.col("status") != "cancelled"), "order_id")
    .groupBy(F.to_date("order_ts").alias("day"))
    .agg(F.round(F.sum(F.col("qty") * F.col("unit_price")), 2).alias("revenue"))
)
w = Window.orderBy("day")
slow = F.sum("revenue").over(w.rowsBetween(Window.currentRow, Window.unboundedFollowing))
total = F.sum("revenue").over(w.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing))
running = F.sum("revenue").over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow))
both = daily.select(
    "day", "revenue",
    F.round(slow, 2).alias("remaining_slow"),
    F.round(total - running + F.col("revenue"), 2).alias("remaining_fast"),
)
rows = both.orderBy("day").collect()
for r in rows[:3]:
    print(r["day"], r["revenue"], r["remaining_slow"], r["remaining_fast"])
print("same on every day:", all(r["remaining_slow"] == r["remaining_fast"] for r in rows))

Same numbers, different cost. The fast version is the partition total minus the running total plus the current value: two linear frames. (A window with no partitionBy is fine for 14 daily rows; on raw events, partition it.)

Nulls in windows

Three null rules decide window results on real data:

  • Sort order. Spark sorts nulls first in ascending order and last in descending order. A dedup with orderBy(F.desc('updated_at')) ranks rows with a null updated_at last, which is usually right; orderBy('updated_at') with F.last picks them up wrongly. Say it on purpose with F.desc_nulls_last('updated_at') or F.asc_nulls_last(...).
  • Partitioning. All null keys form one window partition. partitionBy('user_id') on clickstream puts every anonymous event into one buffer in one task: a hot key made of nulls.
  • Functions. lag returns null on a key's first row (or the default you pass as its third argument); sum and avg over a frame skip nulls.

The browser engine sorts nulls differently inside windows, so the examples here avoid null sort keys.

Where a null updated_at sorts

The same three versions of an order, one with a null updated_at, sorted descending and ascending: descending puts the null last, so number 1 is the newest real row; ascending puts the null first.

Same three rows, two directions: in Spark a null comes first going up and last going down. Say which you want with F.desc_nulls_last or F.asc_nulls_last.

The trap: three window mistakes that pass on small data. No tie-breaker in orderBy, so the "latest" row changes between runs. No frame, so rows that share an orderBy value are summed together. And no partitionBy at all: Window.orderBy("day") is fine for 14 daily rows, but on raw events it sends every row to a single partition on one machine, and Spark logs the warning "No Partition Defined for Window operation!". Partition by something whenever the data is big.

Numbers to remember

Setting or ruleDefault or valueWhat to know
spark.sql.windowExec.buffer.in.memory.threshold4,096 rowsRows of one key kept in a plain array (ExternalAppendOnlyUnsafeRowArray); past it, an UnsafeExternalSorter that can spill.
Frame with orderBy and no rowsBetweenrange, from the first row to the current rowRows that tie on the orderBy value count together.
Frame with no orderBythe whole partitionEvery row gets the same value.
Null sort order in Sparkfirst ascending, last descendingSay it with F.descnullslast or F.ascnullslast.
No partitionByone partitionSpark logs "No Partition Defined for Window operation!"
currentRow to unboundedFollowingn(n-1)/2 row visitsRewrite as partition total minus running total plus current.

What changed at SwiftKart

Tess's board now reads a table with one row per order: each order's versions numbered newest first, with a tie-breaker, and only number 1 kept. It says 40 orders, and 15 of them are still placed. The retry file can arrive five more times and the count will not move.

On Databricks this step usually sits right before a Delta MERGE into a silver table. MERGE fails when several source rows match the same target row, so teams reduce each batch to one row per key first (Module 13).

Next, Lesson 11.4: the app's events are not flat rows at all, and one app update makes Sunday's revenue triple.

In one line

A window keeps every row and looks at its neighbours: number each key's rows newest first with a tie-breaker and keep 1, and give every running total an explicit rowsBetween frame.

Interview corner

Write a deduplication that keeps the latest record per key in PySpark.

w = Window.partitionBy("order_id").orderBy(F.desc("updated_at"), F.desc("ingested_at")), then df.withColumn("rn", F.row_number().over(w)).filter("rn = 1").drop("rn"). The second sort column is the tie-breaker so the survivor is the same on every run. dropDuplicates would keep an arbitrary row, and groupBy with max loses the other columns of the winning row.

What is the difference between row_number, rank and dense_rank?

All three number rows within a window in orderBy order. row_number always gives distinct numbers, so ties are broken by the remaining sort columns. rank gives ties the same number and skips the following numbers (1, 2, 2, 4); dense_rank gives ties the same number without gaps (1, 2, 2, 3). Use row_number for "exactly N per group" and rank/dense_rank when tied rows must stay together.

Why is a window with no partitionBy a problem on big data?

Without a partition, every row belongs to one window, so Spark must move all the data into a single partition and process it on one executor core, logging "No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation." That loses all parallelism and the one buffer spills or runs out of memory. Partition by a natural key (customer, day, product), or aggregate first so the windowed table is small.

How does Spark execute a window function, and what decides how much memory it needs?

The planner shuffles the input by the partitionBy keys and sorts each task's rows by those keys and the orderBy columns. WindowExec then processes one key at a time: it buffers that key's rows in an ExternalAppendOnlyUnsafeRowArray (4,096 rows in memory by default, then a spillable UnsafeExternalSorter), computes the frame for every row and emits them. So memory and spill are driven by the largest key, not the table: one bot or the null key can make a single task spill tens of GB. Frame choice matters too: currentRow to unboundedFollowing is O(n^2), so rewrite it as total minus running.