Add cleanup db optimization (issue #4375)