Polling Strategy for Variable-Lag Record Streams

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

An opaque upstream producer A creates 1 record every 30 seconds without ever dropping data. Each record eventually becomes readable in an intermediate database B after an individual propagation delay ranging between 0 seconds and 5 minutes (300 seconds). You have read-only access to B and cannot alter its schema or behavior, whereas you have full control over your own database C and the polling worker that copies data out of B.

Before entering production, your service runs in an initial calibration mode where you can watch arrivals in B and tune parameters. Once switched into live mode, product stakeholders ask for the fastest sustainable polling cadence while requiring every live tick to hand off strictly one previously unseen record and never fail.

Start by listing the clarifying questions needed to pin down underspecified contracts (history retention and ordering keys in B, single-row query semantics, out-of-order visibility, whether an empty poll counts as a failure, and whether C may stage records ahead of downstream consumption). Then structure your solution around three parts:

  1. Feasibility of direct fixed-interval polling: Using only the 30-second creation cadence and the 0-to-5-minute delay window, prove whether or not any constant polling period directly against B can return strictly one newly visible record on every poll.
  2. Using the calibration mode: Detail what invariants, latencies, and failure scenarios you would measure or test prior to launch, and explain what a finite observation window can refute versus what it can never mathematically guarantee.
  3. Production polling and consumption design: Under explicit assumptions, specify how C, your ingestion worker, and the live one-at-a-time consumer work together—covering polling rates, initial warm-up sizing, gap-safe cursors, deduplication, retry budgets, live health metrics, and your fallback response if a record ever exceeds the 5-minute delay bound.

Scope & Expectations

  • Worst-case arrival reasoning: Separate steady generation rate from variable arrival timing in B (both multi-record bursts and long silent gaps) rather than relying on average-rate intuition.
  • Empirical testing vs. formal guarantees: Identify concrete calibration checks for record identity, sequence gaps, clock skew, and idempotent crash recovery while recognizing the statistical limits of finite pre-launch observation.
  • Decoupled staging architecture: Isolate frequent batch copying from B into C from steady single-record downstream delivery, deriving the required head-start delay, buffer depth, and minimum sustainable live period from the 5-minute bound.
  • Operational resilience: Address reordered arrivals, atomic watermark advancement, bounded retries, multi-worker coordination, early-warning alerts, and graceful handling of upstream SLA breaches.

