Zero-Padded DAU, Rolling MAU, and Identity Rehash Inflation
Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite
Problem Statement
Consider an append-only authentication table logins(user_id BIGINT, login_ts TIMESTAMP) where timestamps are recorded in UTC, no primary key is enforced, and a single account may authenticate multiple times on the same day.
Graded Function (Parts 1 & 2)
Implement the Python metric builder:
def daily_activity_metrics(
rows: List[List[object]],
start_date: str,
end_date: str,
) -> List[Dict[str, object]]:
Given rows (where each element [user_id, login_ts] represents one UTC login record) and inclusive ISO calendar bounds start_date and end_date ("YYYY-MM-DD"), return one dictionary per UTC date d in [start_date, end_date] sorted in ascending chronological order:
"date":"YYYY-MM-DD"string for calendar dayd."dau"(Part 1 — Zero-Padded Daily Active Users): number of distinctuser_idvalues with at least one login on UTC dated. Idle dates with zero logins must still be present with"dau": 0."l30d_mau"(Part 2 — Rolling 30-Day Active Users): number of distinctuser_idvalues with at least one login across the 30-day inclusive UTC window[d - 29 days, d].
Boundary behavior:
- Return [] whenever start_date > end_date.
- Records falling in the 29 days immediately preceding start_date ([start_date - 29 days, start_date - 1 day]) do not produce output rows of their own, yet they still contribute to "l30d_mau" while inside a reported day's 30-day lookback.
- Records older than start_date - 29 days or later than end_date have no effect.
Companion SQL & Analytical Questions (Parts 1–3)
Alongside the implementation, a complete solution addresses:
1. SQL Calendar Spine & Rolling Distincts (Parts 1 & 2): Writing PostgreSQL queries over logins to produce zero-padded dau and mau_l30d across the table's date span, analyzing how intermediate row volume scales, and explaining how weekday-only product usage interacts with a 30-day lookback.
2. Identity Rotation Artifact (Part 3): Suppose at 00:00:00 UTC on cutover date R, every user's user_id is replaced with a brand-new identifier used for all subsequent logins without backfilling historical rows. Determine which calendar dates suffer inflated rolling 30-day MAU, derive the exact formula and minimum/maximum percentage error relative to true MAU, and describe how to detect and repair the artifact.
Examples
Example 1
Input:
rows = [
[10, "2025-07-10 07:30:00"],
[10, "2025-07-10 19:45:00"],
[20, "2025-07-10 23:59:59"],
[30, "2025-07-11 00:00:00"],
[10, "2025-07-13 11:15:00"],
[40, "2025-07-13 15:00:00"],
]
start_date = "2025-07-10"
end_date = "2025-07-14"
Output:
[
{"date": "2025-07-10", "dau": 2, "l30d_mau": 2},
{"date": "2025-07-11", "dau": 1, "l30d_mau": 3},
{"date": "2025-07-12", "dau": 0, "l30d_mau": 3},
{"date": "2025-07-13", "dau": 2, "l30d_mau": 4},
{"date": "2025-07-14", "dau": 0, "l30d_mau": 4},
]
Explanation:
- 2025-07-10 sees two logins from user 10 plus a 23:59:59 login from user 20, yielding dau = 2 and l30d_mau = 2.
- 2025-07-11 starts at 00:00:00 with user 30 (dau = 1), raising cumulative 30-day distinct users {10, 20, 30} to 3.
- 2025-07-12 and 2025-07-14 have no logins (dau = 0), while 2025-07-13 sees returning user 10 and new user 40 (dau = 2, l30d_mau = 4).
Example 2
Input:
rows = [
[50, "2025-08-01 06:00:00"],
[60, "2025-08-15 14:20:00"],
]
start_date = "2025-08-30"
end_date = "2025-09-01"
Output:
[
{"date": "2025-08-30", "dau": 0, "l30d_mau": 2},
{"date": "2025-08-31", "dau": 0, "l30d_mau": 1},
{"date": "2025-09-01", "dau": 0, "l30d_mau": 1},
]
Explanation:
- On 2025-08-30, the 30-day lookback covers 2025-08-01 through 2025-08-30, so both pre-range users 50 and 60 count toward l30d_mau = 2 while dau = 0.
- On 2025-08-31, 2025-08-01 falls outside [2025-08-02, 2025-08-31], dropping user 50 and leaving l30d_mau = 1 (user 60), which persists on 2025-09-01.
Constraints
0 <= len(rows) <= 200,000- Each item in
rowsis a 2-element list or tuple[user_id, login_ts]in arbitrary chronological order. user_idis a hashable value (typicallyint).login_tsis a valid UTC ISO timestamp string ("YYYY-MM-DD HH:MM:SS"or ISO-8601).start_dateandend_dateare valid"YYYY-MM-DD"calendar date strings.
Step-by-step walkthrough
Clarify the contract across all three parts
This interview combines two SQL metric queries with an analytical deep dive on broken user identity:
- Input table:
logins(user_id BIGINT, login_ts TIMESTAMP)in UTC, with no primary key and multiple logins allowed per user per day. - Graded Python function:
daily_activity_metrics(rows, start_date, end_date)receivesrowsas[user_id, login_ts]pairs plus inclusive"YYYY-MM-DD"bounds, and returns[{"date": ..., "dau": ..., "l30d_mau": ...}, ...]in ascending date order (note the SQL notes name these columnsday,dau,mau_l30dacross the table's min-to-max date span).
Upfront answers to the prompt's clarifying questions: - Date range & lookback: In SQL we span
MIN(login_ts)::datetoMAX(login_ts)::date(or caller-supplied bounds); in Python we report[start_date, end_date]while still looking back 29 days (start_date - 29) so early report dates see real prior logins. - Time zone: Cut calendar days in UTC, matchinglogin_ts. - Partial early windows: Report early dates with all distinct users observed so far (optionally adding a booleanis_full_30d_windowflag for dashboards rather than dropping rows). - Test/internal accounts: Filtered out in the initial deduplication CTE if ausersdimension table marks them.- Input table:
Part 1 in SQL: zero-fill missing days with a calendar spine
Grouping
loginsdirectly (GROUP BY login_ts::date) can only output dates where at least one login occurred — quiet days vanish completely. To guarantee a row with0on empty days, build a contiguouscalendarspine first, deduplicateloginsto(day, user_id)pairs, andLEFT JOINactivity onto the calendar:calendar (c) LEFT JOIN daily_users (du) COUNT(du.user_id) 2025-07-11 ---------------> (2025-07-11, user 30) -> 1 2025-07-12 ---------------> (NULL, NULL) -> 0 (COUNT(col) ignores NULL!)-- 1. Find the first and last UTC dates present in the table. WITH bounds AS ( SELECT MIN(login_ts)::date AS first_day, MAX(login_ts)::date AS last_day FROM logins ), -- 2. Generate every calendar date from first_day through last_day inclusive. calendar AS ( SELECT (first_day + offset_days) AS day FROM bounds CROSS JOIN generate_series(0, last_day - first_day) AS offset_days ), -- 3. Collapse repeat same-day logins to one row per (day, user_id). daily_users AS ( SELECT DISTINCT login_ts::date AS day, user_id FROM logins ) -- 4. Count non-NULL du.user_id values so empty days report 0 instead of 1. SELECT c.day, COUNT(du.user_id) AS dau FROM calendar AS c LEFT JOIN daily_users AS du ON du.day = c.day GROUP BY c.day ORDER BY c.day;In PostgreSQL, subtracting two
DATEvalues returns an integer day count andDATE + INTEGERproduces aDATE, avoiding any time-zone or daylight-saving conversions. AndCOUNT(du.user_id)skipsNULLon empty days, whereasCOUNT(*)would mistakenly return1.Part 2 in SQL: inclusive 30-day MAU, query cost, and weekday effects
An inclusive 30-day lookback ending on
daycoversday - 29throughday(29 + 1 = 30calendar dates). Because PostgreSQL rejectsCOUNT(DISTINCT user_id)inside anOVER (...)window clause — and summing dailydauwould count a user once per active day rather than once per 30-day window — we use a rangeLEFT JOINondu.day BETWEEN c.day - 29 AND c.day:WITH bounds AS ( SELECT MIN(login_ts)::date AS first_day, MAX(login_ts)::date AS last_day FROM logins ), calendar AS ( SELECT (first_day + offset_days) AS day FROM bounds CROSS JOIN generate_series(0, last_day - first_day) AS offset_days ), daily_users AS ( SELECT DISTINCT login_ts::date AS day, user_id FROM logins ) -- Combine Part 1 (DAU via FILTER) and Part 2 (L30D MAU) in one pass. SELECT c.day, COUNT(DISTINCT du.user_id) FILTER (WHERE du.day = c.day) AS dau, COUNT(DISTINCT du.user_id) AS mau_l30d FROM calendar AS c LEFT JOIN daily_users AS du ON du.day BETWEEN c.day - 29 AND c.day GROUP BY c.day ORDER BY c.day;Two key analytical points to explain alongside the query: - Query cost: If
daily_usersholdsPdistinct(day, user_id)rows, each row matches up to30calendar dates, expanding the join intermediate to roughly30 * Prows before per-dayCOUNT(DISTINCT ...). That scales linearly inP, though the30xmultiplier becomes expensive at billion-row scale. - Weekday-only follow-up: Since30 = 4 * 7 + 2, an L30D window contains 20 weekdays when ending on Sunday, 21 on Monday or Saturday, and 22 on Tuesday through Friday. For a B2B workplace tool with near-zero weekend usage, light users have slightly more chances to be caught in a Tuesday–Friday window than a Sunday window, adding artificial weekly ripple to MAU while weekenddau = 0tanks rawDAU / MAU. Using L28D (4exact weeks = always20weekdays) removes that calendar artifact.Part 3: analyze how a user-ID rehash inflates MAU
Suppose at
00:00:00UTC on dateR, every user is assigned a brand-newuser_id(disjoint from recent old IDs) and logs in exclusively under that new ID fromRonward:Timeline: ... R-29 ... R-1 | R R+1 ... R+28 | R+29 ... ID regime: (old IDs) | (new IDs only) | (new IDs only) Window on d = R: [R-29 ....... R] <- straddles R (inflated!) Window on d = R+28: [R-1 ........ R+28] <- last straddling day (inflated!) Window on d = R+29: [R .......... R+29] <- 100% post-rehash (clean!)- DAU impact:
0%error (unaffected), because on any single calendar day every user appears under only one ID. (Caveat: if the rehash deployed midday onR, users logging in both before and after deployment on dayRinflateR's DAU too, and extend the MAU impact by one day throughR + 29.) - Which MAU dates are affected, and for how long: A date
d's window[d - 29, d]mixes old and new IDs if and only if it includes at least one day< Rand at least one day>= R. That happens forR <= d <= R + 28— 29 calendar days in total. Byd = R + 29, the window is[R, R + 29], all old IDs have aged out, and MAU returns to normal. - Exact overestimate formula & bounds: For any date
din[R, R + 28], split its window atR. LetAbe the set of real people active in[d - 29, R - 1](logged under old IDs) andBbe the set of real people active in[R, d](logged under new IDs):
reported_MAU = |A| + |B| true_MAU = |A ∪ B| = |A| + |B| - |A ∩ B| absolute_overestimate = reported_MAU - true_MAU = |A ∩ B| percentage_overestimate = (|A ∩ B| / |A ∪ B|) * 100% (when |A ∪ B| > 0)- Extreme cases:
- Maximum overestimate = +100% (reported MAU is
2xtrue MAU): Achieved whenA = B(every user active in the window logged in at least once beforeRand at least once on/afterR, as in a daily-habit tool), so|A ∩ B| = |A ∪ B|. - Minimum overestimate = 0%: Achieved when
A ∩ Bis empty (|A ∩ B| = 0), meaning nobody active beforeRalso logged in on/afterRwithin that 30-day window.
- Maximum overestimate = +100% (reported MAU is
- Detection and correction: You can spot an unannounced rehash on
Rbecause first-timeuser_idcounts spike to ~100% of DAU onR, pre-Rcohort retention drops to0%overnight, andmau_l30dclimbs steadily for up to 29 days whiledaustays flat before dropping sharply aroundR + 29. To fix historical numbers, joinloginsagainst anold_id -> new_idmapping table usingCOALESCE(map.new_id, logins.user_id)before deduplicating; without a mapping table, exact deduplication is impossible and[R, R + 28]must be annotated on dashboards.
- DAU impact:
Slide a 30-day window in Python with per-user day counts
Now let's implement
daily_activity_metrics(rows, start_date, end_date). Scanning allLrows for every reported datedwould costO(D * L)time. Because[day - 29, day]and yesterday's window share 29 days, only two dates change when advancing today: -dayenters on the right. -leaving_day = day - 30leaves on the left.We track
active_day_counts[user], the integer count of active days thatusercurrently has inside[day - 29, day]. If user10logged in on Jul 10 and Jul 13, their count becomes2on Jul 13; when Jul 10 slides out 30 days later, their count drops from2to1(not0), keeping them inl30d_mauuntil Jul 13 also expires.Group rows by UTC day and run the daily sweep
We first normalize each timestamp to a UTC
dateviautc_day, group distinct user IDs intousers_by_dayover[start - 29, end], and then stepdayforward one day at a time fromfirst_needed(start - 29) toend, appending output dicts onceday >= start.from datetime import date, datetime, timedelta, timezone WINDOW_DAYS = 30 def utc_day(login_ts: str) -> date: """Return the UTC calendar date of a timestamp like '2025-07-10 07:30:00'.""" # Replace trailing 'Z' with '+00:00' so datetime.fromisoformat works across Python 3 versions. moment = datetime.fromisoformat(login_ts.replace("Z", "+00:00")) if moment.tzinfo is not None: moment = moment.astimezone(timezone.utc) # Naive timestamps without an offset are already in UTC per the schema contract. return moment.date() def daily_activity_metrics( rows: List[List[object]], start_date: str, end_date: str, ) -> List[Dict[str, object]]: start = date.fromisoformat(start_date) end = date.fromisoformat(end_date) if start > end: return [] # Phase 1: Lookback boundary. An inclusive 30-day window ending on `start` # spans [start - 29, start] (29 prior days + `start` itself = 30 calendar days). first_needed = start - timedelta(days=WINDOW_DAYS - 1) # Phase 2: Deduplicate login rows per UTC calendar day inside [first_needed, end]. # users_by_day: {date(2025, 7, 10): {10, 20}, ...} mapping each date to distinct user_ids users_by_day: Dict[date, Set[object]] = {} for user_id, login_ts in rows: day = utc_day(str(login_ts)) # Rows older than `first_needed` expire before `start`; rows after `end` affect no output day. if day < first_needed or day > end: continue if day not in users_by_day: users_by_day[day] = set() users_by_day[day].add(user_id) # Phase 3: Slide the 30-day window one day at a time from `first_needed` through `end`. # active_day_counts: {user_id: number_of_active_days_inside_current_30d_window} # Keeping an integer count (instead of a plain set) ensures a user stays in MAU when # an older login day leaves the window while a more recent login day remains inside. active_day_counts: Dict[object, int] = {} result: List[Dict[str, object]] = [] day = first_needed while day <= end: today_users = users_by_day.get(day, set()) # Enter: increment active-day count for every distinct user active on `day`. for user in today_users: active_day_counts[user] = active_day_counts.get(user, 0) + 1 # Leave: `day - 30` just stepped off the left edge of [day - 29, day]. leaving_day = day - timedelta(days=WINDOW_DAYS) for user in users_by_day.get(leaving_day, set()): active_day_counts[user] -= 1 if active_day_counts[user] == 0: del active_day_counts[user] # Emit one zero-filled dictionary per date once warm-up reaches `start`. if day >= start: result.append({ "date": day.isoformat(), "dau": len(today_users), "l30d_mau": len(active_day_counts), }) day += timedelta(days=1) return resultTrace Example 1
On Example 1 (
2025-07-10to2025-07-14), deduplication collapses user10's two07-10logins (07:30:00and19:45:00) into one, keeps23:59:59on07-10, and places00:00:00on07-11:Date | today_users | active_day_counts | dau | l30d_mau -----------+-------------+-------------------------------+-----+--------- 2025-07-10 | {10, 20} | {10: 1, 20: 1} | 2 | 2 2025-07-11 | {30} | {10: 1, 20: 1, 30: 1} | 1 | 3 2025-07-12 | {} | {10: 1, 20: 1, 30: 1} | 0 | 3 2025-07-13 | {10, 40} | {10: 2, 20: 1, 30: 1, 40: 1} | 2 | 4 2025-07-14 | {} | {10: 2, 20: 1, 30: 1, 40: 1} | 0 | 4Notice
2025-07-12and2025-07-14are zero-filled (dau = 0), and on2025-07-13user10increments their active-day count to2whilelen(active_day_counts)rises to4— counting distinct users rather than summing daily DAU.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import date, datetime, timedelta, timezone WINDOW_DAYS = 30 def utc_day(login_ts: str) -> date: """Return the UTC calendar date of a timestamp like '2025-07-10 07:30:00'.""" # Replace trailing 'Z' with '+00:00' so datetime.fromisoformat works across Python 3 versions. moment = datetime.fromisoformat(login_ts.replace("Z", "+00:00")) if moment.tzinfo is not None: moment = moment.astimezone(timezone.utc) # Naive timestamps without an offset are already in UTC per the schema contract. return moment.date() def daily_activity_metrics( rows: List[List[object]], start_date: str, end_date: str, ) -> List[Dict[str, object]]: start = date.fromisoformat(start_date) end = date.fromisoformat(end_date) if start > end: return [] # Phase 1: Lookback boundary. An inclusive 30-day window ending on `start` # spans [start - 29, start] (29 prior days + `start` itself = 30 calendar days). first_needed = start - timedelta(days=WINDOW_DAYS - 1) # Phase 2: Deduplicate login rows per UTC calendar day inside [first_needed, end]. # users_by_day: {date(2025, 7, 10): {10, 20}, ...} mapping each date to distinct user_ids users_by_day: Dict[date, Set[object]] = {} for user_id, login_ts in rows: day = utc_day(str(login_ts)) # Rows older than `first_needed` expire before `start`; rows after `end` affect no output day. if day < first_needed or day > end: continue if day not in users_by_day: users_by_day[day] = set() users_by_day[day].add(user_id) # Phase 3: Slide the 30-day window one day at a time from `first_needed` through `end`. # active_day_counts: {user_id: number_of_active_days_inside_current_30d_window} # Keeping an integer count (instead of a plain set) ensures a user stays in MAU when # an older login day leaves the window while a more recent login day remains inside. active_day_counts: Dict[object, int] = {} result: List[Dict[str, object]] = [] day = first_needed while day <= end: today_users = users_by_day.get(day, set()) # Enter: increment active-day count for every distinct user active on `day`. for user in today_users: active_day_counts[user] = active_day_counts.get(user, 0) + 1 # Leave: `day - 30` just stepped off the left edge of [day - 29, day]. leaving_day = day - timedelta(days=WINDOW_DAYS) for user in users_by_day.get(leaving_day, set()): active_day_counts[user] -= 1 if active_day_counts[user] == 0: del active_day_counts[user] # Emit one zero-filled dictionary per date once warm-up reaches `start`. if day >= start: result.append({ "date": day.isoformat(), "dau": len(today_users), "l30d_mau": len(active_day_counts), }) day += timedelta(days=1) return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine an office building's badge-swipe ledger that prints one line for every calendar date — even quiet weekends when nobody badges in — alongside a 30-day rolling attendance roster. DAU (Daily Active Users) counts unique employees who swiped in today, while rolling MAU (L30D) counts unique employees who swiped in at least once during [day - 29, day]. In SQL, we build every calendar date in a CTE (Common Table Expression) — a named temporary subquery written with WITH — and attach deduplicated user-days via a LEFT JOIN, which keeps every calendar date and fills NULL on zero-swipe days. In Python, we avoid recounting 30 days from scratch by using a reference-counted sliding window, a dictionary active_day_counts[user] storing how many active days inside the current 30-day window belong to each user. This same mental model makes Part 3 crystal clear: if HR replaces everyone's badge ID on day R without linking old and new badges, anyone who swiped both before R and on/after R inside a 30-day window looks like two separate people (|A ∩ B| extra IDs, inflating MAU by 0% to +100%) for the 29 dates R through R + 28 until all pre-R days slide out on R + 29.
Naive approaches fail for three reasons. Grouping logins directly in SQL omits empty dates altogether, summing daily DAU with a window function (an OVER (...) aggregate across neighbouring rows) counts repeat visitors multiple times instead of once, and scanning all L login rows per day in Python takes O(D * L) time by repeating 29 days of identical work on every step.
Walk through Example 1 (2025-07-10 to 2025-07-14, where user 10 logs in twice and user 20 once on 07-10, user 30 logs in at midnight on 07-11, and users 10 and 40 log in on 07-13):
1. Deduplicating by UTC day produces {2025-07-10: {10, 20}, 2025-07-11: {30}, 2025-07-13: {10, 40}}, merging user 10's morning and evening logins on 07-10.
2. On 2025-07-10, users 10 and 20 enter (active_day_counts = {10: 1, 20: 1}), emitting {'date': '2025-07-10', 'dau': 2, 'l30d_mau': 2}.
3. On 2025-07-11, user 30 enters (dau = 1, l30d_mau = 3), and on 2025-07-12, today_users is empty so dau = 0 while l30d_mau stays 3.
4. On 2025-07-13, user 10 increments to 2 and user 40 enters (active_day_counts = {10: 2, 20: 1, 30: 1, 40: 1}), emitting dau = 2, l30d_mau = 4, followed by dau = 0, l30d_mau = 4 on 2025-07-14.
Complexity
Let L be the number of input login rows, D be the number of reported dates in [start_date, end_date], and P be the number of distinct (day, user_id) pairs in [start_date - 29, end_date] (P <= L).
- Time:
O(L + D + P)in Python. One pass overrowsbuildsusers_by_dayinO(L)average time, the sweep steps throughD + 29calendar days, and each of thePdistinct(day, user_id)pairs incrementsactive_day_countsonce on entry and decrements it at most once on exit. In the PostgreSQL range-join query,SELECT DISTINCTscansLrows once and the30-day join produces up to30 * Prows before grouping per day (O(L + 30 * P)). - Space:
O(P + D)in Python, holdingPuser-day entries inusers_by_day, at mostPactive users inactive_day_counts, andDresult dictionaries.
Edge cases
- Empty
rowsinput: Returns allDcalendar dates in[start_date, end_date]zero-filled withdau = 0andl30d_mau = 0(whereas a SQL query deriving bounds fromMIN/MAXof an emptyloginstable yields zero rows). - Inverted range (
start_date > end_date): Returns[]. - Exact midnight & 30-day cutoffs:
23:59:59and the next second00:00:00land on consecutive UTC dates; a login on dayXcontributes tol30d_mauforXthroughX + 29(30dates) and drops out onX + 30. - Logins before
start_date: Logins in[start_date - 29, start_date - 1]warm upl30d_mauwithout emitting early rows; logins<= start_date - 30or> end_dateare skipped. - Unsorted input rows or tuples: Grouping into
users_by_dayhandles arbitrary row ordering and both[user_id, ts]lists and(user_id, ts)tuples. - Rehashed IDs without a mapping table: Counted as distinct users until
R + 29clears all pre-rehash dates from the 30-day window.
Common mistakes
- Grouping
loginswithoutLEFT JOINing a calendar spine: Drops zero-login dates instead of outputtingdau = 0. - Writing
COUNT(*)instead ofCOUNT(du.user_id)afterLEFT JOIN: Counts theNULL-extended calendar row and outputs1on empty days. - Off-by-one window bounds (
c.day - 30instead ofc.day - 29): Covers 31 calendar days instead of 30. - Using
COUNT(DISTINCT user_id) OVER (...)orROWS 29 PRECEDINGon sparse dates: PostgreSQL rejectsDISTINCTin window functions, and row-based frames span more than 30 days whenever empty dates are missing. - Using integer division (
dau / mau_l30d) in SQL: Truncates ratios below1to0unless cast toNUMERIC. - Part 3 traps: Claiming the rehash inflates MAU on only 1 day (it lasts 29 days,
RthroughR + 28), claiming it always doubles MAU (+100%is the upper bound; actual inflation is|A ∩ B| / |A ∪ B|), or claiming it alters boundary-aligned DAU.
Follow-up questions
- How should you calculate the DAU-to-MAU stickiness ratio in SQL, and why do quiet weekends skew that metric for workplace software? The stickiness ratio (
DAU / MAU) measures what fraction of monthly users engage on an average day, written safely in PostgreSQL asROUND(dau::numeric / NULLIF(mau_l30d, 0), 4)to avoid integer truncation and division by zero. For B2B software used primarily Monday through Friday, Saturday and Sundaydauvalues near0make raw daily stickiness plunge every weekend and pull a 7-day average down to roughly5/7of true workday engagement. Report average weekday DAU divided by L28D MAU (orWAU / MAU) so every numerator and denominator window contains an exact multiple of 5 workdays. - What techniques avoid the 30x range-join cost when computing daily rolling MAU across billions of login records? First incrementally append each night's distinct
(day, user_id)pairs into a partitioneddaily_userstable so raw login logs are never rescanned. Next, eliminate the30xrange-join blowup by turning each user-day into a non-overlapping coverage interval[day, LEAST(next_login_day, day + 30))usingLEAD(day) OVER (PARTITION BY user_id ORDER BY day): each interval emits+1on entry and-1on exit, and a cumulativeSUMover the calendar yields exactmau_l30dinO(P log P + D)work (or, if ~1% approximate error is acceptable, union 30 daily HyperLogLog sketches — compact fixed-size probabilistic distinct-count summaries):
WITH spans AS (
-- Each login keeps its user active in MAU until their next login or 30 days later.
SELECT day AS start_day,
LEAST(
COALESCE(LEAD(day) OVER (PARTITION BY user_id ORDER BY day), day + 30),
day + 30
) AS end_day
FROM daily_users
),
deltas AS (
SELECT start_day AS day, 1 AS delta FROM spans
UNION ALL
SELECT end_day AS day, -1 AS delta FROM spans
),
daily_deltas AS (
SELECT day, SUM(delta) AS net_delta
FROM deltas
GROUP BY day
)
SELECT c.day,
SUM(COALESCE(d.net_delta, 0)) OVER (
ORDER BY c.day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS mau_l30d
FROM calendar AS c
LEFT JOIN daily_deltas AS d ON d.day = c.day
ORDER BY c.day;
- Suppose a subset of accounts had their IDs rotated and a lookup table maps legacy IDs to current IDs—how do you backfill accurate historical MAU? Map every historical login to a single canonical identifier before deduplicating (
COALESCE(m.new_id, l.user_id)via aLEFT JOINtoid_map(old_id, new_id)), so unrotated accounts keep their originaluser_idwhile rotated accounts unify pre-Rand post-Revents undernew_id:
WITH canonical_logins AS (
-- Rewrite legacy IDs to canonical current IDs before computing daily_users.
SELECT COALESCE(m.new_id, l.user_id) AS user_id,
l.login_ts
FROM logins AS l
LEFT JOIN id_map AS m
ON m.old_id = l.user_id
)
SELECT ... -- run the exact Part 1 + Part 2 query against canonical_logins
Before trusting the backfill, validate three data-hygiene invariants on `id_map`: `old_id` must be unique (no 1-to-many fanout), multi-hop rotations (`A -> B -> C`) must be flattened to `A -> C` first, and if an `old_id` was ever recycled for a different user after `R`, restrict the join condition with `AND l.login_ts < rehash_ts`.
Follow-up questions
- How should you calculate the DAU-to-MAU stickiness ratio in SQL, and why do quiet weekends skew that metric for workplace software?
- What techniques avoid the 30x range-join cost when computing daily rolling MAU across billions of login records?
- Suppose a subset of accounts had their IDs rotated and a lookup table maps legacy IDs to current IDs—how do you backfill accurate historical MAU?
Similar questions
- Daily Active Users and 30-Day Rolling MAU
- Alphabet-First Wikipedia Crawler with Rate Pacing
- Score-Sorted React Feed with Vote Toggles and Pins
- Station Reachability Across Time-Indexed Train Schedules
- Minimum Removals for Valid Parenthesis Nesting
- Testing Strategy for a Large-Scale Leaf Counter
More Glean interview questions
- Daily Active Users and 30-Day Rolling MAU Easy
- Circular Worker Assignment and Top-K Load Hard
- Alphabet-First Wikipedia Crawler with Rate Pacing Medium Pro
- Score-Sorted React Feed with Vote Toggles and Pins Medium Pro
- Station Reachability Across Time-Indexed Train Schedules Medium Pro
- Minimum Removals for Valid Parenthesis Nesting Medium Pro
- Enterprise Colleague Proximity and Similarity Service Medium Pro
- Multi-Source Real-Time Autocomplete for Workplace Search Medium Pro
- Testing Strategy for a Large-Scale Leaf Counter Medium Pro
- Modeling Pairwise Collaboration Distance Across an Enterprise Medium Pro