Building a Production Pipeline for Photo Object Recognition
System DesignModel answerLast updated
Design a scalable, reliable service that accepts images, runs object-detection models on GPUs, and returns labeled bounding boxes through sync and bulk APIs, with ML lifecycle and operations covered.
You are asked to design a platform that receives user-supplied images, finds the objects in them, and exposes the findings through APIs. For every image, the service returns bounding boxes, class labels and confidence scores.
Walk through the design end to end. Your answer should cover:
Requirements
- Functional needs: what clients send (raw bytes, URL or storage reference), what they receive, how model versions are chosen, and how results are retrieved later.
- Non-functional targets: accuracy, latency, throughput, availability and durability. State your assumptions with numbers.
- Clarifying questions you would ask (fixed vs. custom classes, multi-tenancy, sensitive content, data residency).
Architecture
- Ingestion, storage, preprocessing, model serving, and asynchronous workers and queues.
- Interactive (single-image) versus bulk (many-image) request paths.
- Metadata, dataset and model versioning.
Serving efficiency
- Batching, GPU utilization, autoscaling and caching.
- Capacity estimation.
Modeling and ML lifecycle
- Single-stage versus two-stage detectors and when to use each.
- Labeling and training pipeline, including how hard or uncertain examples are fed back.
- Offline evaluation metrics and online monitoring.
- A/B testing and safe rollout.
Operations and governance
- Failure modes and backpressure.
- Privacy and compliance.
- Cost controls.
- Rollback and blue-green or canary deployment.
Be explicit about the trade-offs you make and why.
Hints
Hint 1
Start by fixing numbers: daily volume, peak-to-average ratio, average image size and a latency budget for the interactive path. Everything else (GPU count, storage, queue sizing) follows from these.
Hint 2
Split traffic into two paths: a low-latency interactive path with small batches, and a throughput-oriented bulk path fed by a durable queue with large batches. Give each its own worker pool and scaling signal.
Hint 3
For the ML lifecycle, think in loops: versioned data plus code plus config produce a registered model; a frozen golden test set gates promotion; canary and shadow traffic validate in production; low-confidence and user-corrected samples flow back into labeling.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Questions to ask first: Is the class list fixed (COCO-like) or customer-defined? Is the service multi-tenant? Do images contain sensitive content such as faces or license plates? Are there data-residency rules?
Assumptions I would state:
| Dimension | Target |
|---|---|
| Volume | 10M images/day, about 115 QPS average, about 600 QPS peak (5x) |
| Image size | about 500 KB, so roughly 5 TB/day raw |
| Interactive latency | p50 < 100 ms, p99 < 300 ms server-side, excluding upload |
| Bulk latency | p99 under 5 minutes per job |
| Availability | 99.9% for the interactive API; bulk jobs are durable and never lost |
| Quality | mAP@[.5:.95] at or above the current baseline; recall of at least 0.9 at 0.9 precision on priority classes |
2. API surface
POST /v1/detect: image bytes or URL, optional model, min confidence and class filter. Returns image_id, model_version and a list of {label, score, box}.POST /v1/jobs: list of image URIs, callback URL, model. Returns 202 with a job_id. Idempotency keys are required.GET /v1/jobs/{id}andGET /v1/results/{image_id}for status and retrieval.POST /v1/feedback: corrected boxes go to the labeling queue.- Per-tenant authentication, rate limits and quotas at the gateway.
3. Architecture
Client -> API gateway (auth, quotas)
-> Detect service
sync: CPU preprocess -> inference gateway -> GPU model servers -> postprocess -> response
async: object store -> queue (Kafka/SQS) -> GPU workers -> results DB -> webhook
Cache (Redis): sha256(image)+model_version+params -> result
Feedback and low-confidence samples -> labeling -> training -> registry -> canary
Storage:
- Object store for raw images, keyed by tenant/date/hash, with lifecycle rules (for example delete after 30 days unless retention is opted into).
- Metadata DB (Postgres or DynamoDB) for images, jobs and detections.
- Model registry holding ONNX/TensorRT artifacts with training-data snapshot ID, metrics and owner.
- Versioned datasets (DVC or LakeFS manifests) so any model is reproducible from code commit, data snapshot and config.
Preprocessing (decode, validate, letterbox to about 640x640, normalize) runs on a CPU tier so GPUs only do tensor math. If decoding becomes the bottleneck, move it to GPU with a library such as DALI.
4. Model choice
- Single-stage (YOLO-family, RetinaNet, RT-DETR): one pass, roughly 5-15 ms on a T4/A10-class GPU with TensorRT. Slightly weaker on small or occluded objects. Default for the interactive path.
- Two-stage (Faster/Cascade R-CNN): better localization but 3-5x slower. Use on the bulk tier, for auditing, and as a teacher for distillation or pseudo-labeling.
A tiered setup is sensible: serve fast online, run the heavy model on a sample offline to audit and generate labels.
5. Serving efficiency
Dynamic batching. The server waits up to a few milliseconds (5-10) or until the batch is full (16-32). This typically gives 3-5x throughput over batch size 1. Tune the wait against the p99 budget.
Separate pools. Interactive: small batches, short delay, on-demand GPUs. Bulk: batches of 64 or more, near-full utilization, spot GPUs (jobs are retryable).
Other levers. FP16 or INT8 (validate calibration against an mAP regression check), multiple model instances per GPU to overlap copy and compute, pinned memory.
Capacity. At about 400 img/s per GPU with batching, 600 QPS peak needs roughly 2 GPUs. Provision 4-6 for N+2 and multi-AZ. Size the bulk pool from the backlog SLA.
Autoscaling. Scale on queue depth (for example KEDA on Kafka lag) and inference latency or GPU utilization, not CPU. GPU nodes cold-start in minutes, so keep warm minimum replicas, pre-pull images and use predictive scaling for daily peaks.
Caching. Content-addressed key of image hash, model version and normalized params. Duplicate uploads are common (10-30% hit rate is plausible), and including the model version gives automatic invalidation on release.
6. Training, labeling and evaluation
- Fine-tune from pretrained weights on domain data.
- Label with guidelines, consensus on a subset and inter-annotator agreement checks.
- Use active learning to pick samples: low confidence, disagreement between online and teacher models, user feedback, rare classes.
- Keep a frozen, versioned golden set that never enters training, plus slice sets (night, small objects, per customer).
- Orchestrate as snapshot, train, evaluate, register, with all metrics logged.
Offline metrics: mAP@[.5:.95], [email protected], per-class AP, small/medium/large AP, recall at fixed precision for critical classes, plus latency and memory per model.
Online monitoring: latency percentiles, GPU utilization, queue lag, error rate; and ML signals such as confidence histograms, detections per image, class distribution drift and input-size drift. Labels arrive late, so use proxies (feedback rate, audit-model disagreement) and a small continuously labeled sample.
7. Rollout and A/B testing
- Shadow the new model on live traffic and compare outputs without exposing them.
- Canary at 1%, 5%, 25%, then 100%, with automatic rollback on latency, error or drift guardrails.
- Blue-green for infrastructure changes: keep the previous fleet warm, flip traffic at the gateway, and roll back by flipping back.
- Since ground truth is delayed, A/B decisions rely on audit-model agreement, feedback rate and sampled human review, with enough sample size per slice.
8. Failure modes and backpressure
- Queue growth: bounded queues, per-tenant quotas, and 429 with Retry-After on the interactive path.
- Overload: shed or degrade (smaller model, lower resolution) before timing out.
- Bad inputs: reject corrupt, oversized or decompression-bomb images at preprocessing.
- Worker crashes: at-least-once delivery with idempotent writes, retries with backoff and a dead-letter queue.
- GPU or node failure: health checks, multi-AZ, and enough headroom to lose a node.
- Poison model: registry gates plus the canary guardrails above.
9. Privacy, compliance and cost
- Encrypt in transit and at rest, enforce tenant isolation, and keep audit logs.
- Retention limits with deletion on request; regional storage for residency.
- Optional face or plate blurring, and no training on customer data without consent.
- Cost: spot GPUs for bulk, INT8/FP16, right-sized batches, cache hits, tiered storage for old results, and scale-to-minimum off-peak.
Common mistakes
- Scaling GPU services on CPU metrics.
- Ignoring cold-start time when autoscaling.
- Using one pool for latency-sensitive and bulk work.
- Leaking the golden set into training.
- Quantizing without an accuracy regression gate.
- Treating monitoring as infra-only and missing data drift.
- Forgetting idempotency in the async path.