System Design Problem

Design a Vector Database (Semantic Search Infrastructure)

Commonly Asked By:PineconeMilvusWeaviateQdrantZilliz

Interview Setup

Interview Prompt

Design a managed vector database (Pinecone/Milvus style) for 10B vectors, 100K tenant namespaces, 50K peak ingest QPS, 20K query QPS. Support HNSW approximate nearest neighbor search, metadata filtering, hybrid dense+sparse search, and multi tenant isolation.

Clarifying Questions (ask before designing)

QuestionWhy it matters
Is this a standalone product or the retrieval layer for a RAG platform?The Document QA Platform (RAG) is the application layer that chunks, embeds, retrieves, and prompts the LLM. This is the infrastructure layer: a managed vector database that RAG platforms, Recommendation Systems, and other services consume via API.
What vector dimensions and distance metrics?1536 dimensions with cosine similarity is an illustrative embedding configuration. The dimension and metric lock at namespace creation, preventing incompatible vectors from entering the same index.
Exact or approximate nearest neighbor?Exact brute force search is O(n), which is intractable at 10B vectors. ANN via HNSW can trade some recall for large latency and throughput gains. The stated 1-2% recall trade and 1000x speedup are scenario assumptions rather than universal guarantees. Recall@10 should be measured against exact search on a representative evaluation sample rather than a production 10B vector brute force query. Interviewers frequently probe ef and M parameter tuning.
How is multi-tenancy enforced?Namespaces isolate tenant data. Pre filtering by namespace_id on every query prevents cross tenant leaks. Large tenants may get dedicated shards.

Scope

In scope

  • Vector upsert API (single and batch)
  • HNSW based approximate nearest neighbor query
  • Metadata pre filtering on queries
  • Hybrid search (dense ANN + sparse BM25)
  • Multi tenant namespace isolation
  • Horizontal sharding and replication
  • Async ingest pipeline for high throughput writes

Out of scope (state explicitly)

  • Embedding model training or inference (upstream service)
  • LLM generation (handled by Document QA Platform orchestration layer)
  • Full text search engine such as Elasticsearch used for the sparse leg of hybrid search
  • Reranking models (downstream in Document QA Platform)

Functional Requirements

Start by asking your interviewer whether you are designing the application layer such as a Document QA Platform (RAG) or the vector infrastructure beneath it. Clarify ANN vs hybrid search, namespace isolation, and recall@K targets before discussing HNSW tuning.

  • Vector upsert: Insert or update dense vectors (and optional sparse vectors) with metadata, keyed by unique ID within a namespace
  • Approximate nearest neighbor query: Given a query vector, return Top K most similar vectors using HNSW index
  • Metadata filtering: Pre-filter vectors by metadata fields (tenant, category, document_id) before ANN search
  • Hybrid search: Combine dense vector similarity with sparse keyword matching (BM25) via score fusion
  • Namespace management: Create/delete isolated namespaces with per tenant index configuration (dimension, metric, replica count)
  • Vector delete: Remove vectors by ID or metadata filter (e.g., delete all chunks for document_id)
  • Batch operations: Bulk upsert and delete for high throughput ingestion pipelines

Non-Functional Requirements

Your interviewer will stress test p99 query latency under 50ms and recall@10 above 98%. They will also probe pre filtering vs post filtering, because post filtering after ANN can return zero results for valid queries when the global top K belongs to another tenant.

  • Low query latency: p99 < 50ms for ANN search (excluding client network)
  • High ingest throughput: 50K vectors/sec peak via async pipeline
  • Multi tenant isolation: Namespace level data separation with zero cross tenant leakage
  • Scalability: 10B vectors horizontally sharded across 100+ nodes
  • High recall: ANN recall@10 > 98% compared to exact search on a representative evaluation sample
  • Durability: Vectors are persisted to disk with replication and are recoverable from the WAL on node failure
  • Eventual consistency: Upserted vectors searchable within 5 seconds (p99)

Capacity Estimations

