Lesson 3 of 8 · 2 min
Backend with rate limits
Save as app/main.py. Replace predict with your project's function.
# run locally: uvicorn app.main:app --reload
import time, uuid, logging, json
from collections import defaultdict, deque
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse
from prometheus_client import Counter, Histogram, generate_latest
from pydantic import BaseModel, Field
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("app")
REQUESTS = Counter("requests_total", "Requests", ["status"])
LATENCY = Histogram("request_seconds", "Time to answer")
LIMIT, WINDOW = 20, 60
hits: dict[str, deque] = defaultdict(deque)
app = FastAPI()
def allow(key: str, now: float) -> bool:
q = hits[key]
while q and now - q[0] > WINDOW:
q.popleft()
if len(q) >= LIMIT:
return False
q.append(now)
return True
class Ask(BaseModel):
text: str = Field(min_length=1, max_length=2000)
def predict(text: str) -> str:
return text.upper()
@app.post("/predict")
def run(body: Ask, request: Request):
if not allow(request.client.host, time.time()):
REQUESTS.labels("limited").inc()
raise HTTPException(429, "Too many requests", headers={"Retry-After": str(WINDOW)})
rid, start = uuid.uuid4().hex[:8], time.time()
try:
answer = predict(body.text)
except Exception:
REQUESTS.labels("error").inc()
log.exception("failed id=%s", rid)
raise HTTPException(500, "Something failed. Quote id " + rid)
took = time.time() - start
LATENCY.observe(took)
REQUESTS.labels("ok").inc()
log.info(json.dumps({"id": rid, "ms": round(took * 1000), "chars": len(body.text)}))
return {"id": rid, "answer": answer}
@app.get("/health")
def health():
return {"ok": True}
@app.get("/metrics", response_class=PlainTextResponse)
def metrics():
return generate_latest()Note that the log records sizes and times, not what the person typed.
