Rewrite for better scalability and to avoid deadlocks.