HNSW indexes live in RAM, so shard count and vectors per shard drive the largest memory cost. Average vectors per namespace hide tenant skew, so p99 namespace size and hot tenant traffic matter for placement. Ingest QPS determines whether synchronous upsert is viable or whether a Kafka async pipeline is required.

MetricCalculationValue
Total vectors indexedGiven10B
Vector dimensionsGiven (text-embedding-3-large)1536
Namespaces (tenants)Given100K
Avg vectors per namespace10B ÷ 100K100K
Ingest QPS (peak)Given50K vectors/sec
Query QPS (peak)Given20K queries/sec
Raw dense vector storage10B x 1536 x 4B61.44 TB
HNSW index RAM per primary shard100M vectors x 1536 x 4B x 1.5 memory multiplier~921.6 GB/shard
HNSW RAM across 100 primary shards100 x ~921.6 GB~92.16 TB (excluding metadata)
Three-copy HNSW resident memory~92.16 TB x 3~276.48 TB (before metadata)
Ingest throughput50K x 1536 x 4B~300 MB/sec raw vectors
Query latency targetGiven (p99)< 50ms (ANN only)

100 primary shards x ~100M vectors each. At 1536 dimensions with float32 values, raw vectors are ~614.4 GB per primary shard. Applying the stated 1.5x memory multiplier gives ~921.6 GB of index RAM per primary shard before metadata, or ~92.16 TB across 100 primary shards. With 1 leader and 2 read replicas, the vector and index memory footprint is roughly ~276.48 TB before metadata. These figures are scenario assumptions for capacity planning because actual HNSW memory depends on graph parameters such as M, vector encoding, metadata structures, and implementation overhead. Query: 20K QPS ÷ 100 shards = 200 QPS/shard only under an even routing assumption for single shard tenant queries, so capacity planning should also use p99 tenant size, hot namespace skew, and multi shard query fan out. The ~1K QPS/shard HNSW capacity is an illustrative benchmark assumption that must be validated on the chosen hardware and index configuration. Ingest: 50K upserts/sec via Kafka with a scalable Index Builder worker pool batching over 100ms windows.

Architecture Diagram

Walk your interviewer through scope first: this is infrastructure, not the application layer. The Document QA Platform (RAG) and Recommendation System are consumers that invoke upsert and query APIs, while this system owns storage, HNSW indexing, and filtered ANN search.

Writes and reads have different shapes. Ingest at 50K vectors/sec flows through an async Kafka pipeline into per shard HNSW segments. Queries at 20K QPS hit a shard router that applies metadata pre filters before graph traversal. Embedding generation and LLM orchestration stay upstream.

Multi tenancy is namespace scoped. Every upsert and query carries a namespace_id. Large enterprise tenants may get dedicated shards, while small tenants share pools with per namespace quotas to prevent noisy neighbors.

Loading...

In the room

Clarify immediately: "I am designing vector database infrastructure rather than the RAG pipeline." If the interviewer mentions SKUs or acronyms, pivot to hybrid search because dense ANN alone will miss exact keyword matches.

Component Deep Dives

1. HNSW Index ⭐

HNSW is a widely used billion scale ANN approach based on multi layer graphs and greedy walks. Have the tuning knobs and the post filtering failure mode ready because they are common interview probes.

Loading...

HNSW (Hierarchical Navigable Small World) is a widely used ANN algorithm in vector search systems. It builds a multi layer graph where upper layers enable coarse navigation and Layer 0 provides fine grained nearest neighbor search, delivering low latency on appropriately sized shards when benchmarked and tuned for the workload.

2. Filtered ANN (Pre filtering)

Pre filtering restricts HNSW traversal to authorized vectors, which is critical for access control enforcement in the Document QA Platform (RAG) and category scoped queries.

Loading...

Metadata fields are indexed in an inverted index. The authorization layer validates the namespace independently, while the query planner evaluates metadata filters before ANN traversal and uses the resulting set as the relevance candidate boundary. For highly selective filters, direct candidate enumeration may be more efficient than graph traversal. For broader filters, the planner can use the pre filtered HNSW path.

