code refactor and fix cache bug