DataEng Hub
Spark SQLintermediateArticle · 2 min read

Window functions you will actually use in pipelines

Four window patterns cover almost every pipeline need: latest-row dedupe, sessionization, running totals and gap detection — with the performance traps of each.

Balaji S.
Lead Data Engineer

TL;DR

  • 90% of pipeline window use is four patterns: latest row per key, sessionize, running total, find gaps.
  • Every window with PARTITION BY shuffles on that key — a skewed key skews the whole stage.
  • A window without PARTITION BY sends everything to one task. On big data that is an outage, not a query.

Pattern 1 — latest row per key

The workhorse of every bronze-to-silver step:

WITH ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (
           PARTITION BY order_id
           ORDER BY updated_at DESC, _ingest_seq DESC
         ) AS rn
  FROM bronze.orders_cdc
)
SELECT * FROM ranked WHERE rn = 1;

Use ROW_NUMBER, not RANK — RANK returns ties and your dedupe stops deduping. Always add a deterministic tie-breaker column.

Pattern 2 — sessionize events

Mark a new session when the gap from the previous event exceeds a threshold, then cumulatively sum the markers:

WITH gaps AS (
  SELECT *,
         CASE WHEN ts - LAG(ts) OVER (PARTITION BY user_id ORDER BY ts)
                   > INTERVAL 30 MINUTES
              THEN 1 ELSE 0 END AS new_session
  FROM events
)
SELECT *,
       SUM(new_session) OVER (
         PARTITION BY user_id ORDER BY ts
         ROWS UNBOUNDED PRECEDING
       ) AS session_id
FROM gaps;

Pattern 3 — running totals

SELECT order_date,
       SUM(amount) OVER (
         PARTITION BY store_id ORDER BY order_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_revenue
FROM gold.daily_sales;

Spell out the frame. The default frame with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE treats ties as one group — subtly different sums, and slower.

Pattern 4 — find gaps in sequences

SELECT user_id, ts AS gap_starts_after,
       next_ts AS resumes_at
FROM (
  SELECT user_id, ts,
         LEAD(ts) OVER (PARTITION BY user_id ORDER BY ts) AS next_ts
  FROM heartbeats
)
WHERE next_ts - ts > INTERVAL 5 MINUTES;

Performance notes

  • One stage can evaluate multiple window functions only if they share the same PARTITION BY and ORDER BY. Group your windows accordingly.
  • Check the plan for a single-partition Window node (Exchange SinglePartition above it) — that's the no-PARTITION BY trap.
  • Pre-filter before the window. A WHERE after the window still pays for the full shuffle.

Practice

Further reading

#window-functions#row_number#sessionization#performance

Keep going

ProblemBronze

Deduplicate a raw events table

Keep exactly one row per event_id — the latest by timestamp — from a bronze table that receives replays and retries.

One practical note a week

Get new articles, problems and guides in your inbox.