Design a Multimodal Video Search Engine
Machine LearningModel answerLast updated
Design a scalable text-to-video and video-to-video retrieval architecture handling billions of clips, detailing modeling choices, vector indexing, serving pipelines, and evaluation strategy.
Design an end-to-end multimodal search system capable of supporting both text-to-video and video-to-video queries across a collection of hundreds of millions of long-form videos (totaling billions of distinct video clips).
Requirements & Scope
-
Functional Capabilities
- Text Querying: Natural language searches (e.g., "fast-moving sports car turning a corner on a rainy night").
- Video Querying: Finding visually or semantically similar clips, including near-duplicate detection and style-matching given a query video clip or uploaded file.
- Clip-Level Granularity: Queries must return precise time segments (start and end timestamps) within videos, not just video-level metadata.
-
System Scale & Constraints
- Corpus: 500 million long videos, yielding ~5 billion clips after temporal segmentation (~6-second average clip duration).
- Ingestion: Up to 1 million new uploaded videos per day. Target end-to-end processing freshness of <15 minutes.
- Query Traffic: 5,000 queries per second (QPS) at peak.
- Latency Budget: End-to-end $p_{99}$ latency $\le 300\text{ ms}$ (Vector retrieval budget $\le 80\text{ ms}$).
- Operations: Instant compliance with copyright/takedown requests and real-time metadata filtering (date ranges, video quality, safety tags, licensing).
Instructions
Walk through the complete architectural design for this system:
- System Scale & Resource Estimation: Provide a concrete memory and storage budget for embeddings, indexes, and raw media assets.
- Model Architecture & Training: Define the dual-encoder layout (video and text towers), frame-level temporal aggregation mechanisms, embedding dimension, loss functions (e.g., InfoNCE, hard-negative mining strategies), and fine-tuning approaches. Explain how long videos are segmented and aggregated.
- Serving & Infrastructure Pipeline: Describe offline batch processing vs. online streaming ingestion, metadata enrichment (ASR, OCR, optical flow, VLM captioning), and real-time query handling.
- Vector Indexing & Retrieval: Architect a multi-tiered vector search scheme (e.g., main index vs. fresh index), trade-offs between algorithm choices (HNSW vs. IVF-PQ), memory footprint optimization, and strategy for metadata filtering and instant deletion propagation.
- Evaluation, Reranking & Feedback: Detail offline/online evaluation metrics, second-stage reranking (cross-encoder vs. dual-encoder), online A/B testing, and click/relevance feedback integration.
Hints
Hint 1
Break the system down into two fundamental sub-problems: learning a unified embedding representation space across modalities, and executing low-latency high-throughput vector search at multi-billion scale.
Hint 2
Consider memory constraints: 5 billion raw high-dimensional floating-point vectors cannot fit cost-effectively into uncompressed in-memory indexes (like pure HNSW). Contrast inverted file indexes with product quantization (IVF-PQ) against graph-based approaches.
Hint 3
For long videos, avoid encoding the entire video into a single vector, as local actions will be lost. Segment videos at natural shot boundaries, represent each segment as an individual embedding, and aggregate clip matches at request time.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Capacity Planning
Scale Assumptions & Targets
- Total Videos ($V$): 500 million videos. Average length = 3 minutes.
- Segmentation: Shot-boundary detection segments each video into ~10 clips of 4–8 seconds (average 6s). Total searchable corpus = 5 billion clips ($N = 5 \times 10^9$).
- Query Latency ($p_{99}$): $\le 300\text{ ms}$ total. Search engine allocation:
- Text/Video Query Encoding: $15\text{ ms}$
- ANN Retrieval (Vector Engine): $60\text{ ms}$
- Candidate Merging & Filtering: $15\text{ ms}$
- Reranking (Cross-Encoder): $50\text{ ms}$
- Result Hydration & Response Formatting: $30\text{ ms}$
- Headroom/Network overhead: $130\text{ ms}$
- Throughput: Peak $5,000\text{ QPS}$.
+----------------------------------------------------+
| End-to-End Budget: <= 300ms |
+----------+--------+---------+----------+-----------+
| Enc (15) | ANN(60)| Merge(15| Rerank(50| Hydr (30)|
+----------+--------+---------+----------+-----------+
Back-of-the-Envelope Estimation
Vector Memory Storage
- Vector Dimension ($D$): 512 dimensions in
float16($1,024\text{ bytes}$ per vector). - Uncompressed Raw Embeddings: $$5 \times 10^9 \times 1,024\text{ bytes} = 5.12\text{ TB}$$
- Compressed Index Footprint (IVF-PQ64):
Compressing 512 dimensions to 64 bytes using Product Quantization (PQ64), plus 8 bytes for
clip_id: $$5 \times 10^9 \times 72\text{ bytes} \approx 360\text{ GB}$$ 360 GB easily fits across a cluster of 12–16 nodes with 32 GB RAM per node.
Ingestion & Bandwidth Requirements
- Daily Ingestion: $1 \times 10^6$ videos/day $\approx 11.6$ new videos/sec $\approx 116$ clips/sec.
- Peak Processing: Accounting for traffic bursts ($3\times$ multiplier), target ingestion capacity is ~350 clips/sec.
- Re-embedding Cost: Re-indexing all 5 billion vectors with an optimized GPU pipeline running at 100 clips/sec/GPU requires ~13,800 GPU-hours (or ~29 hours on a 480-GPU cluster).
2. Model Architecture & Shared Representation
To handle both text-to-video and video-to-video search, the model projects text tokens and video frame/audio sequences into a shared $D=512$ L2-normalized embedding space.
[ Text Query ] [ Video Query / Ingested Clip ]
│ │
▼ ▼
+---------------+ +---------------+
| Text Tower | | Video Tower |
| Transformer | | ViT + Temp-TF |
+---------------+ +---------------+
│ │
▼ ▼
( 512-d Vector ) ◄── Cosine Similarity Metric ──► ( 512-d Vector )
Video Encoder (Video Tower)
- Frame Sampling: Extract 8–16 uniformly spaced frames per 6-second clip.
- Spatial Feature Extraction: Pass sampled frames through a Vision Transformer (ViT-B/16) backbone initialized from image-text contrastive models (e.g., CLIP).
- Temporal Aggregation: Pass spatial frame tokens through a multi-layer Temporal Transformer with learned temporal positional embeddings, followed by attention pooling across frames.
- Alternative trade-off: Mean pooling across frame embeddings reduces compute by ~30%, but fails to capture directional motion (e.g., distinguishing "person opening a door" vs. "person closing a door").
- Multimodal Fusion (Optional late-stage): Combine video frame representations with Audio Spectrogram Transformer (AST) features and parsed ASR (Automatic Speech Recognition) text representations via a gated cross-attention block.
Text Encoder (Text Tower)
- Multilingual Transformer (e.g., mBERT or RoBERTa-based architecture).
- The
[CLS]token output is passed through a dense linear layer to project it down to 512 dimensions, followed by L2 normalization: $$\hat{\mathbf{z}}{\text{text}} = \frac{W_t \cdot \mathbf{h}{\text{CLS}}}{|W_t \cdot \mathbf{h}_{\text{CLS}}|_2}$$
Distance Metric & Scoring
Relevance score between text query vector $\mathbf{q}$ and video clip embedding $\mathbf{v}_i$: $$S(\mathbf{q}, \mathbf{v}_i) = \mathbf{q} \cdot \mathbf{v}_i = \cos(\mathbf{q}, \mathbf{v}_i)$$
Video-to-video retrieval follows the exact same formulation, passing the query video through the Video Tower to generate $\mathbf{q}_{\text{video}}$, ensuring mathematical symmetry.
3. Training & Fine-Tuning Strategy
[ Anchor Video Clip ] [ Positive Pair ]
│ │
├───────────┬───────────┘
│
▼
+-----------------------+
| Symmetric InfoNCE Loss | ◄── Hard Negative Queue
+-----------------------+
Pretraining Objective: Symmetric Contrastive Loss (InfoNCE)
Given a batch of $B$ matching (Video, Text) pairs $(\mathbf{v}_i, \mathbf{t}_i)$, the loss combines video-to-text and text-to-video cross-entropy over softmax-normalized similarities:
$$\mathcal{L}{\text{V}\to\text{T}} = -\frac{1}{B} \sum{i=1}^{B} \log \frac{\exp(\mathbf{v}_i \cdot \mathbf{t}i / \tau)}{\sum{j=1}^{B} \exp(\mathbf{v}_i \cdot \mathbf{t}_j / \tau)}$$
$$\mathcal{L}{\text{total}} = \frac{1}{2} \left( \mathcal{L}{\text{V}\to\text{T}} + \mathcal{L}_{\text{T}\to\text{V}} \right)$$
where $\tau$ is a learnable temperature parameter.
Self-Supervised Video-to-Video Loss
To improve performance on video-to-video similarity and robustness against spatial cropping, transcoding, or framerate shifts, add a video-video contrastive loss branch:
- Two overlapping segments or augmented renditions (e.g., color jitter, crop, scale) from the same shot form positive pairs $(\mathbf{v}_i, \mathbf{v}_i')$.
Negative Sampling & Mining
- Large In-Batch Negatives: Distributed training across 64 GPUs with cross-GPU gradient aggregation yields effective batch sizes $B = 32,768$, providing strong negative coverage.
- Hard Negative Mining:
- Periodically sample the top-100 nearest non-matching neighbors for training samples using the existing index.
- False Negative Filtering: Mined negatives with high visual similarity (e.g., cosine similarity > 0.85) or transcript BLEU/ROUGE overlap > 0.7 are removed to prevent penalizing valid alternate matches.
4. Ingestion & Feature Extraction Infrastructure
[ Video Upload ]
│
▼
[ Kafka Stream ] ──► [ Decoupled Workers ] ──► Shot Boundary Detection
│
▼
[ Lakehouse Storage ] ◄── [ GPU Inference ] ◄── Metadata Processing
(Parquet/Source-of-Truth) (Clip Embedding) (ASR/OCR/Safety Gate)
│
▼
[ Index Ingestion Engine ]
├──► Primary Index (IVF-PQ64 - Nightly Batch)
└──► Fresh Index (In-Memory HNSW - Real-Time)
Offline & Streaming Processing Pipeline
- Ingest Queue: Video upload triggers an asynchronous Kafka event containing video storage URI and raw metadata.
- Segmentation: Worker instances execute Shot Boundary Detection (using histogram changes + lightweight CNNs) to break videos into distinct visual shots bounded between 4 and 8 seconds.
- Safety & Compliance Gate:
- Frame hashes are matched against perceptual hash databases (e.g., PDQ/PhotoDNA) for illegal content.
- Multi-label classifiers output safety probabilities (violence, adult content). Flags update the vector's dynamic metadata bitmask.
- Enrichment:
- ASR: Whisper model extracts dynamic spoken transcripts.
- OCR: Text detected in keyframes is stored for keyword matching.
- VLM Captions: Dense descriptions generated for low-text clips.
- Embedding Workers: Batch inference on GPU workers runs frame sampling + Video Encoder to produce 512-d vectors.
- Storage Layer:
- Embeddings written to an immutable Lakehouse store (Parquet partitioned by
model_versionanddate). - Primary database stores clip metadata, video links, timestamps, and permissions.
- Embeddings written to an immutable Lakehouse store (Parquet partitioned by
5. Vector Indexing & Retrieval Engine
Index Architecture: Hybrid Tiering
To support multi-billion vector retrieval under $80\text{ ms}$ while preserving freshness (<15 min SLA), the system separates storage into two distinct index tiers:
[ User Query ]
│
├───────────────────────────┐
▼ ▼
+-------------------+ +-------------------+
| Fresh Index | | Primary Index |
| In-Memory HNSW | | IVF-PQ64 |
| (Last 24 Hours) | | (Nightly Merge) |
+---------┬---------+ +---------┬---------+
│ │
└───────────┬───────────┘
▼
[ Candidates Merging ]
1. Primary Index (Bulk Engine)
- Algorithm: Inverted File Index with Product Quantization (IVF-PQ).
- Configuration: $2^{18} \approx 262,144$ centroids (
nlist), quantized to 64 bytes (m=64, $d^*=8$, 8 bits per sub-vector). - Partitioning Strategy: Vectors are sharded across 32 cluster nodes using a consistent hash on
video_id. - Execution: During query execution, the system probes
nprobe = 64clusters. Top-1000 candidate indices are fetched, and their uncompressed vectors are pulled from SSD storage to execute float32 reranking (rescoring).
2. Fresh Index (Real-Time Ingestion)
- Algorithm: In-memory HNSW graph ($M=16$,
efConstruction=200). - Role: Ingests new clips in real time.
- Lifecycle: Updated continuously. Every night, the fresh index flushes into the main IVF-PQ index build pipeline, after which its memory is reclaimed.
Metadata Filtering & Instant Deletions
- Pre-Filtering: Selective filters (e.g.,
license_type == "commercial") use bitset masks stored directly alongside index centroids to avoid scanning invalid vectors. - Post-Filtering: Highly unselective filters evaluate candidates post-ANN retrieval. Over-fetching multipliers ($k_{\text{ann}} = 3 \times k$) prevent returning fewer candidates than requested.
- Dynamic Takedowns (Deletions):
- Rebuilding compressed indexes for every DMCA/Safety event is inefficient. Instead, an in-memory Takedown Bitset (Tombstone Vector) is replicated to every shard node.
- During retrieval, candidates with an active tombstone bit are filtered out with $O(1)$ overhead before candidates are compiled.
6. End-to-End Query Execution & Reranking
[ User Query Text ]
│
▼
1. Query Encoding (Text Transformer) ──► Vector q (512-d)
│
▼
2. Vector Retrieval (Scatter-Gather) ──► Top-500 Candidates (IVF-PQ + HNSW)
│
▼
3. Merging & Metadata Deduplication ──► Filter Tombstones & Group by Video ID
│
▼
4. Heavy Reranking (Cross-Encoder) ──► Top-200 Candidate Rescoring (GPU)
│
▼
5. Diversity & MMR Post-Processing ──► Final Top-K Clips with Timestamps
Retrieval & Ranking Workflow
- Query Encoding ($15\text{ ms}$):
- Query text is embedded into vector $\mathbf{q} \in \mathbb{R}^{512}$ via the Text Encoder.
- Scatter-Gather ANN Search ($60\text{ ms}$):
- Request sent in parallel to all 32 primary shards + fresh index node.
- Each shard collects local top-$K$ candidates ($K=500$) based on cosine distance.
- Merge & Filter ($15\text{ ms}$):
- Central Query Router aggregates candidate lists, applies tombstone bitsets, and deduplicates multiple clips originating from the same video ID (keeping the highest-scoring clip per video for candidate diversity).
- Cross-Encoder Reranking ($50\text{ ms}$):
- Top 200 candidates are passed to a fine-grained Multimodal Cross-Encoder.
- The Cross-Encoder performs joint token-to-patch cross-attention between raw text tokens and visual frame features.
- Captures fine-grained spatial and compositional relationships (e.g., "red car behind blue truck") that standard dual-encoders compress away.
- Post-Processing & MMR ($30\text{ ms}$):
- Maximal Marginal Relevance (MMR) balances relevance scores against diversity (avoiding returning 10 visually identical shots of the same event).
- Final output payload hydrates thumbnails, clip timestamps (
start_ms,end_ms), and video metadata for rendering.
7. Evaluation, Monitoring & Feedback Loops
Evaluation Metrics
| Metric Type | Metric Name | Target / Purpose |
|---|---|---|
| Offline Quality | Recall@K ($K=10, 50$) | Evaluate vector index recall relative to brute-force exact $k$-NN. Target: Recall@50 > 93%. |
| nDCG@10 | Measure ranking quality on human-annotated relevance evaluation sets. | |
| Mean Reciprocal Rank (MRR) | Assess rank precision for single-shot factual video targets. | |
| Online Business | Click-Through Rate (CTR) | Fraction of searches resulting in a play of $\ge 30\text{s}$ or user engagement. |
| Long Play Rate (LPR) | Proportion of queries leading to significant watch-time ($>50%$ of video duration). | |
| Zero-Result Rate | Measure query failure rate; target < 1.5%. |
Dynamic System Feedback & Continuous Learning
[ User Interaction ] ──► [ Click/Watch Logs ] ──► [ Implicit Feedback Processing ]
│
▼
[ Model Fine-Tuning ] ◄── [ Hard Negative Pairs ] ◄── [ Triplet Loss Extraction ]
- Implicit Click Feedback:
- Search queries leading to a click-and-watch duration $> 30\text{ seconds}$ generate positive training pairs $(\text{Query}, \text{Clip}_i)$.
- Search queries followed by skipping a displayed candidate generate negative pairs $(\text{Query}, \text{Clip}_j)$.
- Incremental Fine-Tuning:
- Triplet loss fine-tuning runs weekly using collected implicit interaction pairs: $$\mathcal{L}_{\text{triplet}} = \max(0, D(\mathbf{q}, \mathbf{v}^+) - D(\mathbf{q}, \mathbf{v}^-) + \alpha)$$
- Automated Monitoring & Alerts:
- Embedding Drift: Track cosine distance distributions of ingested daily vectors against baseline distributions; alert on shift $>3\sigma$.
- Latency Trajectory: Monitor $p_{99}$ latency across individual search shards to detect index skew or hardware bottlenecks.
8. Summary Matrix of Design Trade-Offs
| Component | Choice Selected | Alternative Considered | Selected Rationale |
|---|---|---|---|
| Temporal Pooling | Temporal Transformer | Mean Frame Pooling | Temporal Transformers capture temporal order, motion, and action trajectories crucial for video queries. |
| Vector Index Type | IVF-PQ (Primary) + HNSW (Fresh) | Pure HNSW across all vectors | 5 billion vectors in pure HNSW require ~10 TB of RAM. Compressed IVF-PQ reduces memory footprint to ~360 GB. |
| Clip Granularity | 4–8 second shot segments | Full long-video embeddings | Full-video vectors blur granular temporal details, preventing precise scene jump-to targets. |
| Reranking System | 2-Stage (Dual-Encoder + Cross-Encoder) | Single-Stage Dual-Encoder | The Cross-Encoder restores fine compositional relevance while preserving real-time retrieval speed at scale. |