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:

  1. 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.
  2. Exact vs. partial counts: Return n items whenever at least n unread items remain in the source; return fewer than n items only when the entire upstream sequence has ended.
  3. Zero and invalid counts: Calling fetchN(0) must return [] immediately without invoking fetch. Calling fetchN(n) with n < 0 must raise an exception (ValueError).
  4. 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, subsequent fetchN(n) calls (n >= 0) return [] with zero upstream calls.
  5. 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 fetchN run 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 pages contains "items": List[Any] and optionally "nextPage": Optional[str].
  • Pages must be fetched lazily: never request a page when n == 0 or when buffered items already satisfy n.
  • Negative n or cyclic "nextPage" chains must raise an exception rather than returning a list or hanging.

Step-by-step walkthrough

  1. 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 call fetchN(n) repeatedly and receive the next n items 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:
      1. _next_token: the token of the next page to request, or None once the final page has been read (which doubles as our end-of-source marker).
      2. _buffer: fetched items that have not been handed to a caller yet, kept in source order.
      3. _seen_tokens: the set of page tokens already fetched, used to detect malformed pagination cycles.
    • Invalid input (n < 0) and zero (n = 0): n = 0 returns [] immediately without calling fetch. A negative n is a caller bug, so we raise ValueError rather 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 "" nextPage marks the final page. Once _next_token becomes None and _buffer is empty, every future fetchN returns [] with zero upstream calls.
    • Pagination loops: if nextPage ever points back to a token we already fetched, we raise RuntimeError right before re-fetching it instead of looping forever or duplicating items.
  2. 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 each fetchN(n) call. That passes tiny happy-path examples, but fails in real systems for three reasons:

    1. 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.
    2. 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.
    3. 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.

  3. 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 order
    

    Notice 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._buffer and advances self._next_token to nextPage.
    • Answering fetchN(n) pops up to n items from the front of self._buffer into the returned list.

    Why keep those two phases separate instead of popping items into result as each page arrives? Imagine fetchN(5) loads page 1 ([1, 2]), pops [1, 2] into a local result list, and then fails with a network timeout while requesting page 2. Because the exception aborts fetchN(5), the caller never receives [1, 2] — and because [1, 2] was already popped from self._buffer, the next call starts at page 2 and permanently loses [1, 2]!

    By filling self._buffer first and draining self._buffer second, 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!
    
  4. Store state and load one page atomically

    We store _buffer in a collections.deque (a double-ended queue that appends to the right and pops from the left in O(1) constant time, whereas list.pop(0) shifts every remaining element in O(k) time).

    Inside _load_next_page, we check _seen_tokens before calling _fetch(token), and we extract page["items"] and page.get("nextPage") before modifying _seen_tokens, _buffer, or _next_token. That way, if _fetch raises 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_token
    
  5. Implement `fetch_n` (fill, then drain)

    Now fetch_n(n) is short and easy to verify:

    1. Reject n < 0 with ValueError, and return [] right away for n == 0 so zero upstream calls are made.
    2. Fill loop: while len(self._buffer) < n and self._next_token is not None, call _load_next_page(). Notice the strict <: if _buffer already holds 3 items and n == 3, we make zero upstream calls. Also notice what happens on consecutive empty pages (items == [] with a valid nextPage): len(self._buffer) stays < n and _next_token is still not None, so the while loop naturally keeps stepping past empty pages until items arrive or the source ends.
    3. Drain loop: pop up to n items from the left of self._buffer into result and 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
    
  6. 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]
    
  7. Handle transient upstream failures and shifting pages

    In production, network calls time out, drop connections, and hit rate limits. Because PaginatedReader mutates state only after fetch(token) returns, we can wrap fetch cleanly 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_n implements all-or-error: if retries run out mid-call, fetch_n raises the exception while keeping any earlier pages safely buffered in self._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_tokens blocks 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 fetchN call, 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
    
  8. Complete solution

    Finally, we add stateful_fetch_n to connect the judge's simulated pages dictionary and operation list to one PaginatedReader instance.

    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 I total items and P fetched pages, plus one upstream call per fetched page. Each page token is checked and inserted into _seen_tokens once in O(1) average hash-set time, and each item is appended once to the right of _buffer and 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 single fetch_n(n) call therefore does O(n + w) in-memory work, where w is 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 p is the maximum number of items on a single page and P is the number of pages fetched so far. Because the fill loop stops as soon as len(_buffer) >= n, the buffer holds at most (n - 1) + p items before draining, leaving fewer than p leftover items after n items are popped, while _seen_tokens stores 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: raises ValueError immediately rather than silently returning [].
  • Buffer already satisfies n: len(_buffer) >= n skips 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 or nextPage becomes empty/None.
  • Missing, None, or "" nextPage: marks the final page (_next_token = None), and every call after _buffer drains returns [] with no more upstream calls.
  • Pagination cycle (t1 -> t1 or t1 -> t2 -> t1): _seen_tokens detects the repeated token lazily when the reader tries to fetch it again and raises RuntimeError instead 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 _buffer and _next_token still 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/empty nextPage signals exhaustion.
  • Popping items into result before 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_token or _seen_tokens before _fetch(token) succeeds and validates: if _fetch(token) fails, advancing early skips that page on retry or falsely triggers loop detection.
  • Using <= instead of < in while len(self._buffer) < n: when the buffer holds exact n items, <= triggers an unnecessary extra network request.
  • Using list.pop(0) instead of deque.popleft(): popping from index 0 of a Python list shifts 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 a while token is not None: generator is concise, but in Python an unhandled exception inside a generator permanently closes it (StopIteration on every future call), and list(islice(gen, n)) discards items already pulled before the exception raised. Keeping an explicit deque preserves 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_tokens is 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 fetchN concurrently? Protect fetch_n with 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_token twice. Holding one lock across the entire fetch_n call 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 _buffer and _next_token updates 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 fetchN calls, self._next_token can 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 value 5 or the same item delivered twice. You need an identity separate from the payload: either a unique item ID (such as event_id) or a deterministic (page_token, index_in_page) coordinate. Checking _seen_tokens catches 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

Similar questions

More Lyft interview questions

All 52 Lyft questions →