Rewritten in October 2026. The earlier version presented memory, latency and speed-up figures as measurements and said one of the models was unused. The figures were estimates, and that model serves a real share of requests, so we kept it. This version describes the changes that shipped.
The service classifies the sentiment of social posts for Twiscope's reports: Arabic, including Gulf and Egyptian dialects, and English. It serves three pretrained Hugging Face models behind FastAPI — a CAMeL-Lab dialect model for Arabic, a Twitter RoBERTa model for English, and a multilingual model for mixed or other-language text. No models are trained here; the work is in serving them reliably.
1. Load models in the lifespan, not at import
The prototype loaded models when the module was imported, so a download failure happened before the application's startup lifecycle was clear. Moving loading into FastAPI's lifespan makes startup responsible for the work: either loading completes and the service begins accepting requests, or startup fails and the orchestrator handles it as a startup failure.
from contextlib import asynccontextmanager
from fastapi import FastAPI, Response
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.ready = False
app.state.models = load_models(settings) # pinned revisions, see below
app.state.ready = True
yield
app.state.models = None # release memory on shutdown
app = FastAPI(lifespan=lifespan)
@app.get("/ready")
def ready(response: Response):
if not app.state.ready:
response.status_code = 503
return {"ready": app.state.ready}An exception inside the lifespan stops the application from starting, which is the intended behaviour: fail fast and let the orchestrator restart it. The readiness endpoint describes application state after startup; it is not called while the models load, because FastAPI does not accept requests before the lifespan reaches yield.
2. Pin model revisions
A model id on the Hugging Face Hub points at whatever was pushed last. For an analytics product, the same text should get the same label next month, so every model is loaded at a pinned revision kept in configuration.
model = AutoModelForSequenceClassification.from_pretrained(
cfg.model_id,
revision=cfg.revision, # commit SHA or tag, reviewed like any dependency bump
)3. Keep downloaded models on a volume
Without a persistent cache, every container restart downloaded the models again. A named volume mounted as the Hugging Face cache makes restarts and redeploys reuse what's already there.
services:
sentiment-api:
environment:
HF_HOME: /models-cache
volumes:
- hf-cache:/models-cache
volumes:
hf-cache:4. Half precision only where it helps
float16 roughly halves weight memory and speeds up inference on GPUs. On CPUs it often doesn't help and can be slower, so the service chooses the dtype from the device: half precision on CUDA or Apple MPS, float32 on CPU. CPU hosts behave exactly as they did before the change.
def model_dtype(device: str) -> torch.dtype:
return torch.float16 if device in ("cuda", "mps") else torch.float325. Batch on the way in
Callers send texts in batches (the Twiscope backend sends up to 100 at a time) and the service runs batched inference, which amortises tokenisation and model overhead far better than one request per post.
The model we didn't delete
The tempting memory optimisation was to drop the multilingual model and keep only the Arabic and English ones. The logs said otherwise: mixed-language and other-language posts — the team estimated 20–30% of calls — depend on it. Measure who uses a component before you remove it.
What we deliberately left for later
- More worker processes. Each uvicorn worker loads its own copy of every model, so workers multiply memory. PyTorch already uses several threads per process for inference, so add processes only after measuring that a single process is the bottleneck.
- ONNX Runtime and INT8 quantization. Both can cut latency and memory substantially, but each needs an accuracy check on Arabic dialect data before it's worth the migration.
- Rewriting the service in another language. The bottleneck is the model, not Python request handling.
None of these changes is clever. Together they turned a service that worked on a laptop into one that starts predictably, behaves the same after every deploy, and makes its trade-offs explicit.