1

After reading "Pro ASP.NET Core" about the middleware pipeline, I'm struggling to understand its implementation.

  1. If it is implemented recursively, isn't there a risk of stack overflow?

  2. If it's not implemented recursively, and the ASP.NET Core platform calls each middleware component sequentially, how does it manage to continue executing subsequent code after the "next()" function is called?

middlware pipeline schema

I came across a middleware pipeline flowchart in Microsoft's documentation, and its calling process seems to follow a recursive pattern. Assuming that the Invoke function of each middleware calls "next", when the first middleware calls "next", it goes into the second middleware, and so on until the last middleware calls its "next". This would create a stack of calls that is released layer by layer, and the program flow returns to the front to execute the code after each "next".

But that would be a stack overflow (if there are thousands of middleware), and I don't believe that would be the implementation, and if it's called sequentially by asp.net core, how does it manage to continue executing the code after "next"?

However, this approach could potentially lead to a stack overflow, especially if there are thousands of middleware components. I find it hard to believe that this is the actual implementation. On the other hand, if middleware components are called sequentially by ASP.NET Core, how does the platform manage to continue executing the code after each "next" call?

2 Answers 2

1

The diagram you posted is accurate. Each layer of middleware will call the next layer with the stack unwinding layer by layer after the final layer is reached. This means each layer can perform pre- and post- activity before and after calling "next" on the next middleware layer.

Yes, theoretically you could get a stack overflow exception if the stack of middleware is soooo deep. But that applies to any chained set of functions. If you have enough middleware that you hit a stack overflow, you probably have a design problem.

Sign up to request clarification or add additional context in comments.

Comments

0

The middlewares are in the chain and rely on recursive composition. You can manage to continue executing the code because you are effectively waiting for the return value of the next middleware. So the first completed middleware is the third one in your image which returns to middleware two. So you can do whatever you want after you call the next() method.

You can check and try the pattern Chain of Responsibility and create similar example for yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.