3. Hybrid Search Pipeline

Hybrid search runs dense and sparse recall in parallel and fuses candidates with Reciprocal Rank Fusion, which is essential when queries contain part numbers, SKUs, or legal citations.

Hybrid Search Pipeline (used by RAG Platform and Recommendation System):

Stage 1: Parallel recall:
  Dense ANN (HNSW):     query_vector → Top-100 candidates    ~15ms
  Sparse BM25:          query_text  → Top-100 candidates    ~20ms

Stage 2: Fusion:
  Reciprocal Rank Fusion (RRF):
    score(d) = Σ 1/(k + rank_i(d))   where k=60, rank_i from each retriever
  Output: Top-50 unified candidates                              ~2ms

Stage 3: Optional rerank downstream in the RAG Platform:
  Cross-encoder: 50 → Top-10                                    ~150ms

When to use hybrid vs dense only:
  - SKU, serial number, legal citation: hybrid is typically preferred
  - Semantic Q&A, recommendation similarity: dense may be sufficient
  - Recommendation System candidate generation: dense ANN on item embeddings

Latency note:
  The ~15ms, ~20ms, ~2ms, and ~150ms figures are illustrative stage budgets, not universal guarantees.

4. Async Ingest Pipeline

High throughput writes cannot be synchronous, so Kafka buffering and batch index updates mirror the write pattern found in Live Likes Reactions.

High throughput writes (50K vectors/sec) enqueue to Kafka before being batch applied to HNSW segments by Index Builder workers. Stable vector IDs and idempotency keys make client retries safe, while per vector versions prevent stale updates from overwriting newer state. Large backfills return 202 Accepted with a job ID for status polling.

Ingest flow:
  1. POST /vectors/upsert → validate dimension, namespace quota
  2. Publish to Kafka: vector-upsert (partition by namespace_id)
  3. Index Builder consumer: batch 100ms window → apply to HNSW segment
  4. Flush segment to disk → replicate to followers
  5. Update metadata index (inverted index for filters)
  6. Vector searchable within ~5s (eventual consistency)

5. Delete, Compaction, and Index Lifecycle

Deletes and frequent updates create tombstones and stale graph entries, so the index needs background segment compaction and periodic rebuilds. Durable WAL records preserve ordering during recovery, while immutable segment snapshots provide faster restore points.

  • Write tombstones with a monotonically increasing vector version.
  • Exclude tombstoned vectors from ANN and metadata candidate sets immediately after the index version becomes visible.
  • Compact segments when tombstone density or fragmentation crosses a configured threshold.
  • Build replacement segments in the background, validate recall@10, then atomically switch the shard manifest.
  • Retain tombstone metadata until all replicas and replay paths are beyond the delete version.

6. Multi-Tenant Namespace Isolation

API keys map to namespaces and namespaces map to shards, ensuring tenant isolation is enforced at every layer of the architecture.

Multi-Tenant Namespace Model:

  API Key → namespace_id (1:1 or 1:many for enterprise)
  namespace_id → shard assignment via a consistent hash ring with virtual nodes
  large namespace → optional multi shard placement by vector_id hash
  namespace_id → index config (dimension, metric, read replica count)

  Namespace quotas:
    - max_vectors: 10M (default soft limit with alerts at 80%, though enterprise tiers may raise it)
    - max_qps: 1000 queries/sec
    - max_upsert_qps: 500 vectors/sec

  Physical isolation tiers:
    Tier 1 (shared): Small tenants share shards (cost-efficient)
    Tier 2 (dedicated shard): Large tenants get their own shard
    Tier 3 (dedicated cluster): Enterprise SLA, isolated hardware

  Large-namespace routing:
    Namespace placement remains the authorization boundary.
    Vector-level sharding is used only when a namespace exceeds one shard's capacity.

  Live Likes Reactions uses a similar high write Kafka buffer pattern, and embedding math in Vector Embeddings and ANN Search uses a similar Kafka batch to index pattern.