Step-by-step walkthrough

  1. Model the timeline and settle the clarifying questions

    Write down the two timestamps every record has, because every argument in this problem compares them:

    Record n (n = 0, 1, 2, ...) is generated in A at:   g(n) = g0 + 30 * n       seconds
    It becomes visible in B after lag(n) seconds at:    a(n) = g(n) + lag(n),    0 <= lag(n) <= 300
    

    Notice right away that out-of-order arrival in B is already permitted by 0 <= lag(n) <= 300. Whenever lag(n) > lag(n + 1) + 30, the later record overtakes the earlier one: - Record 0 generated at 0 s with lag(0) = 200 s appears in B at 200 s. - Record 1 generated at 30 s with lag(1) = 0 s appears in B at 30 s — 170 s before record 0!

    Before designing anything, align on the five clarifying questions. Our design assumes the strict answers below and notes what changes if an answer differs: 1. History and identity in B: B retains past records (rather than overwriting a single slot), and each record carries a unique record_id plus a gap-free sequence number seq = 0, 1, 2, ... (or generation timestamp g(n)). Without sequence numbers or generation timestamps, no reader can tell whether a delayed record is still missing. 2. LIMIT 1 support: B can return one row or a batch, as our query chooses. 3. Out-of-order visibility: Yes, as shown above, rows can appear in B out of seq order. 4. Zero-row polls: In the live consumer contract, getting zero unprocessed records counts as a failure (otherwise LIMIT 1 at any rate would trivially satisfy "at most one"). 5. Buffering in C: Allowed. The strict contract ("one fresh record per tick with zero empty reads") applies to live downstream consumption from C, while a background ingestor may copy batches from B into C.

  2. Part 1: Why no fixed polling interval on B works

    It is tempting to argue from averages: "Because A produces 1 item per 30 s without drops, B averages 1 arrival per 30 s — so why not query B every 30 s?" That fails because "never fail" is a worst-case requirement on every single poll, not an average requirement.

    Within the allowed 0 <= lag(n) <= 300 s bound, consider two valid arrival patterns (with g0 = 0):

    1. Worst-case burst (11 records at once): give records 0, 1, ..., 10 decreasing lags 300, 270, ..., 30, 0. Every one of those 11 records arrives at a(n) = 30 * n + (300 - 30 * n) = 300 s:
    n:        0     1     2    ...    9    10
    g(n):     0    30    60   ...  270   300
    lag(n): 300   270   240   ...   30     0
    a(n):   300   300   300   ...  300   300   <-- all 11 records appear at t = 300 s!
    
    In fact, `11` is the exact maximum for any half-open `30 s` poll window `(s, s + 30]`: to arrive in `(s, s + 30]`, a record must be generated in `(s - 300, s + 30]`, a `330 s` span containing at most `330 / 30 = 11` multiples of `30`.
    
    1. Worst-case silence (330 seconds with zero arrivals): give records 0..10 lag = 0 (so record 10 arrives at 300 s), and give records 11 onward lag = 300 (so record 11, generated at 330 s, arrives at 330 + 300 = 630 s):
    Timeline in B:
      t = 0..300 s       records 0..10 arrive right on schedule (last one at t = 300 s)
      t = (300, 630) s   ZERO new arrivals for 330 seconds straight!
      t = 630 s          record 11 finally arrives
    
    `330 s` is also the tightest possible silence bound: once `s >= g0`, any half-open poll window `(s, s + 330]` has width `330 s`, so `(s, s + 30]` contains some generation time `g(n)` whose latest allowed arrival `g(n) + 300` still falls at or before `s + 330`.
    
    PERIOD = 30
    MAX_LAG = 300
    
    def arrival_times(lags):
        """Sorted visibility times in B when record n is generated at 30 * n."""
        times = []
        for n, lag in enumerate(lags):
            times.append(PERIOD * n + lag)
        return sorted(times)
    
    # 1. Burst: lags 300, 270, ..., 0 put 11 records at t = 300
    burst_lags = [MAX_LAG - PERIOD * i for i in range(11)]
    assert arrival_times(burst_lags) == [300] * 11
    
    # 2. Silence: lag 0 through n = 10, then lag 300 from n = 11 onward
    silence_lags = [0] * 11 + [MAX_LAG] * 3
    arrivals = arrival_times(silence_lags)
    assert arrivals[10] == 300 and arrivals[11] == 630  # 330 s gap with 0 arrivals
    

    Putting both bounds together rules out every fixed poll interval P if "newly arrived" means arrived since the previous poll: - If P < 330 s, a poll window (s, s + P] can land inside the (300, 630) silence and return 0 records. - If P >= 330 s, empty windows disappear after warm-up, but the long-run generation rate is 1 record per 30 s, so an average of P / 30 >= 11 new records arrive per poll — breaking the single-record-per-poll requirement. - Adding LIMIT 1 caps the "too many" side (leaving extras queued for later polls), yet at the live edge it still fails on the empty side whenever P < 330 s. Direct 30 s polling without buffering would only work if the jitter (the spread max_lag - min_lag between the slowest and fastest lag) were strictly under 30 s; here the spread is 300 s, ten times too wide.

  3. Part 2: What to measure and validate in the boot state

    Use the boot/test phase to verify how B behaves and to stress-test our own ingestion logic:

    • Record identity and sequence: confirm every row has an immutable unique record_id and check whether seq (or g(n)) is strictly gap-free (0, 1, 2, ...). Measure how frequently rows appear out of seq order in B.
    • Observed lag and clock skew: poll B every 1-2 s during boot so arrival-time measurement error is at most 1-2 s. If records store g(n), compute first_seen(n) - g(n) after correcting for clock skew (any constant offset between A's clock and our poller's clock). Even without g(n), first_seen(n) - 30 * n reveals the lag spread (max - min), giving a hard lower bound on true jitter.
    • Read consistency in B: check whether rows that appear once ever disappear (for example, when reading from an asynchronous read replica during failover) and whether late-committing transactions insert smaller IDs behind larger ones.
    • Cursor and idempotency: idempotency means applying the same operation multiple times produces the exact same stored state as applying it once. Crash-test the poller mid-batch (after inserting into C, before updating its cursor) and replay the same rows twice; C must end up with zero duplicates and zero skipped sequence numbers.
    • Startup backlog policy: decide with stakeholders whether boot should bulk-copy B's existing historical rows and replay them from seq = 0, or anchor at a chosen starting seq near the present.
  4. Part 2: Why finite observation is evidence, never a proof

    Boot measurements can falsify the 5-minute bound — a single record arriving 305 s late disproves lag <= 300 s immediately. However, no finite test can prove an upper bound holds in production, because rare tail events (such as database checkpoints, lock convoys, or network failovers) may simply not trigger during the window you watched.

    Verify this with a concrete calculation. Suppose 1 in 100,000 records (p = 0.00001) violates the 5-minute bound:

    Records emitted per day:             86,400 s / 30 s = 2,880 records/day
    Probability of 0 late rows in 1 day: (1 - 0.00001)^2880 ≈ 0.9716  (97.2% chance of a clean test!)
    Expected violations in 1 year:       2,880 * 365 * 0.00001 ≈ 10.5 failures/year in production
    

    A full 24-hour boot run passes cleanly more than 97% of the time even when production will break roughly ten times a year. Treat the 300 s bound as an explicit SLA contract with B's owners, use boot to measure typical lag and B's query latency, and build runtime monitoring for bound violations.

  5. Part 3: Decouple ingestion into C from live one-at-a-time consumption

    Instead of forcing one loop to both scrape B and feed downstream, split the system into two independent loops separated by staging tables in C:

      Store A ──(1 record / 30 s)──> Database B (read-only, 0..300 s lag, out-of-order allowed)
                                          │
                                          │  1. Ingestor loop (every 5 s, batch read)
                                          │     SELECT record_id, seq, payload
                                          │     FROM b_records WHERE seq > :watermark ORDER BY seq
                                          ▼
                        Database C (under our control)
                        ┌──────────────────────────────────────────────────────────┐
                        │ staged_records(record_id UNIQUE, seq UNIQUE, payload,    │
                        │                consumed BOOL DEFAULT FALSE)              │
                        │ ingest_cursor(id = 1, watermark INT)                     │
                        │   Single transaction:                                    │
                        │     INSERT ... ON CONFLICT (record_id) DO NOTHING;       │
                        │     advance watermark to highest contiguous seq in C     │
                        └──────────────────────────────────────────────────────────┘
                                          │
                                          │  2. Live consumer loop (every 30 s after warm-up)
                                          │     Fetch seq = next_seq, process downstream, mark consumed
                                          ▼
                                Downstream consumer (1 record / 30 s, in order)
    

    Each piece solves one hazard cleanly: - Frequent batch ingestion: polling B every 5 s (where 0 to 11 rows per poll is completely normal) copies records into C quickly and isolates the live consumer from brief slowdowns in B. - Contiguous watermark cursor: a contiguous watermark is the highest sequence number W such that every record 0, 1, ..., W is already safely stored in C. If W = 4 and record 6 arrives before delayed record 5, C stores 6 but keeps watermark = 4. The next poll re-queries seq > 4; when 5 arrives, 6 is harmlessly ignored by ON CONFLICT (record_id) DO NOTHING and watermark jumps from 4 to 6. Under the 300 s lag bound, at most 11 out-of-order rows ever sit above watermark, so re-reading above W is tiny. Updating staged_records and watermark in one C transaction prevents crash drift. - Retries: transient B read errors retry with exponential backoff (doubling the wait between retries, plus small random jitter so retries do not synchronize) within a fixed retry budget included in slack S below.

  6. Part 3: Size the warm-up delay, buffer, and shortest live interval

    This architecture acts as a jitter buffer — a holding queue that delays the start of playback by a fixed head start D so variable arrival delays smooth back into a steady 30 s cadence.

    Suppose record n is generated at g(n) = g0 + 30 * n. It appears in B by g(n) + 300, and reaches C within S extra seconds of ingestion slack (5 s ingest poll interval + query/commit latency + retry budget; say S = 30 s). Thus record n is guaranteed to sit in C no later than g0 + 30 * n + 300 + S.

    If the live consumer processes record n at scheduled tick c(n) = g0 + D + 30 * n, it never misses a record as long as c(n) is at or after C's worst-case arrival time for every n:

    Schedule safe for all n:   g0 + D + 30 * n  >=  g0 + 30 * n + 300 + S
    Subtract (g0 + 30 * n):    D >= 300 + S
    With S = 30 s:             D = 330 s  (5.5 minutes after record 0 was generated)
    

    Notice why 30 * n cancels out: both the generator A and our live consumer advance by 30 s per record, so a single one-time head start D = 330 s protects record 0, record 1,000, and record 1,000,000 alike!

    import math
    
    def size_warmup_and_buffer(max_lag=300, period=30, slack=30):
        """Compute head-start delay D, count-based warm-up threshold, and max time-rule buffer."""
        delay_seconds = max_lag + slack
        # Count rule: K distinct records (seq >= 0) include some seq >= K - 1,
        # proving current time >= g0 + period * (K - 1) >= g0 + delay_seconds.
        warmup_record_count = math.ceil(delay_seconds / period) + 1
        # Time rule: at tick c(n) = g0 + D + 30*n, records 0..n-1 are already consumed,
        # and only records m with 30*m <= D + 30*n (m <= n + D // 30) can exist yet.
        max_unconsumed_time_rule = delay_seconds // period + 1
        return delay_seconds, warmup_record_count, max_unconsumed_time_rule
    
    assert size_warmup_and_buffer() == (330, 12, 12)
    
    • Time-based vs count-based warm-up: if records carry g(n) (clock-skew adjusted), start at g0 + 330 s; C never holds more than floor(330 / 30) + 1 = 12 unconsumed records at any tick. If records lack timestamps, wait until C holds 12 distinct records: 12 records from n >= 0 must include at least one with n >= 11, which could not even be generated before g0 + 330 s. (If those first 12 all suffered max lag + slack, warm-up finishes as late as g0 + 660 s, where C can hold at most 23 records 0..22 — still tiny.)
    • Why 30 s is the shortest sustainable live interval: any consumer period P < 30 s drains any finite buffer because consumption outruns generation. With P = 29 s and D = 330 s, consumer tick k (k = 0, 1, ...) runs at g0 + 330 + 29 * k, while record k is not even generated by A until g0 + 30 * k. Once 330 + 29 * k < 30 * k — i.e., k > 330, starting at k = 331 (9,929 s vs 9,930 s, about 2.8 hours in) — the consumer asks for a record before A has created it!
  7. Part 3: Monitoring and handling contract violations

    Track four operational metrics continuously in live mode: 1. Safety margin per tick (c(n) - committed_in_C(n)): guaranteed >= 0 s when bounds hold (typically > 200 s); page an engineer if margin drops below 15 s, meaning a record burned through almost the entire 300 s lag bound plus retry slack. 2. Observed lag distribution in B (first_seen(n) - g(n)): alert if max lag approaches 300 s. 3. Unconsumed buffer depth and oldest sequence gap age: alert if a gap above watermark stays open past 300 s. 4. Ingestor error and retry rate: catches B degradation before S = 30 s of slack runs out.

    If tick c(n) arrives and seq = n is still missing in C, B's 300 s contract (or our S = 30 s outage budget) was violated, so "every 30 s in order and never fail" cannot all hold simultaneously. Pre-agree the fallback policy with the business: - Recommended default — pause and re-warm: hold tick n until record n arrives, shift future ticks forward (D grows by the overshoot), and fire an alert. Downstream still receives every record once and in exact order, trading only extra latency. - Alternative — skip and backfill out of order: only valid if downstream tolerates out-of-order delivery; never emit fake placeholder records or duplicate old records to mask a missed tick.

