From 44ac3065e5e4ef5e0b46aacd851a4835249a3ae3 Mon Sep 17 00:00:00 2001 From: Steffen Deusch Date: Tue, 24 Nov 2026 19:09:06 +0100 Subject: [PATCH 1/2] Allow setting a maximum heap size during request parsing --- lib/plug/parsers.ex | 73 +++++++++++++++++++++++++++++++++----- test/plug/parsers_test.exs | 61 +++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 8 deletions(-) diff --git a/lib/plug/parsers.ex b/lib/plug/parsers.ex index 6246526e9..b1ed8e8e2 100644 --- a/lib/plug/parsers.ex +++ b/lib/plug/parsers.ex @@ -98,6 +98,12 @@ defmodule Plug.Parsers do * `:validate_utf8` - boolean that tells whether or not we want to validate that parsed binaries are utf8 strings. + * `:max_heap_size` - the maximum heap size, in words, of the process + while it reads and parses the request. It accepts any value supported + by `Process.flag(:max_heap_size, value)`, and the previous value is + restored after parsing. By default, no limit is set. See the + "Limiting memory usage" section below. + * `:body_reader` - an optional replacement (or wrapper) for `Plug.Conn.read_body/2` to provide a function that gives access to the raw body before it is parsed and discarded. It is in the standard format @@ -153,6 +159,37 @@ defmodule Plug.Parsers do {:multipart, length: 20_000_000} # Increase to 20MB max upload ] + ## Limiting memory usage + + The `:length` option limits the size of the request body, but the parsed + params may need much more memory than the body itself. For example, each + element of a JSON list of small integers, such as `1,`, takes 2 bytes in + the body and 16 bytes once decoded on 64-bit systems. A decoder may also + need several times the size of the decoded data while it runs. + + The `:max_heap_size` option limits the memory a request can use while it + is parsed: + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + json_decoder: Jason, + max_heap_size: 4_000_000 + + The size is given in words (8 bytes on 64-bit systems), so the example above + allows roughly 32MB. If the limit is exceeded, the process is killed, so no + error is raised and no response is sent by `Plug.Parsers`. The web server + decides how the connection ends. Large binaries, such as the raw request + body, are stored outside of the process heap and, by default, do not count + towards the limit. + + The limit is checked during garbage collection against the whole heap of + the process, not only the parsed data. This includes data the process held + before parsing and garbage it has not collected yet, such as memory left + over from an earlier request on the same keep-alive connection. A process + that already uses more than the limit is killed at the first garbage + collection during parsing, even for a small body. Set the limit well above + the memory the process uses outside of parsing. + ## Built-in parsers Plug ships with the following parsers: @@ -255,13 +292,14 @@ defmodule Plug.Parsers do {parsers, opts} = Keyword.pop(opts, :parsers) {pass, opts} = Keyword.pop(opts, :pass, []) {query_string_length, opts} = Keyword.pop(opts, :query_string_length, 1_000_000) + {max_heap_size, opts} = Keyword.pop(opts, :max_heap_size) validate_utf8 = Keyword.get(opts, :validate_utf8, true) unless parsers do raise ArgumentError, "Plug.Parsers expects a set of parsers to be given in :parsers" end - {convert_parsers(parsers, opts), pass, query_string_length, validate_utf8} + {convert_parsers(parsers, opts), pass, query_string_length, validate_utf8, max_heap_size} end defp convert_parsers(parsers, root_opts) do @@ -288,7 +326,32 @@ defmodule Plug.Parsers do @impl true def call(%{method: method, body_params: %Plug.Conn.Unfetched{}} = conn, options) when method in @methods do - {parsers, pass, query_string_length, validate_utf8} = options + {parsers, pass, query_string_length, validate_utf8, max_heap_size} = options + + with_max_heap_size(max_heap_size, fn -> + parse_body(conn, parsers, pass, query_string_length, validate_utf8) + end) + end + + def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8, _}) do + body_params = make_empty_if_unfetched(body_params) + {conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8) + %{conn | params: params, body_params: body_params} + end + + defp with_max_heap_size(nil, fun), do: fun.() + + defp with_max_heap_size(max_heap_size, fun) do + previous = Process.flag(:max_heap_size, max_heap_size) + + try do + fun.() + after + Process.flag(:max_heap_size, previous) + end + end + + defp parse_body(conn, parsers, pass, query_string_length, validate_utf8) do %{req_headers: req_headers} = conn conn = @@ -323,12 +386,6 @@ defmodule Plug.Parsers do end end - def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8}) do - body_params = make_empty_if_unfetched(body_params) - {conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8) - %{conn | params: params, body_params: body_params} - end - defp reduce( conn, [{parser, options} | rest], diff --git a/test/plug/parsers_test.exs b/test/plug/parsers_test.exs index 342da3e9a..40a06a7b8 100644 --- a/test/plug/parsers_test.exs +++ b/test/plug/parsers_test.exs @@ -14,6 +14,12 @@ defmodule Plug.ParsersTest do {:ok, body, conn} = Plug.Conn.read_body(conn, opts) {:ok, body <> "BAZ", conn} end + + def read_body_and_heap_size(conn, opts) do + {:max_heap_size, max_heap_size} = Process.info(self(), :max_heap_size) + Process.put(:max_heap_size_while_parsing, max_heap_size) + Plug.Conn.read_body(conn, opts) + end end def parse(conn, opts \\ []) do @@ -620,4 +626,59 @@ defmodule Plug.ParsersTest do assert conn.params["foo"] == "bar" assert conn.body_params == %Plug.Conn.Unfetched{aspect: :body_params} end + + describe ":max_heap_size" do + @max_heap_size %{size: 100_000, kill: true, error_logger: false} + + test "kills the process when parsing goes over the limit" do + body = String.duplicate("list[]=1&", 100_000) + + {pid, ref} = + spawn_monitor(fn -> + conn(:post, "/", body) + |> put_req_header("content-type", "application/x-www-form-urlencoded") + |> parse(max_heap_size: @max_heap_size) + end) + + assert_receive {:DOWN, ^ref, :process, ^pid, :killed}, 5_000 + end + + test "applies the limit while parsing and restores the previous value" do + {:max_heap_size, previous} = Process.info(self(), :max_heap_size) + + conn = + conn(:post, "/?query=elixir", "body=foo") + |> put_req_header("content-type", "application/x-www-form-urlencoded") + |> parse( + max_heap_size: @max_heap_size, + body_reader: {BodyReader, :read_body_and_heap_size, []} + ) + + assert conn.params == %{"query" => "elixir", "body" => "foo"} + assert %{size: 100_000} = Process.get(:max_heap_size_while_parsing) + assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous} + end + + test "restores the previous value when parsing raises" do + {:max_heap_size, previous} = Process.info(self(), :max_heap_size) + + assert_raise Plug.Parsers.UnsupportedMediaTypeError, fn -> + conn(:post, "/", "foo") + |> put_req_header("content-type", "text/plain") + |> parse(max_heap_size: @max_heap_size) + end + + assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous} + end + + test "does not change the process flag by default" do + {:max_heap_size, previous} = Process.info(self(), :max_heap_size) + + conn(:post, "/", "body=foo") + |> put_req_header("content-type", "application/x-www-form-urlencoded") + |> parse(body_reader: {BodyReader, :read_body_and_heap_size, []}) + + assert Process.get(:max_heap_size_while_parsing) == previous + end + end end From 95a3ff20e76933e76fad022c1388627d4a92f4ec Mon Sep 17 00:00:00 2001 From: Steffen Deusch Date: Thu, 26 Nov 2026 11:37:00 +0100 Subject: [PATCH 2/2] calculate on top of current heap size --- lib/plug/parsers.ex | 88 +++++++++++++++++++++++++++----------- test/plug/parsers_test.exs | 49 +++++++++++++++++++-- 2 files changed, 108 insertions(+), 29 deletions(-) diff --git a/lib/plug/parsers.ex b/lib/plug/parsers.ex index b1ed8e8e2..2f893e3ad 100644 --- a/lib/plug/parsers.ex +++ b/lib/plug/parsers.ex @@ -98,11 +98,14 @@ defmodule Plug.Parsers do * `:validate_utf8` - boolean that tells whether or not we want to validate that parsed binaries are utf8 strings. - * `:max_heap_size` - the maximum heap size, in words, of the process - while it reads and parses the request. It accepts any value supported - by `Process.flag(:max_heap_size, value)`, and the previous value is - restored after parsing. By default, no limit is set. See the - "Limiting memory usage" section below. + * `:max_heap_size` - limits the memory the process may use while it reads + and parses the request. The value is the number of extra heap words + allowed on top of what the process already holds when parsing starts + (8 bytes per word on 64-bit systems). It also accepts a map in the shape + of `Process.flag(:max_heap_size, map)`, in which case `:size` is that + headroom. The previous flag value is restored after parsing. Defaults to + `4_000_000` (roughly 32MB of headroom); set it to `:infinity` to disable. + See the "Limiting memory usage" section below. * `:body_reader` - an optional replacement (or wrapper) for `Plug.Conn.read_body/2` to provide a function that gives access to the @@ -167,28 +170,41 @@ defmodule Plug.Parsers do the body and 16 bytes once decoded on 64-bit systems. A decoder may also need several times the size of the decoded data while it runs. - The `:max_heap_size` option limits the memory a request can use while it - is parsed: + `Plug.Parsers` sets a `:max_heap_size` while it parses a request, defaulting + to `4_000_000` words (roughly 32MB). You can raise it, lower it, or disable + it: plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], json_decoder: Jason, - max_heap_size: 4_000_000 - - The size is given in words (8 bytes on 64-bit systems), so the example above - allows roughly 32MB. If the limit is exceeded, the process is killed, so no - error is raised and no response is sent by `Plug.Parsers`. The web server - decides how the connection ends. Large binaries, such as the raw request - body, are stored outside of the process heap and, by default, do not count - towards the limit. - - The limit is checked during garbage collection against the whole heap of - the process, not only the parsed data. This includes data the process held - before parsing and garbage it has not collected yet, such as memory left - over from an earlier request on the same keep-alive connection. A process - that already uses more than the limit is killed at the first garbage - collection during parsing, even for a small body. Set the limit well above - the memory the process uses outside of parsing. + max_heap_size: 8_000_000 + + # or, to turn the limit off entirely + plug Plug.Parsers, parsers: [...], max_heap_size: :infinity + + The size is in words (8 bytes on 64-bit systems). It is headroom on top of the + heap the process already holds when parsing starts, not an absolute ceiling: + the current heap size is read and the configured size is added to it. This way + a process that already holds memory, such as garbage left over from an earlier + request on the same keep-alive connection, is not killed while parsing a small + body. + + If the limit is exceeded, the process is killed, so no error is raised and no + response is sent by `Plug.Parsers`. The web server decides how the connection + ends, and a warning is logged. Large binaries, such as the raw request body + and large string values, are stored outside of the process heap and, by + default, do not count towards the limit. + + Pick the limit against the memory a single request legitimately needs to + parse, not the raw body size. A body made mostly of one large value (an + upload, a base64 field) costs almost no heap, because that value stays off the + heap. A body made of many small elements costs much more: decoding is a few + times the decoded size, and structured data expands further, so tens of + thousands of small fields or list elements are needed before the default + limit is reached. To keep a limit from killing legitimate large requests, + size it above the heap those requests need (or set `:infinity`), and pass a + map such as `%{size: 4_000_000, kill: true, error_logger: false}` if you want + to tune the kill or silence the log. ## Built-in parsers @@ -292,7 +308,7 @@ defmodule Plug.Parsers do {parsers, opts} = Keyword.pop(opts, :parsers) {pass, opts} = Keyword.pop(opts, :pass, []) {query_string_length, opts} = Keyword.pop(opts, :query_string_length, 1_000_000) - {max_heap_size, opts} = Keyword.pop(opts, :max_heap_size) + {max_heap_size, opts} = Keyword.pop(opts, :max_heap_size, 4_000_000) validate_utf8 = Keyword.get(opts, :validate_utf8, true) unless parsers do @@ -339,10 +355,10 @@ defmodule Plug.Parsers do %{conn | params: params, body_params: body_params} end - defp with_max_heap_size(nil, fun), do: fun.() + defp with_max_heap_size(limit, fun) when limit in [nil, :infinity], do: fun.() defp with_max_heap_size(max_heap_size, fun) do - previous = Process.flag(:max_heap_size, max_heap_size) + previous = Process.flag(:max_heap_size, add_current_heap_size(max_heap_size)) try do fun.() @@ -351,6 +367,26 @@ defmodule Plug.Parsers do end end + # The configured size is extra headroom on top of what the process already + # holds, not an absolute ceiling. Adding the current heap size means a + # process that already holds memory (for example, garbage left over from an + # earlier request on the same keep-alive connection) is not killed while + # parsing a small body. + # + # A bare word count also enables the kill and a logged warning. A map is + # honored as given (so `:kill` and `:error_logger` can be set), except that + # its `:size` is likewise treated as headroom over the current heap. + defp add_current_heap_size(size) when is_integer(size), + do: %{size: size + current_heap_size(), kill: true, error_logger: true} + + defp add_current_heap_size(%{size: size} = max_heap_size), + do: %{max_heap_size | size: size + current_heap_size()} + + defp current_heap_size do + {:total_heap_size, size} = Process.info(self(), :total_heap_size) + size + end + defp parse_body(conn, parsers, pass, query_string_length, validate_utf8) do %{req_headers: req_headers} = conn diff --git a/test/plug/parsers_test.exs b/test/plug/parsers_test.exs index 40a06a7b8..1ec2c454a 100644 --- a/test/plug/parsers_test.exs +++ b/test/plug/parsers_test.exs @@ -655,10 +655,39 @@ defmodule Plug.ParsersTest do ) assert conn.params == %{"query" => "elixir", "body" => "foo"} - assert %{size: 100_000} = Process.get(:max_heap_size_while_parsing) + + # The configured size is added on top of the current heap, so the flag + # applied while parsing is strictly larger than the 100_000 we asked for. + assert %{size: size, kill: true, error_logger: false} = + Process.get(:max_heap_size_while_parsing) + + assert size > 100_000 assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous} end + test "sets the limit relative to the current heap, not as an absolute ceiling" do + parent = self() + + {_pid, _ref} = + spawn_monitor(fn -> + # Hold far more live data than the 100_000-word (~800 KB) headroom + # below. With an absolute max_heap_size this process would be killed + # at the first garbage collection, even for this tiny body; with + # headroom over the current heap it parses normally. + big = for i <- 1..200_000, do: {i, i + 1} + :erlang.garbage_collect() + + conn = + conn(:post, "/?query=elixir", "body=foo") + |> put_req_header("content-type", "application/x-www-form-urlencoded") + |> parse(max_heap_size: @max_heap_size) + + send(parent, {:parsed, conn.params, length(big)}) + end) + + assert_receive {:parsed, %{"query" => "elixir", "body" => "foo"}, 200_000}, 5_000 + end + test "restores the previous value when parsing raises" do {:max_heap_size, previous} = Process.info(self(), :max_heap_size) @@ -671,14 +700,28 @@ defmodule Plug.ParsersTest do assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous} end - test "does not change the process flag by default" do + test "applies the default limit while parsing" do + conn(:post, "/", "body=foo") + |> put_req_header("content-type", "application/x-www-form-urlencoded") + |> parse(body_reader: {BodyReader, :read_body_and_heap_size, []}) + + # Defaults to 4_000_000 words of headroom over the current heap, with the + # kill and a logged warning enabled. + assert %{size: size, kill: true, error_logger: true} = + Process.get(:max_heap_size_while_parsing) + + assert size > 4_000_000 + end + + test "max_heap_size: :infinity disables the limit" do {:max_heap_size, previous} = Process.info(self(), :max_heap_size) conn(:post, "/", "body=foo") |> put_req_header("content-type", "application/x-www-form-urlencoded") - |> parse(body_reader: {BodyReader, :read_body_and_heap_size, []}) + |> parse(max_heap_size: :infinity, body_reader: {BodyReader, :read_body_and_heap_size, []}) assert Process.get(:max_heap_size_while_parsing) == previous + assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous} end end end