I am aware of ulimit and I know how to limit memory for a process that I explicitly start, or start using a script. But in this case I have a service that is managed and launched by systemd.

How can I limit its max memory and have it killed (or even better: prevent it from memory allocation (return NULL to malloc / realloc)) when it reaches the memory usage maximum?


The manpage for systemd.exec has a list of LimitXXXX instructions and a handy table comparing them to the ulimit options, by way of the setrlimit() system call.

To limit the process's entire address space (ulimit -v) use LimitAS=. Otherwise to limit the just the stack (ulimit -s) use LimitSTACK= or data segment (ulimit -d) use LimitDATA=

According to the setrlimit() manpage, these limits will cause allocating additional memory to fail. STACK and AS will terminate the program with a sigsegv if the limit is reached and the stack needs to grow (and the program did not handle this).


Systemd supports limiting memory usage via the MemoryLimit option, as described at: https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html

The way system handles the situation when maximum memory allowed (per service) is exhausted depends on both the underlying cgroups implementation and the way systemd implements resource control; I'm guessing the process would be killed (via OOM killer).

  • 1
    Would it restart the service when memory limit is reached? – Aftab Naveed Jul 12 '18 at 8:30

For limits analogous to ulimit:

man systemd.exec

LimitAS=(like ulimit -v)
LimitRSS=(like ulimit -m)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.