Building Production HTTP APIs for ML Model Serving
System DesignModel answerLast updated
Design a production-grade REST API for serving machine learning predictions on images, covering endpoints, schemas, auth, reliability, and safety.
You're building an HTTP API that will serve predictions from a machine learning model that processes images. Your API needs to handle both real-time requests and batch processing workloads.
Design a complete API specification that addresses:
-
Core endpoints and patterns: What HTTP endpoints will you expose? How will you handle synchronous vs. asynchronous requests? What versioning strategy will you use, and how do you ensure safe retries?
-
Request and response design: What formats will you accept for image data? Define the JSON schemas for requests and responses. How will you represent errors in a standard way? What HTTP status codes map to which scenarios?
-
Security and access control: How will clients authenticate? How will you implement authorization with different permission levels? What rate limiting strategy will you use, and how do you prevent abuse?
-
Evolution and compatibility: How will you evolve the API over time without breaking existing clients? What's your deprecation process for old versions or endpoints?
-
Operational concerns: How will you handle personally identifiable information in images? What security measures will you implement for image uploads? How will you make the API observable (logging, metrics, tracing)?
-
OpenAPI specification: Provide a concrete OpenAPI 3.0 snippet for at least one endpoint showing parameters, request/response schemas, and error cases.
Explain your design choices and trade-offs. Consider that the service will handle thousands of requests per second, support multiple tenants, and run on GPU infrastructure where compute time is expensive.
Hints
Hint 1
Consider separating fast single-image predictions from slow batch jobs into different endpoint patterns
Hint 2
Think about how to make POST requests safe to retry when network failures happen mid-request
Hint 3
Image URLs as input create security risks - what attack vectors need protection?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Production ML Inference API Design
Understanding the Problem Space
This question tests whether you can design APIs that are not just functional but production-ready. The interviewer wants to see:
- Recognition that inference workloads have different latency profiles (milliseconds vs. minutes)
- Understanding that retries without proper idempotency can cause duplicate billing on expensive GPU infrastructure
- Awareness of image-specific security concerns (malicious payloads, server-side request forgery)
- Ability to design for evolution and multi-tenancy from day one
Start by clarifying scope with the interviewer. For this answer, I'll assume:
- Peak load: ~10,000 req/sec for single-image predictions
- Latency target: p99 under 500ms for synchronous calls
- Image sizes: up to 15MB, formats JPEG/PNG/WebP
- Multi-tenant SaaS with both internal services and external customers
- GPU backend where cost scales with image resolution and batch size
1. Endpoint Design and Idempotency
Core Endpoints
| HTTP Method | Path | Purpose | Idempotent |
|---|---|---|---|
| POST | /v1/predictions | Single image, synchronous response | Via header |
| POST | /v1/batches | Submit batch job, returns immediately | Via header |
| GET | /v1/batches/{id} | Check job status and progress | Yes |
| GET | /v1/batches/{id}/output | Retrieve completed results | Yes |
| PATCH | /v1/batches/{id} | Cancel running batch | Yes |
| GET | /v1/models | List available models | Yes |
Versioning Strategy
Use path-based versioning (/v1, /v2) for major API contract changes. The version in the path represents the HTTP interface contract, not the ML model version.
Model versions are specified in the request body:
{
"model": "object-detection:v3.1.4"
}
Clients can also use semantic aliases like object-detection:stable or object-detection:latest. The response always includes the resolved version for reproducibility.
Idempotency Implementation
For POST operations, require an Idempotency-Key header (UUID v4). The server maintains a cache mapping (tenant_id, idempotency_key) to stored responses for 24 hours.
Idempotency logic:
- First request with key K: process normally, cache
(request_body_hash, response)with key K - Retry with same K and same body: return cached response immediately (any status code, including errors)
- Same K but different body: return
422 Unprocessable Entity - Same K while original is still processing: return
409 ConflictwithRetry-After
This ensures retries after network failures don't cause duplicate GPU computation or double billing.
2. Request and Response Schemas
Input Format Options
Support two content types:
Option A: multipart/form-data (recommended for binary uploads)
POST /v1/predictions
Content-Type: multipart/form-data
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
--boundary
Content-Disposition: form-data; name="image"; filename="photo.jpg"
Content-Type: image/jpeg
[binary data]
--boundary
Content-Disposition: form-data; name="parameters"
Content-Type: application/json
{"model": "object-detection:stable", "confidence_threshold": 0.85}
Option B: application/json with image reference
{
"image_url": "https://trusted-storage.example.com/uploads/abc123.jpg",
"model": "object-detection:stable",
"parameters": {
"confidence_threshold": 0.85
}
}
Also support image_base64 for small images, but cap at ~8MB since base64 encoding adds 33% overhead.
Success Response
{
"request_id": "req_2J9mKP3x4L",
"model": {
"name": "object-detection",
"version": "3.1.4"
},
"results": [
{
"class": "person",
"confidence": 0.94,
"bounding_box": {"x": 120, "y": 50, "width": 180, "height": 340}
}
],
"metadata": {
"inference_time_ms": 87,
"queue_time_ms": 12
}
}
Error Responses
Use RFC 7807 Problem Details (application/problem+json):
{
"type": "https://api.example.com/problems/image-format-unsupported",
"title": "Unsupported Image Format",
"status": 415,
"detail": "Only JPEG, PNG, and WebP formats are supported",
"request_id": "req_2J9mKP3x4L",
"instance": "/v1/predictions"
}
Status Code Strategy
| Code | Scenario | Retry Safe? |
|---|---|---|
| 200 | Success | - |
| 202 | Batch accepted | - |
| 400 | Malformed request syntax | No |
| 401 | Invalid/expired token | No (refresh token first) |
| 403 | Insufficient permissions | No |
| 404 | Unknown batch/model ID | No |
| 409 | Idempotency key conflict | Yes, after delay |
| 413 | Payload too large | No |
| 415 | Unsupported media type | No |
| 422 | Validation failed | No |
| 429 | Rate limit exceeded | Yes, respect Retry-After |
| 500 | Internal error | Yes, with backoff |
| 503 | Service overloaded | Yes, with backoff |
| 504 | Gateway timeout | Yes, with backoff |
Retry policy for clients: Use exponential backoff with jitter: sleep = random(0, min(max_delay, base * 2^attempt)) where base=200ms, max_delay=30s, max 4 retries. Always reuse the same idempotency key.
3. Authentication, Authorization, and Rate Limiting
Authentication
Use OAuth 2.0 / OpenID Connect:
- Machine-to-machine: OAuth 2.0 client credentials flow
- User applications: Authorization code flow with PKCE
- Tokens: Short-lived JWTs (15 min), verified against cached JWKS
JWT validation checklist:
- Verify signature with public key from JWKS endpoint
- Validate
iss,aud,exp,nbfclaims - Allow ±90s clock skew
- Reject algorithm
noneand prevent HS/RS confusion attacks - Extract tenant ID from registered claim (never trust client-provided tenant ID)
Authorization
Use scope-based permissions:
predictions:create- Submit single predictionsbatches:create- Submit batch jobsbatches:read- View batch status and resultsmodels:read- List available modelsadmin- Administrative operations
Every resource includes tenant ownership. Job lookups verify job.tenant_id == token.tenant_id to prevent IDOR (Insecure Direct Object Reference) vulnerabilities.
Rate Limiting
Implement token bucket algorithm at the API gateway level with Redis-backed counters.
Key insight: weight requests by computational cost, not just count. One 8MP image consumes more GPU time than one 0.5MP image.
cost = ceil(width * height / 1_000_000) # megapixels
Limits per tenant:
- 1000 credits/second for sync predictions
- 100 concurrent batch jobs
- 1M credits/month quota
Response headers:
RateLimit-Limit: 1000
RateLimit-Remaining: 847
RateLimit-Reset: 1640000000
Retry-After: 5
When limits exceeded, return 429 Too Many Requests with appropriate Retry-After value.
4. Backward Compatibility and Deprecation
API Evolution Rules
Safe additive changes (no version bump):
- Add optional request fields
- Add response fields (clients must ignore unknown fields)
- Add new endpoints
- Add enum values (clients must handle unknown values gracefully)
Breaking changes (require new major version):
- Remove or rename fields
- Change field types
- Make optional fields required
- Change validation rules to be stricter
- Change semantic meaning
Client Contract
Clients must:
- Ignore unknown fields in responses
- Treat enums as open sets (don't crash on new values)
- Not rely on field ordering in JSON
Deprecation Process
- Announcement (T-0): Release notes, email notifications, dashboard banner
- Headers (T+0): Add
Deprecation: trueandSunset: Sat, 31 Dec 2025 23:59:59 GMTheaders - Grace period: Minimum 12 months for API versions, 6 months for model versions
- Usage tracking: Monitor per-tenant usage of deprecated features
- Targeted outreach: Contact heavy users of deprecated features
- Brownout testing (T+10 months): Scheduled 1-hour outages to force client updates
- Final removal (T+12 months): Remove feature, return
410 Gone
5. Security and Privacy
Transport Security
- TLS 1.3 only on public endpoints
- HSTS headers with long max-age
- mTLS for service-to-service communication
Image Upload Security
File validation:
- Check magic bytes, don't trust
Content-Type - Limit dimensions (e.g., 50 megapixels) to prevent decompression bombs
- Process uploads in sandboxed workers with resource limits
- Scan for malware signatures
URL fetching (SSRF prevention):
When accepting image_url:
- Only HTTPS, no HTTP
- Maintain allowlist of trusted domains
- Block RFC 1918 private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
- Block link-local (169.254.0.0/16)
- Block localhost/127.0.0.0/8
- Validate after DNS resolution and after each redirect
- Set connection timeout (5s) and total timeout (30s)
- Limit download size before starting transfer
PII Handling
Images may contain:
- Faces (biometric data)
- License plates
- Documents with names/addresses
- EXIF metadata with GPS coordinates
Mitigations:
- Strip all EXIF metadata on ingestion
- Log only metadata, never image contents or predictions
- Provide customer data deletion endpoints
- Document data retention policies clearly
- Consider region-specific compliance (GDPR, CCPA)
Audit Logging
Maintain tamper-evident audit log separate from application logs:
- Who:
subject_id,client_id,tenant_id - What: endpoint, method, model version, resource IDs
- When: ISO 8601 timestamp
- Where: source IP, geolocation
- Outcome: status code, error type
- Correlation:
request_id
Store in append-only system with separate retention policy (7 years for compliance).
6. Observability
Structured Logging
Use JSON logs with consistent schema:
{
"timestamp": "2025-01-15T10:30:45.123Z",
"level": "INFO",
"request_id": "req_2J9mKP3x4L",
"tenant_id": "tenant_abc",
"endpoint": "/v1/predictions",
"method": "POST",
"status": 200,
"duration_ms": 104,
"model": "object-detection:3.1.4",
"image_size_bytes": 2847291,
"image_dimensions": "1920x1080"
}
Generate unique request_id at ingress, propagate through all services, return in responses and error messages.
Metrics
Key metrics to track:
- Request rate by endpoint, tenant, status code
- Latency percentiles (p50, p95, p99)
- Error rate by type
- GPU utilization and queue depth
- Model inference time distribution
- Image size distribution
- Rate limit hit rate
Use labels carefully—high cardinality (per-user) causes metric explosion.
Distributed Tracing
Implement OpenTelemetry tracing with spans for:
- HTTP request handling
- Authentication/authorization
- Image download/validation
- Model inference
- Response serialization
Propagate trace context via W3C Trace Context headers.
7. OpenAPI 3.0 Specification Example
openapi: 3.0.3
info:
title: ML Inference API
version: 1.0.0
paths:
/v1/predictions:
post:
summary: Submit single image for prediction
operationId: createPrediction
security:
- oauth2: [predictions:create]
parameters:
- name: Idempotency-Key
in: header
required: true
schema:
type: string
format: uuid
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [image]
properties:
image:
type: string
format: binary
description: Image file (JPEG, PNG, or WebP)
parameters:
type: object
properties:
model:
type: string
example: "object-detection:stable"
confidence_threshold:
type: number
minimum: 0
maximum: 1
default: 0.5
responses:
'200':
description: Prediction successful
content:
application/json:
schema:
type: object
properties:
request_id:
type: string
model:
type: object
properties:
name:
type: string
version:
type: string
results:
type: array
items:
type: object
properties:
class:
type: string
confidence:
type: number
bounding_box:
type: object
'401':
description: Authentication failed
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
'413':
description: Image too large
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
'429':
description: Rate limit exceeded
headers:
Retry-After:
schema:
type: integer
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
components:
securitySchemes:
oauth2:
type: oauth2
flows:
clientCredentials:
tokenUrl: https://auth.example.com/oauth/token
scopes:
predictions:create: Submit predictions
schemas:
Problem:
type: object
properties:
type:
type: string
format: uri
title:
type: string
status:
type: integer
detail:
type: string
request_id:
type: string
Common Mistakes to Avoid
- No idempotency: Retries cause duplicate GPU billing
- Trusting Content-Type: Attackers upload malicious files with fake headers
- No URL validation: SSRF allows scanning internal networks
- Logging sensitive data: PII in logs creates compliance risk
- Tight coupling: Changing model versions breaks clients
- Count-based rate limiting: One huge image == one tiny image
- No request IDs: Debugging distributed failures becomes impossible
This design balances pragmatism with production-readiness, focusing on the non-negotiable requirements for a multi-tenant ML API serving real traffic.