Multimodal Video Retrieval and Ranking at Billion-Clip Scale

Hard · ML System Design · Machine Learning Engineer · Technical Screen

Prompt

Architect a production multimodal video retrieval platform capable of indexing billions of video segments and serving both natural-language text queries (text-to-video) and visual reference queries (video-to-video).

  1. Modeling & Representation: Define the neural retrieval and ranking stack, including separate query and visual encoders, frame-level vs. temporal sequence aggregation, multi-stage pretraining and domain adaptation losses, in-batch and hard-negative sampling strategies, and how long-form uploads are segmented and sampled into searchable clips. Explain how modalities align inside a common vector space and how multi-stage re-ranking computes final relevance scores.
  2. Data & Serving Infrastructure: Detail the end-to-end ingestion, shot boundary segmentation, multimodal metadata enrichment, and offline/online feature computation pipelines. Specify the approximate nearest-neighbor (ANN) vector index architecture (comparing graph-based vs. quantized inverted-file designs, shard partitioning, and replica layout), object-storage organization for preview streams and thumbnails, hybrid query routing, multi-tier caching, and concrete latency and compute budgets at multi-billion-clip scale.
  3. Evaluation, Safety & Lifecycle: Describe offline benchmark metrics, online A/B test design, production drift monitoring, trust-and-safety / copyright filtering, fast takedown propagation, in-session and logged relevance feedback loops, and how to ship model improvements without search downtime or constant full-corpus re-decoding.

Scope & Expectations

  • Quantitative scale and memory reasoning: Ground index compression, shard sizing, tail-latency mitigation, and backfill compute in explicit back-of-the-envelope math across billions of embeddings and petabytes of video.
  • Multimodal ML depth: Justify temporal modeling choices, false-negative handling in contrastive learning, modality-gap calibration, and the split between lightweight candidate generation and cross-modal re-ranking.
  • End-to-end systems architecture: Show how ingestion, lexical + dense retrieval, tenant access control, media preview delivery, and graceful degradation fit within a sub-200 ms latency budget.
  • Rigorous validation and iteration: Connect offline human-graded metrics to debiased online experiments, safety guardrails, and a practical cadence for updating rankers, text towers, and visual backbones.

