Open
Description
Summary
When using an ensure
block after redirect_to
in a long-running Rails controller action, Kamal Proxy returns a 502 with EOF
error.
Reproduction Steps
- Long-running controller action (e.g., 48s)
- Ends with
redirect_to
- Has
ensure
block with I/O (e.g.,Tempfile.unlink
) - Deployed via Kamal
Environment
- Rails 8.0.x
- Ruby 3.4.x
- Puma 6.x (worker_timeout: 600s)
- Kamal 2.x + Kamal Proxy (HTTP/2 → HTTP/1.1)
Actual Behavior
- Rails returns 302 successfully
- Kamal Proxy returns
502 EOF
after response completes
Root Cause
Response is sent, but ensure
block continues I/O. Connection is already closing, causing EOF at proxy.
Workaround
Move I/O operations before redirect_to
.
# Don't use ensure block after redirect_to
temp_file.close
temp_file.unlink
redirect_to ...
Suggested Fixes
- Rails: Warn or finalize response before executing ensure
- Kamal Proxy: Handle post-response I/O gracefully
- Docs: Recommend not using
ensure
with I/O afterredirect_to
Optional: Detailed Logs and Analysis
Actual Error Logs
Kamal Proxy logs:
{"time":"2025-06-12T03:48:47.88591784Z","level":"ERROR","msg":"Error while proxying","target":"containerid:80","path":"/documents","error":"EOF"}
{"time":"2025-06-12T03:48:51.882280088Z","level":"INFO","msg":"Request","status":502,"service":"myapp-web","duration":51821493715}
Rails logs:
[request-id] Completed 302 Found in 48300ms (ActiveRecord: 167.1ms)
Example Code
class DocumentsController < ApplicationController
def create
result = DocumentGenerator.generate(params)
temp_file = result[:file]
# ... save to database ...
redirect_to documents_path, notice: "Success"
ensure
if defined?(temp_file) && temp_file.is_a?(Tempfile)
temp_file.close
temp_file.unlink
end
end
end
Metadata
Metadata
Assignees
Labels
No labels