Skip to content

Advanced Concepts · Concept lesson

Search Indexing: Freshness, Relevance, and Safe Deletion

Build search as a derived, eventually consistent view with explicit freshness, relevance, privacy, and deletion safeguards.

Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.

Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.

What you will be able to explain

  • Explain how source writes become searchable documents and why lag exists.
  • Design relevance evaluation, reindexing, and failure-safe indexing pipelines.
  • Prevent stale authorization data or deleted private content from leaking in search.

Search is a derived view, not the source of truth

A search index is optimized for finding and ranking documents, not for owning the authoritative transaction. A write to the source database is usually followed by an event or change-log record, a transformation, and one or more index updates. Each hop can be delayed or fail, so freshness is a measurable property rather than an assumption. If the index is lost, the system should be able to rebuild it from an authorized source of truth and a documented mapping. Treat each indexed document as a materialized projection with a version, source identifier, schema version, and update timestamp. Queries can use the index to discover candidates, but sensitive access decisions should be checked against current authorization state or a strongly controlled access projection. Search relevance and permission correctness are separate dimensions; a result with an attractive score is still a serious defect if the user cannot read it.

The common inverted index stores terms and references to documents, often alongside analyzed fields, filters, and ranking signals. Text analysis can split words, normalize case, remove stop words, or apply language-specific stemming. Those choices change what users can find and can create surprising matches. A document update may require deleting old term postings and adding new ones; immutable segments and background merges make indexing throughput and query cost interact. A refresh can improve visibility latency but may increase resource consumption. Therefore 'write accepted' and 'searchable now' are different API contracts. State the expected delay and expose indexing status for workflows where users need confirmation. Do not promise strict read-after-write behavior unless the selected engine and query path actually provide it.

Move changes through a versioned indexing pipeline

A robust pipeline captures changes without a loss gap, commonly using a transactional outbox or a database change stream with documented retention. The consumer transforms source records into a search document and applies an idempotent upsert keyed by stable document ID. Source version numbers prevent an old, delayed event from overwriting a newer document. Partition by a stable entity key if per-entity ordering matters, and track consumer lag plus the age of the oldest unapplied change. The pipeline should distinguish source deletion from temporary transformation failure. If source rows are physically removed before a delete event is captured, the index may retain a ghost forever; a tombstone or durable deletion log prevents that gap.

Mapping changes need a safe migration strategy. Build a new index with the new schema, backfill from a consistent snapshot or versioned source, then replay changes newer than the snapshot watermark. Validate document counts, sampled fields, deletion markers, and representative queries before switching an alias or routing layer. Keep the old index available for rollback until the new mapping has proven itself, while avoiding two writers that can race. Backfill rate must be limited so it does not overwhelm the source database or production queries. Record mapping version with the index and make the build repeatable. A full rebuild should not depend on undocumented manual clicks or a one-time export stored outside normal retention controls.

Freshness and access checks in a private document search

Suppose a private document is updated at 10:00:00. The outbox relay polls every 2 seconds, a consumer waits behind up to 3 seconds of work, and the index refresh interval is 1 second. A rough upper bound for ordinary visibility might be 2 + 3 + 1 = 6 seconds, excluding failures and queueing. This is a planning estimate, not a guarantee: a rising backlog can make the real lag minutes. A useful SLI is the fraction of successful source updates reflected in search within 10 seconds, with a denominator of eligible updates rather than all HTTP requests. Track event age at query visibility using sampled version probes or synthetic updates; average consumer throughput alone cannot prove freshness.

For access control, index a tenant or access-scope field to filter candidate results, but do not treat a stale ACL field as the sole security boundary when revocation must be immediate. A safer query path can filter by current tenant, then revalidate candidate document IDs and permissions against an authoritative policy service before returning titles or snippets. If that check is unavailable, fail closed for private results or return a clearly bounded degraded response. Even snippets, counts, autocomplete suggestions, and facets can reveal a private document. A deletion request should create a tombstone, remove the document from live indices, invalidate caches, suppress it from replicas and suggestion dictionaries, and account for snapshots and backups under the documented retention policy. Search deletion is a distributed workflow, not just one `DELETE` call.

Source changes become searchable only after several bounded stages
1. Authoritative database

Commits source row and change intent.

2. Outbox / change log

Durable ordered or versioned update stream, including tombstones.

3. Document transformer

Applies versioned mapping and removes sensitive fields.

4. Search index

Derived inverted/vector representation with refresh behavior.

5. Search API

Filters tenant scope and revalidates sensitive permissions.

6. Authorization source

Current policy check for private candidates.

  1. Authoritative database → Outbox / change log: commit durable change
  2. Outbox / change log → Document transformer: at-least-once change
  3. Document transformer → Search index: versioned upsert / delete
  4. Search API → Search index: candidate retrieval
  5. Search API → Authorization source: current access recheck
  6. Authorization source → Search API: allow only authorized results

Choose a search system for query shape and ownership

A relational database can serve simple prefix or full-text search at modest scale, especially when transactional freshness and operational simplicity matter. It may become expensive when relevance ranking, fuzzy matching, language analyzers, or broad aggregations compete with transactional workloads. A dedicated search engine offers specialized inverted indexes and ranking controls, but adds a derived data store, mapping migrations, capacity planning, and access-control complexity. A hosted search service can reduce cluster operations but may constrain analyzers, query behavior, region placement, and data-processing terms. A vector index supports semantic similarity but does not automatically provide exact filters, fresh permissions, or high-quality lexical matching. Many products need hybrid retrieval: lexical constraints for exact identifiers and semantic retrieval for paraphrases.

