@@ -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
187210async def _registered_api_adapter_async (
0 commit comments