Stateful Batch Reader for Paginated APIs
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
You are integrating with a cursor-paginated upstream API where calling fetch(page_token) returns a dictionary of the form {"items": [...], "nextPage": next_token}. Design a stateful reader initialized with initial_token that exposes fetchN(n) to return items n at a time in exact upstream order across repeated calls, and connect it to the batch harness:
def stateful_fetch_n(
initial_token: str,
pages: Dict[str, Dict],
operations: List[str],
arguments: List[List[int]],
) -> List:
Your reader must satisfy the following behavioral contract:
- Order and leftover buffering: Serve items strictly in source order across page boundaries. Whenever a fetched page supplies more items than the current
fetchN(n)call requires, retain the unconsumed items in an internal buffer and drain that buffer first on later calls before requesting another page. - Exact vs. partial counts: Return
nitems whenever at leastnunread items remain in the source; return fewer thannitems only when the entire upstream sequence has ended. - Zero and invalid counts: Calling
fetchN(0)must return[]immediately without invokingfetch. CallingfetchN(n)withn < 0must raise an exception (ValueError). - Empty pages vs. stream exhaustion: An empty page (
"items": []) that still carries a non-empty"nextPage"token is not the end of the stream—continue following"nextPage"tokens. Only an omitted,None, or empty"""nextPage"marks the final page. Once all buffered items after the final page are consumed, subsequentfetchN(n)calls (n >= 0) return[]with zero upstream calls. - Cycle detection and failure safety: If
"nextPage"ever revisits a page token that was already fetched, raise an error (RuntimeError) before re-fetching it rather than looping infinitely or duplicating items. Update internal state atomically per page and drain the buffer only after required page loads succeed so mid-call upstream failures never drop already-fetched items (and transient network errors can be retried with bounded backoff).
In stateful_fetch_n, pages maps valid token strings to page dictionaries (looking up a missing token raises KeyError), operations lists "fetchN" commands, and arguments supplies [n] for each command. Return a list containing the output list of every "fetchN" operation in order.
Examples
Example 1
Input:
initial_token = "tok_1"
pages = {
"tok_1": {"items": [10, 20, 30], "nextPage": "tok_2"},
"tok_2": {"items": [40, 50], "nextPage": None},
}
operations = ["fetchN", "fetchN", "fetchN", "fetchN"]
arguments = [[2], [2], [0], [3]]
Output:
[[10, 20], [30, 40], [], [50]]
Walk-through:
- fetchN(2): loads "tok_1" ([10, 20, 30]), returns [10, 20], and keeps [30] buffered without requesting "tok_2" yet.
- fetchN(2): buffer holds [30] (fewer than 2), so "tok_2" ([40, 50], nextPage = None) is loaded; returns [30, 40] and leaves [50] buffered.
- fetchN(0): returns [] immediately while preserving [50] in the buffer.
- fetchN(3): no further pages exist, so the reader drains the remaining buffer and returns [50].
Example 2
Input:
initial_token = "start"
pages = {
"start": {"items": [], "nextPage": "mid"},
"mid": {"items": [99, 100], "nextPage": "end"},
"end": {"items": [], "nextPage": None},
}
operations = ["fetchN", "fetchN"]
arguments = [[1], [4]]
Output:
[[99], [100]]
Walk-through:
- fetchN(1): loads "start" ([], nextPage = "mid"), steps past the empty page to load "mid" ([99, 100], nextPage = "end"), returns [99], and buffers [100].
- fetchN(4): buffer holds [100], loads terminal empty page "end" (nextPage = None), and returns all remaining items [100].
Constraints
- Calls to
fetchNrun sequentially on a single reader instance. 1 <= len(operations) == len(arguments) <= 10,000, where each operation is"fetchN"and each argument entry is[n].- Each page dictionary in
pagescontains"items": List[Any]and optionally"nextPage": Optional[str]. - Pages must be fetched lazily: never request a page when
n == 0or when buffered items already satisfyn. - Negative
nor cyclic"nextPage"chains must raise an exception rather than returning a list or hanging.
Step-by-step walkthrough
Understand the goal and behavioral contract
An upstream service gives us items in fixed pages: calling
fetch(page_token)returns{"items": [...], "nextPage": next_token}. Callers, however, do not want to think about page boundaries — they want to callfetchN(n)repeatedly and receive the nextnitems in order, as if reading a single flat list from left to right.Upstream pages: tok_1: [10, 20, 30] ---> tok_2: [40, 50] ---> None (end) Caller requests: fetchN(2) ---> returns [10, 20] (30 stays buffered for later) fetchN(2) ---> returns [30, 40] (loads tok_2; 50 stays buffered) fetchN(0) ---> returns [] (50 stays buffered) fetchN(3) ---> returns [50] (fewer than 3 because source ended)Before writing code, let's settle every rule of the contract:
- Persistent state between calls:
_next_token: the token of the next page to request, orNoneonce the final page has been read (which doubles as our end-of-source marker)._buffer: fetched items that have not been handed to a caller yet, kept in source order._seen_tokens: the set of page tokens already fetched, used to detect malformed pagination cycles.
- Invalid input (
n < 0) and zero (n = 0):n = 0returns[]immediately without callingfetch. A negativenis a caller bug, so we raiseValueErrorrather than masking the mistake as[]. - Empty pages vs. end of source: an empty page that still provides a non-empty
nextPage(such as{"items": [], "nextPage": "mid"}) is not the end — we keep following tokens. Only a missing,None, or empty""nextPagemarks the final page. Once_next_tokenbecomesNoneand_bufferis empty, every futurefetchNreturns[]with zero upstream calls. - Pagination loops: if
nextPageever points back to a token we already fetched, we raiseRuntimeErrorright before re-fetching it instead of looping forever or duplicating items.
- Persistent state between calls:
Why fetching everything up front falls short
A tempting shortcut is to walk the entire chain of pages inside
__init__, dump every item into one Python list, and slice that list on eachfetchN(n)call. That passes tiny happy-path examples, but fails in real systems for three reasons:- Wasted work and latency: if the upstream has 10,000 pages and the caller only ever asks for
fetchN(3), reading every page up front turns a 1-page read into 10,000 network calls. - Infinite loops on cyclic tokens: if page 50 points back to page 10, an eager constructor hangs or crashes before the caller even reads page 1.
- Fragility on errors: one transient failure on page 500 throws away the first 499 pages of work.
Instead, we fetch lazily: we request a new page only when our leftover buffer does not already hold enough items to answer the current
fetchN(n)call.- Wasted work and latency: if the upstream has 10,000 pages and the caller only ever asks for
Key idea: a leftover buffer and a two-phase commit point
Think of the reader as maintaining one simple invariant (a rule that is always true before and after every call):
+------------------------+ +-------------------+ +----------------------------------+ | items already returned | + | self._buffer | + | pages from self._next_token on | +------------------------+ +-------------------+ +----------------------------------+ == the entire upstream sequence in exact orderNotice that advancing the page token and handing items to the caller are two separate state transitions:
- Loading a page moves items from the upstream into the back of
self._bufferand advancesself._next_tokentonextPage. - Answering
fetchN(n)pops up tonitems from the front ofself._bufferinto the returned list.
Why keep those two phases separate instead of popping items into
resultas each page arrives? ImaginefetchN(5)loads page 1 ([1, 2]), pops[1, 2]into a localresultlist, and then fails with a network timeout while requesting page 2. Because the exception abortsfetchN(5), the caller never receives[1, 2]— and because[1, 2]was already popped fromself._buffer, the next call starts at page 2 and permanently loses[1, 2]!By filling
self._bufferfirst and drainingself._buffersecond, the start of the drain loop acts as a clean commit point:fetch_n(4) when tok_1=[10, 20, 30] succeeds and tok_2 times out: Phase 1 (Fill): load tok_1 --> _buffer = deque([10, 20, 30]), _next_token = "tok_2" load tok_2 --> TimeoutError raised! Phase 2 never runs: _buffer still holds [10, 20, 30], _next_token is still "tok_2". Retrying fetch_n(4) later loads tok_2 and returns [10, 20, 30, 40] with zero loss!- Loading a page moves items from the upstream into the back of
Store state and load one page atomically
We store
_bufferin acollections.deque(a double-ended queue that appends to the right and pops from the left in O(1) constant time, whereaslist.pop(0)shifts every remaining element in O(k) time).Inside
_load_next_page, we check_seen_tokensbefore calling_fetch(token), and we extractpage["items"]andpage.get("nextPage")before modifying_seen_tokens,_buffer, or_next_token. That way, if_fetchraises an error or returns a malformed dictionary, none of our internal fields are half-updated.from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque class PaginatedReader: def __init__(self, first_token: Optional[str], fetch) -> None: self._fetch = fetch # _next_token: token of the next page to request (e.g. "tok_1"), or None once exhausted. self._next_token: Optional[str] = first_token if first_token else None # _buffer: deque([30, 40, ...]) of items already fetched but not yet handed to the caller. self._buffer = deque() # _seen_tokens: {"tok_1", "tok_2", ...} of tokens already loaded, used to catch pagination loops. self._seen_tokens: Set[str] = set() def _load_next_page(self) -> None: token = self._next_token if token is None: return if token in self._seen_tokens: raise RuntimeError(f"pagination loop detected: token {token!r} was already fetched") page = self._fetch(token) items = page["items"] raw_next_token = page.get("nextPage") next_token = raw_next_token if raw_next_token else None # Commit the page transition only after the response succeeded and validated. self._seen_tokens.add(token) self._buffer.extend(items) self._next_token = next_tokenImplement `fetch_n` (fill, then drain)
Now
fetch_n(n)is short and easy to verify:- Reject
n < 0withValueError, and return[]right away forn == 0so zero upstream calls are made. - Fill loop: while
len(self._buffer) < nandself._next_token is not None, call_load_next_page(). Notice the strict<: if_bufferalready holds 3 items andn == 3, we make zero upstream calls. Also notice what happens on consecutive empty pages (items == []with a validnextPage):len(self._buffer)stays< nand_next_tokenis still notNone, so thewhileloop naturally keeps stepping past empty pages until items arrive or the source ends. - Drain loop: pop up to
nitems from the left ofself._bufferintoresultand return it.
class PaginatedReader(PaginatedReader): def fetch_n(self, n: int) -> List[Any]: if n < 0: raise ValueError(f"n must be non-negative, got {n}") if n == 0: return [] # Phase 1 (Fill): pull pages into _buffer until we have at least n items or hit the end. while len(self._buffer) < n and self._next_token is not None: self._load_next_page() # Phase 2 (Commit / Drain): pop up to n items only after all required page loads succeeded. result: List[Any] = [] while len(result) < n and self._buffer: result.append(self._buffer.popleft()) return result- Reject
Trace Example 1 and Example 2 step by step
Let's trace Example 1 with
pages = {"tok_1": {"items": [10, 20, 30], "nextPage": "tok_2"}, "tok_2": {"items": [40, 50], "nextPage": None}}:Start: _buffer = deque([]), _next_token = "tok_1" Call 1: fetchN(2) Fill 1: len(_buffer)=0 < 2 --> load "tok_1" --> _buffer = deque([10, 20, 30]), _next_token = "tok_2" Fill end: len(_buffer)=3 >= 2 (no call to "tok_2" yet!) Drain 2: popleft 2 times --> returns [10, 20] After: _buffer = deque([30]), _next_token = "tok_2" Call 2: fetchN(2) Fill 1: len(_buffer)=1 < 2 --> load "tok_2" --> _buffer = deque([30, 40, 50]), _next_token = None Drain 2: popleft 2 times --> returns [30, 40] After: _buffer = deque([50]), _next_token = None Call 3: fetchN(0) n == 0 --> returns [] immediately (_buffer still holds [50]) Call 4: fetchN(3) Fill: _next_token is None --> loop does not run Drain 3: popleft 1 item --> returns [50]And Example 2 with
pages = {"start": {"items": [], "nextPage": "mid"}, "mid": {"items": [99, 100], "nextPage": "end"}, "end": {"items": [], "nextPage": None}}:Start: _buffer = deque([]), _next_token = "start" Call 1: fetchN(1) Fill 1: load "start" (empty!) --> _buffer = deque([]), _next_token = "mid" Fill 2: load "mid" --> _buffer = deque([99, 100]), _next_token = "end" Drain 1: popleft 1 item --> returns [99], leaves deque([100]) Call 2: fetchN(4) Fill 1: len(_buffer)=1 < 4 --> load "end" (empty, terminal) --> _next_token = None Drain 4: popleft 1 item --> returns [100]Handle transient upstream failures and shifting pages
In production, network calls time out, drop connections, and hit rate limits. Because
PaginatedReadermutates state only afterfetch(token)returns, we can wrapfetchcleanly without tangling retry logic into our buffer logic:- Bounded retries with exponential backoff and jitter: retry only transient errors (timeouts, connection resets, HTTP 429/503 overload), never permanent ones (bad credentials, malformed JSON, invalid token). Exponential backoff doubles the maximum wait after each failed attempt (
0.1s, 0.2s, 0.4s, ...), and full jitter picks a random sleep inside[0, cap]so hundreds of clients recovering from a brief outage do not all slam the server at the exact same millisecond. - All-or-error vs. partial-return contract: our
fetch_nimplements all-or-error: if retries run out mid-call,fetch_nraises the exception while keeping any earlier pages safely buffered inself._buffer. A partial-return contract would instead return(items_so_far, error), which avoids throwing away latency for streaming UIs, at the cost of forcing every caller to distinguish a partial failure from true end-of-source. - Duplicate responses and shifting pages: in synchronous code, an abandoned timed-out call never mutates state, and
_seen_tokensblocks loading the same token twice. If an upstream mutates while we paginate, numeric offset tokens (offset=20) skip or repeat rows whenever items are inserted or deleted above us; ask the upstream for cursor tokens tied to a stable sort key (e.g.,after_id=9812) or a fixed snapshot ID, and deduplicate by item ID if the upstream can replay items across tokens. - Operational metrics: emit counters and histograms for upstream latency per page, retry count by error class, pages loaded per
fetchNcall, empty non-terminal pages, pagination-loop errors, and source-exhaustion events.
import random import time RETRYABLE_ERRORS = (TimeoutError, ConnectionError) def make_retrying_fetch(fetch, max_attempts: int = 4, base_delay: float = 0.1): def fetch_with_retries(token: str) -> Dict[str, Any]: attempt = 1 while True: try: return fetch(token) except RETRYABLE_ERRORS: if attempt >= max_attempts: raise backoff_cap = base_delay * (2 ** (attempt - 1)) sleep_seconds = random.uniform(0.0, backoff_cap) time.sleep(sleep_seconds) attempt += 1 return fetch_with_retries- Bounded retries with exponential backoff and jitter: retry only transient errors (timeouts, connection resets, HTTP 429/503 overload), never permanent ones (bad credentials, malformed JSON, invalid token). Exponential backoff doubles the maximum wait after each failed attempt (
Complete solution
Finally, we add
stateful_fetch_nto connect the judge's simulatedpagesdictionary and operation list to onePaginatedReaderinstance.from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque import random import time class PaginatedReader: """Reads items from a paginated upstream source in exact source order, n at a time. Invariant maintained between calls: (items already returned) + list(self._buffer) + (items from self._next_token onward) == the entire upstream sequence in order. """ def __init__(self, first_token: Optional[str], fetch) -> None: self._fetch = fetch # _next_token: token of the next page to request (e.g. "tok_1"), or None once exhausted. self._next_token: Optional[str] = first_token if first_token else None # _buffer: deque([30, 40, ...]) of items already fetched but not yet handed to the caller. self._buffer = deque() # _seen_tokens: {"tok_1", "tok_2", ...} of tokens already loaded, used to catch pagination loops. self._seen_tokens: Set[str] = set() def fetch_n(self, n: int) -> List[Any]: """Return the next n items in source order, or fewer only when the source ends.""" if n < 0: raise ValueError(f"n must be non-negative, got {n}") if n == 0: return [] # Phase 1 (Fill): pull pages into _buffer until we have at least n items or hit the end. # Strict '<' ensures we never request a new page when _buffer already holds n items. while len(self._buffer) < n and self._next_token is not None: self._load_next_page() # Phase 2 (Commit / Drain): pop up to n items only after all required page loads succeeded. # If an upstream call raised during Phase 1, nothing was popped and no items are lost. result: List[Any] = [] while len(result) < n and self._buffer: result.append(self._buffer.popleft()) return result def _load_next_page(self) -> None: """Fetch one page at self._next_token and append its items atomically to self._buffer.""" token = self._next_token if token is None: return if token in self._seen_tokens: raise RuntimeError(f"pagination loop detected: token {token!r} was already fetched") # Validate the upstream response fields before mutating any reader state, so a failed # or malformed response leaves _seen_tokens, _buffer, and _next_token untouched. page = self._fetch(token) items = page["items"] raw_next_token = page.get("nextPage") next_token = raw_next_token if raw_next_token else None # Commit the page transition in memory. self._seen_tokens.add(token) self._buffer.extend(items) self._next_token = next_token RETRYABLE_ERRORS = (TimeoutError, ConnectionError) def make_retrying_fetch(fetch, max_attempts: int = 4, base_delay: float = 0.1): """Wrap fetch(token) to retry transient network failures with exponential backoff + jitter.""" def fetch_with_retries(token: str) -> Dict[str, Any]: attempt = 1 while True: try: return fetch(token) except RETRYABLE_ERRORS: if attempt >= max_attempts: raise # Full jitter spreads concurrent client retries across [0, base_delay * 2^(attempt-1)]. backoff_cap = base_delay * (2 ** (attempt - 1)) sleep_seconds = random.uniform(0.0, backoff_cap) time.sleep(sleep_seconds) attempt += 1 return fetch_with_retries def stateful_fetch_n( initial_token: str, pages: Dict[str, Dict], operations: List[str], arguments: List[List[int]], ) -> List: """Execute a sequence of fetchN operations against one stateful PaginatedReader.""" # Simulate the upstream API: looking up an unknown token raises KeyError. def fetch(token: str) -> Dict[str, Any]: return pages[token] reader = PaginatedReader(initial_token, fetch) results: List[List[Any]] = [] for op, args in zip(operations, arguments): if op == "fetchN": requested_count = args[0] results.append(reader.fetch_n(requested_count)) else: raise ValueError(f"unknown operation {op!r}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine pouring water for guests when your water arrives in sealed bottles of varying sizes, and you keep a pitcher on the counter between pours. When a guest asks for n ounces, you first check the pitcher: only if the pitcher holds fewer than n ounces do you open new bottles and pour them into the pitcher until either you have enough or you run out of bottles. Then you pour n ounces from the pitcher into the guest's glass, leaving any surplus in the pitcher for the next guest.
The naive alternative — opening every bottle up front and pouring everything into a giant tank before serving anyone — wastes huge amounts of network work when a caller only asks for a few items and hangs forever if two page tokens form a loop. A second naive approach — pouring items directly into the caller's result list while still opening more pages — loses items permanently if a later page request fails mid-call, because those early items have already left the buffer yet never reached the caller. Separating each fetchN(n) into fill the buffer first, drain the buffer second keeps the state completely consistent even across transient failures.
For example, suppose page "tok_1" has [10, 20, 30] (nextPage = "tok_2") and page "tok_2" has [40, 50] (nextPage = None):
1. fetchN(2): the buffer starts empty, so we load "tok_1" (buffer [10, 20, 30]), pop 2 items from the left to return [10, 20], and leave [30] buffered without requesting "tok_2" yet.
2. fetchN(2): the buffer holds only [30] (< 2), so we load "tok_2" (buffer [30, 40, 50], _next_token = None), return [30, 40], and keep [50] in the buffer.
3. fetchN(0) returns [] immediately with zero upstream calls, and fetchN(3) drains the remaining [50] because _next_token is None.
Complexity
- Time: Across the entire lifetime of the reader, O(I + P) in-memory work for
Itotal items andPfetched pages, plus one upstream call per fetched page. Each page token is checked and inserted into_seen_tokensonce in O(1) average hash-set time, and each item is appended once to the right of_bufferand popped at most once from the left of_buffer(collections.deque, a double-ended queue supporting O(1) appends and pops at both ends). A singlefetch_n(n)call therefore does O(n + w) in-memory work, wherewis the total number of items on the pages loaded during that call — making the amortized cost (the average cost per item spread across a sequence of calls) O(1) per item. - Space: O(n + p + P) peak memory during a call, and O(p + P) between calls, where
pis the maximum number of items on a single page andPis the number of pages fetched so far. Because the fill loop stops as soon aslen(_buffer) >= n, the buffer holds at most(n - 1) + pitems before draining, leaving fewer thanpleftover items afternitems are popped, while_seen_tokensstores one string per fetched page.
Edge cases
n = 0: returns[]immediately without touching the upstream, even before the very first page has been loaded.- Negative
n: raisesValueErrorimmediately rather than silently returning[]. - Buffer already satisfies
n:len(_buffer) >= nskips the fill loop completely and makes zero upstream calls. - Empty non-terminal pages (
items = [],nextPage = "mid"): not treated as end of source; the fill loop keeps advancing through consecutive empty pages until items arrive ornextPagebecomes empty/None. - Missing,
None, or""nextPage: marks the final page (_next_token = None), and every call after_bufferdrains returns[]with no more upstream calls. - Pagination cycle (
t1 -> t1ort1 -> t2 -> t1):_seen_tokensdetects the repeated token lazily when the reader tries to fetch it again and raisesRuntimeErrorinstead of hanging or duplicating items. - Mid-call upstream failure: if page 1 succeeds and page 2 raises an exception during
fetch_n(5), page 1's items remain safely in_bufferand_next_tokenstill points at page 2 so a later call can continue cleanly.
Common mistakes
- Stopping as soon as an empty page arrives: many paginated APIs filter out records per page (such as soft-deleted or unauthorized rows) and legitimately return
{"items": [], "nextPage": "t2"}. Only a missing/emptynextPagesignals exhaustion. - Popping items into
resultbefore all required pages are loaded: if the 3rd page fails with a timeout, items popped from the 1st and 2nd pages vanish into the aborted stack frame. - Advancing
_next_tokenor_seen_tokensbefore_fetch(token)succeeds and validates: if_fetch(token)fails, advancing early skips that page on retry or falsely triggers loop detection. - Using
<=instead of<inwhile len(self._buffer) < n: when the buffer holds exactnitems,<=triggers an unnecessary extra network request. - Using
list.pop(0)instead ofdeque.popleft(): popping from index 0 of a Pythonlistshifts every remaining item left in O(buffer_size) time, turning 1-by-1 reads over a 10,000-item page into O(p^2) work.
Alternative approaches
- Python generator +
itertools.islice: yielding items one by one from awhile token is not None:generator is concise, but in Python an unhandled exception inside a generator permanently closes it (StopIterationon every future call), andlist(islice(gen, n))discards items already pulled before the exception raised. Keeping an explicitdequepreserves full control on errors. - Bounded empty-page budget instead of
_seen_tokens: if a reader runs over millions of pages and O(P) memory for_seen_tokensis too large, you can drop the full token set and instead cap consecutive empty pages (for example, raising after 1,000 empty pages in a row) while relying on upstream cursor monotonicity.
Follow-up questions
- How would you synchronize the reader if multiple worker threads call
fetchNconcurrently? Protectfetch_nwith a mutex (a mutual-exclusion lock that lets only one thread execute the protected block at a time) so two callers never pop the same item or fetch the same_next_tokentwice. Holding one lock across the entirefetch_ncall is the simplest correct design and guarantees each caller gets a contiguous slice in source order. If high-latency network calls under a global lock become a bottleneck, use a single-flight pattern (where only one thread performs an in-flight upstream fetch while waiting threads sleep on a condition variable) while keeping all_bufferand_next_tokenupdates inside the lock. - How does your design need to adapt when upstream pagination cursors have a limited TTL? Because a lazy reader may pause for minutes or hours between
fetchNcalls,self._next_tokencan expire while sitting idle, causing a non-retryable token-expired error. To handle this, treat token expiry as a distinct error class (do not retry the dead token with backoff), and either proactively refresh/prefetch before the token's time-to-live (TTL) elapses or require the upstream to issue cursor-based tokens anchored to the last item's sort key (for example,after_id = last_seen_id) so the reader can mint a fresh cursor from the last item it saw. - How can the wrapper tell apart two genuinely identical items in the data from an upstream page replay? Looking at item values alone cannot tell whether
[5, 5]is two real items with value5or the same item delivered twice. You need an identity separate from the payload: either a unique item ID (such asevent_id) or a deterministic(page_token, index_in_page)coordinate. Checking_seen_tokenscatches whole-page replays that reuse the same token, while tracking a sliding window or set of seen item IDs catches item-level duplicates even if the upstream re-packs them under a new page token. - Which fields must be checkpointed to disk so a restarted process can continue without skipping or duplicating items? Persist
(next_token, list(buffer), exhausted_flag)— or, if pages are immutable and tokens do not expire quickly, persist(current_page_token, offset_within_page)to keep checkpoints tiny and re-fetch that single page on startup. The write order relative to handing items to the consumer defines your delivery guarantee: persisting state before handing items out gives at-most-once delivery (a crash loses the in-flight batch), persisting after gives at-least-once delivery (a crash replays the batch), and exactly-once delivery requires committing the reader checkpoint and the consumer's output inside the same atomic database transaction.
Follow-up questions
- How would you synchronize the reader if multiple worker threads call `fetchN` concurrently?
- How does your design need to adapt when upstream pagination cursors have a limited TTL?
- How can the wrapper tell apart two genuinely identical items in the data from an upstream page replay?
- Which fields must be checkpointed to disk so a restarted process can continue without skipping or duplicating items?
Similar questions
- Key-Value Store with Shared Monotonic Snapshot Versions
- In-Memory Key-Value Store with Nested Transactions and Value Counts
- Transactional Key-Value Store with Nested Rollbacks
- Chunked Word Reader Over a Variable-Size Page API
- Commuter Retention Probabilities Under Dynamic Fare Trials
- Data Science Hiring Manager Chat: Influence, Values & Setbacks
More Lyft interview questions
- Distributed Web Crawler Across Heterogeneous Worker Nodes Medium
- In-Memory Transactional Key-Value Store Easy
- Shortest Substring Covering Character Multiplicities Medium Pro
- Minimum-Worker Interval Task Scheduling Medium Pro
- Chunked Word Reader Over a Variable-Size Page API Medium Pro
- Poisson Supply-and-Demand Coverage and Fill Rate Medium Pro
- Leading Through Ambiguity and Compensation Negotiation Medium Pro
- Multi-Device Direct Chat and Real-Time Sync Architecture Medium Pro
- Key-Value Store with Shared Monotonic Snapshot Versions Medium Pro
- Direct Messaging Service Architecture Medium Pro