Evaluate using representative queries and a labeled set of relevant results, not a vendor's demonstration. Precision asks how many returned items are relevant; recall asks how many relevant items were found. At rank k, measure user-visible quality such as NDCG or reciprocal rank, segmented by language and query class. Query latency must include authorization rechecks and network hops. Index size depends on source text, analyzed fields, stored fields, replicas, and merge overhead; do not assume compressed source size equals index size. The smallest system that meets measured query and freshness needs is often the most reliable. Keep a database query path available for administrative recovery when suitable, but do not use it as an unbounded fallback that overloads the source of truth.

Detect stale, partial, and unauthorized results

An indexing consumer can be healthy while silently dropping a new field after a schema mismatch. Count transformed, indexed, rejected, retried, and deleted documents by mapping version. Alert on the oldest event age and on a divergence between source and index for sampled IDs. Dead-letter records should contain enough identifiers and error context to repair, but not copied secrets or full private bodies unless access and retention are explicitly controlled. Reprocessing must preserve source version ordering. If the index is unavailable, decide whether to return no results, a stale cached answer with a visible freshness bound, or a constrained source query; never quietly broaden authorization or query every source row.

Deletion and permission revocation deserve their own failure drills. Simulate a delete during an index outage, then restore service and prove the tombstone is replayed before search reopens. Test an ACL revocation while an old result is cached, including autocomplete and snippets. If search has replicas or regional copies, verify deletion fan-out and define what a backup restore does with previously deleted documents. A denylist can temporarily block a deleted ID while asynchronous physical cleanup completes, but the denylist itself needs durable replication and bounded lookup cost. Treat a lagging permission projection as a security incident when the threat model requires immediate revocation. A search result cache key must include the security scope or avoid caching private results across users.

When to avoid a dedicated index or a search-first design

Do not deploy a search cluster because the product contains a text box. If exact lookups by primary key or a small filtered list meet the need, a transactional query is easier to keep current and secure. A dedicated index is a poor fit when no one owns mapping evolution, relevance evaluation, and deletion propagation. Search is also not a reliable system of record for inventory counts, financial balance, or other values that must be current at the instant of action. It can identify a candidate item, but the final operation must validate authoritative state. Avoid indexing all fields by default: every searchable field expands storage, reindex work, and potential exposure. Minimize document content and retain a way to rebuild only what is needed.

Do not use semantic search to bypass clear permission or exact-match requirements. Similarity scores are not confidence guarantees, and embedding models can preserve sensitive information in ways that need separate review. For private multi-tenant data, shard or filter boundaries should be selected with defense in depth, not merely as a performance trick. Strongly isolate tenants if a filter omission would expose data. A dedicated index may be unsuitable when data residency, deletion guarantees, or provider processing terms do not meet requirements. Document the index's freshness promise, recovery source, and deletion lifecycle before launch.

Senior questions for indexing and retrieval

Ask what is authoritative and how a lost index is reconstructed. What event or log guarantees every committed change is observed, how are duplicates and stale versions handled, and what is the freshness SLI denominator? How does an index mapping change move through build, validation, cutover, rollback, and cleanup? Who owns relevance evaluation and what labeled queries represent actual language, spelling, and filter patterns? If embeddings or external analyzers are involved, where does the data go, what is retained, and what does deletion mean for derived artifacts?

Then trace the privacy boundary end to end: source ACL, index fields, query filter, result title, snippet, autocomplete, cache, replicas, backups, analytics, and operator tooling. Can permission revocation hide an item before the index catches up? If not, is that delay acceptable and explicitly risk-approved? How are tombstones retained through a prolonged outage and replayed before traffic returns? What happens when a restore resurrects old documents? Check peak backfill impact, replica storage, refresh cost, and capacity headroom. A strong answer gives a test for both stale search and unauthorized search, plus a controlled way to rebuild or delete without exposing data.

Terms in plain language

Inverted index
A structure mapping terms to the documents containing them, enabling efficient text lookup.
Refresh
A search-engine operation that makes recently indexed changes visible to queries, often with a latency and resource cost.
Tombstone
A durable deletion marker that downstream consumers can observe even after the source row is gone.

Preparing practice controls…

Check your understanding

These checks explain concepts. They do not measure architecture seniority or update readiness.

1. Why is a search index a derived view rather than a reliable source of truth?
2. A private document was deleted while the index was offline. What protects against it reappearing after recovery?

Design independently

Design search for private team documents. A user can revoke access or delete a document, while the search index may be unavailable for an hour. Explain indexing, query-time safeguards, deletion propagation, freshness measurement, and recovery.

Hints, not a solution
  • Do not make the search index authoritative for permissions.
  • Include snippets, suggestions, caches, replicas, and backups in the deletion boundary.
  • Define how long a tombstone survives an index outage.

0 / 20,000 characters · Not saved

Your learning notes

Sign in to save

Marking a lesson read and reviewing an exercise are separate actions. Neither implies mastery. Saved work is account-owned; saves are explicit and do not queue offline.

References and boundaries

Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.

Elasticsearch Guide: Near real-time search

Primary Elasticsearch documentation on refresh and why indexed changes are not immediately query-visible.

Elasticsearch Guide: Document APIs

Primary API documentation for indexing, updating, and deleting documents; application-level privacy and propagation remain the operator's responsibility.

Back to curriculum