Seven-Day Retention Rates by Weekly Cohort

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

You are analyzing product engagement across two datasets:

  • users: account records with user_id (unique identifier), signup_date (registration date or timestamp), and plan_type (subscription tier).
  • events: activity records with user_id (account identifier) and event_ts (activity timestamp).

Bucket accounts into weekly registration cohorts defined by the ISO calendar week of signup_date, where every week begins on Monday at 00:00:00 (signup_week).

An account counts as retained in week one if at least one events record with the same user_id falls inside the half-open window [signup_date, signup_date + 7 days)—meaning event_ts >= signup_date and event_ts < signup_date + 7 days. Activity at the exact registration timestamp qualifies, whereas activity at signup_date + 7 days (or before signup_date) does not.

Implement:

def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]:

(In PostgreSQL, write a single read-only SELECT query producing the equivalent result table.)

Return one summary dictionary (or row) per weekly cohort present in users, containing these four fields in order:

  • signup_week: Monday 00:00:00 timestamp formatted as 'YYYY-MM-DD HH:MM:SS' (or None / NULL if signup_date is missing).
  • cohort_size: count of distinct non-null user_id values belonging to that cohort, whether or not they logged qualifying activity.
  • retained_users: count of distinct user_id values in that cohort with at least one qualifying first-week event (multiple qualifying events for one user still count once).
  • retention_rate: retained_users / cohort_size rounded half-up to 4 decimal places (None / NULL if cohort_size == 0).

Keep cohorts whose retained_users is 0, but do not fabricate rows for calendar weeks that have zero records in users. Sort the output by signup_week ascending, placing any None (NULL) cohort row last.

Examples

Example 1

Input:
users = [
    {"user_id": 101, "signup_date": "2025-04-07 08:30:00", "plan_type": "starter"},
    {"user_id": 102, "signup_date": "2025-04-09 15:00:00", "plan_type": "team"},
    {"user_id": 103, "signup_date": "2025-04-13 22:00:00", "plan_type": "starter"},
    {"user_id": 104, "signup_date": "2025-04-14 09:00:00", "plan_type": "team"},
]
events = [
    {"user_id": 101, "event_ts": "2025-04-07 08:30:00"},
    {"user_id": 101, "event_ts": "2025-04-10 12:00:00"},
    {"user_id": 102, "event_ts": "2025-04-16 15:00:00"},
    {"user_id": 103, "event_ts": "2025-04-20 21:59:59"},
    {"user_id": 104, "event_ts": "2025-04-14 08:59:59"},
    {"user_id": 999, "event_ts": "2025-04-08 10:00:00"},
]

Output:
[
    {"signup_week": "2025-04-07 00:00:00", "cohort_size": 3, "retained_users": 2, "retention_rate": 0.6667},
    {"signup_week": "2025-04-14 00:00:00", "cohort_size": 1, "retained_users": 0, "retention_rate": 0.0},
]

Explanation: - Users 101 (Mon Apr 7), 102 (Wed Apr 9), and 103 (Sun Apr 13) belong to Monday cohort '2025-04-07 00:00:00' (cohort_size = 3). User 101 qualifies via two in-window events (counted once), 102's sole event lands at the excluded +7 days endpoint, and 103 qualifies 1 second before +7 days, giving 2 / 3 = 0.6667. - User 104 starts Monday cohort '2025-04-14 00:00:00'; their only event is 1 second before signup, leaving 0 / 1 = 0.0. Event 999 has no matching users record and is ignored.

Example 2

Input:
users = [
    {"user_id": "acct_1", "signup_date": "2025-06-02", "plan_type": "basic"},
    {"user_id": "acct_2", "signup_date": "2025-06-06", "plan_type": "pro"},
    {"user_id": "acct_3", "signup_date": "2025-06-18", "plan_type": "pro"},
]
events = [
    {"user_id": "acct_2", "event_ts": "2025-06-08 18:00:00"},
]

Output:
[
    {"signup_week": "2025-06-02 00:00:00", "cohort_size": 2, "retained_users": 1, "retention_rate": 0.5},
    {"signup_week": "2025-06-16 00:00:00", "cohort_size": 1, "retained_users": 0, "retention_rate": 0.0},
]

