Low-Latency Rolling-Window Analytics for Food Delivery

Medium · System Design · Software Engineer · Onsite

Prompt

Design the backend streaming pipeline, storage layout, and serving tier for a live merchant analytics dashboard operating across a worldwide meal-delivery marketplace. Both individual restaurant operators and internal operations teams rely on this dashboard to monitor order count, gross sales revenue, and best-selling menu items across three continuously moving lookback intervals: the past 1 hour, past 24 hours (1 day), and past 7 days.

Your design must meet four operational targets:

  • Write throughput: Process 100,000 incoming orders per second worldwide.
  • End-to-end freshness: Surface newly placed orders on dashboard widgets within at most 5 seconds.
  • Aggregation scopes: Serve both single-restaurant metrics and platform-wide rollups.
  • Spike durability: Absorb sudden mealtime traffic surges without dropping order events.

Scope & Expectations

  • Streaming Ingestion & Windowing: Trace event delivery from the transactional order service through durable queuing and distributed stream processing, detailing how sliding windows, watermarks, and late or out-of-order events are handled inside the 5-second latency budget.
  • Write-Optimized Primary Persistence: Propose a long-term database schema and partitioning strategy engineered to sustain continuous high-volume writes without hot partitions.
  • Serving Cache & Query API: Define the Redis key layout and read endpoints that deliver multi-window totals and top-selling items efficiently for both individual merchants and global views.
  • Fault Tolerance & Cache Reconstruction: Explain how the system recovers from worker, broker, or cache failures and how lost or drifted cache state can be rebuilt rapidly without hours of dashboard downtime.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Counting incoming food orders sounds simple until three real-world constraints collide:

    • Sliding windows move forward even when a restaurant is quiet. In a sliding window (a continuously moving lookback interval such as "the past 60 minutes right now"), totals must automatically decrease as 61-minute-old orders age out—even if zero new orders arrive.
    • Events arrive late, duplicated, or retracted. Network retries create duplicates, database failovers delay events by minutes, and order cancellations subtract revenue that was already counted.
    • "Top-selling dishes" is not a simple sum. Unlike order count or revenue, you cannot find the new #1 dish after a cancellation or window slide unless you track underlying dish frequencies.

    Our core architecture solves all three inside a stateful stream processor that pushes finished, ready-to-display answers into Redis so dashboard reads are single-key lookups.

    Functional requirements

    • Track total order count, gross revenue, and top 10 selling dishes across 1-hour, 1-day, and 7-day sliding windows.
    • Serve both per-restaurant views (for restaurant managers) and platform-wide / regional aggregate views (for internal operations).
    • Persist historical aggregates in a primary database for trend charts, auditing, and fast cache recovery.

    Non-functional requirements & confirmed assumptions

    • Throughput: Ingest 100,000 orders/s globally at peak (~35,000 orders/s average, or ~3.0B orders/day), with zero event loss during spikes.
    • End-to-end latency: Maximum 5 seconds from order placement to visible dashboard numbers.
    • Catalog scale: ~1,000,000 active restaurants across 3 cloud regions, averaging ~100 menu dishes per restaurant (~3 dish line items per order = 300,000 dish updates/s at peak).
    • Window precision: Exact per-millisecond sliding over 7 days would require keeping ~21 billion individual orders in RAM. Instead, we divide windows into fixed time buckets: 1h = 60 x 1-minute buckets, 1d = 288 x 5-minute buckets, and 7d = 168 x 1-hour buckets (plus the active partial bucket), bounding edge approximation error to <= 1.7% while slashing memory by orders of magnitude.
    • Money & time semantics: Windows use event time (placed_at, the timestamp when the customer placed the order). Revenue is stored in integer minor currency units (for example, cents) in the restaurant's local currency, and converted to USD cents at placed_at exchange rates for platform-wide views.
  2. Back-of-the-envelope numbers

    1. Ingestion & durable log (Kafka)
       Peak order rate:     100,000 orders/s x ~1 KB/event = ~100 MB/s ingress (~300 MB/s disk writes at 3x replication)
       Daily volume:        35,000 orders/s avg x 86,400 s = ~3.0B orders/day (~300,000 dish items/s at peak)
       7-day Kafka log:     3.0B x 7 days x 1 KB = ~21 TB logical (~63 TB raw disk across 3 replicas)
    
    2. Stream processor state (Apache Flink + RocksDB, upper bound across 1M restaurants)
       Order & revenue buckets per restaurant:
         (61 x 1-min) + (289 x 5-min) + (169 x 1-hr) = 519 buckets x 16 bytes (count + rev) = ~8.3 KB
         Across 1M restaurants: ~8.3 GB raw payload (~22 GB on disk/RAM with RocksDB key overhead)
       Dish frequency buckets per restaurant (coarser buckets to bound state: 5-min for 1h, 1-hr for 1d, 1-day for 7d):
         (12 x 40 dishes) + (24 x 60 dishes) + (7 x 90 dishes) = ~2,550 entries x 20 B = ~51 KB/restaurant
         Upper bound if all 1M restaurants are busy: ~51 GB raw (smaller in practice due to long-tail skew)
       1-hour event_id deduplication state:
         At sustained 100k/s peak: 360M IDs x ~30 B = ~11 GB total across the cluster
       Task parallelism: ~10,000 orders/s per Flink slot -> 10 slots needed; run 64 slots globally (~22/region)
                         for ~6x spike headroom and 3x catch-up replay speed (~1.5-2 GB state per slot)
    
    3. Serving cache (Redis) & primary database writes
       Redis memory:   1M restaurants x ~3.5 KB (metrics hash + three top-10 JSON lists + 60-min chart) = ~3.5 GB!
       Redis reads:    200,000 open dashboards polling every 2 s = 100,000 reads/s (served across read replicas)
       Redis writes:   <=100,000 active restaurant updates/s (coalesced once per second)
                       + <=1M minute-boundary bucket expirations/min (~17,000/s avg, <=200,000/s over 5 s jitter)
       DB writes:      ~1M restaurant-minute rows/min (~17,000 writes/s) + ~60M dish-hour rows/hr (~17,000 writes/s)
    
    4. Cold replay time from raw events
       7 days = ~21B events; replaying at 1M events/s takes ~5.8 hours (or ~1.5 hours at 4M/s) -> we need fast rebuild tiers!
    

    What the numbers reveal: 100 MB/s of Kafka ingest and 3.5 GB of Redis RAM are modest, whereas per-dish state (~51 GB) and multi-hour raw replay times are the real engineering constraints that shape our bucket sizes and recovery design.

  3. Event contract and dashboard API

    Every state change in the Order Service emits an immutable OrderEvent (serialized in Protobuf or Avro, partitioned in Kafka by restaurant_id):

    OrderEvent
      event_id         UUID (unique per emission; used for deduplication)
      event_type       PLACED | CANCELLED | AMENDED | CORRECTION
      order_id         string
      restaurant_id    string (Kafka partition key -> keeps each restaurant ordered on one stream task)
      region           string ("us-east", "eu-west", "apac")
      placed_at        int64 epoch ms (ORIGINAL order placement time, carried even on CANCELLED events!)
      occurred_at      int64 epoch ms (when this specific event happened)
      currency         string ("EUR", "USD", ...)
      usd_fx_rate      fixed-point integer (for platform-wide USD aggregation)
       signed_orders   +1 for PLACED, -1 for CANCELLED, 0 for price-only AMENDED
      signed_rev_minor int64 signed cents (+3250 or -3250; never IEEE floats, which drift over billions of sums)
      items_delta      [ { dish_id, dish_name, signed_qty, signed_rev_minor } ]
    

    Carrying the original placed_at and full items_delta directly inside every CANCELLED and AMENDED event is vital: stream workers can subtract cancelled dishes immediately in memory without querying an external order database at 100,000 req/s.

    GET /v1/restaurants/{restaurant_id}/metrics?windows=1h,1d,7d
      200 OK
      { "restaurant_id": "m-805", "currency": "USD",
        "as_of": "2026-11-30T18:00:03Z", "stale": false,
        "windows": {
          "1h": { "orders": 385, "gross_revenue_minor": 1078000,
                  "top_dishes": [ {"dish_id": "item-19", "name": "Garlic Noodles", "qty": 96}, ... ] },
          "1d": { ... },
          "7d": { ... }
        } }
    
    GET /v1/platform/metrics?windows=1h,1d,7d&region=all     (internal ops; revenue in USD minor units)
    GET /v1/restaurants/{restaurant_id}/series?window=1h     (60 one-minute points for live sparkline chart)
    WS  /v1/stream?restaurant_id=m-805                       (optional WebSocket push for active screens)
    

    Returning as_of and stale explicitly ensures that during a pipeline delay, managers see "Updated 45s ago (delayed)" instead of mistaking frozen numbers for zero new orders.

  4. Tiered storage strategy and write-heavy database schema

    No single database excels at 100,000 append-only raw writes/s, 2-year historical scans, and sub-millisecond dashboard reads, so we separate storage into four purpose-built tiers:

    Tier                         Technology                 Retention   Role
    -------------------------------------------------------------------------------------------------------------
    1. Immutable streaming log   Apache Kafka               7 days      Buffers spikes, feeds Flink, short replays
    2. Cold data lake            Object Storage (Iceberg)   Multi-year  Raw Parquet archive for audits & backfills
    3. Primary aggregate DB      ScyllaDB / Cassandra       2 years     Durable minute/hour buckets & cache bootstrap
    4. Low-latency serving view  Redis Cluster              Live state  Pre-computed window hashes read by dashboards
    

    Primary database schema (Cassandra / ScyllaDB — a distributed wide-column store optimized for high-throughput partitioned writes without master bottlenecks):

    CREATE TABLE restaurant_minute (
        restaurant_id  text,
        day            date,          -- UTC YYYY-MM-DD
        minute         timestamp,     -- truncated to minute
        orders         bigint,
        gross_minor    bigint,
        cancelled_cnt  bigint,
        currency       text,
        version        bigint,
        is_final       boolean,
        PRIMARY KEY ((restaurant_id, day), minute)
    ) WITH CLUSTERING ORDER BY (minute DESC);
    
    CREATE TABLE restaurant_dish_hour (
        restaurant_id  text,
        day            date,
        hour           timestamp,
        dish_id        text,
        qty            bigint,
        gross_minor    bigint,
        version        bigint,
        is_final       boolean,
        PRIMARY KEY ((restaurant_id, day), hour, dish_id)
    );
    
    CREATE TABLE platform_minute (
        scope          text,          -- 'global' or 'region:eu-west'
        day            date,
        minute         timestamp,
        orders         bigint,
        gross_usd_minor bigint,
        version        bigint,
        is_final       boolean,
        PRIMARY KEY ((scope, day), minute)
    );
    

    How this schema handles write-heavy workloads cleanly:

    • Composite partition key (restaurant_id, day) avoids hot partitions and unbounded growth. Partitioning by minute alone would hammer a single storage node with all 17,000 writes/s for the current minute! Including restaurant_id spreads writes evenly across all cluster nodes, while including day caps every physical partition at a predictable 1,440 minute rows (~100 KB) so partitions never grow unbounded over years.
    • Idempotent absolute-value upserts instead of COUNTER columns. An operation is idempotent if applying it once or three times produces the exact same stored result. Distributed COUNTER increments (SET orders = orders + 1) double-count whenever a network timeout triggers a retry. Instead, Flink writes the complete bucket total (orders = 18, gross_minor = 54200, version = 4)—if a late event updates that minute or a write retries, overwriting with the latest absolute value is 100% safe.
  5. High-level data pipeline and 5-second latency budget

     [ Order Service DB ]  (commits order row + outbox_event row in ONE atomic local DB transaction)
              |
              v
     [ CDC / Outbox Relay ] --(acks=all)--> [ Kafka: orders (128 partitions, key = restaurant_id) ] ---> [ Iceberg Sink ]
                                                        |
                                                        v
                [ Apache Flink Stream Job (per region, ~22 task slots, RocksDB incremental checkpoints / 30 s) ]
                  |-- 1. Deduplicate event_id (keyed state per restaurant, 1 h TTL)
                  |-- 2. Update 1h / 1d / 7d metric buckets + running totals + staggered expiry timers
                  |-- 3. Update coarse dish buckets + recompute exact per-restaurant Top-10
                  |-- 4. Emit regional partial sums & top-10 candidates (unbatched forwarding)
                         |                                     |                                   |
            (every 1 s: dirty keys)              (on watermark: final buckets)         (streamed partials)
                         v                                     v                                   v
             [ Regional Redis Cluster ]            [ ScyllaDB / Cassandra ]           [ Global Aggregator ]
              (versioned Lua HSET)                  (long-term bucket store)           writes g:{global} to all regions
                         ^
                         | single HGETALL (~0.5 ms)
             [ Dashboard API / WebSocket Gateway ] <--- Restaurant & Ops Browsers (2 s poll or live WS push)
    

    To guarantee zero lost events between the Order Service committing an order and Kafka receiving it, we use the transactional outbox pattern: the Order Service inserts both the orders row and an outbox event row inside the same database transaction, and a Change Data Capture (CDC) relay tails the database commit log into Kafka with acks=all.

    Verifying the 5-second end-to-end latency budget:

    Stage                                              Worst-case time
    ------------------------------------------------------------------
    Order DB commit -> CDC outbox relay -> Kafka             0.50 s
    Kafka fetch -> Flink in-memory bucket update             0.10 s
    Flink per-restaurant micro-batch emit interval           1.00 s
    Redis pipelined Lua HSET                                 0.02 s
    Dashboard browser poll interval (or <0.1 s via WS)       2.00 s
    ------------------------------------------------------------------
    Per-restaurant worst-case delay:                         3.62 s  (~1.38 s safety margin)
    Platform-wide view (+ unbatched cross-region merge):     3.82 s  (~1.18 s safety margin)
    

    Notice why only the first Flink stage batches for 1.00 s: if the regional and global merge stages also buffered for 1 second each, platform-wide latency would climb to 5.62 s and miss the SLA! Because 22 task slots produce only 22 partial messages per second per region, forwarding those partials immediately adds just ~200 ms (including the cross-region network hop).

  6. Deep dive 1: Sliding windows with buckets and expiry timers

    Instead of scanning 60 buckets on every read, Flink maintains a running window total in RocksDB keyed state alongside the active buckets—adding new events at the front and subtracting expired buckets at the back:

    1-hour window for Restaurant m-805 at 18:03:20 (sum of 60 completed 1-min buckets + current 18:03 bucket):
    
      [17:03: 4]  [17:04: 2]  [17:05: 0] ... [18:01: 5]  [18:02: 3]  |  [18:03 (active): 2]
      ^--- expires when clock passes 18:04 -> subtract 4 from running_total!    ^--- new order adds +1 here & +1 to running_total
    
    When OrderEvent(placed_at, signed_orders, signed_rev_minor) arrives for restaurant r:
      For each window W in { 1h (1-min bucket), 1d (5-min bucket), 7d (1-hr bucket) }:
        b = truncate_to_bucket(placed_at, W.bucket_size)
        if b is within W's active time range relative to now():
            bucket[r][W][b] += (signed_orders, signed_rev_minor)
            running_total[r][W] += (signed_orders, signed_rev_minor)
            register_expiry_timer_if_absent(r, W, b.expires_at + jitter(r))
            mark_dirty(r)
    
    When expiry timer fires for (r, W, b):
      running_total[r][W] -= bucket[r][W][b]
      delete bucket[r][W][b]
      mark_dirty(r)
    
    Every 1 second:
      Flush running_total[r] to Redis for all dirty restaurants r, then clear dirty set.
    

    Three subtle edge cases this handles cleanly:

    • Quiet restaurants decay to zero automatically: Because every non-empty bucket registers a processing-time expiry timer, if a restaurant gets a rush at 18:05 and closes at 18:10, its timer at ~19:06 still fires, subtracts the 18:05 bucket, and pushes the reduced total (0) to Redis—no incoming event required.
    • Timer jitter prevents minute-boundary write spikes: Minute boundaries happen simultaneously for everyone (18:04:00.000). Offsetting each restaurant's timer by jitter(r) = hash(r) mod 5,000 ms spreads up to 1M bucket expirations smoothly across 5 seconds (<= 200,000 writes/s peak, <= 17,000/s average, zero timers for empty buckets) while staying inside our 5-second freshness budget.
    • Out-of-order cancellations commute: Because PLACED (+1) and CANCELLED (-1, carrying the original placed_at) are signed deltas added to the same bucket, even if a cancellation arrives before its placement event due to a retry quirk, their sum nets cleanly to 0.
  7. Deep dive 2: Watermarks, late events, and deduplication

    In stream processing, event time is when an order actually happened (placed_at), processing time is the server's current wall clock, and a watermark is a moving timestamp marker asserting "we believe almost all events with placed_at <= W have arrived" (computed per Kafka partition as max_seen_placed_at - 10 seconds, with idle-partition bypass so a quiet partition never stalls progress).

    Critical insight—never block live dashboard updates on the watermark! Waiting 10 seconds for a watermark before emitting to Redis would violate our 5-second SLA on every single order. Instead, we decouple live serving from finality:

    1. Immediate provisional serving: Flink updates running window totals and emits to Redis every 1 second as events arrive.
    2. Seamless late-event absorption: Suppose a mobile or DB hiccup delivers an order 20 minutes late. Because Flink retains 7 days of buckets in RocksDB state anyway, that 20-minute-late event lands cleanly into its historical 1-minute, 5-minute, and 1-hour buckets—immediately correcting the 1h, 1d, and 7d dashboard totals and re-upserting its historical row in ScyllaDB with version + 1! Events older than 7 days route to a side output for our batch reconciliation job.
    3. What the watermark actually triggers: Once the watermark passes bucket_end + 1 minute, Flink flushes that completed bucket to ScyllaDB marked is_final = true and increments a late_events_count metric on anything arriving afterward so SREs get alerted if upstream lag grows.

    In-place deduplication and effective exactly-once: Because CDC relays guarantee at-least-once delivery, retries produce duplicate event_ids. Keeping a MapState<event_id, timestamp> with a 1-hour TTL inside the already restaurant_id-keyed operator drops duplicates with zero extra network shuffle. Combined with Flink's 30-second state checkpoints and absolute-value overwrites into Redis (never INCRBY!), replaying the last 30 seconds after a worker crash recalculates the exact same totals without needing a slow 30-second two-phase-commit transactional sink.

  8. Deep dive 3: Top-selling dishes — exact lists vs. Count-Min Sketch

    1. Per-restaurant Top 10 (exact in memory): Each restaurant has ~100 menu items. Using coarse dish buckets (12 x 5-min for 1h, 24 x 1-hr for 1d, 7 x 1-day for 7d) keeps RocksDB state bounded while maintaining an exact Map<dish_id, window_qty> per restaurant. Whenever a restaurant's dish counts change, sorting ~100 entries in memory to extract the top 10 takes microseconds.

    2. Platform-wide Top 10 — depends on whether dish_id is per-store or shared across locations:

    • Case A — dish_id belongs to a single restaurant storefront: Any dish in the global top 10 has at most 9 dishes ahead of it across the entire world, so it certainly cannot have 10 dishes ahead of it inside its own restaurant! (Break ties identically everywhere by (qty DESC, dish_id ASC).) Thus the exact global top 10 is guaranteed to sit inside the union of per-restaurant top-10 lists: 64 parallel merge tasks maintain top-10 heaps over ~15,600 restaurants each, and 1 global task merges those 64 x 10 = 640 finalists in under a millisecond—100% exact!
    • Case B — Cross-restaurant dish names or chain catalog IDs (for example, summing "Crispy Tofu Bowl" across 25,000 chain locations or tracking top dishes per city and cuisine): Here a dish could rank #12 at each of 25,000 stores and still be #1 globally, and tracking exact counts for millions of dish names across thousands of slices and 43 buckets explodes state and shuffle cost. This is where a Count-Min Sketch shines.

    A Count-Min Sketch (CMS) is a compact, fixed-size 2D table of d rows by w columns of integer counters indexed by d independent hash functions: adding (dish, +qty) adds qty to table[row][hash_row(dish) mod w] in all d rows, and querying dish takes the minimum of its d cells (since hash collisions only add extra counts, CMS never underestimates, and overestimates by at most epsilon * N_total_items with probability >= 1 - delta).

    Sizing a linear Count-Min Sketch (using 8-byte int64 counters so 7-day 63B-item sums never overflow):
      w = ceil(e / epsilon),   d = ceil(ln(1 / delta))
      Global sketch (epsilon = 1e-5, delta = 0.01):
        w = 271,829, d = 5  ->  1.36M x 8 bytes = ~10.9 MB per sketch (max error <= 0.001% of window items)
      Per city-cuisine slice (epsilon = 1e-3, delta = 0.01):
        w = 2,719,   d = 5  ->  13,595 x 8 bytes = ~109 KB per sketch (~4.7 MB across all 43 buckets of a slice)
    

    Because standard CMS counters are plain linear sums, we slide a window sketch just like integer buckets: add the active bucket sketch and subtract the expiring bucket sketch! And because a sketch only answers "how many of dish X?" rather than "which 10 dishes are largest?", each bucket also tracks its own heavy-hitter candidate IDs (for example, top 100 items in that bucket via Space-Saving). By averaging, any item exceeding 1% of window volume must exceed 1% in at least one active bucket—so when lunch leaders expire at 1:00 PM, dinner runners-up are guaranteed to sit in the active buckets' candidate union, ready to be scored against the summed window sketch!

  9. Deep dive 4: Redis key design and versioned Lua writes

    Redis key                 Type     Fields / Payload                                         Writer & Cadence
    --------------------------------------------------------------------------------------------------------------------
    g7:r:{m-805}              HASH     o1h, r1h, o1d, r1d, o7d, r7d   (int strings)             Regional Flink (1 s,
                                       top1h, top1d, top7d            (compact Top-10 JSON)     dirty fields only)
                                       cur, as_of, off, edge          (metadata + version pair)
    g7:r:{m-805}:series       STRING   JSON array of 60 per-minute (orders, rev) points         Regional Flink (10 s)
    g7:g:{global}             HASH     Same fields as r:{rid}, revenue in USD cents             Global Aggregator
    g7:g:{reg:eu-west}        HASH     Same fields for one region                               Regional Merge Stage
    gen                       STRING   Active generation prefix ("g7")                          Atomic rebuild pointer
    

    Four deliberate choices make Redis fast, tiny (~3.5 GB), and replay-proof:

    • Single-round-trip reads via hash tags: In Redis Cluster, wrapping {m-805} in curly braces is a hash tag—an instruction telling Redis to hash only the text inside {...} when picking a shard, placing g7:r:{m-805} and g7:r:{m-805}:series on the exact same node so dashboards fetch metrics and charts in one pipelined call.
    • Finished JSON lists instead of ZINCRBY: Updating Redis SORTED SETs with ZINCRBY corrupts counts on Flink crash-replay; overwriting top1h with a complete 10-item JSON string is idempotent and only transmitted when the top 10 actually changes.
    • Monotonic (off, edge) Lua guard prevents backward jumps on failover: Each restaurant maps to one Kafka partition, so its last applied Kafka offset off and last expired bucket boundary edge strictly increase. When a crashed Flink task restarts from a 25-second-old checkpoint and replays those 25 seconds, a naive HSET would briefly rewind live dashboards backward by 25 seconds! Our 6-line Lua script rejects stale replays atomically:
    -- set_if_newer.lua: KEYS[1] = hash key; ARGV[1] = new_off, ARGV[2] = new_edge, ARGV[3..] = field/val pairs
    local cur_off  = tonumber(redis.call('HGET', KEYS[1], 'off') or '-1')
    local cur_edge = tonumber(redis.call('HGET', KEYS[1], 'edge') or '-1')
    local new_off, new_edge = tonumber(ARGV[1]), tonumber(ARGV[2])
    if new_off < cur_off or (new_off == cur_off and new_edge <= cur_edge) then
        return 0
    end
    redis.call('HSET', KEYS[1], 'off', ARGV[1], 'edge', ARGV[2], unpack(ARGV, 3))
    return 1
    
    • Zero-downtime cache generations (g7: -> g8:): During a cache rebuild, workers dual-write live updates to both g7: and g8: while populating g8:, then atomically flip SET gen "g8" so readers never observe a half-populated cache.
  10. Failure recovery, three-level cache rebuilds, and trade-offs

    Component failure              User-visible effect                 Automated recovery
    ----------------------------------------------------------------------------------------------------------------------
    Flink worker node crashes      Updates pause ~30-45 s              Restarts from 30 s RocksDB checkpoint at ~3x speed;
                                                                       Lua (off, edge) guard hides replay rewind
    Kafka broker fails             Zero impact                         RF=3 + min.insync.replicas=2 shifts leader instantly
    Traffic spikes 3x (300k/s)     Zero data loss; <5 s holds          Kafka buffers burst; 64 Flink slots have ~6x capacity
    Redis primary shard fails      1/16 of keys fail over in ~3 s      Replica promoted; Flink runs Level-1 re-emit for slot
    ScyllaDB latency / outage      Live dashboards completely normal   Flink buffers final-bucket flushes asynchronously
    

    Three-level cache & state recovery (cheapest first):

    1. Level 1 — Redis lost or corrupted, Flink RocksDB state healthy (~10 seconds): Send a control command on a Flink broadcast stream instructing all 64 tasks to iterate their local RocksDB keys and write current totals into a fresh generation g8: (~2M keys at 200,000 pipelined writes/s = ~10 s), then flip gen = "g8".
    2. Level 2 — Flink state corrupted by a code bug, ScyllaDB buckets healthy (~5 to 10 minutes): Deploy fixed code, use Flink's State Processor API to preload historical buckets (> 1 hour old) from restaurant_minute and restaurant_dish_hour, replay just the most recent ~70 minutes from Kafka (rebuilding the 5-minute dish buckets), and flip gen = "g8".
    3. Level 3 — Full disaster / schema bug across stored buckets (~1.5 hours): Spin up a temporary 256-slot Flink cluster to replay 7 days of raw Parquet + Kafka events at ~4M events/s into a fresh generation before cutting over.

    Continuous hourly reconciliation: Every hour, a batch job compares ScyllaDB's restaurant_minute sums against the Order Service's authoritative database export. If any bucket drifts (for example, due to an event arriving >1 hour duplicated), it publishes a signed CORRECTION event back into the orders Kafka topic—updating Flink state, Redis, and ScyllaDB together so Flink never overwrites a manual database fix!

    Summary of trade-offs

    • Bucketed sliding windows vs. raw event windows: Trades <= 1.7% boundary granularity for fixed, predictable memory (~8.3 KB/restaurant instead of 21 billion raw events).
    • Immediate 1-second emit vs. watermark-gated output: Hits the < 5 s freshness target with provisional numbers that self-heal on late arrivals, rather than stalling every dashboard by 10+ seconds.
    • Versioned absolute-value Redis writes vs. INCRBY or 2PC sinks: Gives effective exactly-once accuracy at 1-second latency without double-counting on retries or stalling behind 30-second checkpoint commits.
    • Three-tier rebuilds (State -> Buckets -> Raw Lake) vs. raw replay only: Adds generation prefixes and bucket tables so production cache corruption recovers in 10 seconds instead of 6 hours.

