Middleware fixes to hopefully prevent memory leaks