Explanation: Bare date strings represent 00:00:00 midnight. Cohort '2025-06-02 00:00:00' retains acct_2 (1 / 2 = 0.5). The empty week '2025-06-09 00:00:00' is skipped because nobody registered that week, whereas '2025-06-16 00:00:00' appears with retention_rate = 0.0.

Constraints

  • Timestamp strings use 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' (or None / NULL).
  • users and events can be empty, contain duplicate user records, or include events for unregistered IDs.
  • Missing (None / NULL) identifiers or timestamps never satisfy join or window comparisons, matching SQL three-valued logic.
  • Rates round half-up to 4 decimal places (matching PostgreSQL ROUND(numeric, 4)).

Step-by-step walkthrough

  1. Understand the cohorts, window, and output rules

    We are given two tables—users (user_id, signup_date, plan_type) and events (user_id, event_ts)—and asked to compute first-week retention grouped by signup cohort (the group of users who signed up during the same Monday-through-Sunday calendar week).

    In the Python judge, both tables arrive as lists of dictionaries, and we return a list of dictionaries with keys signup_week, cohort_size, retained_users, and retention_rate.

    The trickiest part of retention problems is getting every boundary rule exact:

    1. Personal half-open 7-day window [signup_date, signup_date + 7 days): A half-open interval includes its start endpoint (>=) and excludes its end endpoint (<). Notice that the window is measured from each user's exact signup_date timestamp, not from Monday midnight:
    Timeline for a user signing up at 2024-01-02 12:00:00:
    
       2024-01-02       2024-01-02                    2024-01-09       2024-01-09
        11:59:59         12:00:00                      11:59:59         12:00:00
      -----|================[=============================]----------------|----->
          OUT              IN                            IN               OUT
       (before)       (exact signup)               (7d minus 1s)     (exact +7 days)
    
    1. Distinct user counts: Both cohort_size and retained_users count distinct user_id values. A user with five qualifying events—or a duplicate row in users—still counts once.
    2. Zero-retention cohorts stay; empty calendar weeks do not: Every signup week present in users gets a row (even if retained_users == 0), while calendar weeks with zero signups are omitted.
    3. Rounding and ordering: retention_rate is retained_users / cohort_size rounded half-up to 4 decimals. Rows are ordered by signup_week ascending, with any None (NULL) signup week placed last.
  2. Write the PostgreSQL query first

    Because the problem asks for one read-only PostgreSQL query and our Python code must mirror SQL semantics down to NULLs and rounding, let us write the SQL query first and inspect each clause:

    SELECT
        -- Truncate each user's signup timestamp back to Monday 00:00:00 of that ISO week.
        DATE_TRUNC('week', u.signup_date) AS signup_week,
        COUNT(DISTINCT u.user_id) AS cohort_size,
        -- Unmatched LEFT JOIN rows have e.user_id = NULL, which COUNT(DISTINCT ...) ignores.
        COUNT(DISTINCT e.user_id) AS retained_users,
        -- Cast to numeric to avoid integer division; NULLIF prevents division by zero.
        ROUND(
            COUNT(DISTINCT e.user_id)::numeric / NULLIF(COUNT(DISTINCT u.user_id), 0),
            4
        ) AS retention_rate
    FROM users AS u
    -- Keep ALL users in the denominator; put the 7-day window check inside ON, not WHERE!
    LEFT JOIN events AS e
        ON e.user_id = u.user_id
       AND e.event_ts >= u.signup_date
       AND e.event_ts < u.signup_date + INTERVAL '7 days'
    GROUP BY DATE_TRUNC('week', u.signup_date)
    ORDER BY signup_week ASC NULLS LAST;
    

    Why must e.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days' sit inside ON rather than WHERE? In a LEFT JOIN, an ON condition decides which events attach to a user: if a user has no qualifying events, the user still survives with e.user_id = NULL, keeping cohort_size accurate and preserving 0%-retention cohorts. Moving that check to WHERE would filter out the NULL rows after the join, silently turning the LEFT JOIN into an INNER JOIN and making every surviving cohort look 100% retained!

  3. Why naive nested loops are slow, and how indexing fixes it

    In Python, a naive translation loops through every user in users and, inside that loop, scans every row in events looking for a matching user_id and timestamp. If users has 50,000 rows and events has 500,000 rows, that performs 25,000,000,000 comparisons (O(U * E)).

    Almost all of those comparisons check events belonging to completely different users! Instead, we do one pass over events first to build a dictionary events_by_user mapping each user_id to a list of that user's event timestamps. Then each user only inspects their own events, dropping total work to O(U + E)—just like a database hash join.

  4. Parse timestamps and snap signups to Monday midnight

    Input timestamps can arrive as bare dates ('2024-03-04'), space-separated timestamps ('2024-01-01 10:00:00'), 'T'-separated ISO strings, or None. Python's datetime.fromisoformat parses all three text formats into datetime objects (treating a bare date as 00:00:00 midnight).

    To find Monday 00:00:00 of ts's week, we use ts.weekday(), which numbers Monday = 0, Tuesday = 1, ..., Sunday = 6. Subtracting ts.weekday() days from ts.date() always lands on the Monday that started that week—even across month or year boundaries:

    Signup timestamp          ts.weekday()   Subtract weekday() days   signup_week
    ---------------------------------------------------------------------------------------
    2024-01-01 10:00 (Mon)         0         2024-01-01 - 0 days    -> 2024-01-01 00:00:00
    2024-01-07 23:59 (Sun)         6         2024-01-07 - 6 days    -> 2024-01-01 00:00:00
    2024-01-08 00:00 (Mon)         0         2024-01-08 - 0 days    -> 2024-01-08 00:00:00
    2025-01-01 12:00 (Wed)         2         2025-01-01 - 2 days    -> 2024-12-30 00:00:00
    
    from typing import Optional
    from datetime import datetime, timedelta
    
    FIRST_WEEK_WINDOW = timedelta(days=7)
    
    
    def parse_ts(value: Optional[str]) -> Optional[datetime]:
        """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime."""
        if value is None:
            return None
        return datetime.fromisoformat(value)
    
    
    def monday_week_start(ts: datetime) -> datetime:
        """Return Monday 00:00:00 of the calendar week containing ts."""
        # ts.weekday() is 0 on Monday through 6 on Sunday, so subtracting it steps back to Monday.
        monday_date = ts.date() - timedelta(days=ts.weekday())
        return datetime(monday_date.year, monday_date.month, monday_date.day)
    
  5. Check the 7-day window and match SQL half-up rounding

    Next we write two small helpers:

    1. has_qualifying_event(signup_ts, user_event_times) checks whether any of a user's events falls inside [signup_ts, signup_ts + 7 days). If signup_ts is None, the window is unknown (just as event_ts >= NULL is unknown in SQL), so it returns False.
    2. round_half_up(numerator, denominator, digits) matches SQL's ROUND(numeric, 4). Why not call Python's built-in round(retained / size, 4)? Because Python uses round-half-to-even (banker's rounding), whereas SQL ROUND on exact numeric values rounds halves up! For 1 retained user out of 32, 1 / 32 = 0.03125 sits halfway between 0.0312 and 0.0313: Python's round(1 / 32, 4) gives 0.0312, while PostgreSQL gives 0.0313.

    We avoid floating-point inaccuracies completely with exact integer arithmetic. Adding 1/2 before flooring x = (numerator * 10^4) / denominator is the same as (2 * numerator * 10^4 + denominator) // (2 * denominator): - For 1 / 32 at 4 digits (scale = 10000): (2 * 1 * 10000 + 32) // (2 * 32) = 20032 // 64 = 313, and 313 / 10000 = 0.0313.

    from typing import List, Optional
    from datetime import datetime
    
    
    def round_half_up(numerator: int, denominator: int, digits: int) -> float:
        """Compute numerator / denominator rounded half-up to `digits` decimals, matching SQL ROUND."""
        scale = 10 ** digits
        rounded_scaled = (2 * numerator * scale + denominator) // (2 * denominator)
        return rounded_scaled / scale
    
    
    def has_qualifying_event(signup_ts: Optional[datetime], user_event_times: List[datetime]) -> bool:
        """Return True if at least one event falls in the half-open window [signup_ts, signup_ts + 7 days)."""
        if signup_ts is None:
            return False
        window_end = signup_ts + FIRST_WEEK_WINDOW
        for event_ts in user_event_times:
            # Inclusive at signup_ts (>=) and strictly exclusive 7 days later (<).
            if signup_ts <= event_ts < window_end:
                return True
        return False
    
  6. Group users into cohorts, sort weeks, and build output rows

    Now we assemble calculate_first_week_retention in four clean phases matching the SQL query:

    1. Index events (events_by_user): Skip events with None user ID or timestamp, since SQL NULLs never match in ON.
    2. Populate per-cohort sets (cohort_users, cohort_retained): Using sets automatically handles COUNT(DISTINCT ...) when a user has multiple events or duplicate rows in users. Notice we initialize cohort_users[week_key] before skipping user_id is None, matching SQL GROUP BY + COUNT(DISTINCT u.user_id).
    3. Order cohorts (ordered_weeks): Sort all non-None week datetime keys ascending, then append None at the end (NULLS LAST).
    4. Format rows (output_rows): Convert each Monday datetime to 'YYYY-MM-DD %H:%M:%S' ('YYYY-MM-DD 00:00:00') and compute retention_rate when cohort_size > 0.
    from typing import Any, Dict, List, Optional, Set
    from datetime import datetime
    
    
    def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]:
        events_by_user: Dict[Any, List[datetime]] = {}
        for event in events:
            user_id = event["user_id"]
            event_ts = parse_ts(event["event_ts"])
            if user_id is None or event_ts is None:
                continue
            if user_id not in events_by_user:
                events_by_user[user_id] = []
            events_by_user[user_id].append(event_ts)
    
        cohort_users: Dict[Optional[datetime], Set[Any]] = {}
        cohort_retained: Dict[Optional[datetime], Set[Any]] = {}
    
        for user in users:
            user_id = user["user_id"]
            signup_ts = parse_ts(user["signup_date"])
            week_key = None if signup_ts is None else monday_week_start(signup_ts)
    
            if week_key not in cohort_users:
                cohort_users[week_key] = set()
                cohort_retained[week_key] = set()
    
            if user_id is None:
                continue
    
            cohort_users[week_key].add(user_id)
            user_events = events_by_user.get(user_id, [])
            if has_qualifying_event(signup_ts, user_events):
                cohort_retained[week_key].add(user_id)
    
        ordered_weeks: List[Optional[datetime]] = []
        for week_key in cohort_users:
            if week_key is not None:
                ordered_weeks.append(week_key)
        ordered_weeks.sort()
        if None in cohort_users:
            ordered_weeks.append(None)
    
        output_rows: List[Dict] = []
        for week_key in ordered_weeks:
            cohort_size = len(cohort_users[week_key])
            retained_users = len(cohort_retained[week_key])
            retention_rate = None
            if cohort_size > 0:
                retention_rate = round_half_up(retained_users, cohort_size, 4)
    
            week_label = None if week_key is None else week_key.strftime("%Y-%m-%d %H:%M:%S")
            output_rows.append({
                "signup_week": week_label,
                "cohort_size": cohort_size,
                "retained_users": retained_users,
                "retention_rate": retention_rate,
            })
    
        return output_rows
    
  7. Trace Example 1 step by step

    Let us trace Example 1 (2025-04-07 and 2025-04-14 are both Mondays):

    User   signup_date           signup_week           Window [signup, signup + 7d)          User's events            Retained?
    ---------------------------------------------------------------------------------------------------------------------------
    101    2025-04-07 08:30:00   2025-04-07 00:00:00   [04-07 08:30:00, 04-14 08:30:00)      04-07 08:30:00 (IN)      Yes
                                                                                             04-10 12:00:00 (IN)
    102    2025-04-09 15:00:00   2025-04-07 00:00:00   [04-09 15:00:00, 04-16 15:00:00)      04-16 15:00:00 (OUT, +7d) No
    103    2025-04-13 22:00:00   2025-04-07 00:00:00   [04-13 22:00:00, 04-20 22:00:00)      04-20 21:59:59 (IN)      Yes
    104    2025-04-14 09:00:00   2025-04-14 00:00:00   [04-14 09:00:00, 04-21 09:00:00)      04-14 08:59:59 (OUT, -1s) No
    

    Event 999 never appears in users, so it is ignored. Aggregating by signup_week: - '2025-04-07 00:00:00': cohort_users = {101, 102, 103} (size = 3), cohort_retained = {101, 103} (retained = 2), rate = 0.6667. - '2025-04-14 00:00:00': cohort_users = {104} (size = 1), cohort_retained = set() (retained = 0), rate = 0.0.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from datetime import datetime, timedelta
    
    FIRST_WEEK_WINDOW = timedelta(days=7)
    
    
    def parse_ts(value: Optional[str]) -> Optional[datetime]:
        """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime."""
        if value is None:
            return None
        return datetime.fromisoformat(value)
    
    
    def monday_week_start(ts: datetime) -> datetime:
        """Return Monday 00:00:00 of the calendar week containing ts."""
        # ts.weekday() is 0 on Monday through 6 on Sunday, so subtracting it steps back to Monday.
        monday_date = ts.date() - timedelta(days=ts.weekday())
        return datetime(monday_date.year, monday_date.month, monday_date.day)
    
    
    def round_half_up(numerator: int, denominator: int, digits: int) -> float:
        """Compute numerator / denominator rounded half-up to `digits` decimals, matching SQL ROUND."""
        # Python's built-in round() uses round-half-to-even (1/32 = 0.03125 -> 0.0312),
        # whereas SQL ROUND(numeric, 4) rounds halves up (0.03125 -> 0.0313).
        # Exact integer identity: floor((numerator * scale) / denominator + 1/2)
        #                       = (2 * numerator * scale + denominator) // (2 * denominator).
        scale = 10 ** digits
        rounded_scaled = (2 * numerator * scale + denominator) // (2 * denominator)
        return rounded_scaled / scale
    
    
    def has_qualifying_event(signup_ts: Optional[datetime], user_event_times: List[datetime]) -> bool:
        """Return True if at least one event falls in the half-open window [signup_ts, signup_ts + 7 days)."""
        if signup_ts is None:
            return False
        window_end = signup_ts + FIRST_WEEK_WINDOW
        for event_ts in user_event_times:
            # Inclusive at signup_ts (>=) and strictly exclusive 7 days later (<).
            if signup_ts <= event_ts < window_end:
                return True
        return False
    
    
    def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]:
        # Phase 1: Index valid events by user_id for fast lookup (equivalent to a SQL hash join).
        # events_by_user: maps user_id -> list of event datetimes, e.g. {1: [datetime(2024, 1, 1, 10, 0)]}.
        events_by_user: Dict[Any, List[datetime]] = {}
        for event in events:
            user_id = event["user_id"]
            event_ts = parse_ts(event["event_ts"])
            # Events missing user_id or event_ts behave like SQL NULLs and can never satisfy the join.
            if user_id is None or event_ts is None:
                continue
            if user_id not in events_by_user:
                events_by_user[user_id] = []
            events_by_user[user_id].append(event_ts)
    
        # Phase 2: Bucket users into Monday signup-week cohorts and record distinct retained users.
        # cohort_users:    maps week_key (Monday datetime or None) -> set of distinct user_ids.
        # cohort_retained: maps week_key (Monday datetime or None) -> set of distinct retained user_ids.
        cohort_users: Dict[Optional[datetime], Set[Any]] = {}
        cohort_retained: Dict[Optional[datetime], Set[Any]] = {}
    
        for user in users:
            user_id = user["user_id"]
            signup_ts = parse_ts(user["signup_date"])
            week_key = None if signup_ts is None else monday_week_start(signup_ts)
    
            # Create the cohort entry before checking user_id so 0-user or 0-retention cohorts still appear.
            if week_key not in cohort_users:
                cohort_users[week_key] = set()
                cohort_retained[week_key] = set()
    
            # SQL COUNT(DISTINCT user_id) ignores NULL user_ids while preserving the GROUP BY row.
            if user_id is None:
                continue
    
            cohort_users[week_key].add(user_id)
            user_events = events_by_user.get(user_id, [])
            if has_qualifying_event(signup_ts, user_events):
                cohort_retained[week_key].add(user_id)
    
        # Phase 3: Sort real week datetimes ascending and place any None (NULL) week last.
        ordered_weeks: List[Optional[datetime]] = []
        for week_key in cohort_users:
            if week_key is not None:
                ordered_weeks.append(week_key)
        ordered_weeks.sort()
        if None in cohort_users:
            ordered_weeks.append(None)
    
        # Phase 4: Format each cohort row with exact column names and 4-decimal SQL rounding.
        output_rows: List[Dict] = []
        for week_key in ordered_weeks:
            cohort_size = len(cohort_users[week_key])
            retained_users = len(cohort_retained[week_key])
            retention_rate = None
            if cohort_size > 0:
                retention_rate = round_half_up(retained_users, cohort_size, 4)
    
            week_label = None if week_key is None else week_key.strftime("%Y-%m-%d %H:%M:%S")
            output_rows.append({
                "signup_week": week_label,
                "cohort_size": cohort_size,
                "retained_users": retained_users,
                "retention_rate": retention_rate,
            })
    
        return output_rows
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of each calendar week's new signups as a freshman class—called a signup cohort (a group of users bucketed together by the Monday 00:00:00 of the week they joined). The moment a user signs up, they receive a personal 168-hour (7-day) pass covering the half-open interval [signup_date, signup_date + 7 days) (an interval that includes its start timestamp and stops just before its end timestamp). If a user logs at least one event while their pass is active, we check their name off on that class's "retained" roster, and each class's retention rate is (unique retained users) / (unique enrolled users).

