Why you need it
Many containers share one server to save money. They also share its memory. If one of them grows without stopping, from a bug or a big job, it takes the memory the others need, and they crash even though they did nothing wrong.
Think of it like this
Flatmates sharing one fridge. Each has a shelf that is theirs, whatever happens: that is the request. And nobody may fill more than two shelves, however hungry: that is the limit.
Where you’ll find it
- Kubernetes: Every container can set requests and limits for memory and CPU.
- Docker: Can cap a container's memory and CPU with runtime options such as
--memory. - Linux: Both are built on cgroups, the part of the kernel that counts and caps what a group of programs uses.
What to know first
Scheduler. The program that picks a server for each copy, skipping servers without room. See Scheduling.
Memory. The fast working space a program needs while it runs, measured in GB. When a server runs out, something gets killed.
How it works
- Neighbours share one pool. Video and the shop run on the same server and draw from the same memory. With no rules, whoever grabs first wins. This is the crash in the animation.
- A request is a reservation. The shop asks for 2 GB. The scheduler only places it on a server with 2 GB not yet promised to anyone, and adds up requests so it never promises more than the server has. This is the request in the animation.
- A limit is a ceiling. Video may use up to its limit and no more. If it tries to pass the limit, it is stopped and restarted. Only video pays for video's mistake. This is the ceiling in the animation.
- Memory and CPU behave differently. Memory cannot be taken back gently, so a container past its memory limit is killed.CPU can be shared out in slices, so a container at its CPU limit is just slowed down.
- Set them from real numbers. Watch what each container really uses at busy times. Set the request near that, and the limit a little above. Too low and it keeps restarting; too high and servers sit half empty.
An example
A server has 8 GB. The shop requests 2 GB. Video requests 4 GB with a 5 GB limit.
Video has a bug and keeps growing. At 5 GB it is stopped and restarted in a few seconds. The shop still has its 2 GB and never notices.
Without the limit, video grows to 7.5 GB, the server runs out, and the shop is the one that gets killed.
Further reading
- Resource management for pods and containers, Kubernetes docs. What requests and limits do, for memory and for CPU. Start with this one.
- Pod quality of service classes, Kubernetes docs. Who gets killed first when a server runs out, and why.
- Control Group v2, Linux kernel docs. The kernel feature underneath it all, for when you want the real thing.