Intuition & how it works

Imagine running a live digital scoreboard showing how many cars entered a 60-minute highway stretch and how much toll they paid. Re-counting all 300,000 cars on the road from scratch every time someone glances at the scoreboard would melt your computers. Instead, you group entries into 60 one-minute buckets: whenever a car enters at 12:03, you add +1 to the 12:03 bucket and +1 to a single running total; whenever the clock ticks past 12:04, a timer subtracts the 60-minute-old 11:03 bucket from that running total—even if zero new cars entered—and posts the finished answer on a wall display (Redis) so 200,000 viewers read one pre-computed record in half a millisecond.

A naive backend either executes SELECT COUNT(*), SUM(total) FROM orders WHERE placed_at >= NOW() - INTERVAL '7 days' on the database per page load, or tells message consumers to run INCRBY on Redis counters. Scanning billions of 7-day rows at 100,000 dashboard requests per second crashes any database instantly, whereas INCRBY cannot subtract 61-minute-old orders when a restaurant goes quiet and silently double-counts revenue every time a crashed worker replays messages from Kafka.

Walk through four events for Restaurant m-805 on its 1-hour window to see every piece in action:

  1. Order placed (18:00:10): A diner orders 2 Garlic Noodles for 2,800 cents. The Order Service writes the order and an outbox row atomically; Kafka delivers OrderEvent(event_id="e1", placed_at=18:00:10, +1 order, +2800 cents, off=710) to Flink, which updates bucket 18:00 and the 1-hour running total (1 order, 2800 cents) and writes r:{m-805} to Redis within ~1.6 seconds.
  2. Duplicate retry (18:00:14): A network blip replays event_id="e1". Flink checks its 1-hour per-restaurant deduplication map, sees "e1", and drops the duplicate immediately.
  3. Order cancelled (18:02:05): The order is cancelled, emitting CANCELLED(event_id="e2", placed_at=18:00:10, -1 order, -2800 cents, off=711). Carrying the original placed_at lets Flink subtract directly from bucket 18:00, dropping the 1-hour running total back to 0 on screen within ~3.6 seconds.
  4. Silent window decay (19:01:02): Suppose another order arrived at 18:01 and the restaurant closed for the evening. Even with zero new events, Flink's staggered timer fires just after 19:01, subtracts bucket 18:01, and overwrites Redis so the 1-hour dashboard cleanly returns to 0.

