Python service uses 100 of CPU on while loop with sleep inside docker container
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
A Python service can still show very high CPU in Docker even when the loop includes sleep. This usually happens because the loop is still polling too frequently or because container CPU quota makes moderate usage appear as 100 percent. Durable fixes replace busy polling with blocking primitives and validate behavior under real cgroup limits.
Core Sections
1. Why sleep does not automatically solve busy loops
This pattern still wakes frequently and burns scheduler cycles:
A one-millisecond sleep means one thousand wake-ups per second. If check_for_work is cheap but always called, CPU remains high when idle.
2. Container CPU metrics can be misleading
Inside Docker, 100 percent may represent full usage of assigned quota, not full host CPU.
If container is limited to one core, using that one core appears as 100 percent. On a large host, this can still be a small fraction of total machine capacity.
Check cgroup settings:
Interpret metrics relative to configured limits.
3. Replace polling with blocking queue operations
If work arrives through queue semantics, block on queue reads instead of repeatedly checking state.
This drastically reduces idle CPU usage.
4. Use Event.wait for state-change waiting
For non-queue workflows, waiting on synchronization events is usually better than periodic checks.
The thread sleeps efficiently until real work appears.
5. Async services should await IO, not poll
Network-heavy services often perform better with asyncio await semantics.
This model avoids manual loop polling and integrates naturally with async IO stacks.
6. Add profiling before and after fixes
Do not optimize blindly. Capture baseline and compare after changes.
Useful tools:
- '
py-spy topfor live Python stack sampling' - '
cProfilefor function-level hotspots' - Docker metrics under fixed workload
Separate idle profile from peak workload profile. Some fixes only help idle behavior.
7. Handle graceful shutdown correctly
Busy loops often ignore signals, causing abrupt container termination and possible data loss. Use signal handlers that set stop flags.
Graceful shutdown improves reliability and reduces restart instability.
8. Logging volume can amplify CPU use
High-frequency log writes inside hot loops can dominate runtime. If CPU remains high after blocking fixes, inspect logging frequency and formatter overhead.
Use rate-limited logs for repetitive idle states.
9. Production hardening checklist
For long-running containerized services:
- ensure loop waits are blocking where possible
- enforce reasonable backoff for retries
- monitor idle and active CPU separately
- verify cgroup quotas match expectations
- add health and shutdown behavior tests
This prevents recurrence after future refactors.
Common Pitfalls
- Using very short sleep intervals and calling it idle waiting.
- Misreading container CPU percentages without quota context.
- Polling non-blocking APIs continuously instead of waiting.
- Tuning code without collecting baseline profiles.
- Ignoring SIGTERM and forcing hard container kills.
Summary
- High CPU with loop plus sleep usually indicates polling, quota effects, or both.
- Replace polling with blocking queues, events, or async waits.
- Validate Docker cgroup settings before concluding code is broken.
- Profile idle and active paths to confirm real improvements.
- Implement graceful shutdown and controlled logging for stable operations.
Related reading
- Rabbitmq connection refused from Docker container to local host
- RabbitMQ in Docker - user creation not persisted
- RabbitMQ with Unity IOC Container in .NET
- Rails server is still running in a new opened docker container
- Python string 'in' operator implementation algorithm and time complexity
- Python subprocess is not scalable by default, any simple solution you can recommend to make it scalable?
- Python Sets vs Lists
- Python setup.py develop vs install

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.