Backport fix to optimize code for polls to avoid run queries in loop