LitServe icon indicating copy to clipboard operation
LitServe copied to clipboard

Failed requests leave active_requests permanently incremented

Open emecii opened this issue 2 months ago • 0 comments

Bug

With track_requests=True, RequestCountMiddleware increments the shared counter before dispatch and decrements it only after the downstream app returns. If request handling raises, the decrement is skipped. Each 500 response can therefore leave a phantom active request in LitServer.active_requests, affecting callbacks and monitoring that rely on the count.

Reproduction

On main at 16248473bc3127bef5d2cfe11de9d9677d9ee2c3:

import multiprocessing as mp
from fastapi import FastAPI
from fastapi.testclient import TestClient
from litserve.middlewares import RequestCountMiddleware

counter = mp.Value("i", 0, lock=True)
app = FastAPI()
app.add_middleware(RequestCountMiddleware, active_counter=counter)

@app.get("/fail")
def fail():
    raise RuntimeError("boom")

with TestClient(app, raise_server_exceptions=False) as client:
    assert client.get("/fail").status_code == 500

assert counter.value == 0  # currently 1

Expected behavior

The counter is decremented when downstream request handling exits, whether it returns normally or raises, while preserving the original exception behavior.

This report was prepared with Codex assistance.

emecii avatar Sep 10 '26 17:09 emecii