Building Fast Daily Metrics Tables for a Photo App Dashboard
System DesignModel answerLast updated
Design the derived tables and incremental pipeline behind a photo app's KPI dashboard, then extend it with cohort retention, weekly rollups and a change of reporting timezone.
Scenario
You own the analytics layer for a very large photo-sharing product. Leadership looks at a dashboard that shows one row per calendar day. It must load quickly, even though the raw data keeps growing without bound.
All raw timestamps are stored in UTC. The raw tables are:
users(user_id PK, username, created_at)photos(photo_id PK, user_id, created_at)follows(follower_user_id, followed_user_id, created_at): a row means the follow was created atcreated_atand stays active from then on.user_events(event_id PK, user_id, event_type, occurred_at)
Days are initially defined in the America/Los_Angeles timezone.
Metrics (one value per report date, in the reporting timezone)
new_users: accounts created on that date, and its change versus 7 days earlierDAU: distinct users with at least oneuser_eventsrow that day, and its change versus 7 days earlier. Treat the exact definition of "active" as something you would confirm with stakeholders.new_photos, its change versus 7 days earlier, andnew_photos_per_DAUtotal_followers: cumulative number of follow relationships at the end of the date- Share of users, as of end of date, with 0, 1-2, and 3+ inbound followers
What to cover
- Table design. Define the derived tables: grain, keys, columns, what is precomputed and what is computed at read time, partitioning or clustering, incremental loading, idempotency, late-arriving data, and the correctness-versus-cost trade-off.
- Daily refresh. Describe the ETL steps that populate these tables each day from the raw data (SQL or pseudocode is fine).
- Week-1 retention. For each signup cohort date D, what fraction of the cohort is active a week later, using the same definition of active? Explain the table changes and how to compute it cheaply.
- Weekly rollups. The dashboard must also support weekly reporting. Explain what changes in the grain and the computation, how "vs 7 days ago" becomes a weekly comparison, which metrics are additive and which are not, and how to treat a week that is not finished.
- New reporting timezone. A New York team wants
America/New_Yorkdays. Explain what changes in storage, day boundaries, ETL windows, backfills, and support for several timezones, and how to avoid double counting or gaps at day edges.
Prioritize correctness, read performance, and maintainability.
Hints
Hint 1
Start by pinning down definitions: what counts as active, whether unfollows exist, what the denominator of the follower-bucket percentages is, and whether retention means exactly day 7 or any day in days 1 to 7.
Hint 2
Store additive counts in a small per-day table and compute ratios and week-over-week deltas in a view, so a late correction never leaves stale derived numbers. Put a per-user-per-day activity table underneath it to support DAU, weekly actives and retention without touching raw events.
Hint 3
Convert each local day to a half-open UTC interval (23 or 25 hours on DST days), overwrite whole partitions so reruns are idempotent, and re-process a trailing lookback window for late data. For timezone changes, make the timezone a key of every derived table rather than a hard-coded assumption.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first
- Active: any
user_eventsrow on the local day. Confirm that photo posts and follows also emit events; if not, union those sources. - Follows: assume append-only. If unfollows exist, store +1 / -1 deltas instead.
- Bucket percentages: denominator is all users who signed up by the end of the report date.
- Retention: pick "active exactly on D+7" (used below). "Any day in D+1..D+7" is a small variation.
- Scale: assume hundreds of millions of users and billions of events per day, so dashboard loads must never scan raw data.
2. Table design
Principle: store additive atomic counts, derive ratios and deltas at read time. A stored ratio cannot be re-aggregated later.
Layer 1: user-grain facts, partitioned by (tz, local_date) and clustered by user_id:
| Table | Grain | Key columns |
|---|---|---|
dim_user | user_id | signup_ts_utc, signup_date per supported tz |
fct_user_active_daily | (tz, date, user_id) | event_count, posted_photo, followed |
fct_follow_delta_daily | (tz, date, followed_user_id) | new_followers |
user_follower_state | (tz, user_id) | follower_count, as_of_date |
fct_user_active_daily is the pivotal table: one row per active user per day (about DAU rows instead of billions of events). It feeds DAU, weekly actives and retention.
Layer 2: tiny dashboard aggregate, one row per (tz, report_date):
new_users, dau, new_photos, total_followers, total_users, users_0, users_1_2, users_3p, is_final, computed_at
View on top self-joins to report_date - 7 days to compute the three deltas, new_photos / NULLIF(dau,0), and the bucket percentages (users_x / NULLIF(total_users,0)). Deltas live in the view so that a late correction to day D automatically fixes D+7's change.
Physical choices: partition overwrite for idempotency, raw data partitioned by UTC ingestion date, clustering by user_id for cheap joins and distincts.
3. Daily population
Run for local date D after D ends plus a lateness buffer.
- UTC window:
[D 00:00 local, D+1 00:00 local)converted to UTC. It is half-open and DST-aware (23 or 25 hours on transition days). Scan only overlapping raw partitions. - Activity:
INSERT OVERWRITEthe(tz, D)partition offct_user_active_dailywithSELECT user_id, COUNT(*) ... GROUP BY user_idover the window. - Follow deltas: same pattern, grouped by
followed_user_id. - Buckets incrementally: only users who gained followers can change bucket. Join today's deltas to
user_follower_statefor old and new counts; each bucket = yesterday's count + entrants - leavers. New signups enter bucket 0. Then merge state. Cost is O(today's follows), not O(users). - Aggregate row:
dau = COUNT(*)from step 2;new_usersandnew_photosare windowed counts;total_followersandtotal_usersare previous day plus today's additions.
Late data: re-run a trailing N-day window (for example 3, sized from observed lateness). Additive metrics are fixed by overwrite. Cumulative metrics must be recomputed forward from the earliest affected date (a running sum over a tiny table is cheap). Buckets need either short-lived daily snapshots of per-user counts or a periodic full rebuild. Mark rows is_final = false until they leave the window.
Correctness vs cost: schedule a weekly or monthly full recompute to reconcile drift in the incremental path.
4. Week-1 retention
Add agg_retention_d7(tz, cohort_date, cohort_size, retained_d7, is_mature); the rate is derived in the view.
When processing date T, finalize cohort T-7:
SELECT u.signup_date AS cohort_date,
COUNT(*) AS cohort_size,
COUNT(a.user_id) AS retained_d7
FROM dim_user u
LEFT JOIN fct_user_active_daily a
ON a.user_id = u.user_id AND a.tz = :tz
AND a.activity_date = u.signup_date + 7
WHERE u.signup_date = :T - 7
GROUP BY 1;
This joins one cohort day to one activity partition, so it never touches raw events. Cohorts younger than 7 days are immature: show null or flag them. Late data for D+7 reopens cohort D, so include it in the lookback rerun. Key the display by cohort date and label it clearly.
5. Weekly rollups
- Grain:
agg_kpi_weekly(tz, week_start)with an explicit week convention (ISO Monday or US Sunday). - Additive metrics (
new_users,new_photos) are summed from daily rows. - Non-additive: summed DAU is not WAU. Compute WAU as
COUNT(DISTINCT user_id)over the seven daily activity partitions; optionally also report average DAU. - Point-in-time metrics (
total_followers, bucket shares) take the end-of-week value. - Ratios are recomputed from weekly sums (for example weekly photos divided by WAU), never averaged from daily ratios.
- "vs 7 days ago" becomes week over week: join to
week_start - 7 days. - Partial weeks: flag the current week as incomplete (
is_final = false) or compare only like-for-like days. Late data reopens the affected week.
6. Changing the timezone
- Keep raw timestamps in UTC; never rewrite them. The timezone is a reporting parameter.
- Make
tzpart of every derived table key and compute local dates with a timezone-aware conversion, so Pacific and Eastern rows coexist. - Each local day maps to its own half-open UTC window. An event belongs to exactly one local day per timezone, so there is no double counting inside a timezone; never mix timezones within one series.
- Eastern days start 3 hours earlier in UTC than Pacific days, so the same UTC raw partitions feed different windows. Backfill New York history by re-running the same jobs with
tz='ET'; the Layer-1 tables can be rebuilt in parallel by date. - Store a signup date per supported timezone in
dim_user(or derive it from the UTC timestamp) so cohort and retention logic stays identical. - Cumulative metrics and buckets are timezone-specific because "end of day" differs; they need their own state tables per tz.
- Cost grows linearly with the number of timezones, so support a small configured set rather than arbitrary ones.
Common mistakes
- Storing ratios or deltas instead of counts.
- Using fixed 24-hour windows across DST changes.
- Summing DAU to get weekly actives.
- Appending instead of overwriting partitions, which breaks reruns.
- Ignoring late data for cumulative and cohort metrics.
- Scanning raw events on every dashboard load.