Designing a Multi-Modal Document & Asset Vector Search System
System DesignModel answerLast updated
Architect an end-to-end vector storage and retrieval engine for processing user documents, images, and videos, supporting multi-modal search under low-latency constraints.
Design an asynchronous file-embedding ingestion and retrieval system for a multi-tenant cloud application. The platform handles user-uploaded assets including structured documents (PDFs, presentations, raw text), static images, and video files (up to 50 MB per file).
Key Expectations
- Ingestion & Processing Pipeline: Define how multi-modal assets are ingested, decoded, chunked, and parsed.
- Model Strategy: Select and justify embedding model architectures for cross-modal (text-to-image/video) and high-density text search. Explain how space spaces are unified or compared.
- Storage & Vector Indexing: Detail the storage schema, database isolation, vector indexing strategies (e.g., HNSW vs. IVF-PQ), and scalar quantization trade-offs for scaling to billions of vectors.
- Retrieval & Reranking: Detail the search workflow, including tenant isolation, hybrid text search (BM25 + Dense Vector), segment aggregation, and reranking.
- Operational Concerns: Explain zero-downtime model migration strategies, idempotency, and throughput optimization.
Hints
Hint 1
Calculate vector volume: a single 5-minute video at 1 frame/2s produces 150 image vectors plus transcript chunks, making video processing the primary vector volume driver.
Hint 2
Cross-modal standard models (like CLIP) have strict context limits (e.g., 77 tokens), whereas text-dense documents require long-context text encoders. Consider how to query across disjoint vector spaces.
Hint 3
Avoid post-query tenant filtering; standard HNSW traversals degrade severely if pre-filtering selectivity drops below ~10% unless single-tenant partitioning or metadata-aware graph routing is implemented.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale Assumptions
Functional Requirements
- Ingestion: Asynchronous uploading and processing of documents (PDF, DOCX, TXT), images (JPEG, PNG), and videos (MP4, up to 50 MB).
- Retrieval Operations:
- Text-to-Asset: Natural language query returning relevant pages, image regions, or video moments.
- Asset-to-Asset Similarity: Finding similar files or sub-regions based on a seed file.
- Cross-Modal Search: Single query matching text, visual keyframes, and speech transcripts.
- Deletion & Mutability: Hard deletion of files must invalidate associated vector indices within SLA limits.
Non-Functional Requirements & Constraints
- Ingestion SLA: Embedded and searchable within 60 seconds for documents/images; under 5 minutes for videos.
- Query Latency: $p_{99} < 200\text{ ms}$ end-to-end.
- Security & Isolation: Strict multi-tenant data boundaries. Zero data leakage across tenant identifiers (
owner_id). - Zero-Downtime Migrations: Embeddings must support seamless schema and model versioning transitions.
Capacity Estimation
- Daily Ingestion: $2\times 10^6$ files/day ($\approx 23 \text{ files/sec}$ average, $70 \text{ files/sec}$ peak).
- Workload Breakdown: 60% Documents, 35% Images, 5% Videos.
- Vector Generation Rates:
- Document: Average 20 chunks/file $\rightarrow 1.2\times 10^6\text{ docs/day} \times 20 = 24\times 10^6\text{ vectors/day}$.
- Image: 1 global vector + 1 OCR/crop vector average $\rightarrow 7\times 10^5\text{ images/day} \times 2 = 1.4\times 10^6\text{ vectors/day}$.
- Video: 5-min average clip $\rightarrow 1$ keyframe per 2s ($150\text{ vectors}$) + 10 transcript chunks $\rightarrow 10^5\text{ videos/day} \times 160 = 16\times 10^6\text{ vectors/day}$.
- Total Vector Generation: $\approx 41.4\times 10^6\text{ vectors/day}$ ($\approx 15\times 10^9\text{ vectors/year}$).
Storage Footprint (768-dimensional float32 vector = 3,072 bytes)
- Raw Floating Point (Uncompressed): $41.4\text{M} \times 3.072\text{ KB} \approx 127\text{ GB/day} \rightarrow \approx 46.3\text{ TB/year}$.
- Int8 Scalar Quantization (SQ8): 768 bytes/vector $\rightarrow \approx 31.8\text{ GB/day} \rightarrow \approx 11.6\text{ TB/year}$.
- Product Quantization (PQ96): 96 bytes/vector $\rightarrow \approx 3.97\text{ GB/day} \rightarrow \approx 1.45\text{ TB/year}$.
2. High-Level Architecture & API Design
System Architecture
[Client]
│
├── 1. Presigned Upload Request ──► [API Gateway] ──► [Metadata DB]
├── 2. Binary Upload Direct ──────► [S3 Storage Bucket]
│ │
│ (Object Created)
▼ ▼
[API Gateway] ◄── Status Poll ───── [Kafka Ingestion Event Bus]
│
┌──────────────────────────────────────┼──────────────────────────────────────┐
▼ ▼ ▼
[Doc Worker Cluster] [Image Worker Cluster] [Video Worker Cluster]
(PyMuPDF / OCR) (PIL / EXIF / OCR) (FFmpeg / Whisper ASR)
│ │ │
└──────────────────────────────────────┼──────────────────────────────────────┘
▼
[Inference Queue (NATS/Kafka)]
│
▼
[GPU Model Inference Cluster]
(Triton Server: ViT & BGE-m3)
│
▼
[Vector Store Writer]
(Milvus / Vespa Cluster)
API Contracts
1. Initiate Upload
POST /v1/files/upload-url
// Request
{
"filename": "q3_financial_deck.pdf",
"mime_type": "application/pdf",
"size_bytes": 14205000
}
// Response
{
"file_id": "file_8f9a2b1c",
"upload_url": "https://s3.us-west-2.amazonaws.com/ingestion-bucket/file_8f9a2b1c?X-Amz-Signature=...",
"expires_in_seconds": 900
}
2. Multi-Modal Search API
POST /v1/search
// Request
{
"query": {
"text": "Q3 revenue projections by product line",
"image_file_id": null
},
"modalities": ["text", "image", "video_frame"],
"filters": {
"owner_id": "usr_9981",
"mime_types": ["application/pdf", "video/mp4"],
"created_after": "2024-01-01T00:00:00Z"
},
"limit": 10
}
// Response
{
"results": [
{
"file_id": "file_8f9a2b1c",
"score": 0.894,
"modality": "text",
"locator": { "type": "pdf_page", "page": 14 },
"snippet": "Q3 product line revenue reached $14.2M, reflecting a 12% growth..."
},
{
"file_id": "file_1a2b3c4d",
"score": 0.841,
"modality": "video_frame",
"locator": { "type": "video_timestamp", "start_ms": 142000, "end_ms": 144000 },
"thumbnail_url": "https://cdn.platform.com/thumbnails/file_1a2b3c4d_142.jpg"
}
]
}
3. Data Storage Schema
Relational Metadata Store (PostgreSQL / CockroachDB - Partitioned by tenant_id)
CREATE TABLE files (
file_id UUID PRIMARY KEY,
tenant_id UUID NOT NULL,
owner_id UUID NOT NULL,
content_hash VARCHAR(64) NOT NULL, -- SHA-256 for idempotency
mime_type VARCHAR(64) NOT NULL,
size_bytes BIGINT NOT NULL,
s3_uri VARCHAR(512) NOT NULL,
status VARCHAR(32) NOT NULL, -- PENDING, PROCESSING, INDEXED, FAILED
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
) PARTITION BY HASH (tenant_id);
CREATE INDEX idx_files_tenant_owner ON files(tenant_id, owner_id);
CREATE INDEX idx_files_hash ON files(tenant_id, content_hash);
CREATE TABLE segments (
segment_id UUID PRIMARY KEY,
file_id UUID NOT NULL REFERENCES files(file_id) ON DELETE CASCADE,
tenant_id UUID NOT NULL,
segment_type VARCHAR(32) NOT NULL, -- 'TEXT_CHUNK', 'IMAGE_CANVAS', 'VIDEO_KEYFRAME', 'TRANSCRIPT'
locator JSONB NOT NULL, -- e.g., {"page": 3}, {"t_start": 12.5, "t_end": 14.5}
raw_text_content TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_segments_file_id ON segments(file_id);
Vector Store Topology (e.g., Milvus / Vespa Architecture)
Collections are grouped logically by embedding space and model version:
collection_dense_text_v1: Handles document chunks and transcript segments using standard text models.collection_multimodal_v1: Handles images, video keyframes, and cross-modal text vectors (CLIP/SigLIP space).
Field Schema per Document in Vector DB:
- vector_id (UUID, Primary Key)
- segment_id (UUID, External Key)
- file_id (UUID)
- tenant_id (INT64, Partition Key)
- owner_id (STRING, Indexed Scalar Tag)
- model_version (STRING)
- vector_data (FLOAT32[768] or INT8[768])
4. Deep Dives: Processing, Models & Storage
A. Preprocessing Pipeline by Modality
-
Documents (PDF, DOCX):
- Structural Extraction: Parse documents into structural hierarchies (Headers, Paragraphs, Tables) using layout-aware parsers.
- Dynamic Sliding Window Chunking: Token-length sliding window ($512$ tokens, $64$-token overlap). Avoid splitting mid-sentence or breaking raw Markdown/HTML tables.
- OCR Fallback: If page text extraction yields $< 50$ printable characters, route the page rasterized image to an OCR engine (Tesseract/PaddleOCR).
-
Images:
- Pre-filtering: Strip EXIF metadata, decode image into normalized dimensions ($384 \times 384$).
- Text Extraction: Run localized OCR bounding-box detection to extract overlay text (memes, infographics, text slides).
-
Videos:
- Frame Extraction: Run scene-change detection (
ffmpeg select='gt(scene,0.3)'). Fall back to constant sampling rate of 1 frame every 2 seconds if no scene change occurs. - Frame Deduplication: Pass frames through a Perceptual Hash (pHash) filter. Skip embedding frames with a Hamming distance $< 4$ relative to the previously indexed keyframe.
- Audio Pipeline: Extract raw audio track $\rightarrow$ Convert to 16kHz mono WAV $\rightarrow$ Run Whisper Model $\rightarrow$ Emit timestamped transcript segments $\rightarrow$ Process transcripts via the Document Chunking Pipeline.
- Frame Extraction: Run scene-change detection (
[Video File]
│
┌─────┴────────────────────────┐
▼ ▼
[FFmpeg Decoupler] [Audio Extractor]
│ │
▼ ▼
[Scene & pHash Filter] [Whisper ASR Model]
│ │
▼ ▼
(Visual Keyframes) (Timestamped Text)
B. Model Selection Strategy & Multi-Space Search
Using a single multi-modal model for all tasks creates a performance bottleneck. Image-text encoders (e.g., CLIP, SigLIP) have short context windows (often capped at 77 tokens) and lack fine-grained syntax handling for long-form document retrieval.
+---------------------------------------------------------------------------------+
| QUERY SYSTEM |
+---------------------------------------------------------------------------------+
│
┌───────────────────────┴───────────────────────┐
▼ ▼
[Multimodal Vector Space] [Text Vector Space]
(SigLIP / ViT-B/16 - 768 dim) (BGE-M3 / E5-large - 1024 dim)
- Visual Keyframes - Document Chunks
- Raw Images - Video Speech Transcripts
- Short Cross-Modal Queries - Long Text Search Queries
Dual Vector Space Configuration
- Multimodal Space (SigLIP / ViT-B-16, 768 dimensions):
- Encoders: Visual Encoder for images/frames; Text Encoder for cross-modal queries (e.g., "blue sportscar").
- Dense Text Space (BGE-M3 or E5-Large-v2, 1024 dimensions):
- Encoders: High-capacity transformer encoding document chunks and Whisper transcripts.
- Query Fusion Workflow:
- When a text query arrives, send it simultaneously to both the Multimodal Text Encoder and the Dense Text Encoder.
- Search
collection_multimodal_v1andcollection_dense_text_v1in parallel. - Normalize scores (e.g., Min-Max or Z-Score) across result sets, then merge them using Reciprocal Rank Fusion (RRF): $$RRF_Score(d \in D) = \sum_{m \in M} \frac{1}{k + r_m(d)}$$ where $k = 60$, $M$ is the set of search spaces, and $r_m(d)$ is the rank of segment $d$ in space $m$.
C. Ingestion Throughput & GPU Infrastructure Optimization
To manage dynamic batching and maximize GPU throughput (e.g., NVIDIA A10G / L4):
- Decouple CPU & GPU Operations: CPU workers handle FFmpeg decoding, OCR, and chunking, placing structural JSON payloads onto an Inference Request Queue.
- Triton Inference Server Deployment:
- Dynamic Batching: Enable dynamic batching with
max_queue_delay_microseconds: 20000($20\text{ ms}$) andmax_batch_size: 64. - Mixed Precision: Run vision and text models using FP16 / TensorRT executions to double throughput per GPU core.
- Dynamic Batching: Enable dynamic batching with
D. Vector Indexing, Tenant Isolation & Scalar Quantization
Multi-Tenant Query Isolation
- Anti-Pattern: Post-filtering (retrieving top $N$ globally, then dropping vectors where
owner_id != query_owner). If a single tenant owns $0.1%$ of the global dataset, post-filtering top 100 vectors returns zero matches almost every time. - Solution: Use physical or logical index partitioning:
- Partition Key: Partition vector index clusters by
tenant_idhash. - In-Node Metadata Filtering: Use indices like HNSW that support bitset pre-filtering during graph traversal, ensuring only candidate nodes matching
tenant_idandowner_idare visited.
- Partition Key: Partition vector index clusters by
Quantization Strategy (Memory vs. Latency)
- Tier 1 (Hot/Recent Data - Last 30 Days): HNSW (Hierarchical Navigable Small World) with Int8 Scalar Quantization (SQ8). High recall ($>98%$), low latency ($<15\text{ ms}$).
- Tier 2 (Cold/Archival Data): IVF-PQ (Inverted File with Product Quantization, e.g.,
IVF1024,PQ96). Reduces memory overhead by $80-90%$, maintaining target recall ($>90%$) for older vectors.
E. Idempotency, Updates & Zero-Downtime Model Migrations
Idempotent Pipeline Design
- Compute
content_hash = SHA256(file_bytes)prior to embedding generation. - Check database for
(tenant_id, content_hash). If a match exists withINDEXEDstatus, link the existing vector segments to the new file entry without re-running parsing or model inference.
Model Upgrade & Re-Indexing Protocol
Step 1: Deploy Dual-Write Pipeline
----------------------------------
Inference Pipeline ──► Vector Index V1 (Active Reader)
└──► Vector Index V2 (Warming Up)
Step 2: Asynchronous Re-Indexing (Backfill)
-------------------------------------------
Raw Files (S3) ──► Re-Index Worker ──► Triton (Model V2) ──► Vector Index V2
Step 3: Atomic Read Switchover & Deprecation
-------------------------------------------
API Gateway ──► Vector Index V2 (Active Reader)
Vector Index V1 (Marked for Deletion)
- Dual Ingestion: Deploy Model $V_2$. Incoming files generate embeddings for both $V_1$ and $V_2$ indexes, writing to distinct collections (
collection_v1,collection_v2). - Background Re-Indexing: Read raw extracted text chunks and image artifacts from S3/Metadata DB, running them through Model $V_2$ background queues at low priority.
- Atomic Cutover: Once the backfill reaches $100%$ parity, update the application configuration to point read queries to
collection_v2. - Cleanup: Drop
collection_v1to reclaim storage space.
5. Summary of System Trade-Offs
| System Area | Selected Approach | Trade-Off / Consequence | Alternative Considered |
|---|---|---|---|
| Embedding Architecture | Dual-Model Space (SigLIP + BGE-M3) fused via RRF | Higher index complexity; requires multi-index execution and RRF score normalization. | Unified Single Model (CLIP only): Lower text search quality on long documents. |
| Vector Indexing | Tiered HNSW-SQ8 (Hot) + IVF-PQ (Cold) | Additional operational complexity for index lifecycle management. | Pure Uncompressed HNSW: Prohibitively high memory requirements and costs. |
| Tenant Filtering | Bitset Pre-Filtered Graph Traversal | Slight increase in graph search latency per query. | Post-filtering: Causes severe vector recall drops in multi-tenant environments. |