KatInterview

Why a 307 Redirect Makes a Stream-Body POST Stall in Requests

System DesignModel answer
MediumModel answerSystem Designpythonhttpdebugging

Last 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 POST with a plain bytes body completes.
  • The file-like body completes when the server does not redirect.

Your task

  1. Explain exactly why the redirected request hangs, and why it ends in a timeout rather than an error.
  2. Find the root cause in the library and fix it.
  3. 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 POST by 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, 302 and 303 show 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.