Design a Mobile Sleep-Tracking App

Updated · techinterview.org

The interview is multidisciplinary — but first, some context: mobile sleep tracking has gone from gimmick to mainstream — Apple Health, Fitbit, Oura Ring, Whoop, and dozens of dedicated apps capture sleep data nightly. The interview is multidisciplinary: sensor integration, signal processing, ML for sleep-stage classification, and the privacy / battery tradeoffs of always-on health monitoring.

Functional requirements

  • Detect when user falls asleep / wakes up. Interviewers probe how you tell lying in bed reading from actual sleep onset — motion drops and heart rate falls, but the transition is gradual, so most systems use a rolling window rather than a single threshold.
  • Track sleep stages (light, deep, REM). Consumer devices can’t measure brain activity directly, so stages are inferred from heart rate, HRV, and motion. Be ready to say that staging accuracy is far lower than accuracy for total sleep time.
  • Monitor heart rate variability. HRV — the variation between heartbeats — is a proxy for recovery and stress; expect questions on sampling frequency and how you smooth noisy overnight readings.
  • Show trends over time. A single night is noisy, so the value is in weekly and monthly aggregates. Decide early what you roll up on-device versus in the cloud.
  • Smart alarm: wake during light sleep window. This is the marquee feature and a common deep-dive: the app watches sleep stage near the target time and triggers the alarm during a lighter phase so the user wakes less groggy.

Sources of data

  • A phone on the bedside or under a pillow uses its accelerometer to detect motion and its microphone to detect sounds.
  • A wearable (Apple Watch, Whoop, Oura Ring) captures motion, heart rate, and skin temperature.
  • A bed sensor (Withings, Eight Sleep) uses ballistocardiography from underneath the mattress.

Wearables provide the richest data; phone-only is a degraded experience but accessible.

Sleep stage classification

Inputs combined to classify sleep stages:

  • Heart rate (lowest in deep sleep, fluctuating in REM). Resting heart rate bottoms out in deep sleep and turns irregular during REM; a clean separation here is the strongest single signal you have without EEG.
  • Heart rate variability (HRV). HRV tends to rise in deep sleep and drop during REM and brief arousals, so it helps split stages that look alike on motion alone.
  • Motion (least in deep sleep, sometimes paradoxically still in REM). Actigraphy is cheap and always available, but on its own it mostly tells you asleep-versus-awake, which is why phone-only staging is weak.
  • Skin temperature (drops during sleep). Skin temperature follows the circadian dip overnight and moves slowly, so it’s better for confirming sleep onset than for catching stage-by-stage transitions.

ML model (typically a time-series classifier) outputs stage every 30 seconds.

Smart alarm

User sets a target wake time and a window (e.g., 7:00–7:30 AM). Within the window:

  • Algorithm watches for transitions to lighter sleep. It tracks stage transitions in near-real time, which means the classifier has to run on-device with low latency rather than batch-processing everything in the morning.
  • Wakes user during a light-sleep window — feels less groggy. Waking during light sleep avoids sleep inertia, the grogginess of being pulled out of deep sleep, and it’s the effect users notice most.
  • Falls back to target time if no light-sleep window detected. If the user stays in deep sleep through the whole window, the alarm fires at the hard target time so they’re never late — a guarantee worth stating explicitly.

Battery

For phone-on-nightstand tracking, battery during sleep:

  • ~20-30% of overnight battery on motion-only mode. Sampling the accelerometer at a low rate and buffering writes keeps drain in this range; be ready to name the sensor duty cycle you’d pick.
  • More if microphone is active. Continuous audio capture and any on-device sound analysis push power use up sharply, so gate the mic behind an explicit user setting.
  • Recommend charging during sleep. Charging overnight sidesteps the drain problem, but don’t rely on it — many users forget, so degrade to a lower sampling rate as the battery falls.

For wearable-based tracking: built for low power; minimal battery impact.

HealthKit / Health Connect integration

Write sleep data to platform health stores:

  • iOS: HKCategoryTypeIdentifierSleepAnalysis. You write sleep segments to this category type in HealthKit; interviewers may ask about requesting read and write permissions separately and handling a user who grants only partial access.
  • Android: Health Connect SleepSessionRecord. Health Connect stores sleep as session records with stage sub-records; note that it’s an on-device store, not a cloud API, so sync is still your responsibility.

This makes data available to other apps the user has authorized.

Visualization

Common patterns:

  • Hypnogram showing stages over the night. The hypnogram — a stepped chart of stage versus time — is the signature view; keep it readable at a glance rather than exposing every 30-second epoch.
  • Weekly / monthly trend lines. Trend lines answer “am I improving?” and smooth out single-night noise; pick a small set of metrics like total sleep and time in deep sleep.
  • Comparison vs your baseline. Comparing against the user’s own rolling baseline is more meaningful than population averages, since healthy sleep varies widely from person to person.
  • Correlations: how sleep affects mood, performance, illness. Correlation views (sleep versus mood, workout performance, or an oncoming cold) drive engagement, but present them as associations, not medical claims.

Privacy

Sleep data is highly personal. Considerations:

  • Default to local storage; opt-in to cloud sync. Keeping data on-device by default and making cloud sync an explicit choice is a strong default to state up front, and it simplifies your compliance story.
  • Don’t share sleep data with marketing partners. Sleep data can reveal health conditions and daily routines, so a clear no-sale stance is both an ethical and a trust decision worth calling out.
  • Make export and deletion easy (GDPR / CCPA). Users have a right to export and delete their data under GDPR and CCPA; design deletion to cascade through backups and derived aggregates, not just the primary store.
  • Microphone-based tracking has additional privacy concerns. Audio can capture conversations, so process it on-device, store derived features rather than raw recordings, and make the mic strictly opt-in.

Common gotchas

  • User co-sleeps with partner — motion gets contaminated. A partner’s movement bleeds into a phone or mattress sensor; wearables largely sidestep this, and bed sensors need per-side calibration to attribute motion correctly.
  • Cat on the bed — motion gets contaminated. Pets create motion no sensor can attribute to the sleeper, so favor body-tied signals like heart rate over bed-level motion when they disagree.
  • Phone falls off the bed — tracking corrupted. Detect the sudden impact and the long flat-on-the-floor signature, then flag the night as low-confidence rather than reporting garbage stages.
  • User wakes briefly to use bathroom — counted as awake. Short awakenings are normal; use a minimum-duration threshold so a two-minute bathroom trip doesn’t fragment the night into separate sleep sessions.

Robust apps handle these gracefully.

Frequently Asked Questions

How accurate are phone-based sleep trackers?

Total sleep time: pretty accurate (within 10–15 minutes typically). Sleep stages: less accurate without heart-rate data; mostly heuristic.

Why do sleep trackers disagree with each other?

Different sensors, different algorithms. No standardized ground truth. Polysomnography (clinical sleep study) is the gold standard but inaccessible.

What is the battery impact of overnight tracking?

For wearables: minimal. For phone: 20-30% overnight. Charge while you sleep.

newsletter

What's actually being asked right now

Interview patterns & comp trends, straight to your inbox.

No spam. Unsubscribe anytime.

newsletter

What's actually being asked right now

Interview patterns & comp trends, straight to your inbox.

No spam. Unsubscribe anytime.

1972 Soviet postage stamp commemorating the Mars 2 probe

worth a read

Mars For The Rest of Us — a weekly-or-more deep dive on the technical side of Mars exploration: rocket propulsion, microbiology, mission architecture, and everything in between. Written by Maciej Ceglowski.

Read it on Substack
Scroll to Top