starlette-context icon indicating copy to clipboard operation
starlette-context copied to clipboard

Context overwritten on non-async API route

Open Bharat23 opened this issue 10 months ago • 1 comments

I am using this in fastAPI and when I use this in a route that doesn't use async keyword the context is overwitten by the call that responded faster.

from starlette_context import context
from fastapi import Query
from time import sleep


### Steps to reporoduce

@app.get("/")
def health(value_to_set: str = Query(), time_to_sleep: int = Query()):
    context.some_value = value_to_set
    sleep(time_to_sleep)
    return context.some_value

Call these in parallel with one worker

curl /?value_to_set=a&time_to_sleep=10

output:
b


curl /?value_to_set=b&time_to_sleep=2

output:
b

Middleware is already setup as per the docs. Also, using the async keyword resolves the issue.

I am not sure if I am missing something or is this a bug. Any help on this appreciated.

Bharat23 avatar Jan 27 '25 20:01 Bharat23

Great question. Sadly, I have no idea either. IIRC sync requests are run in a separate thread and I found this. https://github.com/encode/starlette/pull/1258

Contributions welcome.

tomwojcik avatar Mar 03 '25 22:03 tomwojcik