Step-by-step walkthrough

  1. Clarify requirements and frame the ML problem

    Before choosing neural architectures or vector databases, pin down who is searching, what unit is returned, and how relevance is measured—because both the model and the storage engine depend on those choices.

    Product assumptions (state clearly and confirm with the interviewer): - Users are video creators and editors (for example, in a cloud-based video creation and editing studio) searching a massive catalog of stock footage, user uploads, and AI-generated clips to drop into timelines. - Text-to-video search: A prompt like "coastal lighthouse in storm waves, slow pull back" returns specific video clips with start_ms and end_ms timestamps, not unsearchable 2-hour raw files. - Video-to-video search: Clicking "More like this" on an existing clip—or uploading a reference shot—retrieves visually and motion-similar clips. A stricter near-duplicate mode also supports copyright and moderation checks. - Access scopes and filters: Users search either the global public catalog, their private team workspace (strict ACL — Access Control List isolation so private footage never leaks), or both, filtered by duration, aspect ratio, license, and safety tier.

    ML problem framing: - Frame search as a multi-stage retrieval and ranking funnel: 1. Candidate generation (retrieval): A dual encoder (two separate neural networks—one for queries and one for video clips—that map both into the same fixed-length list of numbers called an embedding) narrows 5 billion clips down to ~1,000 candidates via Approximate Nearest-Neighbor (ANN) search, blended with keyword search for spoken words and on-screen text. 2. Multi-stage re-ranking: A fast tabular ranker scores ~1,200 candidates using metadata and engagement signals, and a heavier cross-encoder (a neural network that lets query words attend directly to candidate video frames) refines the top 100. - Training and evaluation labels: Offline evaluation uses human raters grading (query, clip) pairs on a 0–3 relevance scale. Online learning uses implicit user actions ordered by signal strength: project insert or download (strong positive), hover preview or click (weak positive), and skipped impression (weak negative, corrected for rank position bias).

    Non-functional targets: - Scale & latency: 5 billion clips, 5,000 peak QPS (Queries Per Second), server-side latency p95 < 200 ms and p99 < 400 ms. - Freshness & availability: Newly uploaded videos become searchable within < 10 minutes (p95); model upgrades roll out with zero search downtime.

  2. Estimate scale, memory, and compute with back-of-the-envelope math

    1. Corpus & ingestion rate
       200M source videos x ~200 s average duration, split into 2-15 s shots (~8 s avg -> ~25 clips/video)
       Total corpus            = 200M x 25 = 5,000,000,000 (5B) clips
       Daily growth            = 1M videos/day -> 25M clips/day = ~290 clips/s avg (~600 clips/s peak)
    
    2. Vector index RAM math (embedding dimension d = 512)
       Raw float32 vector      = 512 x 4 bytes = 2,048 B (~2 KB/clip) -> 5B x 2 KB = ~10.2 TB
       Scalar int8 vector      = 512 x 1 byte  = 512 B/clip           -> 5B x 512 B = ~2.56 TB
       PQ compressed code      = 64 sub-vectors x 1 B + 8 B clip_id   = 72 B/clip -> ~360 GB total!
       HNSW graph overhead     = M = 32 -> 2M = 64 layer-0 links x 4 B local shard ID = 256 B/clip
                                 (+ ~24 B upper-layer links & ID map -> ~2.3 KB/clip with float32 = ~11.5 TB RAM)
       Saved per-frame vectors = 8 frames x 512 dims x 2 B (float16)  = 8,192 B/clip -> ~41 TB on object store
    
    3. Serving traffic
       Peak traffic            = 5,000 QPS (90% text-to-video, 10% video-to-video)
       Thumbnails              = 5B x ~20 KB WebP = ~100 TB on object storage behind a CDN
    
    4. Offline & backfill compute bottlenecks (order-of-magnitude benchmarks)
       ViT-B/16 video tower    = ~500 clips/s per GPU (4,000 frames/s) -> steady peak 600/s needs just 2-4 GPUs
       VLM synthetic captioner = ~10 clips/s per GPU -> ~30 GPUs avg, ~60 GPUs peak (biggest live GPU cost!)
       Full 5B re-embedding    = 5B / 500 clips/s = 10M GPU-s = ~2,800 GPU-hours (~14 h on 200 GPUs)
       Hidden video decode tax = 200M videos x ~12.5 MB (360p @ 0.5 Mbit/s) = ~2.5 PB to read (~50 GB/s for 14 h)
                                 and 200M x 200 s x 30 fps = 1.2 trillion frames (~330k CPU core-hours to decode!)
    

    Three architectural decisions fall straight out of this math: 1. Uncompressed float32 HNSW needs ~11.5 TB of RAM, so billion-scale serving must use Product Quantization (PQ) compression (~360 GB of codes) paired with int8 re-scoring (~2.6 TB) to preserve accuracy at ~4x lower RAM cost. 2. Re-embedding 5B clips is bottlenecked by reading 2.5 PB and decoding 1.2T video frames, not GPU matrix multiplies. Persisting the 8 x 512 float16 per-frame features (~41 TB on cheap object storage) lets us retrain temporal heads and projection layers in hours without touching video files! 3. Query encoding is tiny compared to shard fan-out, so serving cost and p99 tail latency are governed by how we shard, replicate, and hedge the vector index.

  3. API contract and clip-centric data model

    POST /v1/search
    {
      "query": { "text": "coastal lighthouse in storm waves, slow pull back" },  // OR {"clip_id": "c_49..."} OR {"upload_id": "u_3..."}
      "filters": {
        "duration_s": [2, 15], "aspect_ratio": "16:9", "license": ["commercial"],
        "safety": "strict", "scope": "public" | "team:42" | "all_visible"
      },
      "group_by_video": true, "limit": 40, "cursor": null
    }
    -> 200 OK
    {
      "results": [
        { "clip_id": "c_49b2", "video_id": "v_718", "start_ms": 18400, "end_ms": 25600,
          "score": 0.89, "thumbnail_url": "https://cdn.../c_49b2.webp", "preview_hls_url": "..." }
      ],
      "next_cursor": "req_88c:40", "request_id": "req_88c",
      "model_version": "v7.2", "index_version": "idx_2026_11", "partial": false
    }
    
    POST   /v1/feedback          { request_id, clip_id, position, action: "impression"|"preview"|"insert"|"report" }
    POST   /v1/videos             Initiate upload -> { video_id, status: "PROCESSING" }
    DELETE /v1/videos/{video_id} Owner delete or legal takedown -> purged from search within minutes
    
    • Cursor pagination over cached top-1,000: ANN indexes do not efficiently compute "items 400 to 440 from scratch," so page 1 retrieves and ranks the top ~1,000 once, caches the ordered ID list for 10 minutes under request_id, and slices pages via cursor.
    • Version stamps on every response: Returning model_version and index_version guarantees click/insert logs join back to the exact model that served them.

    Core data schemas:

    videos          video_id PK, owner_id, team_id NULL, visibility (PUBLIC|TEAM|PRIVATE),
                    license, duration_ms, source_uri, status, created_at, deleted_at NULL
    clips           clip_id PK (= hash(video_id, start_ms, end_ms)), video_id, start_ms, end_ms,
                    thumbnail_uri, vlm_caption, asr_text, ocr_text, aesthetic_score,
                    safety_scores JSON, phash_cluster_id, popularity, embedding_version
    frame_features  (frame_model_ver, clip_id) -> 8 x 512 float16   (Parquet on object store + SSD KV copy)
    clip_vectors    (model_version, clip_id)   -> 512 float32       (Parquet on object store, per shard)
    interactions    request_id, user_id, clip_id, position, action, model_version, ts  (append-only log)
    

    Notice a critical storage trick: a clip is a database row (video_id, start_ms, end_ms), not a duplicated MP4 file. Hover previews play byte/time ranges over the parent video's HLS (HTTP Live Streaming) segments, cutting media storage in half.

  4. End-to-end ingestion and serving architecture

                            NEAR-LINE INGESTION PIPELINE (< 10 min p95 freshness)
      New Uploads / Stock Imports
           |
           v
      Source Object Store --> Transcoder (360p + 720p HLS) --> Shot Detector --> Clip Rows [start_ms, end_ms]
                                                                                       |
                             +---------------------------------------------------------+
                             |                                                         |
                             v (8 sampled frames @ 224x224)                            v (parallel enrichment)
                GPU Embedder: ViT-B/16 -> Temporal Head                    VLM Captioner, Whisper ASR, OCR,
                     |                         |                           Safety Classifiers, Perceptual Hash
                     v                         v                                       |
           Frame Features (41 TB)     512-d Clip Vectors                               v
           (Parquet + SSD KV Store)            |                          Metadata Store + BM25 Lexical Index
                                               v
                         Index Pipeline: 50 Shards x 3 Replicas (IVF-PQ + int8 + Fresh HNSW Buffer)
    
                            ONLINE SERVING PATH (< 200 ms p95, < 400 ms p99)
      Client --> API Gateway --> Search Orchestrator (Query Router)
                                   |-- 1. Query Cache & Batched GPU Text Encoder (or fetch stored clip vector)
                                   |-- 2. Parallel Retrieval:
                                   |        a) Hedged fan-out to 50 Vector Shards (+ per-team exact store)
                                   |        b) BM25 Lexical Index (captions, ASR speech, OCR text, titles)
                                   |-- 3. Metadata & ACL Hydration (~1,200 merged candidates)
                                   |-- 4. Stage-1 GBDT Re-Ranker (~1,200 -> top 100)
                                   |-- 5. Stage-2 GPU Cross-Encoder on top 100 (attends to 8 frame features)
                                   |-- 6. Diversity (MMR, <= 2/video), Dedup & Defense-in-Depth Safety Filter
                                   v
                             Ranked Clips + Signed CDN Thumbnail/Preview URLs
    
  5. Model deep dive: Dual encoders, temporal aggregation, and long videos

    1. Text tower and factorized video tower. - Text encoder: A 12-layer multilingual Transformer (up to 64 tokens) initialized from a pretrained image-text contrastive model (such as CLIP/SigLIP), projected to 512 dimensions and L2-normalized (scaled to length 1.0 so cosine similarity equals a fast dot product). - Video encoder (Frame ViT + Temporal Transformer): Sample 8 frames per clip using stratified segment sampling—divide the clip into 8 equal time buckets and pick a random frame per bucket during training (for augmentation) and the midpoint frame at inference. Pass each frame through a ViT-B/16 (Vision Transformer) image backbone (196 16x16 patch tokens per 224x224 frame), then aggregate across time:

    Temporal Strategy               Captures Motion/Order?    Compute & Operational Impact
    ------------------------------  ------------------------  --------------------------------------------------
    Mean pooling over 8 frames      No ("zoom in" == "out")   ~0 extra FLOPs; strong appearance-only baseline
    2-4 layer Temporal Transformer  Yes (camera moves, order  Tiny extra FLOPs (8 frame tokens); lets us cache
      over 8 frame summary tokens     of actions)               8 x 512 frame features (41 TB) for fast updates!
    Joint space-time attention      Finest intra-frame        Attention over 8 x 196 = 1,568 tokens = 8x the
      across all 1,568 patch tokens   pixel trajectories        attention FLOPs (~1.3x total ViT FLOPs since MLPs
                                                                are ~96% of 1-frame ViT-B), AND forces re-decoding
                                                                2.5 PB of raw video on every temporal model tweak!
    

    We choose the factorized Frame ViT + 4-layer Temporal Transformer: it distinguishes "door opening" from "door closing" and "slow push in" from "pull out", while keeping per-frame embeddings reusable across model iterations.

    2. Shared embedding space and the modality gap. Both towers project into the same 512-d unit sphere, supporting text-to-video (dot(q_text, c_video)) and video-to-video (dot(q_video, c_video)) in a single vector index. However, contrastive dual encoders exhibit a modality gap: two clips of the same snowy mountain often have cosine similarity 0.85, while an exact text caption scores 0.34 against the same clip. Never share raw score cutoffs across query types—calibrate thresholds and pass query_modality as an explicit feature to the re-ranker.

    3. Splitting and searching long videos. Run shot boundary detection (detecting abrupt cuts and gradual dissolves from frame color/feature deltas) during ingestion: split shots longer than 15 s into 15 s windows and merge micro-cuts shorter than 2 s into neighbors. A 2-hour movie becomes ~500–1,000 timestamped clip rows, plus one video-level summary vector (normalized mean of its clip vectors). For multi-shot queries ("car chase entering a tunnel"), boost adjacent clip hits from the same video at ranking time, and cap page-1 results at at most 2 clips per source video so one long upload never monopolizes the screen.

  6. Training deep dive: Contrastive objectives and negative sampling

    1. Three-stage training data curriculum: - Stage 1 — Noisy web/catalog pairs (hundreds of millions): Titles, tags, and time-aligned ASR (Automatic Speech Recognition) transcripts. High volume, high noise (narration rarely describes camera framing). - Stage 2 — Synthetic VLM captions (tens of millions): Run a Vision-Language Model (VLM) offline on sampled shots to generate rich visual descriptions ("handheld tracking shot of a cyclist in rain at night"). Audit samples manually to catch model hallucinations. - Stage 3 — Curated human annotations (hundreds of thousands): High-precision editor descriptions plus debiased user download pairs, trained with a small learning rate. - Leakage-proof splits: Partition train/validation/test sets by video_id and perceptual-hash near-duplicate cluster, never by clip_id; otherwise sister shots from the same video leak into evaluation and inflate metrics.

    2. Symmetric InfoNCE + video-to-video alignment objective: We train with InfoNCE (a contrastive cross-entropy loss that pulls matching (text_i, video_i) pairs together on the batch similarity diagonal while pushing mismatched pairs apart, scaled by a learned temperature tau ~ 0.05), plus a self-supervised video-similarity loss L_vv across augmented views of the same shot (random frame offsets, crops, color jitter, bitrate re-encode) so video-to-video search stays sharp:

    s(t_i, v_j) = dot(text_emb[i], video_emb[j]) / tau
    L_tv        = 0.5 * (CrossEntropyRows(s) + CrossEntropyCols(s))
    L_total     = L_tv + lambda * L_vv(view1(v), view2(v))
    

    3. Negative sampling without false-negative poison: - Distributed in-batch negatives: Across 256 GPUs x 128 clips/GPU = 32,768 global batch size, gather embeddings across GPUs so each GPU computes only its local 128 x 32,768 logit slice (~16.8 MB in float32, rather than materializing a 4.3 GB 32k x 32k matrix on every GPU). - Eliminating false negatives: Two clips from the same source video—or two re-uploads of the same stock sunset—frequently match the same caption. Sample at most one clip per video_id / duplicate cluster per batch, and explicitly mask any remaining same-video off-diagonal pairs out of the denominator:

    import numpy as np
    
    
    def cross_entropy_on_diagonal(logits):
        """Compute mean -log softmax(logits)[i, i] using max-shift for numerical stability."""
        row_max = logits.max(axis=1, keepdims=True)
        shifted = logits - row_max
        log_probs = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))
        return -np.mean(np.diag(log_probs))
    
    
    def video_text_contrastive_loss(text_emb, video_emb, video_ids, temperature=0.05):
        """Symmetric InfoNCE loss masking off-diagonal clips that share the same source video."""
        # Pairwise scaled cosine similarities: shape (B, B), matching pairs sit on diagonal
        logits = (text_emb @ video_emb.T) / temperature
    
        # Mask (i, j) where i != j and video_ids[i] == video_ids[j] so sister clips are not penalized
        same_video = video_ids[:, None] == video_ids[None, :]
        off_diagonal = ~np.eye(len(video_ids), dtype=bool)
        masked_logits = np.where(same_video & off_diagonal, -1e9, logits)
    
        loss_t2v = cross_entropy_on_diagonal(masked_logits)
        loss_v2t = cross_entropy_on_diagonal(masked_logits.T)
        return 0.5 * (loss_t2v + loss_v2t)
    
    • Semi-hard mined & compositional negatives: Mine top-50 ANN neighbors per training query from the previous model checkpoint, discard ranks 1–5 (frequently unlabeled true positives!), and sample from ranks 10–50. Pair these with compositional text hard negatives (swapping "zoom in" <-> "zoom out" or "dog chasing cat" <-> "cat chasing dog") so the model cannot behave like an orderless bag of words.
  7. Ingestion pipeline, metadata enrichment, and media storage layout

    Decouple ingestion stages with durable queues; make every worker idempotent keyed by deterministic clip_id = hash(video_id, start_ms, end_ms) so retries overwrite cleanly without creating duplicate clips:

    1. Upload & priority routing: Store raw upload; give interactive user/team uploads higher queue priority than bulk stock backfills so creators see their own footage quickly.
    2. Transcode & shot split: Produce 360p (for cheap ML decoding) and 720p HLS 4 s segments (for instant hover previews), then run shot detection to emit clip rows.
    3. Safety hash gate (before anything else): Match perceptual hashes against known illegal-content databases first; positive hits halt immediately before generating thumbnails or embeddings.
    4. GPU embedding: Decode 8 frames from 360p, run ViT-B/16, persist 8 x 512 float16 frame features to Parquet + SSD key-value store, run the temporal head, and output the 512-d vector.
    5. Parallel metadata enrichment: Run VLM captioning (budgeted to public/opted-in clips since it takes ~60 GPUs at peak), Whisper ASR speech-to-text, OCR (Optical Character Recognition) for on-screen signs/titles, NSFW/violence classifiers, perceptual hash (pHash) near-duplicate clustering, and technical/aesthetic quality scoring (sharpness, motion-blur, framing).
    6. Dual index publish: Insert the vector into its shard's fresh in-memory buffer and index text fields into the BM25 lexical engine; mark clip SEARCHABLE (< 10 min p95).
    Storage Path Pattern                                        Purpose & Lifecycle
    ----------------------------------------------------------  ------------------------------------------------
    media/raw/{video_id}/original.{ext}                         Write-once; tier to cold archival after 30 days
    media/hls/{video_id}/{360p|720p}/seg_{n}.ts + index.m3u8    Shared HLS segments; player trims [start, end]
    media/thumb/{video_id}/{clip_id}-{content_hash}.webp        ~20 KB immutable WebP, 1-year CDN Cache-Control
    features/frames/{frame_ver}/{shard}/part-{k}.parquet        8 x 512 fp16 (~41 TB) for fast temporal re-trains
    features/clips/{model_ver}/{shard}/part-{k}.parquet         512-d vectors grouped by shard for index builds
    index/{index_ver}/{shard}/seg-{n}.ivfpq + manifest.json     Immutable memory-mapped shard files for replicas
    
  8. Vector index deep dive: Scaling ANN search to 5 billion clips

    Let's compare vector index designs for 5B clips (d = 512):

    Index Strategy                 RAM Across 5B Clips      Query Speed & Recall        Insert / Delete Cost
    -----------------------------  -----------------------  --------------------------  ------------------------
    Brute-force flat scan          ~10.2 TB                 100% recall, way too slow   Trivial append
    Float32 HNSW graph             ~11.5 TB                 Excellent recall, < 20 ms   High RAM; deletes costly
    IVF-PQ (72 B) + int8 re-score  ~360 GB + ~2.6 TB = 3 TB >= 95% recall@100, ~10 ms   Fast append + tombstones
    

    How our hybrid IVF-PQ + int8 re-score + Fresh HNSW shard works: - IVF (Inverted File) partitions the vector space into nlist = 65,536 coarse cluster centroids (k-means) so a query only scans the closest nprobe = 64 clusters (~0.1% of the shard). PQ (Product Quantization) splits a 512-d vector into 64 chunks of 8 floats and replaces each chunk with a 1-byte nearest-codeword ID (64 bytes total). - Shard sizing: Split 5B clips by hash(clip_id) across 50 shards (100M clips/shard) with 3 replicas per region (150 hosts/region). Each shard holds ~7.2 GB of PQ codes + ~51.2 GB of int8 vectors = ~60 GB RAM, fitting comfortably on a 128 GB server. Scanning 100M x (64 / 65,536) = ~98,000 PQ codes takes ~10 ms on one CPU core, surfaces the top 200 approximate matches, and re-scores those 200 with int8 vectors to emit the shard's top 100 (>= 95% Recall@100 vs. exact search). - Freshness & deletes: Clips from the last 60 minutes sit in a small per-shard in-memory HNSW (Hierarchical Navigable Small World) delta graph searched alongside IVF-PQ, then compact into immutable IVF-PQ segments hourly. Deletions and takedowns flip a per-segment tombstone bitmap bit checked during scan (instant removal within seconds; physically reclaimed during background compaction). - Beating the 50-shard tail-latency trap: If every shard independently has a 1% chance of exceeding its p99 latency, waiting for all 50 shards hits at least one slow shard on 1 - 0.99^50 = ~39% of requests! Two rules solve this: 1. Hedged requests: If Shard k has not replied by its p95 (30 ms), fire a duplicate read to Replica 2 of Shard k and take whichever answers first. 2. Hard 80 ms deadline with partial results: At 80 ms, merge whatever shards responded (e.g., 49/50 = 98% of corpus) and flag "partial": true rather than failing the user's search. - Private team workspaces (skip global ANN!): Filtering a 50,000-clip private workspace after fetching the global top-1,000 often yields zero results (and risks ACL bugs). Instead, store each team's int8 vectors in an isolated per-tenant partition and run exact brute-force dot products (1M clips = 512 MB scan = ~20 ms across a few cores, 100% recall, hard tenant isolation).

  9. Serving deep dive: Hybrid query routing, multi-stage ranking, and latency budget

    1. Query routing + lexical fusion: - Text queries check a normalized (query_text, model_version) embedding cache; cache misses batch dynamically (<= 3 ms window) on a GPU text-encoder pool. In parallel, BM25 keyword search queries captions, ASR speech, OCR text, and titles—rescuing exact proper nouns and literal text ("sign reading OPEN 24 HOURS", "Eiffel Tower") where dense visual vectors blur details. - Video-to-video queries on an indexed clip_id simply look up its stored 512-d vector (zero GPU compute!); raw uploaded query clips run the ViT + Temporal encoder once (~250 ms).

    2. Four-step ranking funnel & 160 ms server latency budget:

    Stage & Budget      Work Performed
    ------------------  --------------------------------------------------------------------------------
    1. Parse & Cache      5 ms : Auth, query normalization, check result cache & text-embedding cache
    2. Query Encode      15 ms : Batched GPU text tower (0 ms on cache hit or indexed clip_id query)
    3. Hybrid Retrieve   60 ms : Parallel 50-shard hedged ANN (~1,000 hits) + BM25 (~200 hits); 80 ms cap
    4. Hydrate + GBDT    30 ms : Fetch metadata/ACLs for ~1,200 hits; GBDT scores cosine, BM25, quality,
                                 duration match, freshness, debiased popularity -> keeps top 100
    5. Cross-Encoder     40 ms : Reads 100 x 8 KB frame features from SSD KV store; cross-attends query
                                 tokens to 8 frame vectors on GPU; blends with GBDT score
    6. Rules & Sign      10 ms : Re-verify ACL/safety, collapse pHash duplicates, <= 2 clips/video,
                                 MMR diversity pass (avoids 20 identical sunsets), sign CDN URLs
    ------------------  --------------------------------------------------------------------------------
    Total Typical       ~160 ms -> comfortably meets p95 < 200 ms and p99 < 400 ms!
    

    Graceful degradation: If the cross-encoder or GBDT pool saturates, serve filtered ANN+BM25 scores directly; if the GPU text-encoder pool fails, fail over to a distilled CPU student text encoder trained to match the exact same 512-d space.

  10. Evaluation, A/B testing, safety, relevance feedback, and incremental updates

    1. Offline evaluation & online A/B experimentation: - Offline golden benchmark: Stratify ~5,000 text and ~2,000 video queries across head, torso, and tail slices (camera motion, non-English, OCR text, abstract mood). Pool top-20 results across old and candidate models for blind 0–3 human grading. Gate launches on retrieval Recall@100, ranking nDCG@10 (Normalized Discounted Cumulative Gain, which rewards placing grade-3 clips at rank 1 over rank 10), MRR (Mean Reciprocal Rank), and ANN Recall@100 vs. exact search—checking every slice so average gains never hide a regression on motion queries. - Online A/B test: Randomize by user for >= 2 weeks. Primary metric: Search Session Success Rate (fraction of search sessions ending in a timeline insert or clip download). To detect a +1% absolute lift over a 40% baseline (alpha = 0.05, 80% power), sample size is 2 * (1.96 + 0.84)^2 * 0.4 * 0.6 / 0.01^2 = ~38,000 users per arm (with cluster-robust variance for multi-session users). Monitor p99 latency, GPU cost/1k queries, zero-result rate, and user safety report rate as guardrails.

    2. Monitoring, content safety, and fast takedowns: - Safety & anti-spam: Combine ingestion hash gates, multi-head frame safety classifiers (nsfw, graphic_violence, self_harm), audio/video copyright fingerprinting, query-side blocklists, and low trust weights on user-supplied titles (defeating keyword stuffing). Legal/owner takedowns flip shard tombstones, purge cached result lists, and invalidate CDN URLs within minutes. - Drift alerts: Track daily exact-vs-ANN recall@100, query/clip embedding distribution shifts, low-top1-similarity spikes, and weekly top zero-result queries.

    3. Session relevance feedback & zero-downtime model updates: - In-session vector steering (Rocchio update): When a creator clicks "More like these, less like that", shift the query vector in real time without retraining, guarding against zero-norm cancellation:

    import numpy as np
    
    
    def refine_query(query_emb, liked_embs, disliked_embs, alpha=1.0, beta=0.6, gamma=0.2):
        """Steer a 512-d query vector toward liked clips and away from disliked clips (Rocchio)."""
        updated = alpha * query_emb
        if len(liked_embs) > 0:
            updated = updated + beta * np.mean(liked_embs, axis=0)
        if len(disliked_embs) > 0:
            updated = updated - gamma * np.mean(disliked_embs, axis=0)
    
        # Guard against division by zero in case disliked vectors cancel updated out
        norm = max(float(np.linalg.norm(updated)), 1e-12)
        return updated / norm
    
    • Cross-user learning (debiased): Randomize adjacent pairs in a tiny traffic slice to measure rank position bias, then train the GBDT ranker with Inverse Propensity Weighting (IPW) (upweighting clicks on lower ranks that fewer eyes saw) and mix downloaded (query, clip) pairs with curated captions so encoders never collapse onto the old ranker's blind spots.
    • Four-speed incremental model update ladder:
      1. Weekly (0 index work): Retrain GBDT / cross-encoder weights.
      2. Monthly (0 index work): Fine-tune the text tower or a query adapter with the video tower frozen, keeping all 5B indexed clip vectors 100% valid!
      3. Quarterly (no video decode): Retrain the temporal head over the 41 TB stored Parquet frame features and build index_v2 side-by-side (model_version -> index_version routing guarantees queries never hit a mismatched index).
      4. Annually (full visual backbone upgrade): Re-decode 360p videos (~2,800 GPU-hours + decode fleet), dual-writing live uploads during backfill—or use backward-compatible alignment loss if new queries must temporarily search old vectors during migration.

