How to limit memory and processor usage in Windows 10 WSL2

We all love WSL2 and Windows10 for development work and it's really improving over time. WSL which was supposed to consume fewer resources has a bug and at times it could consume a huge (over 90%) RAM of your system. 

There could be 2 solutions to this problem, and we can divide them into temporary and permanent categories. 

Temporary solution

  • In order to free memory simply restart/kill WSL. in order to kill WSL use the below command.
    wsl.exe --shutdown
  • this should free memory from your windows machine.

Permanent Solution

  • In order to permanently solve the problem, we need to restrict WSL to use system resources.
  • Create a .wslconfig file at %UserProfile%\.wslconfig and use it to limit memory assigned to WSL2 on Windows 10.
  • here is the standard wslconfig file for WSL2
    	kernel=              # An absolute Windows path to a custom Linux kernel.
    	memory=              # How much memory to assign to the WSL2 VM.
    	processors=        # How many processors to assign to the WSL2 VM.
    	swap=                # How much swap space to add to the WSL2 VM. 0 for no swap file.
    	swapFile=            # An absolute Windows path to the swap vhd.
    	localhostForwarding= # Boolean specifying if ports bound to wildcard or localhost in the WSL2 VM should be connectable from the host via localhost:port (default true).
    	#  entries must be absolute Windows paths with escaped backslashes, for example C:\\Users\\Ben\\kernel
    	#  entries must be size followed by unit, for example 8GB or 512MB
  • In order to limit memory usage use the below configuration

I hope this will solve your problem. If you have any questions, feel free to ask in the comment section.