Intuition & how it works

Imagine a bus depot (store A) that dispatches exactly one bus every 30 seconds like clockwork, while city traffic independently delays each bus by anywhere from 0 to 5 minutes (0..300 s) before it pulls into a read-only transit terminal (database B). Even though buses leave the depot at a steady pace, variable traffic causes buses to bunch up into packs at the terminal and leaves long empty stretches in between — the exact same phenomenon as network jitter (variation in packet transit delay), which audio and video apps solve with a jitter buffer (a small holding queue that delays playback by a fixed head start so uneven arrivals smooth back into a steady stream).

Polling B directly on a fixed schedule fails no matter what interval P you pick. Polling B every 30 s ("matching the average rate") fails because fast records followed by maximally delayed records create a 330 s silent gap with zero arrivals; polling B every 330 s avoids empty polls only by letting an average of 11 new records pile up per poll; and slapping LIMIT 1 onto a live-edge query still returns zero rows during a silent gap because B cannot hand out a record still in transit.

Walk through four records (g(n) = 30 * n) to see both the problem and how staging into database C fixes it: 1. Suppose records 0, 1, 2, 3 are generated at 0, 30, 60, 90 s with lags 90, 60, 0, 300 s, so they appear in B at a = 90, 90, 60, 390 s — record 2 arrives out of order at 60 s, records 0 and 1 bunch together at 90 s, and then nothing arrives for 300 s until 390 s. 2. Our background ingestor polls B every 5 s into C, deduplicating by record_id and advancing a contiguous watermark (the highest sequence number W where all records 0..W are stored in C): at 65 s C holds {2} (watermark = -1), and at 95 s C holds {0, 1, 2} (watermark = 2). 3. Meanwhile, our live consumer waits a one-time head start of D = 300 + 30 = 330 s (5-minute max lag plus 30 s of ingestion slack) and then reads seq = 0, 1, 2, 3 from C at t = 330, 360, 390, 420 s: even maximally delayed record 3 (visible in B at 390 s, in C by 420 s) is ready right on time for its 420 s tick!

