Built byPhoenix

© 2026 Phoenix

Blog

October 28, 2026·7 min read

Scoring in Under 200ms: ML Behind an API, With Timeouts and Fallbacks

A model that answers in 300ms, when the payment needed 200, didn't answer. Putting ML in a real-time path: a latency budget, hard timeouts at every hop, a circuit breaker, rules worth falling back to, and the metric that tells you when you're running on them.

  • Python
  • FastAPI
  • Machine Learning
  • Reliability
  • Fintech

A model that answers in 300ms, when the payment needed an answer in 200, didn't answer. The customer saw a spinner, the checkout timed out, and the clever model contributed nothing.

Real-time decisions have deadlines: approve or hold a payment, flag a transaction, match two people. I've deployed an ML scoring engine behind an API and lived with its tail latency, and the lesson was always the same. Treat the model as a dependency that will sometimes be slow and sometimes be down, and design so every request still gets a decision inside the budget.

Here's how, with the code in Python and FastAPI.

Start with a budget, not a model

Before writing any code, split the deadline between the hops. A 200ms p99 for a scoring call might look like this:

HopBudget
Network in, TLS, auth, parsing15 ms
Load features20 ms
Model call (hard timeout)120 ms
Rules2 ms
Respond and log10 ms
Headroom33 ms

Two rules come out of this table. Every hop gets a hard timeout smaller than its share, and no hop gets "whatever time is left". The headroom is for garbage collection, a slow network moment, the things you can't plan for. If you spend it on purpose, you'll miss the deadline by accident.

Keep the model warm and close

Most of the latency in a model call isn't the model. It's everything around it.

  • One long-lived HTTP client with a connection pool. A new TLS handshake per request can eat a third of your budget on its own.
  • The model runs as its own service, loaded once at startup, in the same region and ideally the same zone as the API calling it.
  • No cold starts. Keep a minimum number of instances warm. A scale-to-zero model server is fine for batch jobs and a disaster for a payment path.
  • Precompute features. If scoring needs "transactions in the last 10 minutes" and "average amount over 30 days", don't compute them in the request. Keep rolling counters in Redis, updated as events arrive, and read them in one round trip.
  • Don't batch on the real-time path. Batching helps throughput, and every millisecond a request waits for its batch comes out of its latency budget.

Hard timeouts

The model call gets its share and not a millisecond more. If it runs out, the request falls back. It never waits.

python
import asyncioimport timefrom contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom decimal import Decimal
import httpxfrom fastapi import FastAPIfrom pydantic import BaseModel
MODEL_URL = "http://scorer.internal:8080/v1/score"MODEL_TIMEOUT_S = 0.120  # the model's share of a 200ms budget

class Transaction(BaseModel):    id: str    account_id: str    amount: Decimal    device_id: str | None = None

class Decision(BaseModel):    transaction_id: str    score: float  # 0 = safe, 1 = certainly fraud    action: str  # "allow" | "review" | "block"    decided_by: str  # "model" | "rules"    model_version: str | None    reasons: list[str]    latency_ms: int

@dataclassclass Verdict:    score: float    action: str    decided_by: str    model_version: str | None    reasons: list[str]

@asynccontextmanagerasync def lifespan(app: FastAPI):    # One pooled client per process: no new TLS handshake per request.    app.state.model = httpx.AsyncClient(        timeout=httpx.Timeout(MODEL_TIMEOUT_S, connect=0.05),        limits=httpx.Limits(max_keepalive_connections=50),    )    yield    await app.state.model.aclose()

app = FastAPI(lifespan=lifespan)

Two layers of timeout are on purpose. httpx bounds each phase of the request, and asyncio.timeout bounds the whole call, so a response that trickles in slowly can't sneak past either.

A circuit breaker

When the model service is down, every request paying 120ms to discover it again is wasted budget. A circuit breaker remembers: after enough failures it stops calling the model for a while and lets the rules decide straight away.

python
from collections import deque

class CircuitBreaker:    """Stops calling the model after repeated failures, then tries it again."""
    def __init__(self, failures: int, window_s: float, cooldown_s: float):        self.failures, self.window_s, self.cooldown_s = failures, window_s, cooldown_s        self.recent: deque[float] = deque()        self.open_until = 0.0
    def allow(self) -> bool:        return time.monotonic() >= self.open_until
    def record_success(self) -> None:        self.recent.clear()
    def record_failure(self) -> None:        now = time.monotonic()        self.recent.append(now)        while self.recent and now - self.recent[0] > self.window_s:            self.recent.popleft()        if len(self.recent) >= self.failures:            self.open_until = now + self.cooldown_s            self.recent.clear()

