Why a 307 Redirect Makes a Stream-Body POST Stall in Requests
System DesignModel answerLast updated
Diagnose a Requests POST with a file-like body that stalls after a 307 redirect, fix the body-rewind logic, and write a deterministic regression test.
You have a local copy of the Python HTTP client library Requests with one bug planted in it. The bug report may not list every problem, so stay alert for related defects.
Reproduction. A client sends a POST whose body is a file-like object, for example io.BytesIO(b"amount=100"), to a URL that replies 307 Temporary Redirect with a Location header. Requests follows the redirect, but the second request never finishes. It waits until the read timeout fires, or forever if no timeout is set.
Two variants behave correctly:
- The same
POSTwith a plainbytesbody completes. - The file-like body completes when the server does not redirect.
Your task
- Explain exactly why the redirected request hangs, and why it ends in a timeout rather than an error.
- Find the root cause in the library and fix it.
- Write a regression test that fails before the fix and passes after it, without ever hanging the test suite.
Constraints
- Change only the library and its tests. The redirecting server is correct.
- Requests must keep following redirects for
POSTby default. - The body in the reproduction is seekable and its length is known, so it is sent with
Content-Length.
Points to address in your answer
- Do
308,301,302and303show the same hang? - What should happen when the body cannot be rewound, such as a generator or a pipe?
- If the stream was not at position 0 when the request was made, which bytes should the redirected request send?
- Should a redirect to another host re-send the body?
Hints
Hint 1
Think about what the server has been promised by Content-Length, and how many bytes the client actually writes on the second request. Who is waiting for whom?
Hint 2
Trace the file object's read position through prepare, copy and re-send. After the first send, where does tell() point? Look for the code that records and restores that position, and check each place it should be called.
Hint 3
Compare which status codes keep the method and body with those that turn POST into GET and strip the body headers. For the test, use a fake transport adapter that records the bytes it is handed instead of opening real sockets.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Why it hangs
When the body is prepared, a file-like body gets a Content-Length computed from its size, and the client sends exactly that many bytes by reading the stream. For io.BytesIO(b"amount=100") the header is Content-Length: 10.
After the first send, the stream's position is at the end. A 307 means "repeat the same request, same method and same body, at the new URL", so the library re-sends the prepared request with the same Content-Length: 10 header and the same stream object. If nothing rewinds the stream, a read returns b"", so the client writes zero body bytes.
The server on the new location has read the headers and is waiting for 10 body bytes. The client has nothing more to send and is waiting for a response. Both sides are blocked on a perfectly valid connection, so no error occurs. The only way out is the client's read timeout, or never if none is set. This is a framing mismatch, not a protocol failure.
A bytes body works because it is immutable and has no position. The non-redirect case works because the stream is read only once.
Why only some status codes expose it
307and308preserve method and body, so the stale stream is re-sent with itsContent-Length.301,302(for POST) and303turn the request into aGET, and the library drops the body and theContent-Length,Content-TypeandTransfer-Encodingheaders. No body is expected, so nothing hangs.
So the bug appears for 307 and 308, and not for the others.
Root cause
Requests handles this with three cooperating pieces. When a body is prepared, the library records the stream's starting position (tell()) in _body_position. If tell() fails, it stores a sentinel meaning "cannot be rewound". PreparedRequest.copy() must carry that position over. In the redirect loop (Session.resolve_redirects), when the body is kept and a Content-Length or Transfer-Encoding header is present, the library calls rewind_body() before re-sending.
The planted bug breaks one of these links: the position is not recorded, not copied, or the rewind step is skipped or seeks to the wrong place. Confirm which by printing request._body_position and body.tell() at each stage, then fix that link. A sound version looks like this:
# prepare_body
if getattr(body, "tell", None) is not None:
try:
self._body_position = body.tell()
except OSError:
self._body_position = object() # sentinel: cannot rewind
# resolve_redirects, after headers are rebuilt for the new request
rewindable = prepared_request._body_position is not None and (
"Content-Length" in headers or "Transfer-Encoding" in headers
)
if rewindable:
rewind_body(prepared_request)
def rewind_body(prepared_request):
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(prepared_request._body_position, int):
try:
body_seek(prepared_request._body_position)
except OSError:
raise UnrewindableBodyError("Unable to rewind request body")
else:
raise UnrewindableBodyError("Unable to rewind request body")
Because the rewind lives at the layer that re-sends the request, it covers every redirect hop.
Edge cases
- Stream that started mid-way. Seek back to the recorded position, not to 0. If the caller did
seek(7)before sending, both the first request and the redirected one carryb"100", andContent-Lengthis 3. - Unrewindable body (a pipe, a socket, a generator). Fail fast with
UnrewindableBodyErrorrather than sending a mismatched body. A silent empty send is worse than an exception. Generators use chunked encoding and have no position, so they cannot be replayed at all. - Cross-host redirect. Requests still re-sends the body for 307 and 308, as the spec requires, but strips the
Authorizationheader. Leaking credentials is the risk to call out, not the body itself. - Other defects. Since the report is not certain it is the only bug, check that
copy()preserves_body_position, and that rewinding happens once per hop rather than only on the first redirect.
Regression test
Do not open real sockets. Use a fake transport adapter that records the bytes it is handed. This is deterministic and fast, and it asserts the actual symptom: the second request carries the full body.
import io, requests
from requests.adapters import BaseAdapter
class RedirectOnce(BaseAdapter):
def __init__(self):
super().__init__()
self.bodies, self.lengths = [], []
def send(self, request, **kwargs):
body = request.body.read() if hasattr(request.body, "read") else request.body
self.bodies.append(body)
self.lengths.append(request.headers.get("Content-Length"))
r = requests.Response()
r.request, r.url, r.raw = request, request.url, io.BytesIO(b"")
if len(self.bodies) == 1:
r.status_code = 307
r.headers["Location"] = "http://example.test/new"
else:
r.status_code = 200
return r
def close(self):
pass
def run(body, status_body_start=0):
s = requests.Session()
a = RedirectOnce()
s.mount("http://", a)
body.seek(status_body_start)
s.post("http://example.test/old", data=body)
return a
def test_307_resends_full_body():
a = run(io.BytesIO(b"amount=100"))
assert a.bodies == [b"amount=100", b"amount=100"]
assert a.lengths == ["10", "10"]
def test_307_resends_from_original_offset():
a = run(io.BytesIO(b"amount=100"), 7)
assert a.bodies == [b"100", b"100"]
Add a parametrized case for 308, and a test with a body whose tell() raises, asserting UnrewindableBodyError. Before the fix the first test fails with [b"amount=100", b""], which is exactly the hang's cause. For end-to-end confidence, add one test against a local thread server with timeout=1, so a regression fails in about a second instead of hanging.
Common mistakes
- Blaming the server or the timeout instead of the Content-Length/bytes mismatch.
- Seeking to 0 unconditionally, which breaks streams that started mid-way.
- Fixing only the first hop, or only the status code that was reproduced.
- Writing a test that depends on a real network and can itself hang.