The index is being written to while people are paging through it. For a news monitoring service that keeps swallowing a folder of PDFs — press packets, regulator filings, earnings transcripts — that one fact decides the entire pagination design, and semantic retrieval makes it sharper than it ever was for keyword search. Bottom line: pin the query to a snapshot, page with a cursor that carries the last score plus a content-addressed chunk id, and never let a raw offset reach the reader.

Offsets lie the moment the corpus moves.

What actually breaks when the index is moving

A morning digest went out with the same regulator filing cited twice — once in the first block of related coverage, once again when the analyst clicked through to the second. A different filing that should have sat between them never appeared at all. No error was logged. Nothing was down. The retrieval tier had done exactly what it was asked to do: LIMIT 10 OFFSET 10 against an index that had absorbed roughly 400 new chunks in the twenty-six seconds between the two requests. Every fresh chunk scoring above the reader's page boundary pushed one document down a rank, and the offset dutifully skipped past it.

I assumed the ranking was stable because the query text was stable. It isn't.

Three separate things shift underneath a paged semantic query, and only the first one is obvious:

  • Fresh writes. A monitoring pipeline that ingests continuously changes the rank of everything below the newest match, so offset N on request two addresses a different document than offset N on request one.
  • Approximate search. Vector indexes explore a bounded candidate list, so the top 10 of a 40-candidate walk is not simply the first half of the top 20 from a wider walk. Asking for a bigger page can change which documents come back at all, not just how many.
  • Score ties. In news, the same wire story gets republished by six outlets with a rewritten headline; those chunks embed to nearly identical vectors and land on identical rounded scores. Whatever internal order breaks that tie is free to change after a segment merge.

Duplicate citations in a media product are not cosmetic. An analyst counting mentions counts them twice, and the number lands in a client report.

How should pagination work for semantic retrieval in a news monitoring service?

Freeze what you are paging over, order it on a total key, and make the cursor prove it belongs to the query in hand.

Freezing comes first because the other two rules are worthless without it. The first request opens a snapshot — a point-in-time handle, an index generation number, whatever your engine calls a consistent read — and every later page in that session reads that generation. New articles then appear when the reader refreshes, which is the behavior a monitoring UI wants anyway: the result set is a document, not a live tail.

Ordering on a total key is the part teams skip. Cosine similarity gives you a partial order, and partial orders have ties; a keyset predicate over (score, chunk_id) gives you a total one. Concretely, the next page is everything where score < last_score, plus everything where score = last_score AND chunk_id > last_chunk. Ties resolve identically on every node, every merge, forever, because the id is derived from bytes rather than from row position.

The third rule is the one my on-call habits insist on: the same cursor must return the same page, byte for byte, or it is not a cursor. Put the query hash and the snapshot id inside the token, compare on the way in, and reject a mismatch loudly instead of quietly serving results from a different filter set. That is cheap to test — ask for page two five times in a row and diff the citation ids.

Index type How a stable page is expressed Boundary to watch
Elasticsearch / OpenSearch point-in-time id plus search_after from + size is capped by index.max_result_window, 10000 by default
Qdrant scroll returns a next_page_offset handle ordering by similarity still needs an explicit tie-break field
pgvector on Postgres an ordinary SQL keyset predicate hnsw.ef_search (40 by default) bounds the candidate list, so a wider page can change recall

The cursor, in Go

// Cursor is the only state the client hands back. It names the query it // belongs to, the index generation it was answered from, and the exact // position we stopped at. No offsets, no page numbers. type Cursor struct { Query string `json:"q"` // sha256 over normalized query text + filters Snapshot string `json:"s"` // point-in-time / index generation handle Score float32 `json:"sc"` // similarity of the last chunk we emitted ChunkID string `json:"c"` // content-addressed id; breaks score ties } var ErrCursorStale = errors.New("retrieval: cursor does not match this query") // Page returns one page of chunks plus the token for the next one. Called // twice with the same token it returns the same chunks in the same order, // until the snapshot is released. func (s *Store) Page(ctx context.Context, q Query, token string, size int) ([]Chunk, string, error) { cur := Cursor{Query: q.Hash(), Score: math.MaxFloat32} if token == "" { snap, err := s.OpenSnapshot(ctx) // pins the index generation if err != nil { return nil, "", err } cur.Snapshot = snap } else { var err error if cur, err = decodeCursor(token); err != nil { return nil, "", err } if cur.Query != q.Hash() { return nil, "", ErrCursorStale // filters changed: restart at page one } } // One extra row tells us whether a next page exists without a second // round trip. The tie-break lives in the predicate, not in the caller. rows, err := s.searchAfter(ctx, q, cur, size+1) if err != nil { return nil, "", err } if len(rows) <= size { return rows, "", nil // last page: no token, so no empty tail page } last := rows[size-1] return rows[:size], encodeCursor(Cursor{ Query: cur.Query, Snapshot: cur.Snapshot, Score: last.Score, ChunkID: last.ID, }), nil } 

Two details in there earn their keep during an incident. The size+1 lookahead removes the empty final page that makes users think the system dropped their results, and the explicit ErrCursorStale turns a silent wrong-answer class into a 4xx the client can retry from page one. Map snapshot expiry to the same path: a reader who wanders off for an hour should get an honest "start over, here is a fresh snapshot" rather than a page assembled from a generation that no longer exists.

Run the invariant as a test, not as a hope.

go test ./retrieval -run TestPageIsIdempotent -count=5 

Citations only hold if the ids are content-addressed

Grounding is the reason anyone paginates this corpus in the first place — an analyst needs the filing, the page, and the paragraph, not a summary they have to trust.

// ChunkID is derived from the bytes it points at, never from row order. // Reindexing the same PDF yields the same id; re-chunking it yields a new // one, which is exactly what makes a stale cursor detectable. func ChunkID(docDigest string, page, start, end int) string { h := sha256.New() fmt.Fprintf(h, "%s|%d|%d|%d", docDigest, page, start, end) return hex.EncodeToString(h.Sum(nil))[:16] } // Cite resolves an id back to text before a reader ever sees it. If the // bytes moved, drop the citation rather than render one pointing elsewhere. func (s *Store) Cite(ctx context.Context, id string) (Citation, error) { c, err := s.lookup(ctx, id) if err != nil { return Citation{}, err } if ChunkID(c.DocDigest, c.Page, c.Start, c.End) != id { return Citation{}, ErrCitationMoved } return c, nil } 

A citation that resolves to different text after a re-chunk is worse than no citation at all, because nobody checks the ones that look fine. This also gives the ingest side its idempotency key for free: hash the PDF, derive the chunk ids, skip anything already present, and a replayed ingest job stops producing duplicate candidates for the tie-break to trip over.

When an offset is still the right answer

The catch is that cursors cannot jump. A reader who wants page seven has to walk pages one through six, so a numbered pager — the kind editorial teams keep asking for — is not a good fit for keyset pagination without a separate counting path. If the product genuinely needs jump-to-page over a live index, be honest that you are buying an approximate page number and say so in the UI.

Small corpora are the other exception. Under a few thousand chunks, fetch the top 50 in one shot, sort in memory, and slice; the snapshot machinery costs more than it returns, and you can stick with an offset until the corpus grows past what one response can carry.

Snapshots are not free either. A pinned point-in-time keeps segments from being reclaimed, so a long reader session holds disk that a busy ingest pipeline would rather recycle. Set a TTL in minutes and treat expiry as a normal, tested code path. I'm not sure there is a single correct TTL — it depends on how long your readers actually sit on a result set, and the honest way to find out is to measure the age of cursors arriving at your service, not to guess it in a design doc.

References