DEV Community

sawyerflynn1578
sawyerflynn1578

Posted on

Node.js Retrieval Architecture: Metadata Pre- vs Post-Filters (Choose Pre-Filtering at 10M)

TL;DR

Choose metadata pre-filtering for a multi-tenant customer-support knowledge base once the corpus approaches 10 million chunks, because tenant, entitlement, locale, product, and validity constraints should reduce both the candidate set and the amount of duplicated index state before semantic ranking begins. Post-filtering is defensible for a small, low-cardinality corpus whose filters change faster than its embeddings; it is not a safe default for access control, and it becomes expensive when the eligible slice is thin.

The bill is mostly a retention problem disguised as a query problem. Every chunk kept in the searchable index carries a vector, filterable metadata, text or a pointer to text, and often a replica; every superseded policy page kept "just in case" continues to occupy that footprint. A sound design therefore starts with bytes retained per live chunk and the number of live copies, then asks which retrieval plan can avoid indexing records that no current support answer is allowed to cite.

What actually determines metadata-filter cost in a customer-support knowledge base?

Use a unit model before comparing engines. Let N be live chunks, V the vector bytes per chunk, M the filterable metadata bytes, T the retained text or pointer bytes, R the replication factor, and O the engine's index overhead. The approximate retained footprint is N x (V + M + T) x R x O. The equation is intentionally plain: an uncertain overhead factor can be measured on a representative shard, while the other terms come from the ingestion manifest. I'm not sure any generic overhead estimate transfers cleanly between index implementations; a loaded shard and its build artifact resolve that uncertainty.

At 10 million chunks, even a small per-record field deserves scrutiny, yet removing metadata blindly is a false economy. tenant_id, entitlement, locale, product, valid_from, valid_to, and a stable document_version are often the fields that prevent an otherwise similar answer from crossing a contractual boundary. The useful distinction is not metadata versus no metadata. It is query-critical, low-entropy metadata versus descriptive material that belongs in the document store and can be fetched only after ranking.

Consider a B2B SaaS support corpus with 2,000 tenants, five locales, four entitlement tiers, and frequent revisions to billing and permission articles. Those are scenario dimensions for capacity planning, not benchmark results. If all combinations become separate embedded chunks, cardinality expands before a single user asks a question. If one canonical chunk carries compact eligibility fields, pre-filtering can select the permitted slice without reproducing identical prose for every tenant-tier-locale tuple. The dominant change is deduplication: retain one semantic unit where the text is truly identical, and represent applicability as metadata.

Keep the ledger.

An ingestion ledger should record the source digest, parser version, chunker version, embedding model identifier, metadata-policy version, and activation state for every chunk. The index is a derived projection, never the system of record. This matters when an entitlement mapping changes: the pipeline can calculate the affected projection, write a new generation idempotently, validate counts, and atomically activate it instead of mutating records with no audit trail. Exactly-once delivery is rarely available across the whole pipeline, but exactly-once effects are achievable when the chunk key is deterministic and each stage rejects a repeated key with different content.

Pre-filtering and post-filtering are not equivalent

Pre-filtering applies eligible metadata constraints before approximate semantic search. Post-filtering asks the vector index for semantic candidates first and discards ineligible results afterward. The second plan looks simpler, and for a dense eligible population it can be; the catch is that a query requesting the top 20 results may return fewer than 20 after filtering, so the system either accepts weak recall or repeatedly expands the candidate pool.

The distinction is sharpest for access boundaries. A post-filter must never be treated as the authorization check because retrieval traces, caches, or downstream rerankers may observe candidates before that filter runs. Authorization belongs at a trusted boundary before retrieval, with the index filter acting as defense in depth. A denied scope should produce a deliberate 403, be recorded without sensitive document content, and never degrade into a broader query.

Decision condition Prefer pre-filtering Prefer post-filtering
Eligible slice Small or highly variable by tenant Most documents qualify
Constraint purpose Entitlement, tenancy, validity Presentation preference
Metadata churn Controlled through versioned ingestion Changes far more often than embeddings
Recall behavior Engine can search within the filtered population Candidate pool can be safely over-fetched
Audit need Query predicate must be reconstructable Filter is non-security-sensitive

Pre-filtering still has a boundary. It is not suitable when the engine cannot preserve acceptable recall inside very small filtered partitions, or when a high-churn, non-security attribute would force constant index updates. In that case, keep authorization and stable tenancy constraints before retrieval, then apply the volatile preference after ranking. This is a hybrid plan, not an excuse to move access control downstream.

Post-filtering is also reasonable during an early prototype with a few thousand uniformly eligible chunks, provided the team measures eligible-result recall and has no sensitive candidates in the shared search scope. Once tenant-specific eligibility becomes sparse, stick with pre-filtering for stable constraints. The choice can change by field; it doesn't need to change by platform.

How should a customer-support knowledge base preserve metadata filters in retrieval?

Node.js may coordinate uploads and queue work, while the following Go component illustrates the contract at the index boundary; all persistent effects use a deterministic key. The key binds the tenant, source document, source revision, chunk ordinal, parser version, and metadata-policy version. A retry either reproduces the same record or fails closed if the payload differs. There is no "best effort" overwrite because that would destroy the evidence needed for reconciliation.