Intuition & how it works

Think of searching 5 billion video clips in under 200 ms like finding a specific scene in the world's largest film archive using a visual-and-text map plus a two-round casting audition. Offline, when each video enters the archive, we split it into short single-camera shots (2–15 seconds each) and pass 8 sampled frames through a video encoder neural network that summarizes the clip's appearance and camera motion into a 512-number coordinate called an embedding—placing "aerial sunset over snowy peaks" right next to "golden-hour mountain drone flyover" on a shared 512-dimensional map. At search time, a text encoder turns the user's prompt into a single 512-number coordinate on that exact same map (or, for video-to-video search, we simply look up the reference clip's coordinate). Round 1 uses a compressed map index (Approximate Nearest-Neighbor / ANN search) plus a keyword index (BM25 over speech transcripts and on-screen text) to grab ~1,200 plausible clips in 60 ms; Round 2 runs heavier ranking models—including a cross-encoder that compares every query word directly against the top 100 clips' frame features—to pick the best, most diverse 40 clips for page 1.

Why does a single-model or naive vector-search approach fail? A cross-encoder is accurate because query words attend directly to video frames, but running it across 5 billion clips per search would take millions of GPU-seconds per query; conversely, a fast dual encoder (separate text and video networks) compresses an entire clip into one static vector and misses literal spoken quotes or fine word-to-frame details on its own. On the infrastructure side, storing 5 billion uncompressed float32 vectors inside an HNSW graph demands ~11.5 TB of RAM, waiting for all 50 index shards turns a 1% per-shard hiccup into a 1 - 0.99^50 = 39% user tail-latency spike, and re-decoding 2.5 PB (1.2 trillion frames) of raw video every time an ML engineer tweaks temporal modeling makes iteration painfully slow.

