Optimize code for polls to avoid queries to be runned in loop