Real-Time Proximity Push Service for Mobile Devices

Medium · System Design · Software Engineer · Technical Screen

Prompt

A global hospitality and trip-assistance application delivers urgent travel advisories and curated local recommendations to travelers on the go. Design the backend platform that continuously ingests mobile location pings and dispatches push notifications to every active user currently inside a specified radius R (for example, 5 km) around a target (lat, lon) coordinate.

Your architecture must satisfy these core functional and non-functional requirements: - Live Coordinate Ingestion & Freshness: Accept periodic (latitude, longitude, timestamp, accuracy) reports from active mobile apps and ignore stale records from devices that have not checked in within the past 15 minutes. - Proximity Trigger & Deduplicated Delivery: Expose an internal API for operators or automated services to trigger a broadcast inside radius R of (lat, lon), delivering push alerts via APNs and FCM without sending duplicate notifications to the same user for a single campaign. - Throughput & Dispatch Latency: Support 10 million daily active users and peak ingestion of 100,000 location updates per second, beginning outbound push dispatch within 10 seconds of a campaign trigger. - Hotspot Resilience & Privacy: Keep memory and compute overhead small, prevent broadcast storms in ultra-dense hubs (such as major international airports or city centers), retain only minimal recent location state, and block internal callers from inferring exact individual user positions.

Scope & Expectations

  • APIs & Ephemeral Data Model: Device ingestion endpoints, internal campaign APIs, and low-overhead storage structures tailored to rapidly expiring coordinates.
  • Geospatial Indexing & Exact Distance Checks: Choosing and partitioning a spatial grid or index (such as H3, S2, Geohash, or geo-indexed stores), pruning stale entries, and computing exact spherical distances.
  • Asynchronous Fan-Out & Deduplication: Decoupling high-rate location writes from campaign resolution, streaming matches through durable queues, recovering from worker crashes, and preventing duplicate user notifications.
  • Hotspot Scaling, Battery & Privacy Controls: Mitigating skew in crowded cells, pacing push gateways, adapting to mobile OS background/battery constraints, and enforcing location privacy.