breaker = CircuitBreaker(failures=5, window_s=30, cooldown_s=15)

This one is deliberately small. A production breaker would let a single probe through after the cooldown, instead of the whole traffic stream at once, but the idea is the same: stop paying for a dependency you already know is down.

Rules that keep deciding

The fallback is the part people get wrong. "Allow everything when the model is down" is an open door, and "block everything" is an outage you caused yourself. The fallback has to be a real policy: simpler than the model, explainable, and conservative.

python
def rule_score(tx: Transaction, f: "Features") -> Verdict:    score, reasons = 0.0, []    if f.avg_amount_30d and tx.amount > 5 * f.avg_amount_30d:        score += 0.4        reasons.append("amount over 5x the 30-day average")    if f.txns_last_10m >= 5:        score += 0.3        reasons.append("5 or more transactions in 10 minutes")    if tx.device_id and tx.device_id not in f.known_devices:        score += 0.2        reasons.append("first time on this device")    action = "review" if score >= 0.5 else "allow"  # rules never block on their own    return Verdict(min(score, 1.0), action, "rules", None, reasons)

Notice what the fallback can't do: it can't block. When the model is down, risky transactions go to a person for review rather than being declined by a blunter instrument.

Some checks don't belong to the model at all. A sanctions or blocklist hit is a hard rule: it runs first, on every request, and it decides whether the model is up or not. You never want "the model was down" to be the reason a sanctioned account got through.

The endpoint

python
@app.post("/v1/score", response_model=Decision)async def score(tx: Transaction) -> Decision:    started = time.perf_counter()    features = await load_features(tx)  # one Redis round trip
    if hit := hard_rules(tx, features):  # sanctions, blocklists: never delegated        return decide(tx, hit, started)
    if breaker.allow():        try:            async with asyncio.timeout(MODEL_TIMEOUT_S):                resp = await app.state.model.post(MODEL_URL, json=features.payload())                resp.raise_for_status()            breaker.record_success()            return decide(tx, from_model(resp.json()), started)        except (TimeoutError, httpx.HTTPError):            breaker.record_failure()
    return decide(tx, rule_score(tx, features), started)

def decide(tx: Transaction, v: Verdict, started: float) -> Decision:    latency_ms = round((time.perf_counter() - started) * 1000)    metrics.record(decided_by=v.decided_by, latency_ms=latency_ms)    return Decision(        transaction_id=tx.id,        score=v.score,        action=v.action,        decided_by=v.decided_by,        model_version=v.model_version,        reasons=v.reasons,        latency_ms=latency_ms,    )

Record who decided

Every decision says how it was made: decided_by, model_version, the reasons, and the latency. Store it with the transaction. That serves two masters.

  • Audit. In anything regulated, you'll be asked why a transaction was held. "The model said 0.83, version 14, top features X and Y" is an answer. "It was flagged" isn't.
  • Operations. It's the raw material for the one metric that matters most here.

The fallback rate is your health metric

Latency percentiles tell you how fast you answered. The share of decisions made by rules tells you how well you answered. Watch it like an error rate:

  • Alert when the fallback rate goes over a few percent for five minutes. It means the model is slow or down and you're running on the simpler policy.
  • Track p99 per hop, not just end to end, so a slow feature store doesn't hide inside "the model is slow".
  • Count model timeouts and breaker openings separately. They point at different problems.

Before you ship it

  • Load test the whole path, model service included, at realistic concurrency. The p99 under load is the only number that matters.
  • Test the fallback on purpose. Inject latency between the API and the model service and watch decisions keep flowing, with decided_by flipping to rules. A fallback you've never seen run doesn't work.
  • Run new models in shadow first. Score with the candidate in a background task with its own timeout, decide with the current model, and compare the two before switching. The shadow call must never sit on the decision path.

None of this is clever. It's a budget, a timeout at every hop, a breaker, rules worth falling back to, and a metric that tells you when you're flying on them. That's what turns a model into something you can put in front of real money.

