Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

A platform library offers an Iterator<Record> over paginated results from a remote API for many services. Teams report missing or duplicated records when data changes during iteration, and leaked HTTP connections when they stop early. Design the iteration contract.

Missing and duplicated records come from offset paging over data that changes, so the library should page with a cursor or keyset token that marks a position in a stable order, and it must state whether iteration is a consistent snapshot or a live view. Leaked connections come from Iterator having no close method, so the library should return a closeable type, such as a Stream with onClose or an AutoCloseable iterator. Failed page fetches retry that page from its token, and tests cover changing data and early termination.

Why this question is asked

A platform library that wraps a paginated API looks simple: fetch a page, hand out its records, fetch the next page. Used by many services over months, every gap in its contract turns into a data bug somewhere: a report that misses records, a sync job that processes some twice, a pool of HTTP connections that slowly drains. Interviewers ask this design question to see whether we can trace symptoms back to the contract and define one that holds under change and failure. In this answer, we will see why offset paging loses and repeats records, choose stable paging, decide between snapshot and live semantics, make early termination safe, define retries, and plan the tests.

1Why Offset Paging Skips and Repeats

Offset paging asks for page 2 as offset 100, limit 100: skip the first 100 records in the current order and return the next 100. The problem is that the server recomputes that order on every request. If a record before our position is deleted between two requests, everything shifts left by one and we skip a record. If one is inserted before our position, everything shifts right and we see a record twice.

A delete between two page requests
RequestData at that momentOffset, limitRecords returned
Page 1r1 r2 r3 r4 r5 r60, 3r1 r2 r3
(r2 is deleted)r1 r3 r4 r5 r6
Page 2r1 r3 r4 r5 r63, 3r5 r6
r4 moved into position 2 and was never returned. An insert would repeat a record instead.

Nothing is wrong in either request on its own. Each page is correct at the moment it was fetched, but the pages were cut from different versions of the data, so they do not line up.

2Stable Paging With a Cursor or Keyset

Keyset paging asks for records after the last key we saw, in a fixed and unique order: WHERE (created_at, id) > (:lastCreated, :lastId) ORDER BY created_at, id LIMIT 100. A cursor token is the same idea packaged by the server: an opaque string that encodes our position, returned with each page and sent back for the next one. Deletes and inserts before our position no longer shift anything, because the position is a key, not a count.

The library should use the API's cursor if it offers one, and if the remote API only supports offsets, that limitation must be raised with its owners and documented in our contract, because no client-side trick can make offset paging stable under change.

3Snapshot or Live View: Decide and Document

Stable paging fixes skips and repeats caused by shifting, but it does not answer a second question: what about records that change during a long iteration? There are two honest contracts. A consistent snapshot means the iteration returns the data exactly as it was at one moment, which the server can support with a snapshot id or a read timestamp sent with every page. A live view means each record is returned at most once, records inserted behind the cursor are not seen, records inserted ahead of it may be, and updated records appear with whichever version was current when their page was fetched.

Most remote APIs can only offer a live view, and that is fine for most consumers, such as a sync job that runs again every hour. A financial reconciliation, though, needs a snapshot. The library's Javadoc must say which one it provides, because each consuming team will otherwise assume the one they need.

4A Closeable Contract for Early Termination

The leaked connections have a simpler cause. When a caller breaks out of the loop, the library's Iterator has no way to learn that, so the HTTP response it was streaming from is never closed. We change the public type to something closeable and make closing part of normal use.

Java
public interface RecordPages {
/** Lazily fetches pages using the server cursor. Live view: each record at most once.
* Single use. Must be closed; closing releases the open HTTP response. */
Stream<Record> stream(Query q);
}
// inside the library
public Stream<Record> stream(Query q) {
PageIterator it = new PageIterator(client, q); // holds the current page and cursor
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED | Spliterator.NONNULL), false)
.onClose(it::close); // release the response on close
}
// a team's code
try (Stream<Record> records = pages.stream(query)) {
records.takeWhile(r -> r.day().isBefore(cutoff)).forEach(sink::write);
} // closed even though takeWhile stopped early