Trace one concrete creator query end to end to see how each stage earns its keep:

Query: "tracking shot of vintage bakery window at dusk, push in"  (scope: public, safety: strict)

1. Encode (15 ms):
   Text tower maps prompt -> L2-normalized 512-d vector q.

2. Parallel Hybrid Retrieval (60 ms, hedged across 50 shards, 80 ms hard cap):
   - Vector ANN (IVF-PQ 72-byte codes -> int8 re-score): returns 1,000 visually matching dusk/storefront shots.
   - BM25 Lexical Index (OCR + ASR + captions): returns 200 clips where OCR literally read "BAKERY".

3. Stage-1 GBDT Re-Ranker (30 ms over ~1,200 merged candidates):
   Combines cosine similarity (0.37), BM25 OCR hit ("BAKERY"), clip sharpness, and duration fit -> top 100.

4. Stage-2 GPU Cross-Encoder + Diversity Rules (45 ms on top 100):
   Fetches cached 8 x 512 frame vectors from SSD KV store; verifies frame 1 -> frame 8 actually pushes IN
   (demoting pull-out shots!), drops near-duplicates via perceptual hash, caps at <= 2 clips/video -> top 40.

Key trade-offs

  • Two-stage funnel (dual encoder + cross-encoder) vs. single model: Only a dual encoder lets us precompute all 5B video vectors once offline so online search costs a single text forward pass plus dot products, at the price of losing fine token-to-frame interaction. Running a cross-encoder strictly on the top 100 candidates recovers fine-grained motion and object binding within a 40 ms GPU budget.
  • Factorized Frame ViT + Temporal Transformer vs. mean pooling or joint space-time attention: Mean-pooling 8 frames adds zero extra compute but cannot tell "zoom in" from "zoom out". Full joint space-time attention across 8 x 196 = 1,568 image patches multiplies attention FLOPs by 8x (~1.3x total ViT compute) and couples spatial and temporal weights tightly. A lightweight 4-layer temporal Transformer over 8 frame embeddings captures frame order while letting us save 8 x 512 float16 frame features (~41 TB) on object storage—so temporal and projection upgrades skip re-decoding 2.5 PB of video.
  • IVF-PQ + int8 re-scoring vs. uncompressed float32 HNSW: HNSW (a multi-layer proximity graph) over raw float32 vectors needs ~11.5 TB of RAM across 5B clips. IVF-PQ (clustering vectors into coarse buckets and quantizing 512 floats into a 64-byte code) shrinks codes to ~360 GB plus ~2.6 TB of int8 vectors for two-pass re-scoring (~60 GB per 100M-clip shard), trading slight quantization loss for a ~4x RAM reduction while holding >= 95% Recall@100.
  • Hash sharding (hash(clip_id)) vs. semantic cluster sharding: Hash sharding balances storage and QPS evenly across all 50 shards without hot spots, but requires querying every shard per search. Assigning whole IVF clusters to specific shards lets queries probe only ~5 shards (~10x less CPU), at the risk of hot shards on trending topics like "sunset" or "talking head".
  • Hedged requests + 80 ms partial results vs. waiting for 100% of shards: Firing a backup read at 30 ms (p95) and returning 49/50 shards ("partial": true) at 80 ms bounds p99 latency and preserves availability during node brownouts, trading away 2% corpus recall on rare tail spikes.
  • Frozen video tower for fast iteration vs. full joint retraining: Training text-tower updates or query adapters with the video tower frozen requires zero re-indexing of 5B clips, enabling monthly query improvements while reserving expensive side-by-side full index rebuilds for major visual-backbone breakthroughs.
  • Debiased implicit feedback vs. human rater labels: User downloads and timeline inserts are abundant and fresh, whereas human 0–3 ratings are scarce and costly—but raw clicks suffer severe position bias (rank 1 gets clicked far more than rank 15). Use Inverse Propensity Weighting (IPW) on click logs for training while keeping human-graded golden sets as the unbiased launch gate.

Common mistakes

  • Treating other shots from the same video as contrastive negatives: During InfoNCE training, adjacent clips from the same wedding or drone flight often match the same caption; failing to deduplicate batches by video_id / perceptual hash (pHash) cluster and mask off-diagonal same-video pairs teaches the encoder to push semantically identical footage apart.
  • Splitting train/validation/test sets by clip_id instead of video_id and near-duplicate cluster: Sister shots from the same source video or re-uploaded stock clips leak across splits and make an overfit model look artificially strong offline.
  • Proposing in-memory float32 HNSW for 5 billion vectors without doing the RAM math: Neglecting 5B x 2.3 KB = ~11.5 TB per replica immediately signals weak production intuition.
  • Post-filtering small private team workspaces out of global top-1,000 ANN results: A team with 20,000 private clips (0.0004% of 5B) will almost never appear in the global top 1,000—yielding empty results and risking data-leak bugs. Small private scopes should run isolated per-tenant exact int8 search.
  • Sharing one raw cosine-similarity threshold across text-to-video and video-to-video queries: Because of the contrastive modality gap, video-to-video similarities cluster much higher (~0.8+) than text-to-video similarities (~0.3+), so score calibration must be conditioned on query type.
  • Mixing query-encoder and index model versions during rollouts: Encoding a live query with model_v8 against index_v7 produces garbage dot products; the router must strictly pin (model_version, index_version) pairs during side-by-side migrations.
  • Deleting taken-down clips from Postgres while forgetting shard tombstones, result caches, and CDN URLs: Takedowns must set segment tombstone bits, invalidate cached public result lists, and purge CDN edges within minutes.
  • Sizing backfills by GPU TFLOPs alone while ignoring video decoding: Decoding 1.2 trillion frames across 2.5 PB of compressed video easily dwarfs ViT GPU time unless 360p proxies and cached 41 TB frame features are part of the design.