7. Shard Router and Replication

Consistent hashing on namespace IDs routes normal tenants, while large namespaces can use explicit multi shard placement and high volume enterprise tenants can bypass shared pools through dedicated assignments.

  • Consistent hash ring: shard_id = ring.lookup(hash(namespace_id))
  • A placement directory stores dedicated shard overrides and multi shard ranges for namespaces that outgrow one shard.
  • For a multi shard namespace, the query router fans the request out to all assigned shards, applies the same metadata and version visibility constraints, then performs a k way Top K merge before returning the final results.
  • Each shard contains 1 leader for writes and 2 read replicas as the stated scenario topology. The query router selects replicas according to consistency, indexed version, and proximity requirements.
  • Multi shard namespaces require parallel fan out to their assigned shard replicas, followed by a global Top K merge. The shard placement directory is the routing source for those assignments.
  • Large tenants exceeding 10M vectors are an illustrative policy threshold for dedicated placement. Actual promotion should use vector count, QPS, memory, and noisy neighbor measurements.
  • Write ahead logs per shard support crash recovery, paired with periodic HNSW segment snapshots to cloud object storage.

API Design

Upsert Vectors

Every vector API call is namespace scoped, so upsert and query operations require namespace_id in the path. Dimension and metric are locked at namespace creation, allowing the system to reject incompatible vectors before they can corrupt the index.

HTTP
POST /v1/namespaces/{namespace_id}/vectors/upsert
Authorization: Bearer <api_key>
Idempotency-Key: <request_id>
Content-Type: application/json

{
  "vectors": [
    {
      "id": "chunk_abc123",
      "values": [0.014, -0.052, ...],     // 1536-dim dense vector
      "sparse_values": {                   // optional, for hybrid search
        "indices": [41, 992, 104],
        "values": [0.8, 0.4, 0.2]
      },
      "metadata": {
        "document_id": "doc_8899",
        "category": "legal",
        "text": "Employees are entitled to 20 days..."
      }
    }
  ]
}

Response: 200 OK (sync, small batch) or 202 Accepted (async, large batch)
{
  "status": "completed",
  "upserted_count": 1,
  "namespace_id": "org_123",
  "index_version": 3
}

For 202 Accepted, return:
{
  "status": "accepted",
  "job_id": "upsert_job_5678",
  "namespace_id": "org_123"
}

Query (Filtered ANN)

Queries default to eventual index visibility. A caller that needs read your writes can provide a minimum indexed version and request version bound consistency, while tenant authorization remains mandatory regardless of consistency mode. If the requested version is not yet available, the service waits within a bounded timeout or returns an explicit visibility timeout rather than silently returning stale data.

HTTP
POST /v1/namespaces/{namespace_id}/query
Authorization: Bearer <api_key>

{
  "vector": [0.021, -0.048, ...],
  "top_k": 10,
  "consistency": "version_bound",
  "min_indexed_version": 3,
  "filter": {
    "category": {"$eq": "legal"},
    "document_id": {"$in": ["doc_8899", "doc_9900"]}
  },
  "include_metadata": true,
  "include_values": false
}

Response: 200 OK
{
  "matches": [
    {
      "id": "chunk_abc123",
      "score": 0.923,
      "metadata": {"document_id": "doc_8899", "text": "Employees are entitled..."}
    }
  ],
  "namespace_id": "org_123",
  "index_version": 3
}

Hybrid Query

HTTP
POST /v1/namespaces/{namespace_id}/query/hybrid
Authorization: Bearer <api_key>
Content-Type: application/json

{
  "vector": [0.021, -0.048, ...],
  "sparse_vector": {"indices": [41, 992], "values": [0.8, 0.4]},
  "query_text": "PTO rollover policy",          // for BM25 leg
  "top_k": 10,
  "filter": {"category": {"$eq": "HR"}},
  "fusion": "rrf",                               // dense + sparse via RRF
  "rrf_k": 60
}

