Safe Compressed Request Handling in ASP.NET Core: Preventing Decompression Bombs and Memory Spikes

Safe Compressed Request Handling in ASP.NET Core: Preventing Decompression Bombs and Memory Spikes

Clients that send large JSON documents often compress requests with gzip, br, or deflate to reduce network traffic. This is useful for bandwidth efficiency, but it introduces a server-side risk: a few kilobytes of compressed data may expand into hundreds of megabytes. If the application buffers the entire body in memory, only a few concurrent requests can cause high memory pressure, long garbage-collection pauses, or a denial of service.

This article shows how to accept compressed requests in ASP.NET Core, enforce a limit on the decompressed body, and deserialize JSON without first creating a large intermediate string. The example uses a batch import endpoint.

The problem: a small request with a large resource cost

Assume that an import service accepts up to 5 MB of expanded JSON from external systems. A compressed request may contain a Content-Encoding: gzip header. Looking only at Content-Length is not sufficient because that value can describe the compressed representation.

For example, an 800 KB compressed request might expand to 40 MB of JSON. The following implementation increases the cost further:

using var reader = new StreamReader(Request.Body);
var json = await reader.ReadToEndAsync();
var payload = JsonSerializer.Deserialize<ImportRequest>(json);

The application may keep both the complete string and the deserialized object graph in memory. For large bodies, multiple representations of the same data can exist at once. Microsoft’s ASP.NET Core guidance warns that reading large request bodies completely into memory can contribute to out-of-memory failures and denial-of-service risks.

1. Enable request decompression with middleware

ASP.NET Core provides AddRequestDecompression and UseRequestDecompression for automatically decompressing request bodies. The middleware examines Content-Encoding and wraps HttpRequest.Body with the appropriate decompression stream.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestDecompression();
builder.Services.AddControllers();

var app = builder.Build();

app.UseRequestDecompression();
app.MapControllers();

app.Run();

The middleware does not eagerly expand every request at application startup. Decompression occurs when an endpoint reads the body. Therefore, adding the middleware alone is not a complete memory-safety strategy. The endpoint must also have a clear limit for the expanded request.

2. Keep a safe server-wide default

Kestrel’s default maximum request body size is 30,000,000 bytes, approximately 28.6 MB. This default is a useful protection against accepting unlimited bodies. Instead of removing the global limit, configure a higher value only for endpoints that genuinely require it.

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 30_000_000;
});

Kestrel is not the only layer that may enforce a limit. IIS, a reverse proxy, or an API gateway can reject the request before it reaches ASP.NET Core. For example, IIS has its own maxAllowedContentLength request-filtering setting. The proxy, web server, and application limits should therefore be designed together and tested in the deployed topology.

3. Apply a narrow limit to the large endpoint

Not every endpoint needs the same request size. A profile update may need only 256 KB, while a product import may require 5 MB. With MVC controllers, apply the limit at the action level:

[ApiController]
[Route("api/imports")]
public sealed class ImportsController : ControllerBase
{
    [HttpPost]
    [RequestSizeLimit(5_000_000)]
    public async Task<IActionResult> Import(
        CancellationToken cancellationToken)
    {
        var request = await JsonSerializer.DeserializeAsync<ImportRequest>(
            Request.Body,
            cancellationToken: cancellationToken);

        if (request is null)
            return BadRequest("The request body is empty.");

        return Accepted(new { requestId = Guid.NewGuid() });
    }
}

public sealed record ImportRequest(
    string Source,
    IReadOnlyList<ImportItem> Items);

public sealed record ImportItem(string Code, decimal Amount);

The important detail is that the limit protects the expanded request body. A compressed body can be small, but if decompression attempts to produce more data than the configured limit allows, reading the body fails. This is an important defense against decompression bombs.

4. Deserialize JSON directly from the request stream

JsonSerializer.DeserializeAsync can read UTF-8 JSON asynchronously from a Stream. This removes the step that first converts the entire body into a string:

var payload = await JsonSerializer.DeserializeAsync<ImportRequest>(
    Request.Body,
    cancellationToken: HttpContext.RequestAborted);

This does not mean that the result consumes zero memory. The target ImportRequest object graph still has to be created. The benefit is avoiding an additional large string containing the same JSON. For larger data sets, the contract itself matters: a paged or chunked import model usually creates less object pressure than one enormous document.

Pass RequestAborted to downstream operations as well. If the client disconnects, JSON parsing, validation, or database work should not continue indefinitely for a request whose response can no longer be delivered.

5. Separate body limits from workload limits

A request-body limit constrains the total body size, but it does not automatically limit the number of records, the length of individual fields, or the amount of database work. Add business-level limits after deserialization:

if (payload.Items.Count > 10_000)
{
    return UnprocessableEntity(new
    {
        error = "A single request may contain at most 10,000 items."
    });
}

if (payload.Items.Any(x => x.Code.Length > 64))
{
    return UnprocessableEntity(new
    {
        error = "The product code cannot exceed 64 characters."
    });
}

These checks protect different resources. The body-size limit protects network and server resources; record and field limits protect CPU, database, and queue capacity. A robust endpoint needs both types of control.

6. Observe encodings and rejection reasons

Compressed request handling can fail because of an unsupported encoding, invalid compressed bytes, an expanded-body limit, or invalid JSON. Production telemetry should distinguish these cases. Useful low-risk measurements include:

  • Endpoint and HTTP status code
  • The Content-Encoding value
  • Compressed content length and, where available, the expanded byte count
  • Processing duration and cancelled-request count
  • Requests rejected by body-size or JSON-validation rules

Do not log complete request bodies. JSON payloads may contain personal data, credentials, or commercial information. Prefer a request identifier, source-system identifier, and bounded counters that do not expose sensitive content.

Deployment checklist

  1. Register request decompression and enable only the encodings your clients need.
  2. Do not make the global request-body limit unlimited.
  3. Set a measured, endpoint-specific limit for large imports.
  4. Avoid converting large request bodies to strings with ReadToEndAsync.
  5. Use asynchronous deserialization and propagate RequestAborted.
  6. Enforce maximum item counts and field lengths as business rules.
  7. Align IIS, reverse-proxy, gateway, and application limits.
  8. Monitor rejected compressed requests without storing sensitive payloads.

Safe compressed-request support is more than adding one middleware component. The reliable design combines an expanded-body limit, stream-based JSON processing, cancellation, workload validation, and consistent proxy configuration. This preserves the bandwidth benefit of compression while preventing a deceptively small request from consuming uncontrolled server resources.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published