33. Customers to date, counted once

PySparkMediumGrain trap

count distinct · running total · window functions · cohort · first seen

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

The growth team has a chart called "customers to date". It is built from the daily active customers table: add up the daily numbers, day after day.

In June the chart passed the number of people who have an account at all. A customer who buys on five different days is in five daily numbers, and the chart adds them all.

Input tables

purchases

One row per purchase.

Column Type Description
purchase_id BIGINT Unique per purchase.
customer_id BIGINT The customer who bought. Never NULL.
purchased_at TIMESTAMP_NTZ When the purchase happened.

A customer can buy several times on one day.

Requirement

Return one row per date that has at least one purchase.

  • purchase_date is the date part of purchased_at.
  • active_customers is the number of different customers who bought on that date.
  • new_customers is the number of different customers whose first ever purchase was on that date. It is 0 on a date where everybody had bought before.
  • cumulative_customers is the number of different customers who bought on that date or on any earlier date. Each customer counts once, however often they buy.
  • A date with no purchases at all does not appear.

Expected output

One row per date with purchases.

Column Type Description
purchase_date DATE
active_customers BIGINT Distinct customers that day.
new_customers BIGINT Customers buying for the first time that day.
cumulative_customers BIGINT Distinct customers up to and including that day.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

A distinct count cannot be built by adding up smaller distinct counts. A customer who buys on five days is in five daily numbers.

The way out is to find something about each customer that happens exactly once and count that instead. Each customer has exactly one first purchase date. So:

  1. For every purchase, work out the customer's first purchase date: F.min("purchase_date").over(Window.partitionBy("customer_id")).
  2. Per day, count the customers whose first date is that day. These are the new customers. Each customer is new on one day only.
  3. Keep a running sum of the new customers. Numbers that count each customer once can be added up.
is_first_day = F.col("purchase_date") == F.col("first_date")
daily = dated.groupBy("purchase_date").agg(
    F.countDistinct("customer_id").alias("active_customers"),
    F.countDistinct(F.when(is_first_day, F.col("customer_id"))).alias("new_customers"),
)

when without otherwise returns NULL for returning customers, and countDistinct ignores NULLs. On a day with only returning customers the count is 0, and the day still has its row because the grouping is over all purchases.

There are 343 purchases by 70 customers on 29 days. The cumulative number has to end at 70.

Common wrong answers

A running sum of active_customers. The chart from the story. It ends at 208 for 70 customers, and it is wrong on 28 of the 29 days. Only the first day is right, because on the first day everybody is new.

F.countDistinct("customer_id").over(window). The obvious thing to write, and Spark refuses it: [DISTINCT_WINDOW_FUNCTION_UNSUPPORTED] Distinct window functions are not supported. Many people stop here and fall back to the running sum.

F.approx_count_distinct("customer_id").over(window). This one runs. It is an estimate, and even with 70 customers it is off on 12 of the 29 days. Fine for a dashboard with millions of users where a percent does not matter, wrong for anything that has to reconcile.

Counting purchases instead of customers on the first day. F.count instead of F.countDistinct for new_customers. A customer who buys twice on their first day is two new customers. Every row of the result is wrong, because the error is carried forward by the running sum.

Joining a separate "new customers per day" table without handling the misses. Five days have no new customer at all. With a left join those days get NULL instead of 0. With an inner join they vanish: 24 rows instead of 29.

Other correct ways, and what they cost

F.size(F.collect_set("customer_id").over(window)) on the purchases, with a frame from the start up to the current date. Correct values. Two catches: size returns an INT, so the check reports the type until you cast to bigint; and every row carries the full set of customers so far, which is a lot of memory on real data.

A self-join: for every day, join all purchases on or before it and count distinct customers. Correct, and the join grows with days times purchases. It is the first thing to time out when the table grows.

The first-seen method touches every purchase once, and it gives you new_customers on the way, which is usually wanted anyway.

A detail about the window

The running sum uses a window with no partitionBy. Spark warns that all rows move to one partition. Here that is 29 rows, one per day, so it is fine. It is the daily table that goes through the window, not the purchases. If you ever need a running total per something (per country, per product), partition by it.

Edge cases in the data

Case Where What it catches
Returning customers most days A running sum of daily actives.
A day with only returning customers 24 June, and four more days new_customers must be 0, not NULL, and the row must be there.
A day with no purchases 17 June Must not appear. The result has 29 rows, not 30.
Two or three purchases by one customer on one day common Counting purchases instead of customers.
Purchases at 23:59:59 and at 00:00:00 customer 301, 9 and 10 June The date boundary.