Step-by-step walkthrough

  1. Clarify requirements and hidden workload shapes

    Two opposite workloads live inside this single system: a continuous write firehose of tiny location pings (up to 100,000 per second), and occasional broadcast queries that can suddenly fan out to hundreds of thousands of push notifications and must begin sending within 10 seconds. Separating those two paths is the foundation of the whole design.

    Functional requirements

    • Location ingestion: Mobile apps periodically send (latitude, longitude, timestamp, accuracy) for active devices.
    • Radius trigger: Internal services or administrators trigger a broadcast to all users currently within radius R meters of a center (lat, lon).
    • Freshness filtering: Ignore stale locations from devices that have not reported within the last 15 minutes (900 seconds).
    • Durable, deduplicated delivery: Deliver push notifications through APNs (Apple Push Notification service for iOS) and FCM (Firebase Cloud Messaging for Android) so each matched user receives a campaign once, even when workers crash and retry.

    Non-functional requirements

    • Scale: 10 million Daily Active Users (DAU) and up to 100,000 location updates per second at peak.
    • Latency: Notifications must start dispatching within 10 seconds of a campaign trigger.
    • Efficiency and hotspot safety: Keep memory and CPU small—only current locations matter, never historical trails—and avoid broadcast storms in dense hubs like airports or city centers.
    • Privacy: Retain location data only while fresh, coarsen precision where possible, and prevent internal APIs from leaking any individual's exact coordinates.

    Concrete assumptions we make explicit

    • Radius range: Typically 1 km to 10 km (5 km default). Normal campaigns enforce a 1 km minimum radius so an operator cannot draw a tiny 20-meter circle to pinpoint one person.
    • Device vs. user deduplication: Devices report physical locations (device_id), while the auth token maps each device to its user_id. Campaign deduplication happens per (campaign_id, user_id) so a traveler carrying both a phone and a tablet in their backpack is notified once rather than spammed twice.
    • Urgent vs. promotional alerts: Urgent travel alerts (flight gate disruptions, local safety warnings) use a high-priority lane and bypass daily marketing caps; local experience promos obey a per-user daily cap.
    • Noisy GPS fixes: Updates with accuracy > 1,000 m (coarse cell-tower fallbacks) are dropped at ingestion because they cannot reliably place a user inside or outside a 5 km circle.
  2. Back-of-the-envelope numbers

    Before picking databases, let's check the math for write volume, memory size, grid lookup size, and push delivery speed:

    1. Location write load
       Peak updates             100,000 updates/s
                                (e.g., 1M foreground apps reporting every 20 s = 50,000/s
                                 + 4M background apps reporting every ~80 s = 50,000/s)
       Wire payload             ~250 B (JSON + HTTP/2 headers) -> ~25 MB/s inbound
       Message log (Kafka)      100,000 msg/s * ~100 B compact binary = ~10 MB/s
                                1 hour retention = ~36 GB (trivial for a 3-broker cluster)
    
    2. In-memory live index (fresh devices only)
       Active devices stored    <= 10,000,000 (upper bound if every DAU reported in last 15 min)
       Memory per device        ~300 B total in Redis:
                                  - ~180 B for per-device hash (user_id, cell, lat, lon, ts)
                                  - ~120 B for sorted-set index entry (device_id + 8-byte score)
       Total primary RAM        10,000,000 * 300 B = ~3.0 GB (~6.0 GB with 1 replica per shard)
       Redis write commands     ~2.05 commands/update (1 device update + 1 cell timestamp update,
                                plus an old-cell delete on the <5% of pings that cross a cell edge)
                                -> ~205,000 ops/s across 8 shards = ~25,600 pipelined ops/s/shard
    
    3. Spatial query math (R = 5 km)
       Search circle area       pi * 5^2 = ~78.5 km^2
       Uber H3 res-7 hexagon    avg area ~5.16 km^2 (~1.41 km edge, ~2.44 km flat-to-flat)
       Cells overlapping circle ~23 to 30 hexagons (78.5 / 5.16 ≈ 15.2 by area, plus partial border cells)
       Matched users            5,000-50,000 in a typical city; up to ~300,000 in Heathrow or Midtown Tokyo
    
    4. Push fan-out timing
       Safe dispatch ceiling    20,000 pushes/s across worker pool (configurable per provider quota)
       300,000-user campaign    first batch dispatches in < 1 s; entire audience finishes in ~15 s
    

    Three design lessons jump right out of these numbers:

    1. All live location data fits in ~3 GB of RAM. Because positions older than 15 minutes are useless, keeping only the latest point in memory with an automatic expiration timer avoids hammering disk databases with 100,000 writes per second.
    2. Writes outnumber queries by orders of magnitude. We optimize ingestion for lock-free single-key updates and let rare campaign queries do slightly more filtering work.
    3. Push delivery—not spatial lookup—dominates large campaigns. Reading 30 cell keys takes tens of milliseconds, whereas pushing 300,000 messages takes ~15 seconds. Therefore, resolution must stream batches into the send queue immediately so the first notifications leave in under 1 second, easily beating the 10-second target.
  3. API design

    Devices authenticate with a JWT (JSON Web Token)—a cryptographically signed badge encoding device_id, user_id, and home_region that the API gateway verifies in memory without querying a database.

    Device-facing ingestion API

    POST /v1/devices/{device_id}/location
      Headers: Authorization: Bearer <device_jwt>
      Body:    { "lat": 41.8902, "lon": 12.4922, "accuracy_m": 20,
                 "ts": 1764680000, "app_state": "foreground" }
      -> 204 No Content
         Header: X-Report-Interval-S: 30        (server-tuned next ping interval)
      -> 429 Too Many Requests, Retry-After: 60 (shed load safely under extreme bursts)
    
    DELETE /v1/devices/{device_id}/location
      -> 204 No Content                         (user revoked location permission; erase immediately)
    

    Internal campaign API (service-to-service auth, audited on every call)

    Every trigger carries an Idempotency-Key—a unique ticket ID generated by the caller so that if a network timeout causes a retry, our server returns the existing campaign_id instead of launching a second broadcast.

    POST /internal/v1/campaigns
      Headers: Idempotency-Key: <uuid>
      Body:    {
                 "center": { "lat": 51.4700, "lon": -0.4543 },
                 "radius_m": 5000,
                 "priority": "urgent" | "normal",
                 "message": { "title": "Terminal Rail Advisory", "body": "...", "deep_link": "..." },
                 "valid_for_s": 0,
                 "max_recipients": 100000
               }
      -> 202 Accepted { "campaign_id": "cmp_44b", "status": "RESOLVING" }
      -> 422 Unprocessable Entity (RADIUS_TOO_SMALL | AUDIENCE_TOO_SMALL privacy guards)
    
    GET  /internal/v1/campaigns/{campaign_id}
      -> 200 { "status": "SENDING", "cells_total": 27, "cells_done": 27,
               "matched_users": 34800, "sent": 16200, "failed": 31, "first_sent_at": "..." }
    
    POST /internal/v1/campaigns/{campaign_id}/cancel
    POST /internal/v1/campaigns:estimate
      Body: { "center": { "lat": 41.8902, "lon": 12.4922 }, "radius_m": 5000 }
      -> 200 { "approx_users": 34000 }          (rounded to nearest 100; refused if < 50 users)
    

    Notice what is never returned: no internal endpoint ever outputs user_id lists or coordinates.

  4. Data model and separating truth from the spatial index

    We store ephemeral location state in Redis Cluster using two built-in features: a TTL (Time-To-Live), which is an automatic countdown timer that deletes stale keys without manual cleanup, and a Sorted Set (ZSET), which keeps unique member IDs sorted by a numeric score (here, the Unix timestamp in seconds) so we can slice fresh members by time range in logarithmic time.

    Ephemeral state in Redis Cluster

    dev:<device_id>              HASH   { uid, cell, lat_3dp, lon_3dp, ts, acc_m }
                                        TTL = 20 minutes (refreshed on every valid ping)
    
    cell:<h3_cell>               ZSET   member = device_id, score = ts (Unix seconds)
    cell:<h3_cell>:<b>           ZSET   bucketed variant for hot cells (b = hash(device_id) mod B)
    
    hot_cells                    HASH   h3_cell -> bucket_count B (4, 16, or 64)
                                        cached in worker RAM and refreshed every 10 s
    
    dispatch:<campaign_id>:<uid> STRING "claimed:<worker_id>:<ts>" | "sent"
                                        TTL = 48 hours
    

    Two subtle Redis details prevent production outages:

    • Never put {...} curly braces in Redis key names unless you want keys pinned together. Redis Cluster treats {anything} as a hash tag and routes every key sharing that tag to the same single shard—which would pile all 64 buckets of London Heathrow or all 300,000 dispatch keys of a campaign onto one CPU core. Plain colons (cell:87195da49ffffff:3) hash across all shards evenly.
    • Two keys with separate jobs eliminate cross-shard transactions. dev:<device_id> is the single source of truth for where a device is right now; cell:<h3_cell> is merely a candidate list. If removing a moving device from its old cell fails, that leftover entry (a ghost entry) is harmlessly ignored at query time when we check dev:<device_id>.cell.

    Durable metadata in PostgreSQL (low write volume, persistent)

    user_devices    (user_id, device_id) PK, platform (IOS | ANDROID),
                    push_token_enc, push_enabled, home_region, updated_at
    
    campaigns       campaign_id PK, idempotency_key UNIQUE, created_by,
                    center_lat, center_lon, radius_m, priority, message_json,
                    status (RESOLVING | SENDING | DONE | CANCELLED),
                    matched_users, sent_count, failed_count, created_at, first_sent_at
    

    Kafka topics: location-updates (64 partitions keyed by device_id, 1-hour retention), resolve-tasks, send-urgent, send-normal, and delivery-results.

  5. High-level architecture

      [Mobile Devices]
             | POST /v1/devices/{id}/location (foreground ~20-30 s, background movement/heartbeat)
             v
      [API Gateway] (stateless JWT verify, rate limit) ---> [Ingestion Service] (drop stale / acc > 1 km)
                                                                   |
                                                                   | produce (key = device_id)
                                                                   v
                                                     [Kafka: location-updates (1 h TTL)]
                                                                   |
                                                     [Index Writers] (batch 500, keep newest/device)
                                                                   |
                                                                   v
                             +-------------------------------------------------------------------+
                             |           Redis Cluster (8 primaries + 8 replicas, ~6 GB)         |
                             |  dev:<device_id> (HASH, 20m TTL)   cell:<h3>[:<b>] (ZSET by ts)   |
                             +-------------------------------------------------------------------+
                                                           ^ ZRANGEBYSCORE + pipelined HMGET
                                                           |
      [Admin / Trip Alert Trigger]                         |
             | POST /internal/v1/campaigns                 |
             v                                             |
      [Campaign Service] ---> [Kafka: resolve-tasks] ---> [Resolver Workers]
             | (PostgreSQL:                                | (exact Haversine filter, emit user_ids)
             |  idempotency & audit)                       v
             |                              [Kafka: send-urgent | send-normal]
             v                                             |
      [Campaign Status API]                 [Send Workers] (Redis claim + token bucket + PG tokens)
                                                   |                              \
                                                   v                               v
                                            [APNs / FCM]                 [Kafka: delivery-results]
    

    Notice how the write path (top) and query/fan-out path (bottom) meet only at the in-memory Redis Cluster. A 300,000-user broadcast never blocks location ingestion, and a rush-hour location spike never stalls PostgreSQL or push workers.

  6. Deep dive 1: Geospatial indexing with H3 hexagons and exact filtering

    Why not run SELECT user_id FROM devices WHERE distance(lat, lon, center) <= 5000? Computing spherical distance against 10 million moving rows scans the whole table on every campaign, while maintaining a disk spatial index (like PostGIS R-trees) at 100,000 updates/second generates relentless page splits and dead-row cleanup for coordinates that expire in 15 minutes.

    Instead, we use a discrete global grid system—a standard math library that tiles the entire Earth into numbered shapes so any (lat, lon) maps to one string cell ID in microseconds, turning a 2D circle search into ~25 key-value reads:

    • Uber H3 (chosen): Tiles the globe with hexagons. Every hexagon has 6 neighbors whose centers sit at the exact same distance, cell areas vary by less than ~2x globally, and resolution 7 averages 5.16 km^2 (~2.44 km across)—a sweet spot for 1-10 km radii.
    • Google S2: Tiles the globe with projected squares numbered along a Hilbert space-filling curve (a fractal line visiting nearby squares with nearby integer IDs), which excels for range scans in ordered B-trees.
    • Geohash: Encodes (lat, lon) into base-32 rectangles. Easy to implement, but cells warp narrowly near high latitudes and two points 10 meters apart across the Prime Meridian (lon = -0.0001 vs +0.0001) share zero prefix characters.

    How a 5 km radius query executes

              _____
             /     \_____        Search circle (R = 5 km) overlaps ~23-30 H3 res-7 cells:
            /  in   /     \        - Interior cells: every fresh device inside matches
      _____ \_____/ edge  /        - Edge cells: contain both inside (+) and outside (x) devices
     /     \ /     \  + x \
    / edge  /  in   \_____/      Step 1: H3 polygon-to-cells ("overlapping" mode) -> ~27 cell IDs
    \ x  +  \  *C   /     \      Step 2: ZRANGEBYSCORE cell:<c> (now - 900) +inf  -> fresh device_ids
     \_____/ \_____/ edge  \     Step 3: Pipelined HMGET dev:<id>                 -> check truth & distance
             \  +  \   x   /
              \_____\_____/
    

    Because border hexagons stick partially outside the circle, cell lookup gives candidates, not final matches. Resolver workers fetch dev:<device_id> in pipelined batches of 1,000 and apply the Haversine formula—the standard spherical trigonometry equation that computes great-circle distance along Earth's curved surface:

    import math
    
    EARTH_RADIUS_M = 6_371_000
    FRESHNESS_WINDOW_S = 15 * 60
    
    
    def haversine_m(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
        # Convert decimal degrees into radians for trigonometric functions.
        phi1 = math.radians(lat1)
        phi2 = math.radians(lat2)
        delta_phi = phi2 - phi1
        delta_lambda = math.radians(lon2 - lon1)
    
        # Haversine chord-length term between the two points on a unit sphere.
        half_chord_sq = (
            math.sin(delta_phi / 2.0) ** 2
            + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2.0) ** 2
        )
        # Clamp to 1.0 so tiny floating-point rounding at antipodal points never breaks sqrt/asin.
        central_angle = 2.0 * math.asin(math.sqrt(min(1.0, half_chord_sq)))
        return EARTH_RADIUS_M * central_angle
    
    
    def matches_campaign(
        device_record: dict | None,
        queried_cell: str,
        center_lat: float,
        center_lon: float,
        radius_m: float,
        now_ts: int,
    ) -> bool:
        # Missing record means the 20-min TTL expired or the user deleted location sharing.
        if device_record is None:
            return False
        # Ghost check: ignore leftover ZSET entries if the device already moved to a newer cell.
        if device_record["cell"] != queried_cell:
            return False
        # Authoritative 15-minute freshness check.
        if now_ts - device_record["ts"] > FRESHNESS_WINDOW_S:
            return False
    
        distance_m = haversine_m(
            center_lat, center_lon, device_record["lat"], device_record["lon"]
        )
        return distance_m <= radius_m
    

    For example, a campaign centered at the Rome Colosseum (41.8902, 12.4922) with radius_m = 5000 checks a traveler near the Vatican Museums (41.9065, 12.4536): haversine_m evaluates to 3,673 m <= 5,000 m, so the user qualifies.

  7. Deep dive 2: Absorbing 100,000 location updates per second

    To keep the write path fast, cheap, and insensitive to out-of-order mobile packets, updates flow through four stages:

    Mobile ping -> Gateway (JWT check) -> Kafka (key = device_id) -> Index Writer (batch 500)
      |
      +-- 1. Coalesce in batch: if device d1 sent 3 pings in this 500-msg batch, keep only max(ts).
      +-- 2. Atomic Lua script on dev:<d1>:
             if existing.ts >= new.ts then return "STALE_IGNORED"
             save {uid, new_cell, round(lat, 3), round(lon, 3), new_ts, acc}; EXPIRE 1200
             return old_cell
      +-- 3. ZADD cell:<new_cell>[:<b>] new_ts d1
      +-- 4. If old_cell != new_cell: ZREM cell:<old_cell>[:<b>] d1   (best-effort, non-blocking)
    

    Why each detail matters:

    • Kafka buffers spikes and preserves per-device order. Partitioning by device_id routes all pings from one phone to the same consumer, and 1-hour retention acts as our black-box flight recorder if Redis ever loses memory.
    • A Lua script prevents backward time travel. Redis runs a Lua script—a tiny server-side routine executed atomically with zero interleaving—on dev:<d1>. If a delayed cellular packet arrives with ts = 100 after Wi-Fi already wrote ts = 120, the script rejects ts = 100 immediately.
    • No slow cross-shard locks on cell crossings. dev:<d1> and cell:<old_cell> live on different Redis shards. Instead of coordinating a distributed transaction when a traveler crosses a hexagon border, we remove d1 from old_cell best-effort; if that ZREM drops, matches_campaign filters out the ghost entry because device_record["cell"] != old_cell.
    • Bounding sorted-set memory. Redis TTLs expire whole keys, not individual ZSET members. Writers run ZREMRANGEBYSCORE cell:<c> -inf (now - 900) once every ~200 writes to a cell, and a lightweight background sweeper trims idle cells once per minute so quiet towns never leak stale member IDs.
  8. Deep dive 3: Durable fan-out and preventing duplicate pushes

    Once resolver workers match fresh in-radius devices, how do we deliver hundreds of thousands of notifications reliably without double-buzzing users?

    1. Stream user batches immediately. Each resolver task handles one H3 cell (or one hot-cell bucket), deduplicates user_ids locally within that cell, and publishes batches of up to 500 user_ids to Kafka (send-urgent or send-normal). Send workers start pushing the first batch within ~100 milliseconds of the campaign trigger while larger cells are still resolving.
    2. Claim before sending with a crash-safe lease. Before calling APNs or FCM for user u1, a send worker runs a short atomic Lua check on dispatch:<campaign_id>:<u1>:
    Check dispatch:cmp_44b:u1 in Redis:
      - Key missing                       -> SET "claimed:worker_7:1764680010" (TTL 48h) -> SEND
      - Value == "sent"                   -> SKIP (already delivered by an earlier batch or second device)
      - Value == "claimed:..." (< 2m old) -> SKIP (another worker is actively sending right now)
      - Value == "claimed:..." (>= 2m old)-> Overwrite claim & SEND (previous worker crashed mid-flight)
    
    1. Mark "sent" after provider 200 OK, then commit Kafka offset. Why not mark "sent" before calling APNs/FCM? Because if the worker crashed before making the network call, that user would silently miss an urgent trip alert (at-most-once loss). Claiming first and marking "sent" after gives at-least-once delivery.
    2. Device-level collapse IDs catch the final millisecond race. No backend can guarantee mathematical exactly-once delivery across an external network: if APNs accepts a push and our worker loses power 2 milliseconds before writing "sent", a retry worker will resend after 2 minutes. Setting apns-collapse-id = campaign_id on iOS and collapse_key + notification tag = campaign_id on Android instructs the phone's operating system to overwrite the first banner in place instead of buzzing twice.
  9. Deep dive 4: Hotspots, privacy, and failure recovery

    Surviving hotspots (London Heathrow or Midtown Tokyo)

    When 300,000 travelers pack into a few hexagons, three bottlenecks appear at once—and each needs a targeted defense:

    • Hot Redis keys -> Dynamic hash bucketing. Even shrinking H3 from resolution 7 (5.16 km^2) to resolution 9 (~0.10 km^2) still leaves 40,000 passengers inside one airport terminal hexagon, while inflating normal 5 km queries from ~27 keys to ~900 keys! Instead, a 1-minute stats job spots any cell above 15,000 members and sets hot_cells[cell] = B (4, 16, or 64). Writers route updates to cell:<c>:<b> where b = hash(device_id) mod B. Because each bucket key hashes to a different Redis Cluster slot, reads and writes spread evenly across all 8 shards. During a 15-minute transition after B changes, resolvers read both cell:<c> and cell:<c>:0..B-1; user-level dispatch claims prevent duplicates.
    • Push-gateway saturation -> Priority lanes + token-bucket rate limiting. A shared token bucket (a counter refilled at a steady rate, such as 20,000 tokens/second, where each push consumes one token) paces outbound calls to APNs/FCM. send-urgent gets reserved capacity ahead of send-normal, and non-urgent campaigns exceeding max_recipients require secondary approval and smooth pacing over 1–3 minutes.
    • App-open thundering herd -> Paced sends + CDN pre-warming. Notifying 300,000 users in the same second makes tens of thousands tap the deep link simultaneously. Pacing normal campaigns over 60–180 seconds and pre-caching the destination trip page on a CDN (Content Delivery Network) shields core APIs.

    Privacy and regional compliance (GDPR / CCPA)

    • Data minimization and coordinate coarsening: Only the single latest ping is stored, rounded to 3 decimal places (0.001 degrees is ~111 m north-south, shifting a point by at most ~79 m diagonally at the equator), with a 20-minute Redis TTL and 1-hour Kafka retention. No historical breadcrumb table exists.
    • Anti-triangulation guards: Minimum 1 km radius for normal campaigns, rounded estimates refused under 50 users, and strict audit logs prevent an insider from intersecting three slightly shifted circles to isolate one traveler.
    • Traveler data residency: An Italian user visiting Tokyo is routed by home_region = EU to our EU Redis cluster so EU personal data stays in Europe. Because travelers frequently cross continents, the Campaign Service fans each campaign query out to all regional clusters (us, eu, apac) in parallel—only 3 parallel regional lookups of ~27 cells each.

    Failure handling

    • Single Redis primary crash: Its replica promotes automatically within seconds; async replication may drop 1–2 seconds of pings, which devices naturally refresh on their next heartbeat.
    • Total Redis cluster loss: Index writers replay the last 15 minutes of location-updates from Kafka (~90M messages at peak), deduplicating per device_id in memory before writing <= 10M fresh states back into Redis in ~3 minutes.
    • Ingestion overload: Return 429 with X-Report-Interval-S: 120 so phones back off gracefully; dropping an intermediate GPS ping is harmless because the next ping replaces it anyway.
  10. Summary of key design choices

    Requirement / Challenge        Design Choice                         Why It Wins Here
    -----------------------------  ------------------------------------  --------------------------------------------
    100k location writes/s         Kafka + Redis HASH/ZSET (20m TTL)     ~3 GB fits in RAM; avoids disk index churn
    Fast 5 km circle lookup        H3 res-7 cover + exact Haversine      Turns 2D geometry into ~27 key-value reads
    No cross-shard write locks     dev:<id> truth + lazy ghost filter    2 fast single-key ops per ping, zero 2PC
    < 10 s time-to-first-push      Stream cell batches via Kafka         First pushes leave in < 1 s while resolving
    No duplicate user alerts       Per-user Redis claim + collapse IDs   Crash-safe retries + OS-level banner dedup
    Airport / city hotspots        Hash-bucket hot cells + token bucket  Spreads hot cell across all shards; paces push
    