Key trade-offs

  • Bucketed sliding windows vs. exact per-event sliding windows. Keeping all ~21 billion individual orders from the past 7 days in memory to slide windows to the exact millisecond is prohibitively expensive. Grouping into fixed buckets (60 x 1-min for 1h, 288 x 5-min for 1d, 168 x 1-hr for 7d) bounds memory to ~519 metric buckets (~8.3 KB raw) per restaurant, trading at most one bucket of boundary approximation (<= 1.7% on the 1-hour window).
  • Pre-aggregating windows in Flink vs. summing buckets at read time. Having the API read and sum 60 + 288 + 168 = 516 bucket values on every dashboard refresh avoids expiry timers, but multiplies Redis read bandwidth by 500x and cannot merge platform-wide top-10 dishes quickly. Maintaining running totals via staggered Flink timers keeps every dashboard refresh a single HGETALL lookup, at the cost of up to ~17,000 background expiry writes/s averaged across each minute.
  • Emitting every 1 second on arrival vs. waiting for the watermark. A watermark (a stream timestamp marker indicating that almost no older events remain in flight, say max_timestamp - 10 s) tells us when a bucket is complete, yet waiting 10 seconds to publish would break our 5-second latency requirement! Publishing provisional totals every 1 second hits < 5 s freshness while still letting late events update active buckets and using watermarks solely to mark historical database rows is_final = true.
  • Idempotent versioned overwrites vs. INCRBY or transactional sinks. An idempotent write produces the same state even when repeated. Redis INCRBY double-counts on crash replay, while two-phase-commit transactional sinks stall visibility until Flink checkpoints complete (every 30 seconds). Writing complete absolute totals guarded by a monotonic (kafka_offset, bucket_edge) Lua check achieves effective exactly-once accuracy at 1-second latency.
  • Exact hierarchical top-10 vs. Count-Min Sketch. When dish_id belongs to a single restaurant, any global top-10 dish must also rank in its own restaurant's top 10, making a two-stage heap merge 100% exact and cheap. When aggregating dish names or catalog IDs across thousands of restaurants and city slices, exact maps require massive state and shuffles, so a Count-Min Sketch (a fixed-size 2D hash-counter array that estimates frequencies within epsilon * N without storing individual keys) paired with per-bucket heavy-hitter candidates trades tiny bounded overestimation for predictable memory.
  • Transactional outbox + CDC vs. direct dual-writes to Kafka. Writing an outbox row inside the Order Service's local database transaction and streaming it via Change Data Capture (CDC) adds ~0.5 seconds of latency, in exchange for guaranteeing that a service crash between DB commit and Kafka publish can never silently lose an order.

