release-2.4.1 Detect circular middleware stacks

ported #706 to 2.4.1 codebase.