Search code examples
pythonpython-asynciofastapiuvicornasgi

Count number of requests with global variable using FastAPI


I want to count the number of requests in a specific URL path.

app = FastAPI()
counter = 0

@app.get("/do_something")
async def do_something():
    global counter
    counter += 1
    return {"message": "Hello World"}

Is this code ok? The counter should be thread safe? asincio safe? Is that the right way to count requests (Without DB)? Is there a meaning for the "async" in the "do_something" function in this situation? And how to make it work with several workers?


Solution

  • If you're using 1 worker you ushould use an asyncio lock because fastAPI is asynchronous.

    import asyncio
    
    app = FastAPI()
    counter_lock = asyncio.Lock()
    counter = 0
    
    @app.get("/do_something")
    async def do_something():
        global counter
    
        async with counter_lock:
            counter += 1
    
        return {"message": "Hello World"}
    

    But if there is more than 1 worker that wouldn't work because they do not share the same memory. Should be using a cache mechanism or a DB, As explained here.