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:
- 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
Bcan return strictly one newly visible record on every poll. - 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.
- 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
BintoCfrom 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
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) <= 300Notice right away that out-of-order arrival in B is already permitted by
0 <= lag(n) <= 300. Wheneverlag(n) > lag(n + 1) + 30, the later record overtakes the earlier one: - Record 0 generated at0 swithlag(0) = 200 sappears in B at200 s. - Record 1 generated at30 swithlag(1) = 0 sappears in B at30 s—170 sbefore 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_idplus a gap-free sequence numberseq = 0, 1, 2, ...(or generation timestampg(n)). Without sequence numbers or generation timestamps, no reader can tell whether a delayed record is still missing. 2.LIMIT 1support: 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 ofseqorder. 4. Zero-row polls: In the live consumer contract, getting zero unprocessed records counts as a failure (otherwiseLIMIT 1at 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.Part 1: Why no fixed polling interval on B works
It is tempting to argue from averages: "Because A produces 1 item per
30 swithout drops, B averages 1 arrival per30 s— so why not query B every30 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 sbound, consider two valid arrival patterns (withg0 = 0):- Worst-case burst (11 records at once): give records
0, 1, ..., 10decreasing lags300, 270, ..., 30, 0. Every one of those 11 records arrives ata(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`.- Worst-case silence (330 seconds with zero arrivals): give records
0..10lag = 0(so record 10 arrives at300 s), and give records11onwardlag = 300(so record 11, generated at330 s, arrives at330 + 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 arrivalsPutting both bounds together rules out every fixed poll interval
Pif "newly arrived" means arrived since the previous poll: - IfP < 330 s, a poll window(s, s + P]can land inside the(300, 630)silence and return 0 records. - IfP >= 330 s, empty windows disappear after warm-up, but the long-run generation rate is 1 record per30 s, so an average ofP / 30 >= 11new records arrive per poll — breaking the single-record-per-poll requirement. - AddingLIMIT 1caps the "too many" side (leaving extras queued for later polls), yet at the live edge it still fails on the empty side wheneverP < 330 s. Direct30 spolling without buffering would only work if the jitter (the spreadmax_lag - min_lagbetween the slowest and fastest lag) were strictly under30 s; here the spread is300 s, ten times too wide.- Worst-case burst (11 records at once): give records
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_idand check whetherseq(org(n)) is strictly gap-free (0, 1, 2, ...). Measure how frequently rows appear out ofseqorder in B. - Observed lag and clock skew: poll B every
1-2 sduring boot so arrival-time measurement error is at most1-2 s. If records storeg(n), computefirst_seen(n) - g(n)after correcting for clock skew (any constant offset between A's clock and our poller's clock). Even withoutg(n),first_seen(n) - 30 * nreveals 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 startingseqnear the present.
- Record identity and sequence: confirm every row has an immutable unique
Part 2: Why finite observation is evidence, never a proof
Boot measurements can falsify the 5-minute bound — a single record arriving
305 slate disproveslag <= 300 simmediately. 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
1in100,000records (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 productionA 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 sbound 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.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(where0to11rows 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 numberWsuch that every record0, 1, ..., Wis already safely stored in C. IfW = 4and record6arrives before delayed record5, C stores6but keepswatermark = 4. The next poll re-queriesseq > 4; when5arrives,6is harmlessly ignored byON CONFLICT (record_id) DO NOTHINGandwatermarkjumps from4to6. Under the300 slag bound, at most11out-of-order rows ever sit abovewatermark, so re-reading aboveWis tiny. Updatingstaged_recordsandwatermarkin 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 slackSbelow.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
Dso variable arrival delays smooth back into a steady30 scadence.Suppose record
nis generated atg(n) = g0 + 30 * n. It appears in B byg(n) + 300, and reaches C withinSextra seconds of ingestion slack (5 singest poll interval + query/commit latency + retry budget; sayS = 30 s). Thus recordnis guaranteed to sit in C no later thang0 + 30 * n + 300 + S.If the live consumer processes record
nat scheduled tickc(n) = g0 + D + 30 * n, it never misses a record as long asc(n)is at or after C's worst-case arrival time for everyn: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 * ncancels out: both the generator A and our live consumer advance by30 sper record, so a single one-time head startD = 330 sprotects record0, record1,000, and record1,000,000alike!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 atg0 + 330 s; C never holds more thanfloor(330 / 30) + 1 = 12unconsumed records at any tick. If records lack timestamps, wait until C holds12distinct records: 12 records fromn >= 0must include at least one withn >= 11, which could not even be generated beforeg0 + 330 s. (If those first 12 all suffered max lag + slack, warm-up finishes as late asg0 + 660 s, where C can hold at most23records0..22— still tiny.) - Why
30 sis the shortest sustainable live interval: any consumer periodP < 30 sdrains any finite buffer because consumption outruns generation. WithP = 29 sandD = 330 s, consumer tickk(k = 0, 1, ...) runs atg0 + 330 + 29 * k, while recordkis not even generated by A untilg0 + 30 * k. Once330 + 29 * k < 30 * k— i.e.,k > 330, starting atk = 331(9,929 svs9,930 s, about2.8hours in) — the consumer asks for a record before A has created it!
- Time-based vs count-based warm-up: if records carry
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 swhen bounds hold (typically> 200 s); page an engineer if margin drops below15 s, meaning a record burned through almost the entire300 slag bound plus retry slack. 2. Observed lag distribution in B (first_seen(n) - g(n)): alert if max lag approaches300 s. 3. Unconsumed buffer depth and oldest sequence gap age: alert if a gap abovewatermarkstays open past300 s. 4. Ingestor error and retry rate: catches B degradation beforeS = 30 sof slack runs out.If tick
c(n)arrives andseq = nis still missing in C, B's300 scontract (or ourS = 30 soutage budget) was violated, so "every30 sin order and never fail" cannot all hold simultaneously. Pre-agree the fallback policy with the business: - Recommended default — pause and re-warm: hold ticknuntil recordnarrives, shift future ticks forward (Dgrows 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:
1record per30 splus0..300 sindependent lag allows up to11records to arrive simultaneously in B and up to330 sof complete silence between arrivals. - No fixed schedule querying B directly can yield a single fresh arrival every time:
P < 330 scan hit a0-record gap, whileP >= 330 saveragesP / 30 >= 11new records per poll; direct30 spolling would require jitter (max_lag - min_lag) strictly under30 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 sconsumer loop strictly against C. - One constant head start covers the entire infinite stream: delaying consumption by
D = 300 + Sseconds (whereScovers ingest poll interval, query time, and retry budget) guarantees recordnis in C before consumer tickc(n) = g0 + D + 30 * n, while30 sis the shortest sustainable consumer interval (29 swithD = 330 sruns dry at tickk = 331, about2.8hours in). - Finite boot testing can refute a lag bound, never prove it: if
1in100,000records exceeds300 s, a2,880-record test day still looks clean97.2%of the time despite causing~10.5violations per year, so treat300 sas 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 1fixes live-edge polling:LIMIT 1prevents returning multiple rows during a burst, but still returns 0 rows whenever a poll lands inside a330 ssilence. - Advancing the cursor to
max(seq)instead of a contiguous watermark: if record6arrives at180 swhile record5arrives at350 s, settingcursor = 6permanently skips record5onWHERE 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 swith zero ingestion slack: a record taking the legal300 slag in B plus even5 suntil the next ingestor poll misses a300 sdeadline; always budgetD = 300 + S. - Polling downstream faster than
30 sonce the buffer fills: consuming every29 sgains1 sper 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 wheneverlag(n) > lag(n + 1) + 30, and the warm-up delayD = 300 + Sneeds no change because each recordnstill individually reaches C byg0 + 30 * n + 300 + S. What must be designed carefully is the ingestor cursor: never useseq > max_seen, and instead queryseq > contiguous_watermarkcombined withUNIQUE(record_id) ... ON CONFLICT DO NOTHINGso 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 byrecord_idin C, and note that withoutseqorg(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 + Sseconds after record0was generated (330 swhen ingestion slackS = 30 s), under which C never holds more thanfloor(D / 30) + 1 = 12unconsumed records right before a tick. In record count (needed when generation timestamps are unavailable), wait until C holdsceil((300 + S) / 30) + 1 = 12distinct records: any 12 records fromseq >= 0must include at least one withseq >= 11, proving the current time is already at leastg0 + 330 s(whereas waiting for only11records fails if0..10had0lag and11suffers300 slag plus30 sslack). Under the 12-record count rule, warm-up finishes at latest byg0 + 660 s, where C holds at most23buffered 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)withINSERT ... ON CONFLICT DO NOTHINGin C and updatewatermarkusing 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
- How does your design adapt when records become visible out of sequence?
- What warm-up delay or buffered record count is required before starting a 30-second consumer cadence?
- How can two concurrent poller workers prevent duplicate ingestion of the same record?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes