Skip to content

Commit a1f97bd

Browse files
fix(event_handler): run consecutive sync middlewares on one thread in the async chain (#8907)
1 parent 0f41207 commit a1f97bd

3 files changed

Lines changed: 153 additions & 10 deletions

File tree

‎aws_lambda_powertools/event_handler/middlewares/async_utils.py‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,12 @@ def __init__(
145145
self.current_middleware: Callable[..., Any] = current_middleware
146146
self.next_middleware: Callable[..., Any] = next_middleware
147147
self._next_middleware_name = next_middleware.__name__
148+
# Class-based middlewares expose their logic through `handler`, which may be a coroutine
149+
# function even though the instance itself is not
150+
middleware_handler = getattr(current_middleware, "handler", None)
151+
self._is_async_middleware = inspect.iscoroutinefunction(current_middleware) or inspect.iscoroutinefunction(
152+
middleware_handler,
153+
)
148154

149155
@property
150156
def __name__(self) -> str: # noqa: A003
@@ -162,26 +168,43 @@ async def __call__(self, app: ApiGatewayResolver) -> dict | tuple | Response:
162168

163169
extra_kwargs = _resolve_extra_middleware_kwargs(app, self.current_middleware)
164170

165-
# Class-based middlewares expose their logic through `handler`, which may be a coroutine
166-
# function even though the instance itself is not
167-
middleware_handler = getattr(self.current_middleware, "handler", None)
168-
is_async_middleware = inspect.iscoroutinefunction(
169-
self.current_middleware,
170-
) or inspect.iscoroutinefunction(middleware_handler)
171-
172-
if is_async_middleware:
171+
if self._is_async_middleware:
173172
result = self.current_middleware(app, self.next_middleware, **extra_kwargs)
174173
if inspect.iscoroutine(result):
175174
result = await result
176175
return result
177176

178177
loop = asyncio.get_running_loop()
178+
return await asyncio.to_thread(self._run_sync_middleware, app, loop, extra_kwargs)
179+
180+
def _run_sync_middleware(self, app: ApiGatewayResolver, loop: asyncio.AbstractEventLoop, extra_kwargs: dict) -> Any:
181+
"""Run this sync middleware in the current worker thread.
182+
183+
Consecutive sync middlewares stay in this thread. Hopping back to the event loop only to borrow a
184+
second executor thread for the next sync middleware is what deadlocked under load: with every
185+
executor thread blocked inside the first middleware, the second one could never start (#8866).
186+
Only an async next step is scheduled on the event loop.
187+
"""
179188

180189
def sync_next(app: ApiGatewayResolver) -> Any:
181-
future = asyncio.run_coroutine_threadsafe(self.next_middleware(app), loop)
190+
next_middleware = self.next_middleware
191+
if isinstance(next_middleware, AsyncMiddlewareFrame) and not next_middleware._is_async_middleware:
192+
return next_middleware._run_sync_middleware_inline(app, loop)
193+
194+
future = asyncio.run_coroutine_threadsafe(next_middleware(app), loop)
182195
return future.result()
183196

184-
return await asyncio.to_thread(self.current_middleware, app, sync_next, **extra_kwargs)
197+
return self.current_middleware(app, sync_next, **extra_kwargs)
198+
199+
def _run_sync_middleware_inline(self, app: ApiGatewayResolver, loop: asyncio.AbstractEventLoop) -> Any:
200+
"""Entry point used by the previous sync frame to run this frame in the same worker thread."""
201+
logger.debug("AsyncMiddlewareFrame: %s", self)
202+
app._push_processed_stack_frame(str(self))
203+
204+
from aws_lambda_powertools.event_handler.api_gateway import _resolve_extra_middleware_kwargs
205+
206+
extra_kwargs = _resolve_extra_middleware_kwargs(app, self.current_middleware)
207+
return self._run_sync_middleware(app, loop, extra_kwargs)
185208

186209

187210
async def _registered_api_adapter_async(

‎tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,3 +540,68 @@ async def start(name):
540540
await asyncio.gather(*pending, return_exceptions=True)
541541

542542
asyncio.run(scenario())
543+
544+
545+
# =============================================================================
546+
# Concurrency Tests (#8866)
547+
# =============================================================================
548+
549+
550+
async def _asgi_call(app: HttpResolverLocal, path: str) -> dict[str, Any]:
551+
scope = {"type": "http", "method": "GET", "path": path, "query_string": b"", "headers": []}
552+
send, captured = make_asgi_send()
553+
await app(scope, make_asgi_receive(), send)
554+
return captured
555+
556+
557+
async def _gather_with_small_executor(coroutines, max_workers: int = 2):
558+
# A tiny executor makes the thread starvation deterministic: with more in-flight requests
559+
# than worker threads, a sync middleware that needs a second thread to run the next one never gets it
560+
from concurrent.futures import ThreadPoolExecutor
561+
562+
executor = ThreadPoolExecutor(max_workers=max_workers)
563+
asyncio.get_running_loop().set_default_executor(executor)
564+
try:
565+
return await asyncio.wait_for(asyncio.gather(*coroutines), timeout=5)
566+
finally:
567+
executor.shutdown(wait=False, cancel_futures=True)
568+
569+
570+
@pytest.mark.asyncio
571+
async def test_asgi_concurrent_requests_with_validation_do_not_deadlock():
572+
# GIVEN an app with validation enabled, which adds two sync middlewares around every route
573+
app = HttpResolverLocal(enable_validation=True)
574+
575+
@app.get("/ping")
576+
def ping() -> dict[str, str]:
577+
return {"ok": "yes"}
578+
579+
# WHEN more requests arrive at once than there are executor threads
580+
results = await _gather_with_small_executor([_asgi_call(app, "/ping") for _ in range(6)])
581+
582+
# THEN every request is answered
583+
assert [captured["status_code"] for captured in results] == [200] * 6
584+
585+
586+
@pytest.mark.asyncio
587+
async def test_asgi_concurrent_requests_keep_request_state_isolated():
588+
# GIVEN validation enabled plus a sync middleware that stores request data in the context
589+
app = HttpResolverLocal(enable_validation=True)
590+
591+
def remember_path(app: HttpResolverLocal, next_middleware):
592+
app.append_context(seen=app.current_event.path)
593+
return next_middleware(app)
594+
595+
app.use([remember_path])
596+
597+
@app.get("/echo/<value>")
598+
def echo(value: str) -> dict[str, str]:
599+
return {"value": value, "seen": app.context["seen"]}
600+
601+
# WHEN many distinct requests run concurrently through the sync middleware chain
602+
results = await _gather_with_small_executor([_asgi_call(app, f"/echo/v{i}") for i in range(12)])
603+
604+
# THEN each caller gets its own value and its own context back
605+
for i, captured in enumerate(results):
606+
assert captured["status_code"] == 200
607+
assert json.loads(captured["body"]) == {"value": f"v{i}", "seen": f"/echo/v{i}"}

‎tests/functional/event_handler/required_dependencies/test_http_resolver.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,3 +1577,58 @@ def handler():
15771577
assert result["statusCode"] == 200
15781578
assert "cookies" in result
15791579
assert "multiValueHeaders" not in result
1580+
1581+
1582+
# =============================================================================
1583+
# Concurrency Tests (#8866)
1584+
# =============================================================================
1585+
1586+
1587+
def _asgi_scope(path: str) -> dict[str, Any]:
1588+
return {"type": "http", "method": "GET", "path": path, "query_string": b"", "headers": []}
1589+
1590+
1591+
async def _asgi_call(app: HttpResolverLocal, path: str) -> dict[str, Any]:
1592+
send, captured = make_asgi_send()
1593+
await app(_asgi_scope(path), make_asgi_receive(), send)
1594+
return captured
1595+
1596+
1597+
async def _gather_with_small_executor(coroutines, max_workers: int = 2):
1598+
# A tiny executor makes the thread starvation deterministic: with more in-flight requests
1599+
# than worker threads, a sync middleware that needs a second thread to run the next one never gets it
1600+
from concurrent.futures import ThreadPoolExecutor
1601+
1602+
executor = ThreadPoolExecutor(max_workers=max_workers)
1603+
asyncio.get_running_loop().set_default_executor(executor)
1604+
try:
1605+
return await asyncio.wait_for(asyncio.gather(*coroutines), timeout=5)
1606+
finally:
1607+
executor.shutdown(wait=False, cancel_futures=True)
1608+
1609+
1610+
@pytest.mark.asyncio
1611+
async def test_asgi_concurrent_requests_with_chained_sync_middlewares_do_not_deadlock():
1612+
# GIVEN two consecutive sync middlewares and no validation
1613+
app = HttpResolverLocal()
1614+
1615+
def first(app: HttpResolverLocal, next_middleware):
1616+
app.append_context(first="seen")
1617+
return next_middleware(app)
1618+
1619+
def second(app: HttpResolverLocal, next_middleware):
1620+
app.append_context(second="seen")
1621+
return next_middleware(app)
1622+
1623+
app.use([first, second])
1624+
1625+
@app.get("/ping")
1626+
def ping():
1627+
return {"first": app.context["first"], "second": app.context["second"]}
1628+
1629+
# WHEN more requests arrive at once than there are executor threads
1630+
results = await _gather_with_small_executor([_asgi_call(app, "/ping") for _ in range(6)])
1631+
1632+
# THEN every request goes through both middlewares and is answered
1633+
assert [captured["status_code"] for captured in results] == [200] * 6
1634+
assert all(json.loads(captured["body"]) == {"first": "seen", "second": "seen"} for captured in results)

0 commit comments

Comments
 (0)