Common mistakes

  • Incrementing Redis counters (INCR / ZINCRBY) directly from stream workers, which permanently corrupts totals whenever a consumer restarts and replays uncommitted offsets.
  • Forgetting that sliding windows must shrink when no events arrive, leaving closed restaurants frozen at their peak dinner numbers until tomorrow morning.
  • Holding back dashboard updates behind a 10-to-60-second watermark, making it mathematically impossible to meet the 5-second latency SLA.
  • Updating a single global Redis key on every order (100,000 writes/s on one hot shard with cross-region lock contention) instead of two-stage task -> regional -> global pre-aggregation.
  • Partitioning the long-term database by timestamp alone (PRIMARY KEY (minute)), funneling 100% of current writes onto a single storage node instead of spreading across (restaurant_id, day).
  • Storing currency as floating-point numbers (float / double) or summing EUR, JPY, and USD together without integer minor units and exchange-rate normalization.
  • Recommending Count-Min Sketch by itself for Top-K, forgetting that a sketch cannot enumerate keys on its own—it requires a companion heavy-hitter candidate tracker per bucket so expiring leaders promote the right runners-up.
  • Relying solely on a 7-day raw Kafka replay to fix a corrupted Redis cache, turning a 10-second state re-emission into a 5-hour outage.

Follow-up questions

  • Suppose a merchant's kitchen goes offline and cancels dozens of open orders at once—how does your pipeline process that batch and update the rolling 1-hour numbers? The Order Service commits the batch cancellation atomically alongside transactional outbox rows that emit one CANCELLED event per order, each carrying the order's original placed_at timestamp, signed negative revenue, and complete items_delta list. Because Kafka partitions by restaurant_id, every cancellation for that merchant lands in order on a single Flink task slot (~10,000 events/s capacity, absorbing dozens or hundreds of cancellations in milliseconds). Orders placed within the past 60 minutes subtract from their corresponding 1-minute buckets and reduce the rolling 1-hour count, gross revenue, and top-10 dish quantities within < 5 seconds, whereas orders placed 2 hours earlier leave the 1-hour window unchanged and decrement only the 1-day and 7-day windows; exposing a separate cancelled_now counter keyed by occurred_at lets operators distinguish active refunds from slow sales.
  • What concrete changes would you make across event ingestion, stream emission, and dashboard delivery if the freshness target tightened from 5 seconds to 500 milliseconds? Every second-scale buffer in the 3.6-second path must shrink: (1) publish directly from the Order Service to regional Kafka (acks=all, linger.ms=2, ~15 ms) on the primary path while keeping the transactional outbox as a safety net deduplicated by Flink's event_id state; (2) tighten Flink's dirty-key flush cadence from 1,000 ms to 50–100 ms, enabling that rapid cadence only for merchants with an open dashboard session (advertised by API gateways over a lightweight Flink broadcast stream so idle restaurants don't multiply Redis writes); and (3) replace 2-second HTTP polling with WebSockets or Server-Sent Events fed by Redis pub/sub notifications (~50 ms). Single-restaurant and regional views comfortably land around 200–300 ms, while cross-ocean global aggregates either relax slightly (~600–800 ms due to wide-area RTT) or merge regional streams directly in the browser.
  • If a cloud region suffers an outage, how do you keep the live serving cache and the authoritative order database consistent during failover and recovery? Treat the Order Service database as the single source of truth and Redis as a versioned, rebuildable projection that flags staleness transparently during failover and reconciles afterward. Replicate regional orders Kafka topics asynchronously to a standby region (via MirrorMaker 2) and write Flink's 30-second RocksDB checkpoints to cross-region object storage; when a region drops, dashboards serve the last snapshot marked stale: true with its as_of timestamp while the standby region resumes Flink from the latest checkpoint (translating offsets slightly conservatively so the 1-hour event_id deduplicator drops overlap safely) into a new Redis generation g8:. Once the impaired region returns and drains any un-mirrored outbox events, the hourly batch reconciler diffs restaurant_minute buckets against the Order DB over the incident window and emits signed CORRECTION events into Kafka so Flink state, ScyllaDB, and Redis converge to the exact cent.

Follow-up questions

Similar questions

More Uber Freight interview questions

All 4 Uber Freight questions →