Building a Pipeline for Cross-Modal File Vectorization at Scale
System DesignModel answerLast updated
Design a multi-tenant service that turns uploaded documents, images and videos into searchable vectors, covering ingestion, inference, storage, dedup, re-embedding, and operations.
Your team is building a platform where customers upload files and the platform turns each one into vector embeddings that are stored for search. Supported inputs are documents, images and videos, and every file is at most X MB (pick a value, such as 100 MB, and state it).
Design the end-to-end system. Your answer should cover:
- Requirements and scale. Your assumptions about daily volume, peak rate, latency targets, search latency and tenancy.
- Ingestion API. How files arrive, how jobs are tracked, and how deletion works.
- Validation and preprocessing. Per-modality steps such as text chunking, image resizing, and video frame or clip sampling.
- Model choices. Which models you use per modality, and whether you use one shared space or several.
- Throughput. Batching, accelerator scheduling, and concurrency controls, including fairness between tenants.
- Storage and search. Where vectors and metadata live (vector store vs. relational vs. columnar), and how similarity search works.
- Deduplication. How you handle exact and near-identical content.
- Reliability. Retries, idempotency, and re-embedding the corpus when the model changes.
- Operations. Monitoring, quality evaluation, cost control, privacy and security.
Make your trade-offs explicit and support them with rough numbers.
Hints
Hint 1
Begin with a back-of-envelope estimate: vectors per file for each modality, multiplied by daily uploads, times bytes per vector. The result tells you whether you need quantization and storage tiering.
Hint 2
Separate CPU-bound preprocessing (decoding, OCR, ffmpeg) from GPU inference with a queue in between, so each pool scales on its own signal and video decoding cannot starve the GPUs.
Hint 3
Make every stage idempotent by keying results on (content hash, model version, preprocessing version). That one key gives you safe retries, exact dedup, and a cheap way to tell what a model upgrade needs to recompute.
Hint 4
For model upgrades, think in terms of dual-writing to a new index version, comparing quality offline, then flipping a pointer, with backfills at low priority on spare capacity.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Functional: accept documents (PDF, DOCX, TXT), images and videos up to X = 100 MB. Compute and persist embeddings, support within-modality and cross-modal search (text query to image or video), deduplicate, retry safely, and re-embed on model change.
Assumptions: 5M uploads/day (70% docs, 25% images, 5% video), roughly 60 files/s average and 300/s at peak. Processing is asynchronous, with p95 under 30 s for docs and images and a few minutes for video. Search p99 is under 100 ms. The service is multi-tenant with strict isolation.
Vector count:
- Documents: about 20 chunks each, giving about 70M vectors/day.
- Images: 1 each, about 1.25M/day.
- Video: about 60 s average, one vector per 2 s clip, about 30 per video, about 7.5M/day.
- Total is about 80M vectors/day. At 768-dim fp16 (1.5 KB) that is about 120 GB/day, so we need int8 or product quantization and hot/warm/cold tiers.
2. API
POST /v1/files (Idempotency-Key) -> {file_id, upload_url}
POST /v1/files/{id}/complete -> {job_id, status: QUEUED}
GET /v1/jobs/{job_id} -> {status, model_version, num_vectors, error}
POST /v1/search {query_text | query_file_id, modalities, filters, k}
DELETE /v1/files/{id} # cascades to vectors
Clients upload straight to object storage via presigned URLs, so API servers never proxy large bytes. The idempotency key makes client retries safe.
3. Architecture
Gateway (authN, per-tenant rate limits) → object store (encrypted) → metadata DB (files, jobs) → queue partitioned by modality → CPU preprocess workers → inference queue → GPU model servers with dynamic batching → writer (vector DB upsert, metadata update, Parquet lake). Search: query encoder → ANN with mandatory tenant filter → optional rerank → aggregate to file level.
CPU and GPU pools are separate. Video decoding is CPU-heavy and must not starve accelerators.
4. Validation and preprocessing
- All files: enforce size server-side as well as in the presigned policy, detect type from magic bytes, run a malware scan, reject corrupt or encrypted files, compute SHA-256.
- Documents: extract text (OCR fallback for scans), normalize whitespace, chunk at about 512 tokens with about 64 overlap along paragraph and heading boundaries. Keep page, offset and section so hits can be traced back.
- Images: decode, apply EXIF orientation, convert to RGB, resize to model resolution (224 or 384), center crop. Optionally tile very large images.
- Video: probe with ffmpeg, cap duration (say 10 min), sample about 1 fps with shot detection, group into 2 s clips, embed frames and mean-pool per clip. Store clip vectors with timestamps and one video-level vector. Optionally transcribe audio and embed the transcript as text.
Version preprocessing (preproc_v3) separately from the model, since it changes the vectors as much as the weights do.
5. Models
- Cross-modal: a shared text-image model (SigLIP or CLIP ViT-L/14). Images and frames use the image tower, queries use the text tower.
- Document search: a dedicated text embedder (bge, e5). CLIP's text tower is limited to 77 tokens and is weak on long passages. If documents must be cross-modally searchable, also store a CLIP embedding of title or summary.
- Trade-off: one unified model is simpler (one index, comparable scores) but loses quality per modality. Per-modality models are better but need separate indexes and score calibration or rank fusion. I would choose per-modality for text and a shared space for image and video.
6. Throughput and fairness
- Batching: Triton dynamic batching, max batch 64 to 256, queue delay 20 to 50 ms. Bucket text chunks by length to cut padding.
- Scheduling: one GPU pool per model, autoscaled on queue lag rather than CPU. Priority classes: interactive > bulk import > backfill. Backfills use spare or spot capacity and are preempted first.
- Concurrency: per-tenant token buckets at the gateway, per-tenant in-flight caps in workers, bounded queues with backpressure (429 when lag exceeds SLO). Videos fan out into clip tasks and a coordinator joins them.
- Efficiency: fp16/bf16 with TensorRT, int8 if offline eval shows no meaningful recall loss.
7. Storage and search
- Object store: raw files plus a cache of derived artifacts (extracted text, sampled frames) to make backfills cheap.
- Postgres:
files,jobs(state, attempts, model and preproc version),embeddings_meta(vector_id, file_id, segment ref). - Vector DB (Milvus, Vespa, OpenSearch k-NN, pgvector if small): HNSW, or IVF-PQ for the huge text index. Payload fields
tenant_id,modality,model_version,file_id, ACLs. Shard or partition by tenant for isolation and efficient filtering. - Parquet/Iceberg lake: full vectors and metadata for analytics, evaluation and offline rebuilds.
- Query path: encode with the matching model version, ANN with tenant and ACL filter, take top 100, optionally cross-encoder rerank, then aggregate chunks or clips to files (max or top-k sum).
8. Deduplication
| Level | Method | Action |
|---|---|---|
| Exact | SHA-256 | Reuse vectors via cache keyed by (sha256, model_ver, preproc_ver) |
| Near-dup image | pHash/dHash, Hamming ≤ ~6 | Link to canonical asset |
| Near-dup text | MinHash/SimHash | Link to canonical |
| Near-dup video | keyframe hash sequence | Link to canonical |
| Semantic | cosine > ~0.97 | Confirm or cluster |
Scope dedup per tenant by default. Sharing across tenants leaks existence information and complicates deletion.
9. Retries, idempotency, model upgrades
- Job state machine: QUEUED → PREPROCESSING → EMBEDDING → WRITTEN → DONE. Queues are at-least-once, so writes must be idempotent: vector IDs are deterministic (
hash(file_id, segment, model_ver, preproc_ver)) and upserts are safe to repeat. Failed messages go to a DLQ after bounded retries with exponential backoff and jitter. Poison files are marked FAILED with a reason. - Upgrades: vectors from different models are not comparable, so never mix them in one index. Create a new index version, dual-write new uploads, backfill old files in the background from cached derived artifacts, evaluate offline (recall@k against a labeled set, plus overlap with the old index), then switch the search alias and keep the old index for rollback before deleting it.
10. Operations
- Monitoring: queue lag, per-stage latency, GPU utilization and batch size, failure and DLQ rates, vector counts, search latency and recall proxies. Alert on SLO burn.
- Quality: golden query sets per modality, periodic recall@k and NDCG, drift detection on embedding norms and distribution, shadow evaluation of candidate models.
- Cost: quantization, tiering old vectors to cold storage, dedup to skip inference, spot instances for backfills, video caps, per-tenant quotas.
- Privacy and security: per-tenant encryption keys (KMS), TLS everywhere, least-privilege IAM, tenant filter enforced server-side, never client-supplied. Deletion must remove raw files, derived artifacts, vectors and lake rows, with an audit trail. Respect data residency by region-local deployments. Vectors can leak content, so treat them as sensitive.
Common mistakes
- Proxying large uploads through API servers.
- Co-locating video decoding with GPU inference.
- Mixing vectors from different model versions in one index.
- Ignoring preprocessing versions in cache keys.
- Applying tenant filters after ANN retrieval (post-filtering), which hurts recall and risks leaks.
- No per-tenant fairness, letting one bulk import stall everyone.