Handling Seekable Body Replays on 307 Redirects in Python requests
Data Structure DesignModel answerLast updated
Debug and implement stateful body rewind logic for seekable file-like streams when executing HTTP 307 redirects in an HTTP client library.
You are maintaining a Python HTTP client library similar to requests. When executing a POST request that receives an HTTP 307 Temporary Redirect (or 308 Permanent Redirect), the HTTP standard dictates that the client must re-issue the POST request to the target URL using the exact same request body.
Currently, string payload bodies work seamlessly across redirects. However, passing seekable byte streams (such as io.BytesIO) causes the second request attempt to hang and eventually hit a read timeout, or send 0 bytes.
Problem Scenario
Consider three test scenarios:
- String Body: Passing
data='test'. The initialPOSTsendstest. Upon a 307 redirect, the secondPOSTalso sendstest. (Currently PASSING) - Full Seekable Stream: Passing
data=io.BytesIO(b'test'). The stream position starts at0. (Currently FAILING / TIMING OUT) - Partially Read Seekable Stream: Passing
data=io.BytesIO(b'hello world')after reading5bytes (stream cursor is at position5). Both the initial request and the redirected request must send onlyworld(the payload starting from the initial cursor position). (Currently FAILING / TIMING OUT)
Payload (data) | Initial Stream Cursor | Target Body Sent on Attempt 1 | Target Body Sent on Attempt 2 (Post-307) |
|---|---|---|---|
'test' | N/A | 'test' | 'test' |
io.BytesIO(b'test') | 0 | b'test' | b'test' |
io.BytesIO(b'hello world') (after read(5)) | 5 | b' world' | b' world' |
Below are the test cases that demonstrate the expected behavior:
def test_307_redirect_with_string(httpbin):
r = requests.post(
httpbin('redirect-to'),
data='test',
params={'url': httpbin('post'), 'status_code': 307},
timeout=5
)
assert r.status_code == 200
assert r.history[0].status_code == 307
assert r.history[0].is_redirect
assert r.json()['data'] == 'test'
def test_307_redirect_with_seekable_stream(httpbin):
byte_str = b'test'
r = requests.post(
httpbin('redirect-to'),
data=io.BytesIO(byte_str),
params={'url': httpbin('post'), 'status_code': 307},
timeout=5
)
assert r.status_code == 200
assert r.history[0].status_code == 307
assert r.history[0].is_redirect
assert r.json()['data'] == byte_str.decode('utf-8')
def test_307_redirect_with_partially_read_stream(httpbin):
data = io.BytesIO(b'hello world')
data.read(5) # Advance position to 5
r = requests.post(
httpbin('redirect-to'),
data=data,
params={'url': httpbin('post'), 'status_code': 307},
timeout=5
)
assert r.status_code == 200
assert r.history[0].status_code == 307
assert r.history[0].is_redirect
assert r.json()['data'] == ' world'
Task
- Explain the root cause of why plain strings succeed while seekable streams hang or fail upon 307 redirects.
- Outline the exact modifications to request preparation and redirect processing required to fix the stream replay mechanism.
- Account for streams that were already offset prior to the initial request call, as well as non-seekable streams (e.g., sockets, generators).
Hints
Hint 1
Think about what happens to an `io.BytesIO` stream's internal read pointer when read during the first HTTP POST transmission. What state is it in when the client attempts the redirected POST?
Hint 2
If you reset the stream pointer using `.seek(0)`, what breaks in the partially read stream case? How can you preserve the original stream start offset?
Hint 3
How should the HTTP client detect if a stream supports rewinding vs. when it is unseekable (like a socket or generator)?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Technical Root Cause Analysis
When sending HTTP bodies over socket connections, the client reads the underlying payload (via .read() calls or chunked iterations) until EOF is reached.
-
String / Immutable Payloads: When
datais a string or bytes object, the payload is held in memory as an immutable sequence. Re-preparing or re-sending the request simply reads from the immutable sequence again, yielding identical data on subsequent attempts. -
Seekable Streams (
io.BytesIO, file objects): During the firstPOSTrequest, the socket layer reads the stream from its starting cursor position to the end (EOF).- By the end of the initial
POST,stream.tell()is positioned at the end of the stream. - When a
307 Temporary Redirectresponse is received, the client loop constructs a newPreparedRequestor re-uses the existing body reference. - During the second attempt, the client tries to read from the stream again. Because the cursor is already at
EOF,.read()returns an empty byte stringb''. - If
Content-Lengthheader was pre-calculated during initial preparation (e.g., 5 bytes), but the stream now yields0bytes, the underlying HTTP connection pool waits for the remaining 5 bytes to arrive or complete. This results in a hanging socket and a Read Timeout.
- By the end of the initial
Key Requirements for the Fix
- Record Initial Position: Before reading the stream during initial preparation, capture its starting offset:
initial_pos = stream.tell(). - Rewind Mechanism: Before executing a redirected request (where method and body are retained, such as HTTP 307/308), rewind the stream to
initial_posrather than blindly calling.seek(0). - Unseekable Stream Safety: If a stream does not support
.tell()or.seek()(e.g.,io.BufferedReaderaround a socket pipe or a generator), catchio.UnsupportedOperation/AttributeErrorgracefully and mark the body as non-rewindable.
Implementation Details
1. Tracking Body Position in PreparedRequest
We extend PreparedRequest (or request state tracking) to store both the payload source and its initial offset.
import io
class PreparedRequest:
def __init__(self):
self.body = None
self._body_position = None
def prepare_body(self, data, files, json=None):
# ... standard content-type and body encoding logic ...
self.body = data
# Capture starting position if body is seekable
self._body_position = self._get_stream_position(data)
def _get_stream_position(self, body):
if hasattr(body, 'tell'):
try:
return body.tell()
except (io.UnsupportedOperation, OSError):
return None
return None
def rewind_body(self):
"""Resets the body stream back to its original starting position if possible."""
if self.body is None:
return
if self._body_position is not None and hasattr(self.body, 'seek'):
try:
self.body.seek(self._body_position)
except (io.UnsupportedOperation, OSError):
raise RewindError("Unable to rewind stream for request redirect.")
elif hasattr(self.body, 'seek') and not callable(self.body):
# Fallback for streams where tell() failed initially but seek(0) might work
try:
self.body.seek(0)
except (io.UnsupportedOperation, OSError):
raise RewindError("Unable to rewind stream for request redirect.")
2. Handling Redirect Loop Logic
Inside the session/redirect handler (e.g., resolve_redirects):
def rebuild_method_and_body(prepared_request, response):
"""
Determines whether to keep or drop the body on redirect based on status code.
Rewinds body streams when re-using them.
"""
status_code = response.status_code
method = prepared_request.method
# HTTP 301, 302, 303 usually drop the body and change method to GET
if status_code in (301, 302, 303) and method != 'HEAD':
prepared_request.method = 'GET'
prepared_request.body = None
return
# HTTP 307 and 308 preserve the HTTP method and body
if status_code in (307, 308):
if prepared_request.body is not None:
try:
prepared_request.rewind_body()
except RewindError:
raise UnrewindableBodyError(
"Unable to automatically redirect request with an unseekable body stream."
)
Behavior Analysis across Payload Types
-
String Payload (
data='test'):_get_stream_positionreturnsNone.rewind_bodyis a no-op because strings are immutable and evaluated on demand.- Redirect succeeds.
-
Full Stream (
data=io.BytesIO(b'test')):- At initial preparation:
_body_position = 0. - First POST sends 4 bytes (
b'test'). Cursor moves to4. - 307 received:
rewind_body()callsbody.seek(0). - Second POST reads from position
0, sendingb'test'again. - Redirect succeeds.
- At initial preparation:
-
Partially Read Stream (
data=io.BytesIO(b'hello world')afterread(5)):- At initial preparation:
_body_position = 5. - First POST sends 6 bytes starting at index 5 (
b' world'). Cursor moves to11. - 307 received:
rewind_body()callsbody.seek(5). - Second POST reads from position
5, sendingb' world'again. - Redirect succeeds.
- At initial preparation:
-
Non-Seekable Stream (e.g., Generator, Pipe):
_body_position = None.- 307 received:
rewind_body()detects inability to rewind and raisesUnrewindableBodyError(or prevents silent corrupted redirect attempts).
Complexity & Overhead
- Time Complexity: $O(1)$ stream position capture and seek operations per redirect attempt. Payload reading remains $O(N)$ where $N$ is body length.
- Space Complexity: $O(1)$ memory used for storing integer stream offset
_body_position.