package ingest

import (
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    \"errors\"\n    \"sort\"\n    \"strconv\"\n    \"strings\"
)

type Chunk struct {
    TenantID     string   `json:"tenant_id"`
    DocumentID   string   `json:"document_id"`
    Revision     string   `json:"revision"`
    Ordinal      int      `json:"ordinal"`
    Locale       string   `json:"locale"`
    Entitlements []string `json:"entitlements"`
    ValidFrom    string   `json:"valid_from"`
    ValidTo      string   `json:"valid_to"`
    Text         string   `json:"text"`
}

type Index interface {
    PutIfAbsent(ctx context.Context, key string, body []byte) error
}

func Store(ctx context.Context, idx Index, c Chunk, parserVersion, policyVersion string) (string, error) {
    if c.TenantID == "" || c.DocumentID == "" || strings.TrimSpace(c.Text) == "" {
        return "", errors.New("missing required ingestion field")
    }
    sort.Strings(c.Entitlements)
    identity := strings.Join([]string{
        c.TenantID, c.DocumentID, c.Revision,
        strconv.Itoa(c.Ordinal), parserVersion, policyVersion,
    }, "\x1f")
    digest := sha256.Sum256([]byte(identity))
    key := hex.EncodeToString(digest[:])

    body, err := json.Marshal(c)
    if err != nil {
        return "", err
    }
    return key, idx.PutIfAbsent(ctx, key, body)
}
Enter fullscreen mode Exit fullscreen mode

The interface deliberately says PutIfAbsent, not Upsert. An implementation should compare a stored content digest on duplicate keys and emit an immutable conflict event if the bytes differ. The worker can retry timeouts because the logical write remains idempotent. A reconciliation job then compares four counts by generation: source documents discovered, chunks declared in the manifest, chunks acknowledged by the index, and chunks visible under the active filter policy. Count equality isn't proof of semantic correctness, but count inequality is actionable evidence of an incomplete projection.

Canonicalization must be fixed before backfills begin; otherwise a harmless serialization change creates a second population of logical duplicates. Tests should cover retries, out-of-order revisions, empty entitlement sets, expiration boundaries, Unicode normalization, and a policy-version rollback. Deployment should use generation-based activation: build generation g+1, query it with a fixed evaluation set, compare its manifest and access decisions to g, then move the read alias. Never delete g in the activation transaction. A short rollback window buys operational safety without turning every historical vector into permanent inventory.

How should teams measure filtered recall before choosing an index layout?

A retrieval evaluation set needs more than question-answer pairs. Each case should include the caller's tenant, locale, entitlements, evaluation time, expected source documents, and explicitly forbidden documents. Run the exact predicate used in production, record the candidate count before reranking, and separate three failures: no eligible source was indexed, an eligible source was missed by approximate search, or an ineligible source crossed the boundary. The third is a correctness incident even when the final generated sentence happens to be harmless.

Compare pre-filter and post-filter plans with the same embedding, chunk set, top-k target, and reranker. For post-filtering, increase the initial candidate count along a declared sequence and plot eligible recall against candidates examined. For pre-filtering, vary filtered population size and partition skew. There is no universal winner hidden in a single latency percentile; the relevant curve joins eligible recall, bytes retained, candidates scored, and policy-update work.

Observability must preserve enough state to replay a decision without copying support content into logs. Record a query id, caller-policy digest, normalized filter predicate, active index generation, embedding model identifier, candidate counts at each stage, cited chunk keys, and outcome code. Don't log raw tickets by default. Support conversations can contain personal or regulated data, and an audit trail that creates a second uncontrolled corpus defeats its purpose. Compliance requirements vary by contract and jurisdiction, so retention periods and access to traces need review by the responsible legal and security teams rather than an engineering guess.

The most revealing alert is often a ratio: eligible results returned divided by requested k, grouped by tenant and filter-policy version. A sudden drop after a metadata deployment points toward projection or predicate drift; stable latency alone would miss it. Pair that signal with reconciliation lag and the count of forbidden candidates, which should remain zero at every observable stage after authorization.

Retain evidence, not every obsolete vector

After a new generation passes reconciliation and its rollback window closes, delete superseded vectors and duplicated embedded text. Retain the source revision, content digest, chunking manifest, policy version, activation record, and deletion certificate according to the applicable retention schedule. This is the change that moves index cost: old semantic projections stop consuming replicated index capacity, while compact evidence remains available to explain what was processed. The cost is slower forensic replay. If an old vector is gone, reproducing a historical retrieval may require the archived source, the exact parser and chunker, and access to the recorded embedding model version; if any of those are unavailable, byte-for-byte reconstruction may be impossible. Keeping every vector avoids that particular risk but expands the searchable data surface and the recurring index footprint. For most support systems, a bounded rollback generation plus durable manifests is the cleaner compromise, subject to contractual preservation duties. The decision rule is concise: pre-filter stable security and applicability fields, post-filter only volatile non-security preferences, deduplicate identical text, and treat each index generation as a reconcilable projection. Stop keeping obsolete vectors after the approved rollback window. Keep the evidence that proves why they existed and when they were removed.

Evidence stays.

References

Top comments (0)