Fix logic to find available next number for limiters and queues. It fixes #3998