Read next

  • A Sandbox Partners Can Use Without YouIf every new client needs a call with you before their first request works, you don't have a platform yet. Test keys that carry their mode, the real pipeline with simulated providers, magic values for every outcome, and signed webhooks partners can replay.Oct 14, 2026·7 min read
  • The Fix That Didn't Remove the MalwareA cleanup commit for a supply-chain dropper was reviewed and merged, and the malware was still there. How it hid behind hundreds of tabs, why the diff lied, and the required check that now catches it by shape.Sep 14, 2026·6 min read
All postsShare on X ↗
import asyncioimport timefrom contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom decimal import Decimal
import httpxfrom fastapi import FastAPIfrom pydantic import BaseModel
MODEL_URL = "http://scorer.internal:8080/v1/score"MODEL_TIMEOUT_S = 0.120  # the model's share of a 200ms budget

class Transaction(BaseModel):    id: str    account_id: str    amount: Decimal    device_id: str | None = None

class Decision(BaseModel):    transaction_id: str    score: float  # 0 = safe, 1 = certainly fraud    action: str  # "allow" | "review" | "block"    decided_by: str  # "model" | "rules"    model_version: str | None    reasons: list[str]    latency_ms: int

@dataclassclass Verdict:    score: float    action: str    decided_by: str    model_version: str | None    reasons: list[str]

@asynccontextmanagerasync def lifespan(app: FastAPI):    # One pooled client per process: no new TLS handshake per request.    app.state.model = httpx.AsyncClient(        timeout=httpx.Timeout(MODEL_TIMEOUT_S, connect=0.05),        limits=httpx.Limits(max_keepalive_connections=50),    )    yield    await app.state.model.aclose()

app = FastAPI(lifespan=lifespan)
from collections import deque

class CircuitBreaker:    """Stops calling the model after repeated failures, then tries it again."""
    def __init__(self, failures: int, window_s: float, cooldown_s: float):        self.failures, self.window_s, self.cooldown_s = failures, window_s, cooldown_s        self.recent: deque[float] = deque()        self.open_until = 0.0
    def allow(self) -> bool:        return time.monotonic() >= self.open_until
    def record_success(self) -> None:        self.recent.clear()
    def record_failure(self) -> None:        now = time.monotonic()        self.recent.append(now)        while self.recent and now - self.recent[0] > self.window_s:            self.recent.popleft()        if len(self.recent) >= self.failures:            self.open_until = now + self.cooldown_s            self.recent.clear()

breaker = CircuitBreaker(failures=5, window_s=30, cooldown_s=15)
def rule_score(tx: Transaction, f: "Features") -> Verdict:    score, reasons = 0.0, []    if f.avg_amount_30d and tx.amount > 5 * f.avg_amount_30d:        score += 0.4        reasons.append("amount over 5x the 30-day average")    if f.txns_last_10m >= 5:        score += 0.3        reasons.append("5 or more transactions in 10 minutes")    if tx.device_id and tx.device_id not in f.known_devices:        score += 0.2        reasons.append("first time on this device")    action = "review" if score >= 0.5 else "allow"  # rules never block on their own    return Verdict(min(score, 1.0), action, "rules", None, reasons)
@app.post("/v1/score", response_model=Decision)async def score(tx: Transaction) -> Decision:    started = time.perf_counter()    features = await load_features(tx)  # one Redis round trip
    if hit := hard_rules(tx, features):  # sanctions, blocklists: never delegated        return decide(tx, hit, started)
    if breaker.allow():        try:            async with asyncio.timeout(MODEL_TIMEOUT_S):                resp = await app.state.model.post(MODEL_URL, json=features.payload())                resp.raise_for_status()            breaker.record_success()            return decide(tx, from_model(resp.json()), started)        except (TimeoutError, httpx.HTTPError):            breaker.record_failure()
    return decide(tx, rule_score(tx, features), started)

def decide(tx: Transaction, v: Verdict, started: float) -> Decision:    latency_ms = round((time.perf_counter() - started) * 1000)    metrics.record(decided_by=v.decided_by, latency_ms=latency_ms)    return Decision(        transaction_id=tx.id,        score=v.score,        action=v.action,        decided_by=v.decided_by,        model_version=v.model_version,        reasons=v.reasons,        latency_ms=latency_ms,    )