Key points

  • Generation cadence does not equal arrival cadence: 1 record per 30 s plus 0..300 s independent lag allows up to 11 records to arrive simultaneously in B and up to 330 s of complete silence between arrivals.
  • No fixed schedule querying B directly can yield a single fresh arrival every time: P < 330 s can hit a 0-record gap, while P >= 330 s averages P / 30 >= 11 new records per poll; direct 30 s polling would require jitter (max_lag - min_lag) strictly under 30 s.
  • Decouple ingestion from consumption using C: run a fast, idempotent ingestor (meaning repeated writes of the same record have the exact same effect as one write) every few seconds from B into C, and run a separate 30 s consumer loop strictly against C.
  • One constant head start covers the entire infinite stream: delaying consumption by D = 300 + S seconds (where S covers ingest poll interval, query time, and retry budget) guarantees record n is in C before consumer tick c(n) = g0 + D + 30 * n, while 30 s is the shortest sustainable consumer interval (29 s with D = 330 s runs dry at tick k = 331, about 2.8 hours in).
  • Finite boot testing can refute a lag bound, never prove it: if 1 in 100,000 records exceeds 300 s, a 2,880-record test day still looks clean 97.2% of the time despite causing ~10.5 violations per year, so treat 300 s as a monitored SLA with a pre-agreed pause-and-rewarm fallback.

