Move needs_build? check outside thread

It decreases number of database connections so we need lesser pool.