Practice: FB Post Search
Design post search that indexes authored text quickly while checking current visibility and access permissions before returning results.
Design post search that indexes authored text quickly while checking current visibility and access permissions before returning results.
Write your own design before opening hints or the solution review. The numbers below are exercise assumptions, not claims about any company’s production traffic. You may challenge an assumption, but record the replacement and explain which decision changes.
Scenario and constraints
- Assume 2 billion posts, 100 million daily searches, and 10,000 post edits per second at peak.
- Search results should normally reflect a committed post change within 5 seconds.
- A query returns at most 50 results with a stable cursor; private/deleted posts must never leak.
- Index rebuilds may run concurrently with queries and must be switchable by generation.
Your deliverables
- Define post, versioned change event, token/posting entry, index generation, query cursor, and authorization decision.
- Calculate index write amplification and query fanout; partition by document ID and bound scatter/gather.
- Show tokenization and multi-term posting intersection, then apply recency/popularity without losing stable paging.
- Explain index lag, current authorization filtering, backfill/catch-up, hot terms, and generation swaps.
Reason about this sequence
Read the diagram
Post becomes private → Index still returns ID → Viewer is not authorized → Snippet is suppressed → Tombstone removes stale index document
For every step, annotate what is durable, what the caller knows, and which identity survives a retry. Identify the point where two concurrent actors could disagree. Do not assume a timeout means failure or a cache value grants ownership.
Interviewer follow-ups
- An indexer replays an older post version after a newer edit. How does the search projection reject it?
- A private post remains in the search index after permission changes. At what step is it filtered?
- A rebuild falls behind live updates. How can the new generation catch up without a gap or duplicate results?
Answer each follow-up using the same design first. If it breaks, change the smallest boundary that repairs the invariant and explain the new cost. Show whether the change adds latency, storage, coordination, or operational work.
Staged hints
Hint 1 — reveal
Answer: Hint 1 — Search is a derived candidate index; check current authorization against the authoritative post state before returning each result.
Hint 2 — reveal
Answer: Hint 2 — Store post text, owner, audience, group membership, version, and deletion state in authoritative systems. Index analyzed terms with post ID and revision. Avoid putting secret content into a globally shared index document without tenant/audience scoping. Keep the indexing event replayable and versioned.
Hint 3 — reveal
Answer: Hint 3 — A delayed index event for version 6 arrives after deletion version 7 and recreates the document. Store a version or tombstone and apply only monotonic updates. During a reindex, propagate deletes and membership changes to the new index before switching. Test cached result pages and autocomplete, not just the main query endpoint.
Evidence-based self-review
- Post and outbox commit together; the versioned projector applies changes monotonically and is replay-safe.
- The search index returns candidates only; current source authorization decides whether each can be shown.
- Pagination is stable across ranking changes and index-generation swaps.
- Token cardinality, hot terms, query fanout, index lag, and rebuild throughput have explicit bounds and SLIs.
Score each item 0 if absent, 1 if named without an enforceable mechanism, or 2 if the mechanism and a failure are explained. Record evidence from your own diagram beside the score. Then choose one weak decision, revise it, and repeat the relevant follow-up. This rubric is a learning tool, not a hiring forecast.
Clarify this prompt before choosing components
Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.
| Ask the interviewer | Why the answer changes the design |
|---|---|
| Keyword search, personalization or semantic retrieval? | Index/query structures and ranking costs differ. |
| Search freshness and deletion visibility targets? | CDC lag and serving-time visibility checks must satisfy the target. |
| Private posts, blocks and pagination stability? | Authorization must filter current results; cursors declare their snapshot semantics. |
Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.
Reveal the full worked solution
Save your attempt before continuing.
FB Post Search: Understand the building blocks
Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.
FB Post Search: Quick vocabulary
| Term | Meaning and role in this exercise |
|---|---|
| API: Application Programming Interface | The contract for requests, responses and errors between components. An API route does not itself enforce every business invariant. |
| PK: Primary Key | The declared row identity in a database schema; it does not automatically enforce every cross-row business rule. |
FB Post Search: Inverted index and BM25 relevance
What it means: An inverted index maps searchable terms to matching documents. BM25 is a relevance-scoring family using term/document statistics; it ranks candidates rather than deciding access.
Why this problem needs it: Queries should retrieve term matches without scanning every post.
How to use it: Tokenize under a declared analyzer, maintain postings from versioned documents, retrieve candidates and enforce current visibility before disclosure.
Example in this design: A search engine finds matching candidates, then the application enforces current visibility.
When it fits: Useful when text queries should avoid scanning every post or document.
Alternative and limits: Database text search can fit a smaller baseline. An external search index adds lag, repair and operations; high score does not imply current authorization.
FB Post Search: Change Data Capture (CDC)
What it means: CDC exports committed source changes so derived consumers can follow database updates. It is a propagation mechanism, not a second business authority.
Why this problem needs it: Search must follow the authoritative post revisions.
How to use it: Preserve object identity, revision and deletion markers; checkpoint consumption and reject older events during replay/rebuild.
Example in this design: Deletion revision 7 rejects a delayed indexing event for revision 6.
When it fits: Useful when a search/feed projection must follow a source of truth.
Alternative and limits: An outbox adds explicit application event intent; periodic rebuilds are simpler for loose freshness. Delivery does not eliminate version races or permission checks.
FB Post Search: Point-in-time search (PIT) and cursor
What it means: A PIT pins a search view for bounded browsing; a cursor encodes the continuation position and required sort/view identity.
Why this problem needs it: Readers may require stable browsing despite indexing changes.
How to use it: Use a stable sort with a unique tie-breaker, expire the view, and require the continuation to refer to the same query and view.
Example in this design: Continue the same query/view/sort identity, while still enforcing current permissions.
When it fits: Useful when changes between pages would otherwise create duplicates or omissions.
Alternative and limits: Offset pagination is simpler for small stable results. PIT stability is not permanent permission to return documents that became private.
FB Post Search: Access Control List (ACL) and current authorization
What it means: An ACL records which principals may perform specified actions on an object. Authorization evaluates the applicable current policy for this request.
Why this problem needs it: Index lag must not disclose a post whose visibility changed.
How to use it: Authenticate the caller, evaluate object/tenant membership and permission version at the required disclosure/mutation boundary, and declare caching/revocation behavior.
Example in this design: A private post can remain indexed as an ID but must not be returned as readable content.
When it fits: Needed when object access can change while connections, projections or cursors remain alive.
Alternative and limits: Capabilities/signed grants can fit a bounded expiry policy. A valid cursor, cached candidate or open socket is not permanent permission.
Interview scope and guarantees
Search authorized posts by text, filter by author or time, rank results, and paginate. Agree index freshness and deletion propagation targets. Search relevance may be approximate, but access control must not be bypassed by a stale index.
Capacity worksheet
Assume 100 million posts/day averaging 1 KB of searchable text: 100 GB/day raw. If analyzed index data is 2× raw and replicated twice, budget around 400 GB/day before retention and merges. At 10,000 queries/s with 20 shard requests each, the cluster sees 200,000 shard-level searches/s.
Concrete API contract
GET /search?q=...&author=...&cursor=...
POST /posts {text,visibility}
DELETE /posts/{id}
Search response includes post IDs, snippets, cursor and index freshness.Data model and access paths
posts(post_id PK,author_id,text,visibility,version,deleted_at)
index_document(post_id,terms,author_id,created_at,visibility_version)
index_checkpoint(partition,offset)
search_cursor(query_hash,pit_id,sort_values,expires_at)Evolve a solution and explain each change
Read the diagram
Search source records / Filter authorized posts and match terms directly for a small workload. / Scanning the source database is slow at scale.; Build a search projection / Index post text asynchronously through versioned change events. / The index can lag or retain deleted/private content.; Revalidate and rebuild / Filter candidates against current permissions and support versioned projection rebuilds. / Search relevance and index freshness are separate quality dimensions.
Step 1: Search source records
Filter authorized posts and match terms directly for a small workload. Scanning the source database is slow at scale.
Step 2: Build a search projection
Index post text asynchronously through versioned change events. The index can lag or retain deleted/private content.
Step 3: Revalidate and rebuild
Filter candidates against current permissions and support versioned projection rebuilds. Search relevance and index freshness are separate quality dimensions.
Responsibility overview
Read the diagram
Searcher to Search API: search terms; Search API to Post DB: current permissions; Author to Post DB: commit post edit; Post DB to Indexer: versioned change; Indexer to Search index: apply newer document; Search API to Search index: candidate search
Worked end-to-end scenario
Post p9 is indexed at version 3. The author edits it to version 4, then deletes it at version 5. Workers receive those changes out of order. The index must reject the old version 3 update after applying the version 5 tombstone. A search query returns candidate IDs from the index; the serving layer checks current visibility before returning protected text. Permission filtering only after displaying a snippet is already too late. To rebuild, populate a new index from a consistent snapshot plus changes, validate it, and switch an alias without mixing cursor state across incompatible ranking snapshots.
Why these access paths matter
The source post table is authoritative; the search index stores document ID, content version, terms, and permitted filtering metadata. Use stable tie-breakers and search-after style pagination tied to a search snapshot when needed. An authorization index may reduce candidate volume, but its stale state cannot be the only control for strict privacy.
Build the baseline first
Read the diagram
Post transaction → outbox → indexer; Query → inverted index → ranked candidates; Current authorization → hydrated results
- Post transaction → outbox → indexer.
- Query → inverted index → ranked candidates.
- Current authorization → hydrated results.
Evolve the design under load
Read the diagram
Index shards → scatter/gather → bounded top results; Replica groups → query capacity isolation; New index generation → backfill and catch-up → alias switch
- Index shards → scatter/gather → bounded top results.
- Replica groups → query capacity isolation.
- New index generation → backfill and catch-up → alias switch.
Defend the hardest decision
An inverted index maps terms to posting lists; analyzers determine tokenization and normalization. Matching candidates is not the same as ranking them. Apply coarse searchable ACL filters early, then check current access before returning text or snippets. For stable pagination, use a point-in-time snapshot and search-after values with a deterministic tie-breaker rather than large offsets.
Failure and recovery analysis
A deletion event arrives before an older update due to retries. Index updates must compare document versions so stale writes cannot resurrect content. If search indexing lags, show reduced freshness while preserving primary writes. Reindex into a new generation, replay changes from the snapshot boundary, and switch atomically after validation.
Security and privacy boundary
Authorize before returning snippets, protect private terms in logs, and rate-limit exhaustive search scraping.
Interview follow-ups with reasoning
Question: How do multilingual analyzers affect schema?
Show answer and explanation
Answer: Store language-specific fields or choose analyzers deliberately.
Question: How do you reduce shard fanout?
Show answer and explanation
Answer: Route constrained queries by author or tenant where possible.
Question: How do you test privacy?
Show answer and explanation
Answer: Revoke access while replaying old events and assert no snippets leak.
Operate and verify the design
Index freshness, query fanout, deleted-document resurrection and authorization filter failures.
Replay an old update after a deletion and verify that neither the result nor snippet reappears.
A second scenario to test transfer
A post changes from public to a private group. The search index still contains its old public token document for 30 seconds. Search may retrieve that ID, but the authorization step rejects it and suppresses the snippet. Asynchronous index cleanup then removes it from future candidate sets. Measure both exposure correctness and cleanup lag.
How can search remain available during eventual index cleanup without showing a newly private post?
Show answer and explanation
Answer: Allow the index to return a candidate ID but consult current authoritative visibility before returning the post or any excerpt. Versioned delete propagation reduces future index matches; access control on the response is the safety boundary. The query cache also needs viewer scope or an authorization-safe representation.
Compare alternatives
| Layer | Purpose | Privacy control |
|---|---|---|
| Text index | Candidate retrieval | Scope fields and limited payload |
| Authorization owner | Current viewer access | Check before snippets |
| Deletion tombstone | Prevent resurrection | Versioned writes |
| Result cache | Reuse query work | Viewer/audience-aware key |
A design-changing exercise
A private post is removed from the database but remains searchable for a minute. Can a disclaimer solve it?
Show answer and explanation
Answer: Not for a strict privacy contract. Current authorization must protect content and snippets while deletion propagates to the projection.
Design workshop: retrieve candidates, then authorize
Core scope is text search over visible posts with edits/deletion and stable pages. Semantic embeddings are an extension. Choose indexed freshness within ten seconds, p95 under 300 ms for admitted bounded queries and authoritative authorization before returning content or snippets.
Index mapping includes postId, authorId, body tokens, audience hints, sourceVersion and deleted. Tokenization lowercases and normalizes under a pinned analyzer. For documents D1='red bicycle', D2='blue bicycle' and D3='red boat', postings are red→{D1,D3}, bicycle→{D1,D2}. AND intersection returns D1; OR returns all three and needs scoring. BM25-style scoring combines inverse document frequency, term frequency saturation and length normalization; show the ranking objective rather than claiming a term match alone gives relevance.
Read the diagram
Term/query / Posting/candidates / Next step; red / D1,D3 / Authorized candidates only; bicycle / D1,D2 / Apply same analyzer as indexing; red AND bicycle / D1 / Hydrate current visible D1; red OR bicycle / D1,D2,D3 / Score then authorization-safe top-up; D1 made private / Index may still return D1 / Suppress body, snippet and media until ACL permits
Hash post ID to shards for write balance; text queries scatter to selected shards and merge scored candidates. Audience filters prune work but are not the final privacy authority. If many hits are inaccessible, bounded oversampling can fill the page; when its budget is exhausted return fewer results with an honest continuation, not an unbounded loop. Avoid exposing restricted snippets in caches or search-index responses accessible to clients.
Use a point-in-time index snapshot with search_after carrying a deterministic score/tie sort tuple. Sign the PIT ID and tuple to bind query, viewer and expiry. A changed query creates a new cursor; an expired PIT returns reset_required. Current ACL filtering still applies despite the PIT, so visibility can change between pages without exposing protected posts.
Read the diagram
Snapshot source at watermark W; Build new mapping/analyzer index from snapshot; Replay edits/deletes after W with source versions; Retain durable tombstone documents or version ledger; Catch up to chosen cutover watermark; verify counts; Switch alias; authorize every hydrated result
For stale-event protection choose soft tombstone documents carrying the last sourceVersion, or a durable external version ledger checked by the indexer. Elasticsearch's physical delete does not keep version evidence indefinitely; index.gc_deletes bounds that evidence. Align tombstone retention with maximum replay and backfill horizon, including restores. When tombstones are purged, old history must rebuild into a new epoch/index rather than replay into the current one.
Reindex builds a new projection, consumes changes after its snapshot watermark, compares document counts and representative queries, then switches an alias. Do not drop the old index until rollback retention expires. During both paths authorize against current source state. Rate-limit long queries and cap shard/time budgets. Monitor index lag, tombstone age, unauthorized-hit ratio, top-up work and PIT resets independently.
Exercise: Delete version 8 is physically removed, its version evidence expires, and update version 7 arrives from an old replay. What stops resurrection?
Show answer and explanation
Answer: The selected durable tombstone/version ledger rejects 7. A bare physical delete with finite version retention cannot support an indefinite replay guarantee. Alternatively isolate the replay into a new projection and reconstruct correct source state there.
Elasticsearch pagination and delete version retention document the relevant provider boundaries.
Rank candidates before authorized disclosure
Search candidates receive text and recency ranking before current authorization and snippet hydration.
Read the diagram
Ranking is bounded and cursor-stable; current ACL checks remain the final read boundary.
Requirement trace and verification
| Requirement | Implementing design block | Verification link |
|---|---|---|
| R1 — Complete the primary user journey within the stated scope. | P01–P04; P09–P10. | V1 — Exercise the successful journey and the excluded/boundary case stated in the scope. |
| R2 — Preserve the problem's authoritative data invariant under concurrency. | P05–P06; P11–P12; DD1. | V2 — Run the race/replay case below and assert the invariant at the durable authority. |
| R3 — Meet the declared scale and API behavior without unbounded work. | P05–P08; P13–P14; relevant overload deep dives. | V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity. |
| R4 — Recover from the named failure without losing or duplicating the user-visible outcome. | P15–P16; deep dives; Operations contract. | V4 — Search a known corpus with phrase order changes, replay likes, and delete a post; verify results against a small exact evaluator. |
Operational contract
| Area | Decision and signals |
|---|---|
| SLIs | Index freshness; query p99/fanout; stale-version rejects; authorization filter failures; rebuild lag. |
| Overload limits | Cap query terms, shard fanout, candidate set, indexing backlog, and per-tenant write volume. |
| Recovery | Replay versioned outbox changes; rebuild into a new generation and atomically switch after catch-up. |
| Access controls | Search returns candidates only; recheck current post permission before result/snippet; protect index credentials. |
| Dominant cost | Index storage/replicas, refresh work, and scatter-gather query compute. |
Senior-level interviewer follow-ups
Question: A post becomes private while a search result is being hydrated. Can its snippet still be returned?
Show answer and explanation
Answer: Authorization is checked against current visibility before exposing the result or snippet. Search indexes are candidate generators and can lag; stale documents must fail closed at the serving boundary.
Question: How do you prevent deleted text from reappearing after a reindex?
Show answer and explanation
Answer: Carry a durable deletion/version tombstone into the rebuild snapshot and replay changes after its watermark before swapping the index alias.
A 60-second design answer
I would index searchable text into versioned postings, but keep the post store and ACL as the source of truth. Search returns candidate IDs; current authorization and deletion versions are checked before snippets are exposed. A point-in-time cursor stabilizes pagination, and reindexing uses a watermark plus change replay before alias swap. I would measure index lag, ACL rejections, tombstone age, query latency, and rebuild catch-up.
Related concepts to revisit
Elasticsearch Change Data Capture
Technical references
Elasticsearch search pagination.
PostgreSQL transaction isolation and concurrent updates.
Distinguish matching terms from matching a phrase
Post p1 contains positions red:1,bird:2; p2 contains bird:1,red:3. Both appear in the intersection of the two term lists, but only p1 has the adjacent ordered phrase. Store positions or another appropriate phrase representation; an AND intersection cannot recover order it never stored.
red postings: p1@1,p2@3
bird postings: p1@2,p2@1
AND: p1,p2
phrase: p1Read the diagram
red postings: p1@1,p2@3; bird postings: p1@2,p2@1; AND: p1,p2; phrase: p1
Recency and changing like count require different ordering/update work. Batch count updates under a freshness contract; cached counts do not replace the authoritative like identity. Keep source revision and tombstone/ACL versions in projection writes so backfills and delayed updates cannot resurrect deleted/private content. Query complexity, tenant scope and result pagination are bounded. Rechecking current permissions before snippets avoids leaking content even when the index remains stale.
Show answer and explanation
Answer: A stale search result can be filtered out, but merely hiding its link while returning its private snippet still leaks content. Apply the policy before constructing the sensitive response.
Decision review: FB Post Search
FB Post Search: What it is
A post-search design retrieves and ranks bounded candidates while preventing stale indexed visibility from disclosing protected content.
FB Post Search: Why it is needed
Inverted-index membership, phrase matching, ranking and authorization are different decisions with different state boundaries.
FB Post Search: When to use it
Use a derived search index when text/relevance queries justify it, with explicit refresh and delete propagation policy.
FB Post Search: How to use it
Apply monotonic source revisions to the index, retrieve bounded candidates, evaluate the requested phrase/ranking behavior and enforce the declared current visibility before returning content or snippets.
FB Post Search: Compare an alternative
Exact lexical retrieval may satisfy a simpler contract than semantic ranking. A highly ranked stale result must still fail authorization under a strict visibility rule.
FB Post Search: Worked decision exercise
The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.
Post p7 becomes private/deleted at revision 7. A delayed public update for revision 6 arrives afterward. Applying it blindly resurrects an index document. A source-version/tombstone rule rejects the regression.
Read the diagram
p7 public revision 6 was indexed; Source revision 7 removes eligibility; Delayed revision 6 must not resurrect the document; Serving policy checks current visibility before snippets
Can a new reindex generation safely replace the old one after only copying a source snapshot?
Show answer and explanation
Answer: Not without covering changes after the snapshot, including deletes and permission changes. Define the change-stream boundary and catch-up protocol before switching. A serving authorization check remains necessary under the strict product policy.
FB Post Search: Check the design
Observe source-to-index lag, rejected stale updates, missing deletes and authorized-result yield. Test a delayed public update after a newer deletion.
Extension: Coherent snippets and current filtered-page progress
Start with source-versioned indexing, current authorization and PIT pagination. This workshop adds content-compatible disclosure, examined-prefix continuation and named complete rebuild validation.
Deep dive: permission to read a post does not validate its old search text
The baseline already protects tombstones, authorizes candidates before snippets and binds pagination to a point-in-time index. This workshop adds content-versus-permission identity, version-compatible snippets, forward progress over filtered hits and complete rebuild cuts. It is an original post-search exercise, not a description of Facebook's private search architecture. Keep semantic embeddings and ranking-model training outside the initial contract.
Bind the projection to source evidence, not engine counters
A post has immutable identity, an ordered source mutation version, content revision, current audience/lifecycle and their applicable policy evidence. Group membership, friendships, blocks or account status can change without rewriting every post's content revision. A stale audience hint in the index therefore cannot be the only current authorization check.
post(id PK, source_version, content_revision, body, audience_ref, lifecycle)
index_document(generation, post_id, source_version, content_revision, analyzer_version, terms)
source_floor(post_id, last_source_version, tombstone_state, payload_fingerprint)
query_session(id, viewer, query_hash, analyzer, index_generation, pit, expiry)
cursor(query_session, last_examined_sort_tuple, expiry)
rebuild(generation, snapshot_cut, required_partitions, complete_positions, validation_state)Index updates carry source version and canonical payload fingerprint. Greater versions advance the projection; compatible same-version retries leave it unchanged; conflicting same-version bodies or delete flags are quarantined rather than last-writer-wins. Delete/tombstone evidence prevents delayed public text from resurrecting a document even after a retry/backfill. Retire version floors only under a proven replay/restore barrier or a new controlled generation.
Elasticsearch sequence number/primary term protects an engine mutation against an intervening engine change; it is not automatically the source post's content or policy version. External source versioning and an application fingerprint enforce a different contract. Elasticsearch's concurrency documentation explains its conditional mutation tokens; keep their role separate from source ordering and retained deletion evidence.
Work a public edit that invalidates a stale match
The index contains post P at content revision 3: “red bicycle.” A query for that phrase retrieves P. The author changes the still-public post to content revision 4: “blue boat,” but indexing lags. Current authorization alone would allow P, yet returning the old red-bicycle snippet discloses text no longer current; returning blue-boat text as a red-bicycle result misrepresents the match.
Choose a conservative exercise rule: before emitting content/snippets, require both current authorization and equality of candidate indexed content revision with authoritative current content revision. Suppress a mismatched hit for this PIT. An index refresh does not mutate an already open PIT; refreshed candidates require a compatible fresh search session, unless a separately designed path re-evaluates the current body using the pinned analyzer/query semantics. Do not silently combine an old score/match with new unrelated text and call the result current. This rule trades temporary recall for a coherent source-backed response.
Now P becomes group-only while its body remains revision 4. A viewer loses group membership without another body edit. The same content revision and a retained PIT do not permit disclosure: the current viewer/audience relationship must pass. A missing permission dependency is unknown, not proof of access or an empty complete result. Fail closed on protected content and report a bounded retryable/partial state under the API policy.
Apply this boundary to snippets, highlights, title previews, cached results, exports, facets and diagnostics that could reveal protected content/counts. Cache internal candidate IDs where useful, but do not make a viewer-specific authorized snippet a public cache object. Keys alone are not authorization. Current-policy failure reasons should not expose another user's private audience or blocked status.
Read the diagram
Index matches old red bicycle text → Current public body is blue boat revision 4 → Current permission alone still passes → Content revision mismatch suppresses snippet → Fresh compatible PIT or explicit reevaluation is required
Advance the cursor over examined hits, including rejected ones
Bind the search session/cursor to authenticated viewer, normalized query/filters, matching mode, analyzer/ranking version, physical index generation/PIT, deterministic sort tuple and expiry. The signature protects token integrity, not permission to read every referenced post. A changed viewer/query or expired/retired PIT needs a fresh session or explicit reset. An alias switch does not make an old sort tuple portable to another ranking snapshot.
Suppose PIT order is P9, P10, P11, P12. Current policy rejects P9 and P10; P11 has a stale content revision. With a three-candidate examination budget, return an empty authorized page and an opaque cursor after P11, not a cursor before P9. The next request can examine P12. If the cursor advances only after returned hits, empty filtered pages can loop forever. Rejected hits still consume the bounded page budget.
For a page that returns some hits, advance through exactly the examined prefix, not unseen candidate entries. Keep score and unique post-ID tie order stable under the PIT; current filtering may legitimately change visible page length. A PIT preserves index search state, not current source text, membership or a complete immutable public-results transcript. Elasticsearch pagination documentation describes PIT/search-after mechanics; viewer/query binding and authorized examination progress remain application logic.
Bound oversampling, source reads, ACL checks, query complexity, shard fanout and total deadline. Return fewer results or an honest partial/retryable failure when budgets/dependencies are exhausted. Avoid disclosing unfiltered totals or per-rejection reasons. Variable page lengths/timing can still reveal information; final filtering alone is not a proof of full privacy noninterference. Stronger threat models require appropriately isolated candidate/aggregate computation and tested disclosure controls.
Rebuild only from a complete compatible boundary
A new index generation starts from a consistent source snapshot and its complete per-partition cut. Replay the compatible suffix with source versions and tombstones. If partition offset 101 is unresolved while 102 has arrived, the complete prefix remains 100. Do not activate merely because the largest seen position is 102 or document counts happen to match. A bulk write with partial failures needs per-item retry/disposition evidence before advancing its checkpoint.
Validate current required-partition progress, source/content/tombstone consistency, analyzer/schema compatibility and representative queries at a named cut. Copying only live rows without the required source floors can let a delayed deleted row return. Existing external version/delete mechanisms have provider retention limits; a physically empty index is not an eternal source-version ledger. Restore/replay beyond retained evidence must use a controlled rebuild rather than append unknown old updates to the active generation.
Publish the alias/head switch atomically under a stable operation identity after validation. A lost response returns the committed switch result. Existing PITs either remain on their retained compatible generation for a finite lifetime with current source authorization, or explicitly reset when retired. They cannot silently follow the new alias. A rollback creates a current controlled publication decision while preserving current source/permission checks; old indexed audience hints cannot regrant access.
Old PITs also pin segment/deletion state and consume real memory/disk retention. Bound concurrent sessions and lifetime globally and per viewer/tenant. Cleanup must respect retained readers while enforcing access independently; indefinite open PITs are not a free rollback strategy. Do not keep a broken generation serving protected text merely to avoid resetting a cursor.
Budget authorization and retained search state
At 10,000 queries/s and twenty shard requests/query, the cluster sees 200,000 shard searches/s. If the page contract examines at most 200 candidates, the worst-case current-source/permission work can approach two million candidate checks/s before batching/cache savings. An index that returns results in ten milliseconds can still miss the end-to-end latency target when this path is unavailable or overloaded.
At 5,000 new PIT sessions/s and 120 seconds mean retained lifetime, steady-state demand is about 600,000 contexts before admission limits. With an illustrative fifty KiB of context bookkeeping each, that alone is 30.72 GB, excluding pinned segments and runtime overhead. Enforce finite session budgets rather than assuming short tokens imply cheap server state. Expired contexts return reset-required under the same viewer/query rules.
A 600,000-change index backlog at 5,000/s processing with 3,000/s new writes needs at least 300 seconds to drain. Keep author writes available under their own durability contract while search reports freshness honestly; never bypass current permission or content-version checks to hide index lag. Monitor authorized-result yield, revision mismatch, complete-prefix gaps, tombstone horizon, per-item bulk failures, cursor progress and PIT retention pressure.
Canary a new analyzer/index on a compatible source cut, compare query/match behavior, validate required changes and then switch. Match freshness, current access and ranking relevance are separate outcomes. The fixtures exercise a tiny exact projection/query state machine; they are not Elasticsearch, an authorization service, a signed-cursor implementation or proof of production index/rebuild atomicity.
Search assessment: defend what actually matches and may be shown
Question: The old index matches “red bicycle,” but the currently public body is “blue boat.” Can authorization alone permit the old snippet?
Show answer and explanation
Answer: No under this exercise's coherent-content rule. Require indexed/current content revision equality before emission, or explicitly re-evaluate the current body under compatible query semantics. Permission does not validate stale text or make the new body match the old phrase.
Question: The first three candidates fail current policy/version checks and exhaust the examination budget. Where does the empty page's cursor point?
Show answer and explanation
Answer: After the last examined candidate, bound to the same authorized viewer/query/PIT. It cannot remain before the rejected hits or jump over unexamined ones. Current filtering may shorten pages; opaque progress is not a disclosure of hidden result identities/counts.
Question: Rebuild received 102 but has no accepted disposition for 101. Can matching document totals justify switching the alias?
Show answer and explanation
Answer: No. Complete required-partition progress, source/tombstone compatibility and named validation must pass. Preserve or explicitly retire old PITs rather than attach their sort tuples to the new alias. Current source/ACL checks remain enforced through switch and rollback.
Score one point each for source/content/permission/engine identity; coherent match/snippet disclosure under current access; scoped examined-prefix pagination and finite work; complete compatible rebuild/tombstone/PIT recovery; authorization/session/index budgets and honest failure states. Serving old text solely because current permission passes or advancing cutover across unresolved 101 is a critical failure. Repair the projection/serving boundary, then retest with same-version conflicting payloads, membership revocation between pages and a retired index behind an old cursor.
How can search remain available during eventual index cleanup without showing a newly private post?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.