Weighted fusion is a separate mode. In that mode, alpha may be used after
normalizing dense and sparse scores to compatible scales.

Delete Vectors by Filter

HTTP
POST /v1/namespaces/{namespace_id}/vectors/delete
{
  "filter": {"document_id": {"$eq": "doc_8899"}}
}

Response: 202 Accepted
{"status": "accepted", "job_id": "del_job_5678"}

Namespace Management

Namespace creation locks the vector dimension and distance metric, while deletion is asynchronous so large indexes can be removed without blocking the control plane.

HTTP
POST /v1/namespaces
Authorization: Bearer <api_key>
Content-Type: application/json

{
  "namespace_id": "org_123",
  "dimension": 1536,
  "metric": "cosine",
  "read_replica_count": 2
}

Response: 201 Created
{
  "namespace_id": "org_123",
  "status": "ready"
}

DELETE /v1/namespaces/org_123
Authorization: Bearer <api_key>

Response: 202 Accepted
{
  "status": "accepted",
  "job_id": "namespace_delete_5678"
}

Common Error Responses

400 Bad Request: invalid input, missing required fields, or malformed JSON payload
401 Unauthorized: missing or invalid authentication token or API key
403 Forbidden: authenticated caller lacks required permissions for this resource
404 Not Found: requested resource ID does not exist
409 Conflict: duplicate write or version conflict, retry with a unique idempotency key
422 Unprocessable Entity: syntactically valid request failed semantic business validation
429 Too Many Requests: rate limit quota exceeded, client should honor Retry-After header
500 Internal Error: unexpected server failure, retry safely with an idempotency key
503 Service Unavailable: downstream dependency is unavailable or overloaded, retry with exponential backoff

Data Model

Vector Record (per shard)

JSON
// Vector record and tombstone state stored per shard

{
  "id": "chunk_abc123",
  "namespace_id": "org_123",           // tenant isolation key
  "vector": [0.014, -0.052, ...],      // 1536-dim float32
  "sparse_vector": {                    // optional BM25 sparse representation
    "indices": [41, 992, 104],
    "values": [0.8, 0.4, 0.2]
  },
  "metadata": {
    "document_id": "doc_8899",
    "category": "legal",
    "created_at": "2026-03-15T10:00:00Z"
  },
  "version": 3,                         // monotonic per vector
  "state": "ACTIVE",                    // ACTIVE or TOMBSTONED
  "indexed_at": "2026-03-15T10:00:05Z"
}

Tombstones retain delete ordering in durable metadata until all replicas and replay sources
have advanced beyond the tombstone version.

Namespace Configuration

SQL
CREATE TABLE namespaces (
    namespace_id    VARCHAR(64) PRIMARY KEY,
    dimension       INT NOT NULL,              -- locked at creation (e.g., 1536)
    metric          VARCHAR(16) DEFAULT 'cosine',  -- cosine, dotproduct, euclidean
    primary_shard_id INT NOT NULL,             -- default placement for single shard namespaces
    max_vectors     BIGINT DEFAULT 10000000,
    max_qps         INT DEFAULT 1000,
    read_replica_count INT DEFAULT 2,
    created_at      TIMESTAMP NOT NULL
);

CREATE TABLE api_keys (
    api_key_hash    VARCHAR(128) PRIMARY KEY,
    created_at      TIMESTAMP NOT NULL
);

CREATE TABLE namespace_api_keys (
    api_key_hash    VARCHAR(128) NOT NULL,
    namespace_id    VARCHAR(64) NOT NULL,
    created_at      TIMESTAMP NOT NULL,
    PRIMARY KEY (api_key_hash, namespace_id)
);
SQL
CREATE TABLE namespace_placements (
    namespace_id      VARCHAR(64) NOT NULL,
    shard_id          INT NOT NULL,
    hash_start        BIGINT NOT NULL,
    hash_end          BIGINT NOT NULL,
    placement_version BIGINT NOT NULL,
    PRIMARY KEY (namespace_id, shard_id, hash_start)
);

