Orchestrating Classification and Embedding Services at Scale
Machine LearningModel answerLast updated
Build a document processing pipeline that calls two ML services (classification and embedding) for both single-file and bulk uploads up to 1,000 files.
You have access to two third-party ML services that you cannot modify:
-
Classification Service
- Accepts: text documents
- Returns: a category label for each document
-
Embedding Service
- Accepts: text documents
- Returns: a dense vector (e.g., 768 dimensions) for each document
Your task is to design a complete pipeline that:
- Lets users upload files containing text documents
- Handles both individual file uploads and batch uploads (up to 1,000 files at once)
- Processes each document through both services to obtain its label and embedding
- Stores all results for later retrieval and search
- Provides fast responses for small uploads while efficiently handling large batches
Your design should cover:
-
API Interface
- How clients submit files (single vs. bulk)
- Response format (immediate vs. asynchronous)
-
System Architecture
- Workflow for calling the two ML services
- Storage approach for files, text, labels, and vectors
- Strategy to serve both latency-sensitive and throughput-heavy workloads
-
Scale & Performance
- Handling 1,000-file batches without memory issues or timeout failures
- Batching, queueing, and parallelism when interacting with ML services
-
Fault Tolerance & Monitoring
- Handling partial failures (some documents succeed, others fail)
- Logging, metrics, and error recovery
Remember: you can only call the ML services via their APIs; you cannot change how they work internally.
Hints
Hint 1
Separate the request acceptance layer from processing—async patterns help with large uploads
Hint 2
Both ML services can likely accept batched requests; take advantage of this to reduce round trips
Hint 3
Consider using object storage with presigned URLs to avoid streaming gigabytes through your API servers
Hint 4
Use priority queues or multiple lanes to ensure small uploads don't wait behind large batches
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Orchestrating Classification and Embedding Services at Scale
Core Challenge
This problem tests your ability to coordinate external rate-limited services under two opposing goals: interactive responsiveness for small requests and high throughput for bulk workloads. The key is building a unified architecture that handles both without creating separate code paths.
1. Clarifying Assumptions and Scale
Start by establishing concrete numbers:
| Parameter | Assumed Value |
|---|---|
| File size | Up to 10 MB, typically ~20 documents per file |
| Bulk upload | 1,000 files ≈ 20,000 documents, 1–10 GB total |
| Daily volume | ~5 million documents, with 10× peak traffic |
| Single-file latency target | p95 < 2 seconds end-to-end |
| Bulk processing target | Complete within minutes (limited by ML service quotas) |
| Embedding size | 768 floats ≈ 3 KB per document |
| ML service characteristics | Accept batches (~64 docs), have rate limits, 100–300 ms per batch |
Questions to ask:
- What are the ML services' rate limits and batch size constraints?
- Do documents have token limits?
- Is result ordering required?
- What consistency model do we need (strong vs. eventual)?
2. API Design
Single/Small Upload (synchronous with fallback)
POST /v1/files
Content-Type: multipart/form-data
Idempotency-Key: <uuid>
→ 200 OK (if completed in ~2s)
{
"file_id": "f_abc123",
"documents": [{
"doc_id": "d_xyz789",
"label": "invoice",
"embedding_id": "e_123"
}]
}
→ 202 Accepted (if still processing)
{
"file_id": "f_abc123",
"status_url": "/v1/files/f_abc123/status"
}
Bulk Upload (always asynchronous)
POST /v1/batches
{
"files": [{"name": "doc1.txt", "size": 1024, "sha256": "..."}],
"callback_url": "https://client.com/webhook"
}
→ 201 Created
{
"batch_id": "b_def456",
"uploads": [{
"file_id": "f_abc123",
"upload_url": "https://storage.../presigned"
}]
}
POST /v1/batches/{batch_id}/commit
→ 202 Accepted
{
"batch_id": "b_def456",
"status_url": "/v1/batches/b_def456"
}
Status & Results
GET /v1/batches/{batch_id}
→ {"state": "processing", "total": 1000, "completed": 847, "failed": 3}
GET /v1/batches/{batch_id}/results?cursor=abc
→ paginated per-file results with errors
POST /v1/batches/{batch_id}/retry
→ re-process only failed items
POST /v1/search
{"query_text": "...", "k": 10, "filters": {"user_id": "u_123", "label": "invoice"}}
Using presigned URLs keeps the API tier stateless—large files never flow through API servers, eliminating out-of-memory risks.
3. Data Storage
Object Storage (S3/GCS)
raw/{user_id}/{file_id}— original uploaded filesparsed/{doc_id}.txt— extracted text, content-addressed by hash
Relational Database (PostgreSQL, sharded by user_id)
batches— batch metadata, state, countersfiles— file tracking, links to batch, processing statedocuments— doc metadata, label, processing state, timestamps, model versions
Vector Database (Milvus, Pinecone, or pgvector)
- Store
(doc_id, vector, user_id, label, file_id, model_version) - Enables filtered semantic search ("find similar documents labeled 'contract'")
Storing model versions enables backfills when services upgrade.
4. Architecture
Client → API Gateway → Upload Service → Object Storage
↓
Parse Queue → Parser Workers
(extract text, create document records)
↓
Priority Queues: [interactive | bulk] × [classify | embed]
↓
Dispatcher Workers (batch, rate limit, retry)
↓ ↓
Classification Service Embedding Service
↓ ↓
Result Writers → Database + Vector Index
↓
Status Aggregator (update batch state, webhooks)
How This Serves Both Latency and Throughput:
- Priority lanes: Small uploads go to
interactivequeues; bulk uploads usebulkqueues - Weighted scheduling: Dispatchers always process interactive work first and reserve guaranteed capacity (e.g., 30% of quota). Bulk work uses remaining capacity
- Synchronous wait pattern: For single files, API server enqueues work and waits on a notification channel (Redis pub/sub) for ~2 seconds. If complete, return 200; otherwise 202. One code path, no special fast-path logic
- Parallel processing: Classification and embedding run independently—documents can get labels before embeddings
5. Batching and Concurrency
Micro-batching Strategy
Dispatcher workers flush a batch when either condition triggers:
- Batch size reaches limit (e.g., 64 documents)
- Time threshold expires (5 ms for interactive, 50–100 ms for bulk)
This is the key latency/throughput tradeoff. Interactive pays minimal queue delay; bulk achieves maximum batch efficiency.
Rate Limiting & Concurrency Control
- Token bucket controls requests per second to ML services
- Adaptive concurrency (AIMD algorithm): back off on 429s or rising p99 latency, gradually increase when healthy
- Throughput = concurrency × batch_size / latency
- Example: 32 concurrent requests × 64 docs per batch / 0.3s latency ≈ 6,800 docs/s
Memory Management
- Stream files during parsing; never load 1,000 files into memory
- Queue messages contain
doc_idand text URI, not full text - Bounded queue sizes create backpressure that propagates upstream
Large Document Handling
When documents exceed token limits:
- Truncate to first N tokens (simplest)
- Chunk and either store chunk-level vectors or mean-pool into one document vector
- Classify only from document prefix or generated summary
Choice depends on use case; state your pick explicitly.
Deduplication
Key results by (content_hash, model_version). Re-uploaded identical documents skip ML calls entirely—major cost savings for bulk users.
6. Reliability & Error Handling
Retry Strategy
- Exponential backoff with jitter for 429/5xx/timeout errors
- After N attempts (e.g., 5), move to dead-letter queue with error details
- Per-document retry tracking prevents infinite loops
Poison Document Isolation
- If a batch call fails, bisect the batch to isolate problematic documents
- One malformed document shouldn't fail 63 valid ones
Partial Failure Handling
- Per-document states:
pending | succeeded | failed - Batch-level aggregates show partial completion
- Retry endpoints re-process only failed items
Idempotency
- Accept
Idempotency-Keyheader on all write operations - Upsert results by
(doc_id, processing_stage, model_version) - Duplicate deliveries are no-ops
Monitoring
- Metrics: processing latency (p50/p95/p99), throughput, ML service call success rate, queue depths, error rates by type
- Logging: structured logs with
trace_idlinking all operations for a file/batch - Alerting: spikes in error rates, queue buildup, ML service availability, p99 latency SLO violations
7. Common Mistakes to Avoid
- Loading entire batches into memory: Use streaming and message passing instead
- Synchronous processing in API handlers: Always decouple acceptance from processing
- Single queue for all work: Priority separation is essential for latency SLOs
- Batch-level retries only: Track and retry at document granularity
- Ignoring idempotency: Network issues cause duplicates; design for them
- Not storing model versions: Makes model upgrades and backfills impossible
Complexity Analysis
- Latency: Single small file ~2s (network + ML service time + minimal queue delay)
- Throughput: Limited by ML service quotas; architecture enables full utilization
- Storage: O(n) for n documents, ~3 KB per vector
- Cost: Deduplication and batching minimize ML API calls
This architecture scales horizontally (add more workers), handles failures gracefully, and meets both interactive and batch SLOs with a single unified pipeline.