For teams that prefer explicit loops, the library can also offer a CloseableIterator<Record> that extends both Iterator and AutoCloseable, used in try-with-resources. Notice that both forms make ownership clear: whoever opens the iteration closes it.

5Retrying a Failed Page Without Starting Over

With 2 million records over 20,000 pages, some page fetches will fail. If the iterator throws and the caller restarts, it repeats everything already processed. The contract should say instead that the iterator retries the failed page itself, a limited number of times with backoff, using the same cursor token, which is possible because the token names exactly where that page begins.

Step throughFetching the next page
  1. Fetch page with cursor token Tthe token marks the page start
  2. Request succeeded?
    YesReturn records, keep the new tokenNoIs it retryable and attempts left?
  3. Retryable and attempts left?
    YesBack off, fetch with T againNoThrow, carrying token T for resume
  4. Caller closes the streamrelease the open response

4 steps in order. Play them, or step through them one at a time.

The same token is used for every retry, so a retry never restarts the whole iteration.

If the retries run out, the iterator throws an exception that carries the last successful cursor token, so a caller can resume from there later rather than from the start. The library should also define what happens if the token itself expires on the server, which many APIs do after some minutes: either the iteration fails with a clear error, or it restarts from the token's position if the server allows it.

6Tests That Lock the Contract In

Each promise in the contract gets a test against a fake server. One test deletes and inserts records while iteration is in progress and checks that no record is returned twice and none present throughout is missed. One stops after the first page and checks, through the fake server or the HTTP client's connection pool metrics, that no connection is left in use. One fails a page fetch twice and checks that the iteration continues without repeats. These tests protect consumers from a future change in the library as much as from today's bugs.

7Follow-up questions

Can the library dedupe records on the client side instead?

It could remember the ids it has returned and skip repeats, but that costs memory proportional to the whole result and does nothing about skipped records, which are the more dangerous failure. Stable paging solves both at the source.

Should the library prefetch the next page in the background?

It can, to hide latency, but it must then cancel the prefetch when the stream is closed, or it leaks a connection again. Keep prefetching optional and covered by the early termination test.

Why not return a List of all records?

For small results that is the simplest contract and needs no cleanup. For a result of millions of records it costs gigabytes of heap and delays the first record until the last page arrives, so the library should offer both and document the size at which callers should switch.

8Conclusion

In this answer, we traced missing and duplicated records to offset paging over changing data and fixed it with cursor or keyset paging, then made the library state whether it offers a consistent snapshot or a live view. We traced leaked connections to Iterator's missing close method and replaced the public type with a Stream with onClose or a closeable iterator. Failed pages are retried from their own cursor token, an exhausted retry reports the token for resuming, and tests that change data and stop early keep the contract true.

What to say in the interviewAbout 100 seconds aloud

Open with

I'd look at the two symptoms separately. Missing and duplicated records are what offset paging does when data changes: each page is computed as skip n, take m on the current data, so a delete before my position shifts a record past me and an insert makes me see one twice.

Then, if they want more

So the library should page with the API's cursor token, or keyset paging on a unique, stable order, which marks the position by key rather than by count.

Even then, I'd make the contract say whether iteration is a consistent snapshot, which needs server support like a snapshot id, or a live view where each record appears at most once but changes during iteration may or may not be seen. Most consumers are fine with a live view, but they need to know.

The leaked connections come from Iterator having no close method, so a caller who breaks early leaves the HTTP response open. I'd change the public type to a Stream with onClose, or a CloseableIterator that extends AutoCloseable, and document that it's single-use and must be closed, ideally with try-with-resources.

For failures, the iterator retries a failed page a few times with backoff using the same cursor token, so it never restarts from the beginning, and if it gives up, the exception carries the last good token so the caller can resume.

Then I'd add tests against a fake server that modify data mid-iteration, stop after one page and check for open connections, and inject page failures.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A platform library offers an Iterator<Record> over paginated results from a remote API...": https://scrivio-interview-library.netlify.app/java/iteration/c2a265f4f3/