The namespace remains the authorization boundary. Single shard namespaces use the primary placement, while multi shard namespaces use placement ranges to route vector IDs to assigned shards and then merge local Top K results.

Metadata Inverted Index (per shard)

Field index for pre filtering:
  category:legal     → [chunk_001, chunk_042, chunk_998, ...]
  document_id:doc_8899 → [chunk_001, chunk_002, ..., chunk_020]
  namespace_id:org_123 → [all vectors in namespace]

Query: filter(category=legal) AND filter(document_id IN [...])
  → intersect posting lists → candidate set → HNSW search within candidates

Kafka Topics

Topic: vector-upsert
  Partitions: 64 (partition by namespace_id for normal tenants, with adaptive vector-id salting for hot namespaces)
  Producers: Ingest Coordinator
  Consumers: Index Builder worker pool
  Ordering: Per vector_id version order is enforced during apply
  Note: Kafka partitions provide ingestion parallelism. Physical storage shard count is independent.
  Note: Cross-topic ordering is not assumed. The durable per-vector version is authoritative.

Topic: vector-delete
  Partitions: 32
  Consumers: Index Builder (apply tombstone and remove from HNSW + metadata index)
  Ordering: Delete versions must not be older than the latest vector version

Topic: index-segment-snapshot
  Producers: Index Builder (periodic HNSW segment flush)
  Consumers: S3 archival, cross region replication

Fault Tolerance

ConcernSolution
Hot namespace overloads single shardMonitor per shard QPS and tenant skew. Split large namespaces across multiple shard partitions, preserve per vector ordering with version checks, and rate-limit ingest per tenant.
Index stale after vector upsertUse versioned asynchronous ingest via Kafka. Query responses expose index visibility metadata, while a version bound read your writes option waits until a requested minimum version is indexed.
Filtered ANN returns zero resultsEnforce namespace authorization before ANN traversal and use metadata pre filtering. Never relax tenant or security filters. For non-security filters, a controlled fallback may widen the search and report the fallback to the caller.
HNSW index corruption on node crashReplicate index segments to 3 nodes. Maintain a WAL for ordered upserts and tombstones, rebuild the index from WAL on recovery, and periodically snapshot segments to S3.
Embedding dimension mismatchNamespace level index configuration locks dimensions at creation time, rejecting upserts with incorrect dimensions using 400 Bad Request.
Cross tenant data leakEnforce mandatory namespace_id on every upsert and query. The shard router validates API key to namespace mappings before routing, with integration tests for tenant isolation.
Delete followed by stale upsert resurrects a vectorUse monotonic per vector versions and durable tombstones. Reject any stale upsert or delete whose version is older than the latest recorded version.
Read replica serves stale data after a successful writeReturn an index version or visibility token and allow queries to request a minimum indexed version. Route version bound reads to a replica confirmed to have reached that version, or wait within a bounded timeout and return an explicit visibility timeout.

Additional Considerations

Relationship to Document QA Platform (RAG)

The Document QA Platform (RAG) is the application layer that performs document parsing, chunking, embedding generation, reranking, LLM prompt construction, and citation. The vector database is the retrieval infrastructure called through upsert and query APIs. The RAG application decides chunk sizing, overlap boundaries, and access control metadata. The vector database stores embeddings and executes filtered ANN search.

Relationship to Recommendation System

A Recommendation System uses the same ANN infrastructure for candidate generation, querying an item index with user embeddings to retrieve top candidates in approximately 30ms under the stated workload assumption. The vector database serves as shared infrastructure, while different use cases configure isolated namespaces with domain specific metadata schemas.

Relationship to Core Concepts and High-Write Ingestion

The Vector Embeddings and ANN Search concept details HNSW graph mathematics, IVF clustering, and hybrid retrieval formulas. For ingest throughput, the Kafka batch buffering pattern parallels Live Likes Reactions, where high-velocity incoming writes are buffered asynchronously and aggregated before durable persistence.

Index Rebuild and Migration