A naive SQL query that uses an INNER JOIN—or uses a LEFT JOIN (which keeps unmatched left-table rows with NULLs on the right) but puts the 7-day filter in WHERE—discards every user who had zero qualifying events, shrinking the denominator so every cohort falsely reports 100% retention and 0%-retention cohorts vanish completely. In Python, scanning the entire events list for every user takes slow O(U * E) nested loops, and calling built-in round() applies banker's rounding (rounding exact .5 halves to the nearest even digit) instead of SQL's round-half-up rule (0.03125 -> 0.0313). Indexing events by user_id into a dictionary first and using sets of user IDs per cohort gives exact, fast results.

Walk through Example 1's four registered accounts: - User 101 signs up Monday 2025-04-07 08:30:00 (cohort 2025-04-07 00:00:00). Events at 04-07 08:30:00 (exact signup, counts!) and 04-10 12:00:00 (3 days later, deduplicated) -> retained. - User 102 signs up Wednesday 2025-04-09 15:00:00 (same cohort 2025-04-07 00:00:00). Only event is 04-16 15:00:00 (exact +7 days, excluded) -> not retained. - User 103 signs up Sunday 2025-04-13 22:00:00 (still cohort 2025-04-07 00:00:00). Event at 04-20 21:59:59 (1 second before +7 days, counts!) -> retained, so the 2025-04-07 cohort reports 2 / 3 = 0.6667. - User 104 signs up Monday 2025-04-14 09:00:00 (new cohort 2025-04-14 00:00:00). Event at 04-14 08:59:59 (1 second early, excluded) -> not retained, keeping the cohort row with 0 / 1 = 0.0.