Follow-up questions

  • How would you locate a precise 3-second action inside a 2-hour raw video? Ingestion already segments every 2-hour video into ~500–1,000 shot-bounded clip rows (2–15 s each), so initial search directly returns start_ms and end_ms timestamps. To pinpoint exact sub-clip boundaries for the top few returned clips, run a lightweight 1-second sliding-window scorer over cached frame features (or 1 fps embeddings) strictly on those top candidate clips and merge adjacent high-scoring windows. For queries spanning multiple shots ("runner enters stadium and crosses finish line"), either merge consecutive clip hits from the same video_id during ranking or index 3-shot sliding windows on long videos, evaluating accuracy with Recall at IoU >= 0.5 (Intersection over Union between predicted and ground-truth time intervals).
  • If leadership asks you to cut serving infrastructure cost by 50% without hurting user success rate, what levers do you pull first? Because the 50-shard CPU fan-out dominates serving cost, start by routing queries via semantic cluster sharding (placing whole IVF coarse clusters on dedicated shards so a query probes ~5 shards instead of all 50, cutting ANN CPU ~8–10x while replicating hot clusters extra-wide). Second, tier the corpus into a hot in-RAM index for the top ~20% of clips that satisfy ~85% of impressions and a cold NVMe-SSD index (such as DiskANN or on-disk IVF lists) queried only when hot-tier top scores fall below a calibrated confidence threshold. Third, shrink PQ codes from 64 B to 32 B and cache head query results—validating every step against exact-search Recall@100 and online A/B search success rate.
  • How do you make search work reliably when creators search for exact spoken dialogue or words printed on a street sign? Dense visual embeddings recognize "a neon shop sign" or "two people talking" visually, but compress away exact character sequences and ignore audio completely. During ingestion, run ASR (speech-to-text with word timestamps) and OCR (on-screen text extraction) on every clip and index those fields in a parallel BM25 lexical search engine. At query time, retrieve top candidates from both ANN and BM25 in parallel, detect quote/text-heavy queries ("says ...", quoted strings, capitalized proper nouns) to boost lexical weight in the GBDT re-ranker, and optionally add a dedicated audio-text contrastive tower later if sound-effect search ("thunderclap", "vinyl crackle") becomes a core creator workflow.

Follow-up questions

Similar questions

More Runway interview questions

All 2 Runway questions →