In plain English (30 sec): A focused deep-dive on a specific mechanism or problem pattern.

The symptom

“Our ALB returns 504 Gateway Timeout every time a client sends a large file upload (50 MB+). Small requests work fine. The EC2 target reports healthy. If I SSH into the instance and curl the endpoint locally, it works.”

The 504 only happens through the ALB and only for large uploads. Small uploads (under 1 MB) complete successfully.

Reproduce

# Generate a 50 MB file
dd if=/dev/urandom of=large-file.bin bs=1M count=50

# Upload through the ALB — this will 504
curl -X POST -F "file=@large-file.bin" https://myapp.alb.example.com/api/upload

# Upload directly to the EC2 instance — this works
curl -X POST -F "file=@large-file.bin" http://10.0.1.50:5000/api/upload

The root cause chain

1. ALB idle timeout

The Application Load Balancer has a default idle timeout of 60 seconds. If no data flows between the client and the target for 60 seconds, the ALB closes the connection and returns 504 Gateway Timeout.

But the upload is only 50 MB — at typical bandwidth, that should complete in well under 60 seconds. So why does the ALB time out?

2. The application reads the entire body before processing

Examine the ASP.NET Core upload endpoint:

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    // Process the file
    using var stream = new MemoryStream();
    await file.CopyToAsync(stream);  // reads all bytes into memory

    // Validate the file content (slow operation)
    var isValid = await ValidateFileAsync(stream.ToArray()); // ⏱ ~30 seconds

    // Save to S3
    await SaveToS3Async(stream.ToArray()); // ⏱ ~20 seconds

    return Ok(new { size = stream.Length });
}

The IFormFile model binding reads the entire request body into memory. Then ValidateFileAsync takes 30 seconds and SaveToS3Async takes 20 seconds. During those 50 seconds, no data flows between the client and the ALB — the ALB has already forwarded the entire request, and the server is processing it.

3. ALB access logs confirm

Enable ALB access logs and check the log entry for the failed request:

https://s3.console.aws.amazon.com → Your ALB → Attributes → Edit → Enable Access Logs

The access log entry for the 504:

2026-08-24T14:30:15.123Z my-alb my-listener 10.0.1.50:5000 0.000 60.000 504 ...
  • request_processing_time: 0.000 (request was forwarded instantly)
  • response_processing_time: 60.000 (ALB waited 60 seconds for the target to start sending the response)
  • target_status_code: 504 (ALB gave up waiting)

Direct access to the EC2 instance works because there is no intermediate proxy enforcing a 60-second idle timeout.

4. The ALB’s connection flow

When a client uploads a large file through the ALB:

  1. Client sends the POST request body to the ALB
  2. ALB reads the request body in its entirety (buffered) and forwards it to the target
  3. Target receives the request and starts processing
  4. ALB waits for the target to send the response headers + body
  5. If the target takes longer than the idle timeout (60 seconds) to start sending the response, ALB returns 504

The ALB is not timing out the upload — it is timing out the response. The upload completes in seconds, but the server processing takes longer than 60 seconds.

The fix

Option A: Buffer the response asynchronously and return immediately

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    // Accept the upload and return immediately
    var uploadId = Guid.NewGuid().ToString();

    // Fire-and-forget the processing (use a background queue in production)
    _ = Task.Run(async () =>
    {
        var tempPath = Path.GetTempFileName();
        using (var stream = new FileStream(tempPath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        var isValid = await ValidateFileAsync(tempPath);
        if (isValid) await SaveToS3Async(tempPath);
        File.Delete(tempPath);
    });

    return Accepted(new { uploadId, status = "processing" });
}

Option B: Increase the ALB idle timeout

aws elbv2 modify-load-balancer-attributes \
    --load-balancer-arn arn:aws:elasticloadbalancing:... \
    --attributes Key=idle_timeout.timeout_seconds,Value=300

This gives the server up to 5 minutes to respond. But it only masks the problem — long-running requests still tie up ALB connections.

Option C: Use streaming and chunked transfer (best)

[HttpPost("upload")]
public async Task Upload(HttpContext context)
{
    // Stream the request body directly to S3 instead of buffering in memory
    using var s3Stream = await _s3Client.UploadObjectAsync("my-bucket", "uploads", context.Request.Body);
    await context.Response.WriteAsync("{\"status\":\"uploaded\"}");
}

The key: process the data as it arrives, sending periodic progress to keep the ALB connection alive. Chunked transfer encoding (Transfer-Encoding: chunked) also keeps data flowing, resetting the ALB’s idle timeout.

Deeper checks for production

  1. Increase the idle timeout to match your slowest valid request — default 60s is too low for file uploads with server-side processing. 300s (5 min) is a reasonable upper bound.

  2. Use a connection drain (deregistration delay) — set the target group’s deregistration delay to match the idle timeout, so in-flight requests complete when you deploy new code.

  3. Return a Location header for long-running operations — instead of keeping the connection open, accept the upload, return 202 Accepted with a Location header pointing to a status endpoint, and process asynchronously. This is the REST-async pattern.

  4. Consider using S3 pre-signed URLs — for large file uploads, have the client upload directly to S3 via a pre-signed URL and only notify your API when the upload is complete. This removes the ALB from the data path entirely.

Prevention checklist

  • ALB idle timeout is set to at least 300 seconds for APIs that handle large payloads
  • Long-running requests use the 202 Accepted pattern with an async status endpoint
  • ALB access logs are enabled and monitored for 504 patterns
  • Upload endpoints stream request bodies to their destination (S3, disk) instead of buffering in memory
  • Load testing includes the ALB in the test path, not just direct-to-instance calls

Source