Complexity

Let U be the number of rows in users, E be the number of rows in events, and C be the number of distinct signup-week cohorts (C <= U).

  • Time: O(U + E + C log C) when each user_id appears once in users. We scan all E events once to group them into events_by_user, scan the U users once where each user checks only their own list of events (summing to at most E checks overall), and sort the C cohort week keys in O(C log C) time.
  • Space: O(U + E) because events_by_user stores up to E parsed timestamps and the cohort_users / cohort_retained sets store up to U distinct user IDs across cohorts.
  • SQL scaling: Adding a composite B-tree index (a sorted two-column lookup structure) on events(user_id, event_ts) lets PostgreSQL check each user's [signup_date, signup_date + 7 days) window via a fast range probe rather than scanning the entire events table.

Edge cases

  • Exact window endpoints: An event at event_ts == signup_date counts (>=), whereas an event at event_ts == signup_date + 7 days or 1 second before signup_date does not.
  • Monday/Sunday and New Year week boundaries: 2024-01-07 23:59:59 (Sunday night) belongs to Monday 2024-01-01 00:00:00, 2024-01-08 00:00:00 starts a new cohort, and Wednesday 2025-01-01 snaps back across New Year to Monday 2024-12-30 00:00:00.
  • Zero-retention cohorts vs empty calendar weeks: A cohort whose users have zero qualifying events still outputs retained_users = 0, retention_rate = 0.0, while calendar weeks with zero signups in users are skipped.
  • Multiple events or duplicate user rows: Sets in Python (and COUNT(DISTINCT ...) in SQL) guarantee each user_id contributes at most 1 to cohort_size and at most 1 to retained_users.
  • Orphan events: Events whose user_id never appears in users are ignored because cohorts come exclusively from users.
  • NULL / None timestamps or user IDs: Users with signup_date = None form a single None cohort placed last (NULLS LAST) with 0 retained users; rows with user_id = None still create their cohort group if needed, without inflating COUNT(DISTINCT user_id).
  • Empty users table: Produces [] (zero cohort rows).

