Video in progress

You need to write a utility that exposes a paginated external API or table as a lazy Stream. How do you design it and what risks do you account for?

I write a Spliterator that loads each page when needed and wrap it with StreamSupport.stream: if the caller uses limit or takeWhile, extra pages aren't requested. Risks: no parallel splitting, partially consumed streams and open resources, data changing between pages, and retry and rate limits.

📖 Answer

The goal is that the caller doesn't have to think about pagination:

public Stream<Invoice> allInvoices(Instant since) {
    return StreamSupport.stream(new PageSpliterator(since), false);
}

final class PageSpliterator extends Spliterators.AbstractSpliterator<Invoice> {
    private String cursor;                     // marker for the next page
    private Iterator<Invoice> current = Collections.emptyIterator();
    private boolean last;

    PageSpliterator(Instant since) {
        super(Long.MAX_VALUE, ORDERED | NONNULL);
        this.cursor = Cursor.start(since);
    }

    @Override
    public boolean tryAdvance(Consumer<? super Invoice> action) {
        while (!current.hasNext()) {
            if (last) return false;
            Page<Invoice> page = client.fetch(cursor);   // the network call is here
            current = page.items().iterator();
            cursor = page.next();
            last = cursor == null;
        }
        action.accept(current.next());
        return true;
    }
}

AbstractSpliterator's trySplit can copy batches into an array, but parallelizing an I/O source is a bad idea anyway: I document that it runs sequentially even if parallel() is called.

Things to settle in the design:

  • Cursor/keyset, not offset. With offset, if new records are added between pages, elements repeat or get skipped. A cursor (or id > lastId) is stable.
  • Retry and rate limit: retry with backoff inside fetch. But unlimited retry hangs the stream's consumer: set a limit and throw a clear error at the end.
  • An error in the middle: if page 40 fails, the caller has already processed 39 pages. Its writes need to be idempotent, or it needs a way to checkpoint the last cursor. I leave the last successful cursor open to be read.
  • Resources: if the HTTP client itself doesn't hold the connection, close isn't required. If the source is a DB cursor, tie it with onClose and write the closing contract in the Javadoc.
  • Observability: how many pages were requested and how long they took: a metric. With a lazy stream, someone can call count() and unknowingly read the entire API.

The alternative: not a stream but an Iterable or a callback (forEachPage). A stream is convenient, but because of laziness network calls happen at unexpected places in the code. If the team isn't ready for that, a callback API is simpler.