Changing HNSW parameters (such as M and efConstruction) or embedding dimensions requires a full index rebuild. The migration strategy involves creating a new index version, dual-writing upserts to both old and new indexes, backfilling from the WAL, validating recall@10 on sample queries, cutting over the query router, and finally decommissioning the old index.

Interview Walkthrough

  • 25-minute cut

    Skip arch50/arch75 depth unless staff.

    • Clarify: infrastructure vs application layer (5 min)
    • HNSW for ANN graph indexing (6 min)
    • Pre filtering for multi tenant isolation (5 min)
    • Hybrid search: dense ANN plus sparse BM25 via RRF (5 min)
    • Ingest at 50K/sec: Kafka async pipeline with batching (4 min)
  • Clarify scope: this is infrastructure (Pinecone or Milvus style) rather than the RAG application or recommendation service.
  • Explain HNSW for ANN, detailing graph layers, greedy nearest neighbor walking, and runtime tuning knobs like efSearch.
  • Detail pre filtering rather than post filtering for multi tenant isolation and metadata constraints.
  • Walk through hybrid search combining dense ANN and sparse BM25 merged with Reciprocal Rank Fusion for keyword heavy queries.
  • Explain the 50K per second ingest pipeline with Kafka async buffering and batch index updates.
  • Describe sharding using consistent hashing on namespace ID, along with dedicated shards for large enterprise tenants.
  • Cross-link the Document QA Platform for RAG retrieval, Recommendation Systems for candidate generation, and Live Likes Reactions for high throughput write buffering.
  • Highlight common pitfalls like attempting brute force exact search at 10B scale, or post filtering that returns zero results for valid queries.

Engineering Trade-offs

HNSW vs IVF vs Flat (Exact) Index

Flat brute force search guarantees 100% recall with O(n) complexity, which is impossible at 10B vectors. Inverted File Index (IVF) clusters vectors and searches nearest centroids, offering faster builds and lower memory usage but reduced recall at scale. HNSW (⭐) often provides a strong recall and latency trade-off for high dimensional vectors despite a higher memory footprint (~1.5x raw vector size in this scenario). The best choice still depends on workload, update rate, hardware, and recall targets.

Pre filtering vs Post filtering

Post filtering is simpler to implement but can return too few or zero results when the initial ANN candidate set is dominated by vectors that fail the metadata filter, which is common when filters are selective. Pre filtering (⭐) restricts the search space before graph traversal. When the authorization filter is enforced before retrieval, the returned candidate set remains inside the authorized tenant boundary. Performance still depends on filter selectivity and the index implementation. Always enforce pre filtering for multi tenant access control and tenant isolation.

Sync vs Async Ingest

Synchronous upserts can provide immediate searchability but may cap throughput around the stated 1K vectors/sec per shard benchmark assumption because graph insertion is expensive. Asynchronous ingest (⭐) returns HTTP 202 Accepted and makes vectors searchable within 5 seconds, enabling 50K vectors/sec via Kafka batching. In this design, async ingest is preferred for bulk operations, while sync ingest is reserved for small interactive updates under 100 vectors.

Shared Shards vs Dedicated Shards

Shared shards are cost-efficient for smaller tenants with under the stated 1M vector policy threshold, but carry noisy neighbor risks when a hot tenant monopolizes shard compute. Dedicated shards improve isolation and can make enterprise SLAs easier to meet, with the stated 3x cost presented as an illustrative assumption. A tiered strategy (⭐) provides shared tenancy by default and can promote tenants to dedicated shards when vector count exceeds the illustrative 10M threshold or query traffic surpasses allocated quotas.

Cosine Similarity vs Dot Product vs Euclidean

Cosine similarity (⭐) measures the angle between vectors and is invariant to magnitude, making it a common choice for normalized text embeddings. Dot product is equivalent to cosine for normalized vectors and can be slightly faster by omitting explicit normalization at query time. Euclidean distance (L2) measures absolute distance and can be appropriate when vector magnitude is meaningful. The distance metric is locked at namespace creation and cannot be mixed within an index.

💬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...