Common mistakes

  • Putting the 7-day event filter in WHERE instead of LEFT JOIN ... ON: Filtering WHERE e.event_ts >= u.signup_date drops unmatched NULL rows, removing unretained users from cohort_size and hiding zero-retention cohorts.
  • Forgetting DISTINCT in COUNT(e.user_id): A single active user who triggers 10 events in week 1 gets counted 10 times, pushing retention_rate above 1.0!
  • Using <= instead of < at + 7 days: Includes the 8th-day boundary instant (signup_date + 7 days), which fails Example 1 (User 102).
  • Truncating timestamps to calendar dates (event_ts::date < signup_date::date + 7): Snaps a 12:00 afternoon signup back to 00:00, mistakenly counting pre-signup morning events on day 0 and dropping valid morning events on day 7.
  • Starting weeks on Sunday: Functions like strftime('%U') start weeks on Sunday instead of PostgreSQL's ISO Monday.
  • Integer division or Python round(): Writing COUNT(...) / COUNT(...) without ::numeric truncates fractions to 0 in SQL, and Python's round(1 / 32, 4) returns 0.0312 instead of SQL's 0.0313.

Alternative approaches

  • Pre-flagging each user with EXISTS in a CTE: A Common Table Expression (CTE) is a named temporary subquery introduced with WITH. Checking EXISTS (SELECT 1 FROM events e WHERE e.user_id = u.user_id AND e.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days') inside a CTE avoids row multiplication when active users have thousands of events, and still keeps every user in the cohort denominator.
  • Sorting per-user events + binary search in Python: If duplicate user_id rows were very common in users, sorting each user's event list once and calling bisect_left(user_events, signup_ts) would check each [signup_ts, signup_ts + 7 days) window in O(log k) time instead of scanning all k events of that user.

Follow-up questions

  • How do you avoid understating retention for the newest cohort when users signed up fewer than seven days before the snapshot cutoff? Those recent signups suffer from right-censoring—their 7-day observation window has not finished closing yet, so accounts that have not returned today might still log an event tomorrow and artificially depress the latest cohort's rate. Restrict users to mature signups with WHERE u.signup_date + INTERVAL '7 days' <= <snapshot_cutoff_ts> (filtering on users preserves the LEFT JOIN), or mark the incomplete trailing week separately in dashboards.
  • How would you generalize this logic into a multi-week cohort retention matrix covering Week 0, Week 1, Week 2, and beyond? Compute each cohort's total cohort_size in a standalone CTE from users alone so the denominator never shrinks in later weeks. Then join events where e.event_ts >= u.signup_date, derive FLOOR(EXTRACT(EPOCH FROM (e.event_ts - u.signup_date)) / (7 * 86400)) as weeks_since_signup, and divide COUNT(DISTINCT e.user_id) per (signup_week, weeks_since_signup) by that cohort's fixed cohort_size.
  • If raw timestamps are recorded in UTC while business reporting defines Monday cohorts in New York local time, what needs to change? Convert signup_date into local wall-clock time before snapping to Monday midnight—for example DATE_TRUNC('week', u.signup_date AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York') when signup_date is stored without time zone—otherwise a Sunday 9 PM registration in New York (Monday 2 AM UTC) falls into next week's cohort. Meanwhile, evaluate the 168-hour elapsed window [signup_date, signup_date + 7 days) directly in UTC so Daylight Saving Time shifts do not stretch or shrink a user's observation window by an hour.

Follow-up questions

Similar questions

More Mixpanel interview questions

All 7 Mixpanel questions →