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 day d.
  • "dau" (Part 1 — Zero-Padded Daily Active Users): number of distinct user_id values with at least one login on UTC date d. Idle dates with zero logins must still be present with "dau": 0.
  • "l30d_mau" (Part 2 — Rolling 30-Day Active Users): number of distinct user_id values 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 rows is a 2-element list or tuple [user_id, login_ts] in arbitrary chronological order.
  • user_id is a hashable value (typically int).
  • login_ts is a valid UTC ISO timestamp string ("YYYY-MM-DD HH:MM:SS" or ISO-8601).
  • start_date and end_date are valid "YYYY-MM-DD" calendar date strings.

Step-by-step walkthrough

  1. 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) receives rows as [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 columns day, dau, mau_l30d across 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)::date to MAX(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, matching login_ts. - Partial early windows: Report early dates with all distinct users observed so far (optionally adding a boolean is_full_30d_window flag for dashboards rather than dropping rows). - Test/internal accounts: Filtered out in the initial deduplication CTE if a users dimension table marks them.

  2. Part 1 in SQL: zero-fill missing days with a calendar spine

    Grouping logins directly (GROUP BY login_ts::date) can only output dates where at least one login occurred — quiet days vanish completely. To guarantee a row with 0 on empty days, build a contiguous calendar spine first, deduplicate logins to (day, user_id) pairs, and LEFT JOIN activity 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 DATE values returns an integer day count and DATE + INTEGER produces a DATE, avoiding any time-zone or daylight-saving conversions. And COUNT(du.user_id) skips NULL on empty days, whereas COUNT(*) would mistakenly return 1.

  3. Part 2 in SQL: inclusive 30-day MAU, query cost, and weekday effects

    An inclusive 30-day lookback ending on day covers day - 29 through day (29 + 1 = 30 calendar dates). Because PostgreSQL rejects COUNT(DISTINCT user_id) inside an OVER (...) window clause — and summing daily dau would count a user once per active day rather than once per 30-day window — we use a range LEFT JOIN on du.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_users holds P distinct (day, user_id) rows, each row matches up to 30 calendar dates, expanding the join intermediate to roughly 30 * P rows before per-day COUNT(DISTINCT ...). That scales linearly in P, though the 30x multiplier becomes expensive at billion-row scale. - Weekday-only follow-up: Since 30 = 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 weekend dau = 0 tanks raw DAU / MAU. Using L28D (4 exact weeks = always 20 weekdays) removes that calendar artifact.

  4. Part 3: analyze how a user-ID rehash inflates MAU

    Suppose at 00:00:00 UTC on date R, every user is assigned a brand-new user_id (disjoint from recent old IDs) and logs in exclusively under that new ID from R onward:

    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 on R, users logging in both before and after deployment on day R inflate R's DAU too, and extend the MAU impact by one day through R + 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 < R and at least one day >= R. That happens for R <= d <= R + 28 — 29 calendar days in total. By d = 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 d in [R, R + 28], split its window at R. Let A be the set of real people active in [d - 29, R - 1] (logged under old IDs) and B be 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 2x true MAU): Achieved when A = B (every user active in the window logged in at least once before R and at least once on/after R, as in a daily-habit tool), so |A ∩ B| = |A ∪ B|.
      • Minimum overestimate = 0%: Achieved when A ∩ B is empty (|A ∩ B| = 0), meaning nobody active before R also logged in on/after R within that 30-day window.
    • Detection and correction: You can spot an unannounced rehash on R because first-time user_id counts spike to ~100% of DAU on R, pre-R cohort retention drops to 0% overnight, and mau_l30d climbs steadily for up to 29 days while dau stays flat before dropping sharply around R + 29. To fix historical numbers, join logins against an old_id -> new_id mapping table using COALESCE(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.
  5. 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 all L rows for every reported date d would cost O(D * L) time. Because [day - 29, day] and yesterday's window share 29 days, only two dates change when advancing to day: - day enters on the right. - leaving_day = day - 30 leaves on the left.

    We track active_day_counts[user], the integer count of active days that user currently has inside [day - 29, day]. If user 10 logged in on Jul 10 and Jul 13, their count becomes 2 on Jul 13; when Jul 10 slides out 30 days later, their count drops from 2 to 1 (not 0), keeping them in l30d_mau until Jul 13 also expires.

  6. Group rows by UTC day and run the daily sweep

    We first normalize each timestamp to a UTC date via utc_day, group distinct user IDs into users_by_day over [start - 29, end], and then step day forward one day at a time from first_needed (start - 29) to end, appending output dicts once day >= 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 result
    
  7. Trace Example 1

    On Example 1 (2025-07-10 to 2025-07-14), deduplication collapses user 10's two 07-10 logins (07:30:00 and 19:45:00) into one, keeps 23:59:59 on 07-10, and places 00:00:00 on 07-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  |    4
    

    Notice 2025-07-12 and 2025-07-14 are zero-filled (dau = 0), and on 2025-07-13 user 10 increments their active-day count to 2 while len(active_day_counts) rises to 4 — counting distinct users rather than summing daily DAU.

  8. 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 over rows builds users_by_day in O(L) average time, the sweep steps through D + 29 calendar days, and each of the P distinct (day, user_id) pairs increments active_day_counts once on entry and decrements it at most once on exit. In the PostgreSQL range-join query, SELECT DISTINCT scans L rows once and the 30-day join produces up to 30 * P rows before grouping per day (O(L + 30 * P)).
  • Space: O(P + D) in Python, holding P user-day entries in users_by_day, at most P active users in active_day_counts, and D result dictionaries.

Edge cases

  • Empty rows input: Returns all D calendar dates in [start_date, end_date] zero-filled with dau = 0 and l30d_mau = 0 (whereas a SQL query deriving bounds from MIN/MAX of an empty logins table yields zero rows).
  • Inverted range (start_date > end_date): Returns [].
  • Exact midnight & 30-day cutoffs: 23:59:59 and the next second 00:00:00 land on consecutive UTC dates; a login on day X contributes to l30d_mau for X through X + 29 (30 dates) and drops out on X + 30.
  • Logins before start_date: Logins in [start_date - 29, start_date - 1] warm up l30d_mau without emitting early rows; logins <= start_date - 30 or > end_date are skipped.
  • Unsorted input rows or tuples: Grouping into users_by_day handles 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 + 29 clears all pre-rehash dates from the 30-day window.

Common mistakes

  • Grouping logins without LEFT JOINing a calendar spine: Drops zero-login dates instead of outputting dau = 0.
  • Writing COUNT(*) instead of COUNT(du.user_id) after LEFT JOIN: Counts the NULL-extended calendar row and outputs 1 on empty days.
  • Off-by-one window bounds (c.day - 30 instead of c.day - 29): Covers 31 calendar days instead of 30.
  • Using COUNT(DISTINCT user_id) OVER (...) or ROWS 29 PRECEDING on sparse dates: PostgreSQL rejects DISTINCT in 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 below 1 to 0 unless cast to NUMERIC.
  • Part 3 traps: Claiming the rehash inflates MAU on only 1 day (it lasts 29 days, R through R + 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 as ROUND(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 Sunday dau values near 0 make raw daily stickiness plunge every weekend and pull a 7-day average down to roughly 5/7 of true workday engagement. Report average weekday DAU divided by L28D MAU (or WAU / 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 partitioned daily_users table so raw login logs are never rescanned. Next, eliminate the 30x range-join blowup by turning each user-day into a non-overlapping coverage interval [day, LEAST(next_login_day, day + 30)) using LEAD(day) OVER (PARTITION BY user_id ORDER BY day): each interval emits +1 on entry and -1 on exit, and a cumulative SUM over the calendar yields exact mau_l30d in O(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 a LEFT JOIN to id_map(old_id, new_id)), so unrotated accounts keep their original user_id while rotated accounts unify pre-R and post-R events under new_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

Similar questions

More Glean interview questions

All 41 Glean questions →