Common mistakes

  • Using average-rate math for a worst-case guarantee: assuming "1 record per 30 s on average" means every 30-second window contains 1 record ignores bunching and silent gaps.
  • Assuming LIMIT 1 fixes live-edge polling: LIMIT 1 prevents returning multiple rows during a burst, but still returns 0 rows whenever a poll lands inside a 330 s silence.
  • Advancing the cursor to max(seq) instead of a contiguous watermark: if record 6 arrives at 180 s while record 5 arrives at 350 s, setting cursor = 6 permanently skips record 5 on WHERE seq > :cursor.
  • Committing the cursor outside the data-insert transaction: crashing between inserting rows into C and saving the cursor either skips records (if cursor saved first) or relies on deduplication (safe only when inserts are idempotent).
  • Setting warm-up D = 300 s with zero ingestion slack: a record taking the legal 300 s lag in B plus even 5 s until the next ingestor poll misses a 300 s deadline; always budget D = 300 + S.
  • Polling downstream faster than 30 s once the buffer fills: consuming every 29 s gains 1 s per tick on Store A and inevitably exhausts any finite warm-up buffer.

Follow-up questions

  • How does your design adapt when records become visible out of sequence? Under 0 <= lag(n) <= 300 s, records already arrive out of order whenever lag(n) > lag(n + 1) + 30, and the warm-up delay D = 300 + S needs no change because each record n still individually reaches C by g0 + 30 * n + 300 + S. What must be designed carefully is the ingestor cursor: never use seq > max_seen, and instead query seq > contiguous_watermark combined with UNIQUE(record_id) ... ON CONFLICT DO NOTHING so early arrivals above a gap are harmlessly skipped on re-read until the missing sequence number fills in. If B lacks sequence numbers altogether and only exposes B's commit timestamp, query B with a sliding lookback overlap covering any transaction-commit skew, deduplicate by record_id in C, and note that without seq or g(n) downstream must consume in arrival order rather than generation order.
  • What warm-up delay or buffered record count is required before starting a 30-second consumer cadence? In time, wait D = 300 + S seconds after record 0 was generated (330 s when ingestion slack S = 30 s), under which C never holds more than floor(D / 30) + 1 = 12 unconsumed records right before a tick. In record count (needed when generation timestamps are unavailable), wait until C holds ceil((300 + S) / 30) + 1 = 12 distinct records: any 12 records from seq >= 0 must include at least one with seq >= 11, proving the current time is already at least g0 + 330 s (whereas waiting for only 11 records fails if 0..10 had 0 lag and 11 suffers 300 s lag plus 30 s slack). Under the 12-record count rule, warm-up finishes at latest by g0 + 660 s, where C holds at most 23 buffered records (0..22).
  • How can two concurrent poller workers prevent duplicate ingestion of the same record? First make duplicate copying safe at the storage layer: enforce UNIQUE(record_id) with INSERT ... ON CONFLICT DO NOTHING in C and update watermark using compare-and-set (UPDATE ingest_cursor SET watermark = :new WHERE watermark = :old — an atomic conditional update that succeeds only if no other instance changed the row meanwhile). Second, eliminate redundant queries against B by coordinating an active-passive lease (a time-bounded ownership row (holder_id, expires_at, fencing_token) in C renewed every few seconds by the active poller). Attach the monotonically increasing fencing token (a lease counter incremented on every leadership change) to C writes and reject any write carrying a stale token, preventing a paused former leader from corrupting state after waking up.

Follow-up questions

Similar questions

More Layerzero interview questions

All 1 Layerzero questions →