Intuition & how it works

Think of tracking 10 million moving phones like managing a wall of neighborhood cubbyholes where every paper slip self-destructs after 15 minutes. When a traveler's phone reports its location, we do not append to a permanent diary; instead, we overwrite that device's single status card in memory and drop its ID into the cubbyhole for the ~2.4 km hexagonal map tile (Uber H3 cell, a numbered hexagon from a standard global map grid) where the phone currently stands. When an urgent trip alert fires for a 5 km circle, we do not measure distances to all 10 million users—we simply pull the ~27 hexagonal cubbyholes that touch the circle, toss out any slip older than 15 minutes, check exact spherical distance (Haversine distance, the shortest path between two coordinates along Earth's curved surface) for those candidates, and stream matched user IDs into a durable worker queue that pushes notifications through Apple and Google's gateways.

Why do the obvious approaches fall short? Writing 100,000 GPS updates per second into a traditional disk database like PostgreSQL/PostGIS forces constant disk-index splits and dead-row cleanup for coordinates that become worthless 15 minutes later. Scanning every active user without a grid index turns each campaign into millions of trigonometry calculations, while stuffing a whole city or airport into a single spatial key overloads one CPU core. Finally, looping over matched users and calling push gateways directly inside one API server loses half the audience if that server crashes—or double-notifies travelers if a retry restarts from the top.

Let's trace a tiny concrete example with 4 devices near a 5 km campaign centered at the Rome Colosseum (41.8902, 12.4922) triggered at t = 2,000:

1. Live Redis state just before t = 2,000 (freshness cutoff = 2,000 - 900 = 1,100):
   - d1 (user u1, iPhone):  near Vatican Museums (41.907, 12.454), cell H_A, ts = 1,980 (fresh, 3.7 km away)
   - d2 (user u1, iPad):    near Trevi Fountain  (41.901, 12.483), cell H_B, ts = 1,950 (fresh, 1.4 km away)
   - d3 (user u2, Android): rode metro from H_A -> H_C (6.5 km away) at ts = 1,990,
                            but old ZREM on H_A failed, leaving a "ghost" d3 entry in H_A!
   - d4 (user u3, iPhone):  near Pantheon        (41.899, 12.477), cell H_A, ts = 1,020 (stale: 980 s old)

2. Resolve cells overlapping the 5 km circle (includes H_A and H_B, excludes H_C):
   - H_A ZRANGEBYSCORE [1100, +inf] returns [d1, d3] (d4 is skipped immediately because 1020 < 1100).
   - Fetch dev:d1 and dev:d3 hashes:
       * dev:d1 -> cell == H_A, ts = 1980, Haversine = 3.7 km <= 5.0 km -> KEEP user u1!
       * dev:d3 -> dev:d3.cell is H_C != H_A (ghost entry!)             -> DROP!
   - H_B ZRANGEBYSCORE [1100, +inf] returns [d2] -> Haversine = 1.4 km  -> KEEP user u1!

3. Durable deduplicated send:
   - Worker A claims dispatch:cmp_44b:u1 -> "claimed", pushes to u1 with collapse_id = "cmp_44b",
     then marks dispatch:cmp_44b:u1 -> "sent".
   - Worker B sees u1 from H_B, checks dispatch:cmp_44b:u1 == "sent", and skips -> u1 notified once!

Key trade-offs

  • In-memory TTL index (Redis) vs. durable spatial database (PostGIS): Keeping only the latest location in Redis with a TTL (Time-To-Live)—an automatic expiration timer—absorbs 100,000 updates/second in ~3 GB of RAM and forgets old positions automatically. PostGIS offers richer ad-hoc SQL geometry queries, but pays heavy disk write amplification and vacuuming overhead on data that expires in 15 minutes; with Redis, we rely on 1-hour Kafka (a distributed append-only message log) retention to rebuild state after a full cluster outage.
  • Uber H3 hexagons vs. Google S2 squares vs. Geohash rectangles: H3 gives uniform neighbor distances and simple key-value cell lookups, at the cost of reading extra border candidates around the circle's rim and filtering them with exact Haversine math. Google S2 maps nested squares onto a contiguous integer curve (great for ordered range scans), while Geohash is trivial to compute without a library but suffers severe distortion near high latitudes and cliff-edge prefix changes across meridians.
  • Lazy ghost filtering vs. atomic cross-shard cell moves: Updating dev:<id> and cell:<new> without locking cell:<old> avoids slow distributed transactions across Redis shards on 100,000 writes/second. The trade-off is an extra device.cell == queried_cell check when reading candidates, plus occasional ghost IDs lingering for up to 15 minutes if a best-effort ZREM fails.
  • Dynamic hash bucketing for hot cells vs. finer global grid resolution: Splitting only dense cells (like London Heathrow) into B hash buckets (cell:<h3_cell>:0..B-1) caps every sorted set below ~15,000 members across multiple shards while keeping normal 5 km queries at ~27 keys. Globally shrinking cells to resolution 9 (~0.10 km^2) inflates every 5 km query to ~900 keys and still leaves tens of thousands of travelers crowded inside a single airport terminal hexagon.
  • At-least-once leases + OS collapse IDs vs. at-most-once marking: Claiming a user with a 2-minute lease and marking "sent" after APNs/FCM responds guarantees no silent drops when workers crash, whereas marking "sent" beforehand drops urgent alerts on crash. Rare split-second crash duplicates are hidden on the phone using an OS collapse ID (a header telling iOS/Android to replace an existing banner with the same campaign ID).
  • Freshness window length vs. background reach: A strict 15-minute window avoids messaging travelers who already drove out of the area, but excludes backgrounded phones that mobile operating systems throttle to 2–4 updates per hour.

Common mistakes

  • Appending every GPS update to a historical database table: Storing 100,000 rows/second accumulates ~8.6 billion rows per day—massive storage cost and severe privacy liability—when the product only ever queries each device's current position.
  • Accepting H3 cell matches without an exact Haversine distance check: Border hexagons stick up to ~2.4 km outside the circle, silently notifying users well beyond radius R.
  • Putting {...} curly braces in Redis Cluster key names: Writing cell:{87195da49ffffff}:bucket_3 or dispatch:{cmp_44b}:u9 triggers Redis Cluster hash tags, forcing every bucket of an airport or every recipient of a 300,000-user campaign onto a single shard and causing a hot-shard outage.
  • Relying on a whole-key TTL on cell:<h3_cell> for freshness: Every new ZADD to a busy city hexagon resets that key's TTL, so old members inside an active hexagon never expire unless you query with ZRANGEBYSCORE (now - 900) +inf and periodically trim with ZREMRANGEBYSCORE.
  • Allowing out-of-order network packets to overwrite newer locations: Without comparing new_ts > stored_ts inside an atomic Redis Lua check, a delayed 4G packet from 3 minutes ago can teleport a user backward into an old neighborhood.
  • Resolving all 300,000 recipients before dispatching push #1: Waiting for full resolution plus synchronous token lookups risks blowing past the 10-second dispatch SLA; streaming 500-user batches per cell starts delivery in under 1 second.
  • Designing as if background mobile apps can ping GPS every 5 seconds: Both iOS and Android aggressively suspend background GPS polling to protect battery life; any backend assuming continuous 5-second pings from all 10M DAU will find 80%+ of users permanently "stale."

Follow-up questions

  • What happens when an alert targets an ultra-dense transit hub such as London Heathrow or Midtown Tokyo, matching several hundred thousand travelers at once? On the read side, our 1-minute hotspot monitor has already split dense airport and downtown cells into B hash buckets (cell:<h3>:0..63) spread across all Redis shards, so resolver workers scan those buckets in parallel in hundreds of milliseconds and immediately stream 500-user batches into Kafka. On the delivery side, a global token-bucket rate limiter (for example, 20,000 pushes/second) prevents overwhelming APNs/FCM while dedicated priority queues (send-urgent vs. send-normal) ensure a promotional blast in Midtown Tokyo never blocks an emergency terminal alert. Finally, non-urgent campaigns above max_recipients require a second approval and pace delivery over 1–3 minutes while pre-warming deep-linked pages on a CDN so 300,000 simultaneous taps do not crash core backend APIs.
  • How do mobile battery limits and OS background throttling shape your reporting protocol as apps move between active use and background suspension? Continuous GPS hardware polling drains a phone battery in hours, so iOS (significant-change ~500 m events and OS region monitoring) and Android 8+ restrict background apps to sparse, movement-driven updates a few times per hour. To work with the OS instead of fighting it, every 204 ingestion response returns an adaptive X-Report-Interval-S header: while in the foreground, the app sends an immediate fix on open (often reusing the OS's cached location at near-zero battery cost) and pings every 20-30 seconds if moving more than 100 m; when transitioning to the background, it switches to OS significant-location-change events plus sparse heartbeats. For campaigns with an active time window (valid_for_s > 0), the app can also register the nearest few active circles as native OS geofences (both iOS and Android wake the app in the background using low-power Wi-Fi/cell triangulation when crossing a registered boundary).
  • How would you adapt data retention, coordinate precision, and regional indexing to satisfy strict privacy laws such as GDPR and CCPA while preserving proximity alerts? First, enforce strict minimization and coarsening: store only a pseudonymous ID, round coordinates to 3 decimal places (~111 m grid) before writing to Redis, enforce a 20-minute Redis TTL and 1-hour Kafka retention, keep zero historical trails, and immediately DELETE dev:<id> when consent is revoked. Second, lock down the campaign and estimate APIs with a minimum 1 km radius, minimum 50-user rounded estimates, and audit logs so nobody can intersect overlapping circles to locate one person, while routing each user's writes to their home-region cluster (querying eu, us, and apac clusters in parallel during campaigns). If regulations forbid the server from seeing even ~100 m coordinates, switch to client-side fine filtering: devices report only a coarse city-level H3 cell (res 4, ~1,770 km^2), the server sends a silent data push containing (center_lat, center_lon, radius_m) to all devices in that city cell, and the app checks exact GPS distance locally on the phone before displaying the banner—trading higher push volume for zero server-side fine location storage.

Follow-up questions

Similar questions

More Fora Travel interview questions

All 7 Fora Travel questions →