We are building a streaming NLP inference platform with on-demand model swapping. The platform needs:
- Configuration management: store and retrieve model configurations, versions, etc.
- Warmup flows: when a new model is loaded, we need to warm it up (e.g., load into memory, run a few dummy inferences)
- AB guardrails: ability to do A/B testing between models, with traffic splitting and guardrails (e.g., latency, error rates) to rollback automatically.
- Telemetry dashboards: monitor the performance of models (latency, throughput, errors, etc.)
We need to design a system that handles these requirements. We'll break down the components:
High-level architecture:
- A configuration store (database) to keep model configurations, versions, and A/B testing setups.
- A model registry: where model artifacts are stored (e.g., S3, model repository).
- An inference service: that loads models and serves predictions. It should be able to swap models on-demand (without restart) and support A/B testing by routing requests to different model versions based on configuration.
- A warmup service: that can trigger warmup for a new model version when it's promoted.
- A telemetry collector: that collects metrics from the inference service (latency, errors, etc.) and stores them for dashboards.
- A dashboard: to visualize telemetry and manage configurations, A/B tests, etc.
Detailed components:
-
Configuration Management:
- Use a database (e.g., PostgreSQL) to store:
models: id, name, artifact_uri (path to model in S3), version, status (e.g., "loading", "active", "failed", etc.)
ab_tests: id, test_name, model_a_id, model_b_id, traffic_split (e.g., 50/50), start_time, end_time, status (active, paused, completed)
guardrails: thresholds for metrics (e.g., if error rate > 5% for model A, then switch 100% to model B, or rollback to previous version)
- Provide an API (or admin UI) to manage these configurations.
-
Inference Service:
- Should be a long-running service (e.g., in Python with FastAPI) that loads models on demand.
- It should have a model cache (dictionary) of loaded models. When a new model is needed, load it from the artifact URI (using a model loader, e.g., for PyTorch, TensorFlow, etc.)
- The service should periodically check the configuration (or be notified via a message queue) for changes (e.g., new model version, A/B test update).
- For A/B testing: when a request comes in, decide which model to use based on the current A/B test configuration (e.g., hash of user_id mod 100). Then run inference with that model.
- Should expose an endpoint for inference (e.g.,
/predict) and an endpoint for health checks.
- Should collect telemetry (latency, success/failure) per model version and per A/B test.
-
Warmup Flow:
- When a new model version is created and marked as "active" (or when A/B test starts), we need to warm it up.
- Warmup: load the model into memory and run a few dummy inferences (with sample inputs) to initialize any lazy loading and JIT compilation.
- We can have a separate warmup service that listens for events (e.g., when a model is promoted) and then triggers warmup by calling the inference service's warmup endpoint (or directly loading the model in a separate process).
- Alternatively, the inference service can do warmup when it first receives a request for that model? But that would cause the first real request to be slow. So we want to pre-warm.
-
AB Guardrails:
- Monitor the telemetry (errors, latency) for each model in the A/B test.
- If a model violates guardrails (e.g., error rate too high, latency too high), then automatically adjust the traffic split or rollback to the previous version.
- This can be a separate service (or part of the inference service) that periodically checks the telemetry and updates the configuration (e.g., update the
ab_tests table to change traffic split, or set model status to "failed" and stop using it).
-
Telemetry and Dashboards:
- The inference service should emit metrics (e.g., using Prometheus client library) for each model version and for A/B tests.
- Set up a Prometheus server to scrape these metrics.
- Use Grafana to create dashboards showing:
- Requests per second per model
- Error rates
- Latency percentiles (p50, p95, p99)
- A/B test traffic split
- Also, we might want to log each request (with model version, response time, success) to a database (e.g., Elasticsearch) for more detailed analysis and debugging.
Workflow Example:
-
Deploy a new model version (v2) of " sentiment-analysis ":
- Upload model artifact to S3.
- Insert into
models table: name="sentiment-analysis", version=2, artifact_uri="s3://bucket/models/sentiment/v2/", status="created".
- Create an A/B test between v1 (current) and v2: insert into
ab_tests with traffic_split 50/50, status="active".
- Trigger warmup for v2 (maybe by setting status to "warming_up" and then "active" after warmup completes).
-
Warmup service (or inference service on notification) loads v2 and runs dummy inferences. If successful, set model status to "active". If fails, set to "failed".
-
Inference service:
- When a request comes in for "sentiment-analysis", check the active A/B test for that model.
- Use traffic split to decide which version (v1 or v2) to use.
- Load the model if not already loaded (but should be warmed up already).
- Run inference and record metrics (latency, success) with labels: model_version, ab_test_id.
-
Guardrails service:
- Every minute (or configurable interval), query the telemetry (from Prometheus or from a time-series database) for each model in active A/B tests.
- Check if any model violates guardrails (e.g., error rate > 5% over last 5 minutes). If yes, then:
- Option 1: adjust traffic split to 0% for that model (and 100% to the other).
- Option 2: if both models are bad, rollback to a previous known good version (maybe the one before the A/B test?).
- Update the
ab_tests table accordingly and notify the inference service (or the inference service re-reads config periodically).
-
Dashboard:
- Grafana panels showing the metrics and A/B test status.
Implementation Considerations:
- Model Loading: Different model frameworks (PyTorch, TensorFlow, etc.) have different ways to load. We can have a plugin system for model loaders.
- Concurrency: The inference service should handle concurrent requests. Models might be GPU-based, so we need to manage GPU memory and possibly batch requests.
- Hot Swapping: We need to be able to add new models and remove old ones without downtime. The inference service should be able to unload models that are no longer used (but careful with memory). We can use reference counting: if a model is not used in any active A/B test, unload it after some idle time.
- Configuration Propagation: How does the inference service know about config changes? We can have it poll the database periodically, or use a message queue (e.g., Redis Pub/Sub, RabbitMQ) to push updates. Polling is simpler.
- Warmup Triggers: We can set a flag in the
models table: needs_warmup. When a new model is inserted, set it to true. Warmup service picks up models with needs_warmup and status "created" or "active", warms them, then sets needs_warmup to false and updates status.
- Guardrails: The guardrails can be defined per A/B test or globally. We can store guardrail thresholds in the
ab_tests table or in a separate guardrails table.
Technology Stack Example:
- Backend (Inference Service): Python, FastAPI, PyTorch/TensorFlow, Redis (for caching models? maybe not needed if models are in memory), Prometheus client.
- Configuration DB: PostgreSQL.
- Model Artifact Store: AWS S3 or similar.
- Warmup Service: Can be a separate microservice (or part of inference service) that uses the same model loading code.
- Telemetry: Prometheus + Grafana, plus maybe ELK stack for logs.
- Message Queue: Optional, for decoupling (e.g., when a model is promoted, publish an event that warmup service consumes).
API Design:
-
/predict (POST): body: { "model_name": "sentiment", "inputs": [...] }
- Response:
{ "predictions": [...], "model_version": "2" }
- The service routes to the appropriate model based on A/B test.
-
/warmup (POST): { "model_id": 123 } - trigger warmup for model.
-
/admin/models (GET/POST) - manage models (maybe use direct DB access for simplicity, but better to have an admin API).
-
/admin/ab-tests (GET/POST/PUT) - manage A/B tests.
-
/health - health check.
Deployment:
-
The inference service should be deployed with enough resources (CPU/GPU, memory) to hold multiple models if needed.
-
We might want to scale horizontally? But then we need to ensure that all instances have the same set of loaded models? Or we can use a shared model cache? That's tricky. Alternatively, we can have a model server per model and use a router (like TensorFlow Serving) but we want on-demand swapping and A/B testing at the request level. So maybe each instance loads all active models? That might not scale if many models. So we need to design for model size and number.
Alternative: Have a separate model server for each model (or model version) and then have a routing layer that does A/B testing and forwards requests to the appropriate model server. This way, each model server only holds one model. Then we can scale each model server independently. But then we need to manage many servers and routing.
Given the requirement of on-demand model swapping and A/B testing, it might be simpler to have a single inference service that can load multiple models. But if models are large, we might run out of memory. So we need to consider:
- If we have GPU, we might be able to load multiple models if they fit in GPU memory. Otherwise, we need to swap models in and out (which is slow). So maybe we should design so that each instance only loads a subset of models? But then routing becomes more complex.
Perhaps we can have a central configuration that says which models should be loaded on which instance? That adds complexity.
Given the scope, let's assume we have a limited number of active models (maybe 2-3) and they fit in memory. We can design for that and later scale by sharding models across instances.
Implementation Steps:
- Set up the database (PostgreSQL) with tables for models, ab_tests, guardrails.
- Build the model registry (S3) and a way to download and load models (with framework-specific loaders).
- Build the inference service:
- Load models on startup? No, load on demand.
- Have a
model_cache dictionary: key: model_id, value: loaded model and metadata.
- Check configuration (from DB) periodically (e.g., every 10 seconds) for changes:
- Check for new models (status="active" and not in cache) -> load and warmup? Or warmup separately.
- Check for A/B test updates.
- For each prediction request:
- Determine which model to use: look up active A/B test for the requested model_name. If none, use the latest active model (or the one marked as default?).
- If the model is not loaded, load it (but ideally it should be warmed up). We can block the request until loaded? That would be slow. So we need to ensure warmup happens before the model is used.
- Record metrics (latency, error) with labels: model_version, ab_test_id.
- Build warmup service:
- Poll DB for models with
needs_warmup and status "active" (or "created"?).
- For each, call the inference service's warmup endpoint (or load directly using same code). If success, set
needs_warmup=false and maybe set status="active". If fail, set status="failed".
- Build guardrails service:
- Query telemetry (from Prometheus via API or from a TSDB) for each active A/B test.
- Evaluate guardrails (defined per test or global).
- If violation, update the
ab_tests table (e.g., set traffic_split to 0 for bad model, or mark test as completed and maybe create a new test with only the good model?).
- Also, we might want to send alerts.
- Set up Prometheus to scrape metrics from inference service.
- Build Grafana dashboards.
- Build an admin UI (optional) to manage models and A/B tests.
Concurrency and Thread Safety:
-
The inference service will handle multiple requests. The model_cache should be thread-safe. In Python, we can use a lock when loading a model (so only one thread loads a given model). Once loaded, it's read-only for inference, so no lock needed for inference (assuming the model framework is thread-safe for inference). For PyTorch, we might need to use a lock if we use the same model instance from multiple threads? Actually, PyTorch models are not thread-safe by default for concurrent inference? We can use a thread pool and dispatch to multiple model instances? Or use async? Alternatively, we can have a per-model lock, but that would serialize predictions for that model. Better to have multiple copies of the model if we need high concurrency? That uses more memory.
We need to consider the expected load. For high throughput, we might want to batch requests. But for simplicity, we assume that the model can handle concurrent inference (e.g., TensorFlow Serving can). For PyTorch, we can use torch.set_num_threads and use a thread pool. But if we have multiple models, we need to manage resources.
Given the complexity, we can start with a simple approach: each model is loaded once and protected by a lock during inference. That limits concurrency to 1 per model. Not ideal but acceptable for low traffic. Later we can improve by using model parallelism or multiple instances.
Alternatively, we can use a queue per model and multiple workers (processes) each with a copy of the model. That would use more memory but allow parallel inference.
For now, we design for simplicity.
Code Structure for Inference Service (FastAPI):
app = FastAPI()
class ModelManager:
def __init__(self):
self.models = {} # model_id -> {"model": model_obj, "metadata": ..., "lock": threading.Lock()}
self.config = {} # config from DB, maybe cached
self.lock = threading.Lock() # for modifying self.models
def load_model(self, model_info):
# model_info from DB: id, artifact_uri, version, framework, etc.
# load using appropriate loader
# return model object
pass
def warmup(self, model_id):
# load model and run a few dummy inferences
pass
def get_model_for_request(self, model_name):
# Check A/B test configuration for model_name.
# Return model_id and model object.
# If model not loaded, load it (blocking? but we should warmup first to avoid blocking in request)
# So we should ensure that all active models are loaded and warmed up.
pass
def predict(self, model_id, inputs):
with self.models[model_id]["lock"]:
model = self.models[model_id]["model"]
# run inference
return predictions
model_manager = ModelManager()
@app.on_event("startup")
def startup_event():
# Start a background thread to periodically refresh config and warmup new models.
# Also, load any models that are active from the start?
pass
@app.post("/predict")
async def predict(request: Request):
body = await request.json()
model_name = body["model_name"]
inputs = body["inputs"]
model_id, model = model_manager.get_model_for_request(model_name)
start = time.time()
try:
predictions = model_manager.predict(model_id, inputs)
latency = time.time() - start
# record metric: INFERENCE_LATENCY seconds, model_version, ab_test_id (if any)
return {"predictions": predictions, "model_version": model.version}
except Exception as e:
latency = time.time() - start
# record error metric
raise
@app.post("/warmup")
async def warmup(model_id: int):
model_manager.warmup(model_id)
return {"status": "warmed"}
# metrics endpoint for Prometheus
@app.get("/metrics")
async def metrics():
return generate_latest()
Warmup Service:
- Separate service (or part of the same service but separate thread) that polls DB for models needing warmup.
- It can call the
/warmup endpoint of the inference service (if same service) or use the same ModelManager code.
Guardrails Service:
- Periodically (e.g., every minute) query Prometheus for metrics (e.g., using Prometheus HTTP API) for each active A/B test.
- Evaluate thresholds.
- Update DB accordingly.
Telemetry:
- Use Prometheus client in inference service to define counters and histograms.
- Example:
from prometheus_client import Counter, Histogram
INFERENCE_REQUESTS = Counter('inference_requests', 'Total inference requests', ['model_version', 'ab_test_id'])
INFERENCE_LATENCY = Histogram('inference_latency', 'Inference latency in seconds', ['model_version', 'ab_test_id'])
INFERENCE_ERRORS = Counter('inference_errors', 'Total inference errors', ['model_version', 'ab_test_id', 'error_type'])
- In predict function, record metrics accordingly.
Dashboard:
- Grafana: import Prometheus data source. Create panels:
- Rate of requests per model version.
- Error rate (errors/requests) per model version.
- Latency percentiles.
- A/B test traffic split (we can compute from requests? but we need to know which version was chosen for each request. We can record a metric for requests with label
model_version and ab_test_id. Then we can see the split by counting requests per version within an A/B test.
Challenges:
-
Stateful routing for A/B testing: We need to consistently route the same user (or session) to the same model version for the duration of the test. We can use a hash of user_id (if available) or session_id. In the inference service, we need to extract that identifier from the request (maybe from a header). If not provided, we can assign randomly per request? That would break consistency. So we should require a user_id or session_id in the request for A/B tests. Or we can use IP address? Not reliable.
We can design: For each A/B test, we assign a bucket to each version. Then for a request, we compute a hash of a key (like user_id) mod 100 and compare to the split. So we need a way to pass a user identifier. We can define that for requests that are part of an A/B test, the client must send a user_id or session_id. Otherwise, we might use a random assignment per request (but that would not be consistent). So we need to document that.
-
Model unloading: When a model is no longer used (e.g., A/B test ends, and no other tests use it), we can unload it to free memory. We need reference counting: how many A/B tests are using a model? We can compute by scanning the ab_tests table for active tests that include the model. If count==0, then unload after some idle time.
-
Warmup failures: If warmup fails, we should not use that model. We mark it as failed and possibly alert.
-
Guardrail evaluation: We need to define guardrails (e.g., error rate > 5% over 5 min). We need to decide the time window. We can query Prometheus for the rate of errors over the last 5 minutes and compare to threshold. Similarly for latency (e.g., p95 latency > 1000ms).
Simplification for MVP:
We can start without A/B testing: just one active model per model_name. Then add A/B testing later.
But the requirement says on-demand model swapping and A/B guardrails, so we need A/B testing.
Summary of Components to Build:
- Database schema for models and ab_tests.
- Inference service with model caching, config polling, A/B routing, metrics.
- Warmup service (could be a thread in inference service).
- Guardrails service (could be a separate service or part of inference service? Better separate to avoid affecting inference latency).
- Prometheus + Grafana setup.
- Admin UI (optional but nice).
We'll produce a design document and then start implementing.
Given the complexity, we might break the implementation into phases:
Phase 1: Basic inference service with single model (no A/B), config stored in DB, warmup, metrics.
Phase 2: Add A/B testing routing.
Phase 3: Add guardrails service.
Phase 4: Add admin UI and dashboards.
Let's start with Phase 1.
Phase 1: Basic Inference Service
-
DB: models table with columns: id, name, version, artifact_uri, framework (e.g., "pytorch", "tensorflow"), status ("created", "active", "warming_up", "failed"), created_at, updated_at.
-
Inference service:
- On startup, load all models with status="active" and warm them up? Or just load them? We can have a warmup endpoint and call it for each active model on startup.
- Periodic background thread (every 30 sec) to check for new active models (status="active" and not loaded) and load them (and warmup). Also check for models that are no longer active and unload them.
- For prediction: we assume only one active model per name? Actually, we can have multiple versions but only one active? In Phase 1, we don't have A/B, so we just pick the latest active version for a model name. We can have a concept of "default" active model. So we need to query DB: for a given model_name, get the active model (maybe there is only one active at a time? Or we could have multiple active but we need to choose one? Without A/B, we should have only one active per name. So we can enforce that in DB: only one model per name can have status="active". We can have a unique constraint on (name, status) where status='active'? But that might not be needed if we manage in code.
We can do: when activating a new model, deactivate the previous one.
So for prediction: find the model with given name and status='active'. If not found, error.
-
Warmup: after loading the model, run a few dummy inferences (using sample inputs from a config or hard-coded). We can store sample inputs in DB per model? Or use a generic one? For different frameworks, we need different sample inputs. We can require that the model artifact includes a sample_input.json file. Or we can define a standard input shape and generate random data. That might not work for models that require specific preprocessing. So we can have a warmup_script in the model artifact? That's complex.
For Phase 1, we can skip warmup or just do a simple forward pass with random data if we know the input shape. We can store input shape in DB: input_shape and input_type (e.g., "float32"). Then generate random array of that shape.
Alternatively, we can just load the model and not run inference during warmup. That might not trigger JIT compilation. But for many models, just loading might be enough. For PyTorch, we might need to run a forward pass to compile CUDA kernels? Actually, the first inference is slow due to various initializations. So we should run at least one inference.
We can have a simple warmup: after loading, run inference with a dummy input (e.g., zeros) of the expected shape. We need to know the expected shape. We can require that the model artifact includes a input_spec.json that describes the input shape and dtype.
Phase 2: A/B Testing
-
Modify DB: ab_tests table: id, model_name, model_a_id, model_b_id, traffic_split_a (percentage, 0-100), traffic_split_b, start_time, end_time, status ("active", "paused", "completed"), created_at.
- We assume two models only for now. Could be extended to multiple variants later.
-
Inference service: when predicting for a model_name, check if there is an active A/B test for that model_name. If yes, then use traffic split to decide which model (a or b). We need a consistent hash per user/session. We'll require a user_id header? Or we can generate a random bucket per request? But for consistency, we need a stable identifier. We can use user_id from request header if present, else fallback to random? But then the same user might get different models on different requests if no user_id. So we should require user_id for A/B tests? Or we can use IP address? Not reliable.
We can design: the client must provide a session_id or user_id in a header (e.g., X-User-Id) for requests that should be consistent. If not provided, we can treat it as a new user each time (so random assignment). That's acceptable for some use cases.
In the prediction endpoint, we'll look for a header X-User-Id. If present, compute hash(user_id) % 100, then compare to traffic_split_a (e.g., if < split_a, use model_a, else model_b). If no header, we can use a random number per request? But then it's not consistent for the same user if they don't send the header. So we might want to generate a session id on the server side and set a cookie? That's more complex.
For MVP, we'll require user_id header for A/B tests. If not provided, we return error? Or we can use a default model (maybe the control). We'll decide: if A/B test active and no user_id, use model_a (control) by default? Or random? Random would break consistency if the same user sometimes sends header and sometimes not. So better to require it.
Actually, we can do: if no user_id, assign a random bucket once and store in a cookie? That's client-side. Not under our control.
So we'll document that for A/B tests, the client must provide a consistent user identifier.
-
Warmup: when an A/B test becomes active, we need to warmup both models (if not already). So we need to mark both models as needing warmup. We can set a flag or rely on the periodic config refresh to load active models.
In Phase 1, we loaded active models. In Phase 2, we have A/B tests that make two models active for a given name. So we need to adjust: a model is considered active if it is either the sole active model for its name OR part of an active A/B test for its name. So we need a way to determine which models should be loaded. We can have a background task that:
Let's finalize Phase 1 tables:
CREATE TABLE models (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
version INTEGER NOT NULL,
artifact_uri TEXT NOT NULL,
framework VARCHAR(50) NOT NULL, -- e.g., 'pytorch', 'tensorflow'
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (name, version)
);
CREATE TABLE model_defaults (
model_name VARCHAR(255) PRIMARY KEY,
model_id INTEGER REFERENCES models(id) ON DELETE CASCADE
);
-- ab_tests table for Phase 2, but we can create it later.
For Phase 1, we don't have ab_tests. The inference service will query:
SELECT md.model_id FROM model_defaults md
to get the list of models to load.
Warmup Implementation:
When loading a model, we:
- Download the model artifact (from S3) to local disk (maybe cache).
- Load the model using the framework-specific loader.
- Run a warmup inference: we need a sample input. We can store sample input in the model artifact as
sample_input.json (or .npy for numpy). Or we can generate random data based on input shape. We'll require that the model artifact includes a input_spec.json that describes the input shape and dtype. Then we can generate random data accordingly.
For example, for PyTorch:
input_shape = [batch_size, ...] # from spec
dtype = torch.float32 if spec says float32.
dummy_input = torch.randn(*input_shape, dtype=dtype)
with torch.no_grad():
output = model(dummy_input)
For TensorFlow:
dummy_input = np.random.randn(*input_shape).astype(np.float32)
output = model(dummy_input)
We can have a generic warmup(model, framework, input_spec) function.
Metrics:
We'll use Prometheus client. Define:
nlp_inference_requests_total (counter) with labels: model_name, model_version, ab_test_id (empty if not A/B).
nlp_inference_latency_seconds (histogram) with same labels.
nlp_inference_errors_total (counter) with labels: model_name, model_version, ab_test_id, error_type (e.g., "model_load_failed", "inference_failed").
Implementation Plan for Phase 1:
- Set up PostgreSQL and create tables.
- Create a simple model upload API (or use CLI) to insert into
models and set model_defaults.
- Build inference service:
- Start FastAPI.
- On startup, start a background thread that periodically (every 30 sec) runs
refresh_models().
refresh_models():
- Query DB for required model_ids (from model_defaults).
- For each model_id not in
self.loaded_models, load it (in a separate thread? or sequentially? We don't want to block the refresh cycle. We can spawn a thread to load each model asynchronously).
- For each model_id that is loaded but no longer required, unload it (remove from cache, free memory).
- Implement
load_model(model_id):
- Fetch model info from DB (or cache).
- Download artifact from S3 to a local directory (maybe with a cache to avoid re-download if already exists). We can use a hash of artifact_uri? Or just download every time? Better to cache.
- Load the model based on framework.
- Warmup: generate dummy input from input_spec (stored in artifact as
input_spec.json? or we can store in DB? Let's store in artifact).
- If successful, add to
self.loaded_models[model_id] = {"model": model, "metadata": meta, "load_time": now}.
- If fails, log error and maybe set a flag so we don't retry immediately? We can retry on next refresh.
- Implement
/predict:
- Get model_name from request.
- Query DB for the default model_id for that model_name.
- Get model from
self.loaded_models. If not loaded, return error (or trigger load? but we have background loading, so it should be loaded soon).
- Run inference.
- Record metrics.
- Implement
/warmup endpoint that calls load_model for a given model_id (and does warmup) and returns status.
- Build a simple client to test.
- Set up Prometheus and Grafana.
Phase 2: A/B Testing
-
Create ab_tests table.
CREATE TABLE ab_tests (
id SERIAL PRIMARY KEY,
model_name VARCHAR(255) NOT NULL,
model_a_id INTEGER REFERENCES models(id) ON DELETE CASCADE,
model_b_id INTEGER REFERENCES models(id) ON DELETE CASCADE,
traffic_split_a INTEGER NOT NULL CHECK (traffic_split_a >= 0 AND traffic_split_a <= 100),
traffic_split_b INTEGER NOT NULL CHECK (traffic_split_b >= 0 AND traffic_split_b <= 100),
status VARCHAR(50) NOT NULL CHECK (status IN ('active', 'paused', 'completed')),
start_time TIMESTAMP,
end_time TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
We might want to ensure that traffic_split_a + traffic_split_b = 100.
-
Modify refresh_models() to include models from active A/B tests. The query:
WITH active_ab_tests AS (
SELECT model_name, model_a_id, model_b_id
FROM ab_tests
WHERE status = 'active'
)
SELECT md.model_id FROM model_defaults md
WHERE md.model_name NOT IN (SELECT model_name FROM active_ab_tests)
UNION
SELECT model_a_id AS model_id FROM active_ab_tests
UNION
SELECT model_b_id AS model_id FROM active_ab_tests;
This gives all model_ids that need to be loaded.
-
Modify /predict:
Record metrics with label ab_test_id = test.id (or empty if none).
-
Provide admin endpoints to create/pause/complete A/B tests.
-
Warmup: when an A/B test becomes active, both models will be included in the required set and loaded by the background thread. So warmup will happen.
Phase 3: Guardrails
-
Define guardrails: we can store them in a separate table or in the ab_tests table as JSON? Simpler: add columns to ab_tests:
error_rate_threshold FLOAT (e.g., 0.05 for 5%)
latency_p99_threshold FLOAT (seconds)
latency_p95_threshold FLOAT
evaluation_window_seconds INTEGER (how far back to look)
action_on_violation VARCHAR (e.g., "pause_test", "rollback_to_default", "switch_to_model_a", "switch_to_model_b") but we can hardcode: if model A violates, set traffic_split_a=0, and if both violate, then complete test and revert to default? We'll need logic.
-
Create a separate service (or thread) that:
- Periodically (e.g., every 60 sec) for each active A/B test:
- Query Prometheus for metrics for the two models in the test, over the last
evaluation_window_seconds.
- Compute error rate (rate of errors per request) for each model.
- Compute latency percentiles (p95, p99) for each model.
- Compare to thresholds.
- If violation, take action:
- If error_rate > threshold for model A, then set traffic_split_a = 0 and traffic_split_b = 100? But we need to update the
ab_tests table and also possibly notify inference service to reload config? The inference service polls DB, so it will pick up the change.
- We could also pause the test or mark as completed.
- We need to be careful not to flip-flop. So we might require that the condition persists for a few evaluations? Or use a cool-down.
We can implement this as a separate FastAPI app or just a script that runs periodically. But it needs to update the DB.
-
We also need to consider that the guardrails might be based on combined metrics (e.g., overall error rate for the test). But typically per model.
-
After updating the ab_tests table, the inference service will see the new traffic split within its next refresh cycle (e.g., 10 sec) and route accordingly.
Phase 4: Dashboard
Additional Considerations:
-
Model Artifact Storage: We need to design how model artifacts are stored. We can have a standard layout:
s3://bucket/models/{model_name}/{version}/
model.pth (or model.h5, or saved_model.pb)
input_spec.json
tokenizer/ (for NLP)
The input_spec.json might look like:
{
"input_names": ["input_ids", "attention_mask"],
"shapes": [[1, 512], [1, 512]],
"dtypes": ["int64", "int64"]
}
For a simple text classification model, input might be a single tensor.
We need to handle different frameworks. The model loader should be pluggable.
-
Model Loading Library: We can create a ModelLoader interface with load(artifact_path) and warmup(input_spec) methods. Then implement for PyTorch, TensorFlow, etc. We can detect framework from file extension or from a framework field in the DB.
-
Concurrency in Loading: When the background thread discovers a new model, it should load it in a separate thread so that it doesn't block the refresh cycle. We can use a thread pool. Also, we should avoid loading the same model concurrently (if two refresh cycles overlap). We can use a lock per model_id or a global lock for loading? Better to have a dictionary of locks or a loading queue.
We can have a load_queue and a single loader thread? Or use a thread pool with max workers. We'll keep it simple: when we need to load a model, we spawn a daemon thread to do it. But if we spawn many threads, we might overload. So we can have a semaphore limiting concurrent loads (e.g., 2 at a time). Also, we should avoid loading the same model multiple times: if a load is already in progress for a model_id, skip.
We can keep a set models_loading to track which models are being loaded.
Code Structure for ModelManager:
import threading
import time
from collections import defaultdict
from typing import Dict, Any, Optional
import psycopg2
import boto3
import json
import os
import tempfile
class ModelManager:
def __init__(self, db_conn_str, s3_bucket, refresh_interval=30):
self.db_conn_str = db_conn_str
self.s3_bucket = s3_bucket
self.refresh_interval = refresh_interval
self.loaded_models: Dict[int, Dict[str, Any]] = {} # model_id -> {"model": obj, "meta": meta, "lock": threading.Lock()}
self.loading_lock = threading.Lock()
self.models_loading = set() # model_ids currently being loaded
self.stop_event = threading.Event()
self.thread = threading.Thread(target=self.refresh_loop, daemon=True)
# metrics
from prometheus_client import Counter, Histogram
self.load_attempts = Counter('model_load_attempts', 'Model load attempts', ['model_id', 'model_name'])
self.load_success = Counter('model_load_success', 'Model load success', ['model_id', 'model_name'])
self.load_failure = Counter('model_load_failure', 'Model load failure', ['model_id', 'model_name', 'error'])
def start(self):
self.thread.start()
def stop(self):
self.stop_event.set()
self.thread.join()
def refresh_loop(self):
while not self.stop_event.is_set():
try:
self.refresh_models()
except Exception as e:
# log
pass
self.stop_event.wait(self.refresh_interval)
def refresh_models(self):
# 1. Get required model_ids from DB
required_model_ids = self.get_required_model_ids()
# 2. Load any missing models
to_load = [mid for mid in required_model_ids if mid not in self.loaded_models and mid not in self.models_loading]
for model_id in to_load:
# start a thread to load each? or submit to thread pool
t = threading.Thread(target=self.load_model, args=(model_id,), daemon=True)
t.start()
# 3. Unload models no longer needed
to_unload = [mid for mid in self.loaded_models if mid not in required_model_ids]
for mid in to_unload:
self.unload_model(mid)
def get_required_model_ids(self) -> List[int]:
# Connect to DB and run the query that combines defaults and active AB tests.
conn = psycopg2.connect(self.db_conn_str)
cur = conn.cursor()
query = """
WITH active_ab_tests AS (
SELECT model_name, model_a_id, model_b_id
FROM ab_tests
WHERE status = 'active'
)
SELECT md.model_id FROM model_defaults md
WHERE md.model_name NOT IN (SELECT model_name FROM active_ab_tests)
UNION
SELECT model_a_id AS model_id FROM active_ab_tests
UNION
SELECT model_b_id AS model_id FROM active_ab_tests;
"""
cur.execute(query)
rows = cur.fetchall()
cur.close()
conn.close()
return [row[0] for row in rows]
def load_model(self, model_id: int):
with self.loading_lock:
if model_id in self.models_loading:
return # already loading
self.models_loading.add(model_id)
try:
self.load_attempts.labels(model_id=model_id, model_name=self.get_model_name(model_id)).inc()
# Fetch model metadata from DB
meta = self.get_model_meta(model_id)
# Download artifact from S3 to local cache
local_path = self.download_artifact(meta['artifact_uri'], model_id)
# Load model based on framework
model = self.load_model_from_path(local_path, meta['framework'])
# Warmup: need input_spec. We assume it's in the artifact as 'input_spec.json'
input_spec_path = os.path.join(local_path, 'input_spec.json')
if os.path.exists(input_spec_path):
with open(input_spec_path) as f:
input_spec = json.load(f)
self.warmup_model(model, meta['framework'], input_spec)
else:
# log warning: no input_spec, skip warmup
pass
# Store in loaded_models
self.loaded_models[model_id] = {
"model": model,
"meta": meta,
"lock": threading.Lock(),
"load_time": time.time()
}
self.load_success.labels(model_id=model_id, model_name=meta['name']).inc()
except Exception as e:
self.load_failure.labels(model_id=model_id, model_name=meta.get('name','unknown'), error=type(e).__name__).inc()
# log error
finally:
with self.loading_lock:
self.models_loading.discard(model_id)
def get_model_meta(self, model_id: int) -> Dict:
# query DB for model info: id, name, version, artifact_uri, framework
conn = psycopg2.connect(self.db_conn_str)
cur = conn.cursor()
cur.execute("SELECT name, version, artifact_uri, framework FROM models WHERE id = %s", (model_id,))
row = cur.fetchone()
cur.close()
conn.close()
if not row:
raise ValueError(f"Model {model_id} not found")
return {"id": model_id, "name": row[0], "version": row[1], "artifact_uri": row[2], "framework": row[3]}
def get_model_name(self, model_id: int) -> str:
# cache? For now, query DB or use meta if we have it.
# We can store meta in a dict too.
# For simplicity, we can query DB every time? Not efficient. We can have a cache of model_id->name.
pass
def download_artifact(self, artifact_uri: str, model_id: int) -> str:
# artifact_uri like "s3://bucket/path"
# parse s3 path, download to a local cache directory: /tmp/model_cache/{model_id}/
# return local directory path
pass
def load_model_from_path(self, path: str, framework: str):
if framework == 'pytorch':
import torch
return torch.load(os.path.join(path, 'model.pth'), map_location='cpu')
elif framework == 'tensorflow':
import tensorflow as tf
return tf.keras.models.load_model(path)
else:
raise ValueError(f"Unsupported framework: {framework}")
def warmup_model(self, model, framework, input_spec):
# input_spec: {"input_names": [...], "shapes": [...], "dtypes": [...]}
if framework == 'pytorch':
import torch
# create dummy tensors
dummy_inputs = []
for shape, dtype in zip(input_spec['shapes'], input_spec['dtypes']):
# dtype string to torch dtype
torch_dtype = getattr(torch, dtype) if hasattr(torch, dtype) else torch.float32
dummy = torch.randn(*shape, dtype=torch_dtype)
dummy_inputs.append(dummy)
with torch.no_grad():
_ = model(*dummy_inputs)
elif framework == 'tensorflow':
import numpy as np
import tensorflow as tf
dummy_inputs = []
for shape, dtype in zip(input_spec['shapes'], input_spec['dtypes']):
np_dtype = getattr(np, dtype) if hasattr(np, dtype) else np.float32
dummy = np.random.randn(*shape).astype(np_dtype)
dummy_inputs.append(dummy)
# For TF, model expects a list? or dict? We assume list in order.
_ = model(dummy_inputs)
else:
pass
def unload_model(self, model_id: int):
if model_id in self.loaded_models:
# delete model object, maybe call cleanup?
del self.loaded_models[model_id]
def get_model_for_prediction(self, model_name: str, user_id: Optional[str] = None) -> (int, Any):
# First, check if there's an active AB test for this model_name.
ab_test = self.get_active_ab_test(model_name)
if ab_test:
if user_id is None:
raise ValueError("user_id required for A/B test")
# Compute bucket
bucket = hash(user_id) % 100
if bucket < ab_test['traffic_split_a']:
model_id = ab_test['model_a_id']
else:
model_id = ab_test['model_b_id']
else:
# Get default model
model_id = self.get_default_model_id(model_name)
if model_id not in self.loaded_models:
# Model not loaded yet; we can trigger load? But background should have loaded it.
# We can wait a bit? Or return error.
raise ValueError(f"Model {model_id} not loaded")
return model_id, self.loaded_models[model_id]['model']
def get_active_ab_test(self, model_name: str) -> Optional[Dict]:
conn = psycopg2.connect(self.db_conn_str)
cur = conn.cursor()
cur.execute("""
SELECT id, model_a_id, model_b_id, traffic_split_a, traffic_split_b
FROM ab_tests
WHERE model_name = %s AND status = 'active'
LIMIT 1
""", (model_name,))
row = cur.fetchone()
cur.close()
conn.close()
if row:
return {
"id": row[0],
"model_a_id": row[1],
"model_b_id": row[2],
"traffic_split_a": row[3],
"traffic_split_b": row[4]
}
return None
def get_default_model_id(self, model_name: str) -> int:
conn = psycopg2.connect(self.db_conn_str)
cur = conn.cursor()
cur.execute("SELECT model_id FROM model_defaults WHERE model_name = %s", (model_name,))
row = cur.fetchone()
cur.close()
conn.close()
if not row:
raise ValueError(f"No default model for {model_name}")
return row[0]
Then in the FastAPI app:
model_manager = ModelManager(db_conn_str, s3_bucket)
@app.on_event("startup")
def startup():
model_manager.start()
@app.on_event("shutdown")
def shutdown():
model_manager.stop()
@app.post("/predict")
async def predict(request: Request):
body = await request.json()
model_name = body["model_name"]
inputs = body["inputs"]
user_id = request.headers.get("X-User-Id") # for A/B
try:
model_id, model = model_manager.get_model_for_prediction(model_name, user_id)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
start = time.time()
try:
# framework-specific inference
predictions = run_inference(model, model_manager.loaded_models[model_id]['meta']['framework'], inputs)
latency = time.time() - start
# record metrics
ab_test_id = model_manager.get_active_ab_test(model_name)['id'] if model_manager.get_active_ab_test(model_name) else ''
INFERENCE_REQUESTS.labels(model_name=model_name, model_version=model_manager.loaded_models[model_id]['meta']['version'], ab_test_id=ab_test_id).inc()
INFERENCE_LATENCY.labels(model_name=model_name, model_version=..., ab_test_id=ab_test_id).observe(latency)
return {"predictions": predictions, "model_version": model_manager.loaded_models[model_id]['meta']['version']}
except Exception as e:
latency = time.time() - start
# record error metric
ab_test_id = ...
INFERENCE_ERRORS.labels(model_name=model_name, model_version=..., ab_test_id=ab_test_id, error_type=type(e).__name__).inc()
raise HTTPException(status_code=500, detail="Inference failed")
We need to implement run_inference that takes model, framework, inputs and runs prediction. The inputs format should be defined. For simplicity, we can expect JSON that matches the input spec (e.g., for a text model, maybe {"text": "..."}). But different models have different inputs. We can let the client send a dict that we convert to tensors according to the input spec. We can store the input spec in the model metadata and use it to preprocess.
Alternatively, we can have the client send raw tensors? That's not user-friendly.
Better: define a standard request format for NLP models? That's too restrictive.
We can have each model define a preprocess function that is stored in the artifact? That's complex.
For MVP, we assume the model expects a certain format and the client knows it. We can just pass the inputs directly to the model's forward method. For example, if the model is a PyTorch model that expects a dict of tensors, the client should send that as JSON? But JSON doesn't support tensors. So we need to send arrays (lists) and convert to tensors.
We can do: the client sends a JSON object with keys matching the input names from input_spec, and values are lists (or nested lists) of numbers. Then we convert to tensors/numpy arrays of the correct dtype and shape.
We'll implement a helper:
def prepare_inputs(inputs: Dict, input_spec: Dict, framework: str):
tensors = []
for name, shape, dtype in zip(input_spec['input_names'], input_spec['shapes'], input_spec['dtypes']):
if name not in inputs:
raise ValueError(f"Missing input: {name}")
# convert inputs[name] to numpy/tensor
arr = np.array(inputs[name], dtype=getattr(np, dtype))
# reshape if needed? The shape from spec might include batch dimension. We assume the input array matches the shape.
if framework == 'pytorch':
tensors.append(torch.from_numpy(arr))
else:
tensors.append(arr)
return tensors
But note: for TensorFlow, the model might expect a single tensor or a list? We'll assume the model's __call__ takes a list of tensors in order of input_names.
This is getting complex. For simplicity in Phase 1, we can assume a single input tensor named "input" with shape [batch, ...]. But for real NLP models, we often have multiple inputs (input_ids, attention_mask). So we should support multiple inputs.
We'll design the input_spec to have input_names array and shapes array. The client must send a JSON with keys equal to those names. The values should be arrays that can be reshaped to the given shape. We'll convert to tensor accordingly.
In run_inference:
def run_inference(model, framework, inputs_json):
# inputs_json is already parsed dict from request body.
meta = model_manager.loaded_models[model_id]['meta']
input_spec = meta['input_spec'] # we stored it when loading? We can store input_spec in meta.
prepared = prepare_inputs(inputs_json, input_spec, framework)
if framework == 'pytorch':
with torch.no_grad():
outputs = model(*prepared)
# convert outputs to list
if isinstance(outputs, torch.Tensor):
return outputs.cpu().numpy().tolist()
else:
# tuple or dict
return [o.cpu().numpy().tolist() for o in outputs]
elif framework == 'tensorflow':
outputs = model(prepared) # if model expects list
# convert to list
if isinstance(outputs, tf.Tensor):
return outputs.numpy().tolist()
else:
return [o.numpy().tolist() for o in outputs]
But we need to get input_spec for the model. We can store it in self.loaded_models[model_id]['meta']['input_spec'] when loading.
So in load_model, after downloading, we read input_spec.json and store it in meta.
Deployment:
We'll run the inference service in a Docker container with necessary dependencies (torch, tensorflow, etc.). We'll also have S3 credentials to download models.
Phase 2 and 3 will extend this.
Phase 2: A/B Testing
Implement get_active_ab_test and get_default_model_id. Modify refresh_models query to include active AB tests.
In get_model_for_prediction, we now check for active AB test.
We also need to provide admin API to create AB tests. That can be simple endpoints that insert into DB.
Phase 3: Guardrails
We'll create a separate service (maybe in the same repo) that:
- Connects to Prometheus (HTTP API) to query metrics.
- For each active AB test, get the two model_ids.
- Query Prometheus for:
rate(nlp_inference_errors_total{model_id="...", ab_test_id="..."}[5m]) and rate(nlp_inference_requests_total{model_id="...", ab_test_id="..."}[5m]) to compute error rate.
histogram_quantile(0.99, sum(rate(nlp_inference_latency_seconds_bucket{model_id="...", ab_test_id="..."}[5m])) by (le) for p99.
- Compare to thresholds (which we store in
ab_tests table as error_rate_threshold, latency_p99_threshold).
- If violation, update the
ab_tests table: e.g., set traffic_split_a=0 and traffic_split_b=100 if model A violated, or pause the test if both violated.
- We should also record guardrail actions in a separate table for audit.
We'll need to query Prometheus for each model separately. We can use the Prometheus query API.
We can run this guardrails service as a separate process (maybe a simple Python script with a while loop).
Phase 4: Dashboard
Grafana dashboards. We'll create JSON dashboards and import.
Conclusion:
This is a substantial system. We have outlined the design and implementation steps. We'll now produce a final answer summarizing the architecture and key components.
Streaming NLP Inference Platform with On-Demand Model Swapping
Architecture Overview
The platform consists of microservices for configuration management, model inference with A/B testing, warm-up workflows, guardrails, and telemetry. The core is a Model Inference Service that dynamically loads models and routes requests based on A/B test configurations. Supporting services handle warm-up, guardrail monitoring, and dashboards.
Components
-
Configuration Database (PostgreSQL)
- Stores model metadata, defaults, and A/B test configurations.
- Schema:
CREATE TABLE models (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
version INTEGER NOT NULL,
artifact_uri TEXT NOT NULL,
framework VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (name, version)
);
CREATE TABLE model_defaults (
model_name VARCHAR(255) PRIMARY KEY,
model_id INTEGER REFERENCES models(id) ON DELETE CASCADE
);
CREATE TABLE ab_tests (
id SERIAL PRIMARY KEY,
model_name VARCHAR(255) NOT NULL,
model_a_id INTEGER REFERENCES models(id),
model_b_id INTEGER REFERENCES models(id),
traffic_split_a INTEGER NOT NULL CHECK (traffic_split_a BETWEEN 0 AND 100),
traffic_split_b INTEGER NOT NULL CHECK (traffic_split_b BETWEEN 0 AND 100),
status VARCHAR(50) NOT NULL CHECK (status IN ('active', 'paused', 'completed')),
error_rate_threshold FLOAT,
latency_p99_threshold FLOAT,
evaluation_window_seconds INTEGER DEFAULT 300,
start_time TIMESTAMP,
end_time TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
-
Model Inference Service (FastAPI)
- Loads models on-demand from S3.
- Routes requests based on A/B tests using
X-User-Id header for consistency.
- Emits Prometheus metrics.
- Background thread refreshes model set every 30s.
-
Warm-up Service
- Integrated into the inference service’s background thread.
- Loads new models and runs dummy inferences using
input_spec.json from the artifact.
-
Guardrails Service
- Periodically queries Prometheus for active A/B tests.
- Evaluates error rates and latency against thresholds.
- Auto-adjusts traffic splits or pauses tests via DB updates.
-
Telemetry & Dashboards
- Prometheus scrapes metrics from the inference service.
- Grafana dashboards visualize:
- Requests/sec, error rates, latency percentiles per model.
- Active A/B test traffic splits.
- Model load status.
-
Admin API & UI (optional)
- Endpoints to manage models, defaults, and A/B tests.
Workflow Example
-
Deploy New Model
- Upload model to S3 (with
input_spec.json).
- Insert into
models and set as default in model_defaults.
- Inference service detects new active model, downloads, loads, and warms up.
-
Start A/B Test
- Create
ab_tests record with two model versions and split (e.g., 50/50).
- Inference service includes both models in its cache.
- Requests with
X-User-Id are routed: hash % 100 < split_a → model A, else model B.
-
Guardrail Trigger
- If model A’s error rate exceeds threshold, guardrails service sets
traffic_split_a=0.
- Inference service picks up change within 30s and routes 100% to model B.
Implementation Highlights
Model Loading & Warm-up
- Models cached in memory with per-model locks for thread-safe inference.
- Warm-up runs a forward pass with random data based on
input_spec.json.
- Failed loads are logged and retried on next refresh.
A/B Routing
def get_model_for_prediction(model_name, user_id):
ab_test = query_active_ab_test(model_name)
if ab_test:
if not user_id:
raise HTTPException(400, "user_id required for A/B test")
bucket = hash(user_id) % 100
model_id = ab_test.model_a_id if bucket < ab_test.traffic_split_a else ab_test.model_b_id
else:
model_id = query_default_model_id(model_name)
return loaded_models[model_id]
Metrics
INFERENCE_REQUESTS = Counter('nlp_inference_requests_total', 'Requests', ['model_name','model_version','ab_test_id'])
INFERENCE_LATENCY = Histogram('nlp_inference_latency_seconds', 'Latency', ['model_name','model_version','ab_test_id'])
INFERENCE_ERRORS = Counter('nlp_inference_errors_total', 'Errors', ['model_name','model_version','ab_test_id','error_type'])
Guardrails Query (Prometheus)
# Example: error rate for model_a in test 123
query = f'''
rate(nlp_inference_errors_total{{ab_test_id="123", model_id="model_a"}}[{window}s])
/
rate(nlp_inference_requests_total{{ab_test_id="123", model_id="model_a"}}[{window}s])
'''
If > error_rate_threshold, update ab_tests.traffic_split_a = 0.
Deployment
- Inference Service: Docker container with Python, framework libs (PyTorch/TensorFlow), S3 access.
- Database: PostgreSQL instance.
- S3: Model artifacts.
- Prometheus & Grafana: Scrape
/metrics endpoint; pre-built dashboards.
- Guardrails: Separate Python service (or cron job) with Prometheus API access.
Scaling Considerations
- GPU Memory: Load multiple models only if they fit; otherwise, consider sharding by model across instances.
- High Throughput: Use batching and thread pools; each model may require multiple copies for parallelism.
- Hot Swapping: Unload unused models after a cool-down period; monitor memory pressure.
- Consistent Hashing: For A/B tests, use a stable hash (e.g.,
xxhash of user_id) to avoid flip-flops.
Roadmap
- Phase 1: Basic inference with model defaults, warm-up, metrics.
- Phase 2: Add A/B testing routing.
- Phase 3: Guardrails service.
- Phase 4: Admin UI and advanced dashboards.
- Future: Multi-model ensembles, canary deployments, cost tracking.
This design provides a robust, observable, and controllable platform for streaming NLP inference with safe model experimentation.