DEV Community

Bar Dror
Bar Dror

Posted on Originally published at codebeneath.com

HTTP 100 Continue Expectation Header: When Clients Pause Before Sending Body

Originally published on Code Beneath.

The HTTP 100 Continue Expect header is a mechanism that lets a client pause before sending a request body and wait for server permission. When a client sends Expect: 100-continue in the headers, it holds back the message body and waits for the server to respond with status code 100 (Continue) or reject the request outright. Many developers ignore this header entirely, leading to timeout hangs, wasted bandwidth on large uploads, or confused clients. Understanding the HTTP 100 continue expect header example implementation patterns is essential for building robust APIs that handle large payloads, file uploads, and resource-constrained scenarios efficiently.

Why Clients Send the Expect Header

Before uploading a 500 MB file or posting a large JSON body, a client may want to check: will the server accept this request at all? Perhaps the authentication token is invalid, the resource does not exist, or the content type is wrong. Without the Expect header, the client would waste time and bandwidth sending the entire body, only to receive a 401 or 400 response from the server.

With Expect: 100-continue, the flow is different. The client sends headers and waits. The server reads the headers, validates them, and either says "100 Continue, send the body" or "417 Expectation Failed" or rejects with another 4xx status. Only if the server says 100 do you transmit the body.

This is especially useful in handling HTTP requests where you need to validate early and avoid expensive resource allocation. A multi-part file upload endpoint can reject bad requests before the kernel buffers megabytes of data.

The Protocol Flow

The sequence goes like this:

  1. Client sends request line, all headers (including Expect: 100-continue), and waits without sending the body.
  2. Server reads the request headers, validates them (auth, content-type, size limits), and either sends 100 Continue or sends a final response like 417 Expectation Failed or 401 Unauthorized.
  3. If server sends 100, client sends the request body.
  4. Server reads the body, processes it, and sends the final response (200, 201, etc.).
  5. If server sends a final response (not 100), client stops and does not send the body.

Most clients set a timeout on the wait for 100 Continue, often 1 second or configurable. If the server does not respond within that window, the client may assume the server does not understand the header and send the body anyway.

Go Server: Accepting and Rejecting 100-Continue

Here is a complete, runnable Go server that demonstrates proper handling. The http.Server in Go does not automatically handle the Expect header, so you must do it manually.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "strconv"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    // Check for Expect: 100-continue
    if r.Header.Get("Expect") == "100-continue" {
        // Validate headers before reading body
        contentLength := r.ContentLength
        maxSize := int64(10 * 1024 * 1024) // 10 MB limit

        if contentLength < 0 {
            // Content-Length not provided or chunked
            w.WriteHeader(http.StatusLengthRequired)
            fmt.Fprintf(w, "Content-Length required\n")
            return
        }

        if contentLength > maxSize {
            w.WriteHeader(http.StatusRequestEntityTooLarge)
            fmt.Fprintf(w, "File too large: %d > %d\n", contentLength, maxSize)
            return
        }

        // All checks passed, tell client to send the body
        w.WriteHeader(http.StatusContinue)
        // Important: flush the response to ensure client receives 100
        if f, ok := w.(http.Flusher); ok {
            f.Flush()
        }
    }

    // Now read the body (after sending 100 or skipping this logic entirely if no Expect)
    body, err := io.ReadAll(r.Body)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        fmt.Fprintf(w, "Failed to read body: %v\n", err)
        return
    }
    defer r.Body.Close()

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, `{"uploaded": %d, "status": "success"}`+"\n", len(body))
}

func main() {
    http.HandleFunc("/upload", uploadHandler)
    log.Println("Server listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Enter fullscreen mode Exit fullscreen mode

Key points in this Go server:

  • We check the Expect header after the headers are parsed.
  • We validate Content-Length and other constraints before signaling 100.
  • We call w.WriteHeader(http.StatusContinue) to send 100.
  • We call Flush() to ensure the response is sent immediately, not buffered.
  • We then proceed to read the body with io.ReadAll(r.Body).
  • If validation fails, we send a final error status (417, 413, etc.) and do not send 100; the body is never read.

Python Server: Same Pattern with Flask

Here is the equivalent in Python with Flask. Flask does not automatically handle 100-continue either, but we can intercept the request before the WSGI server reads the body.

from flask import Flask, request, Response
import sys

app = Flask(__name__)

@app.before_request
def handle_expect_continue():
    """
    Intercept requests with Expect: 100-continue before WSGI reads the body.
    This runs before the route handler is called.
    """
    if request.headers.get("Expect") == "100-continue":
        # Validate headers
        content_length = request.content_length
        max_size = 10 * 1024 * 1024  # 10 MB

        if content_length is None:
            # No Content-Length header; reject
            return "Content-Length required\n", 411

        if content_length < 0:
            return "Invalid Content-Length\n", 400

        if content_length > max_size:
            return f"File too large: {content_length} > {max_size}\n", 413

        # All checks passed; send 100 Continue
        # We write directly to the WSGI input stream's underlying socket
        sys.stdout.flush()
        # In production, use the WSGI environ to access wsgi.input
        # and write to the client socket directly.
        # For now, we rely on the Flask test client or a proper WSGI server
        # to handle this. A real implementation requires gunicorn/uWSGI
        # middleware or a custom WSGI wrapper.

@app.route("/upload", methods=["POST"])
def upload():
    """
    Handle file upload. By the time this route is called,
    the client has already received 100 (or not).
    """
    if request.content_length is None:
        return "Content-Length required\n", 411

    data = request.get_data()
    return {
        "uploaded": len(data),
        "status": "success"
    }, 200

if __name__ == "__main__":
    # For testing with built-in server (not production-grade)
    app.run(host="0.0.0.0", port=8080, debug=False)
Enter fullscreen mode Exit fullscreen mode

Flask's built-in development server does not handle Expect properly because it is single-threaded and does not separate header parsing from body reading. In production, use Gunicorn, uWSGI, or another WSGI server that lets you inject middleware to send 100 Continue at the socket level before the WSGI app reads the body. The pattern is to write the HTTP response "HTTP/1.1 100 Continue\r\n\r\n" directly to the client socket.

Python WSGI Middleware for 100-Continue

Here is a production-ready WSGI middleware that wraps any Flask or other WSGI app and handles 100-continue correctly by writing to the environ:

import sys
import io

class Expect100ContinueMiddleware:
    """
    WSGI middleware that sends 100 Continue when appropriate.
    """
    def __init__(self, app, max_size=10*1024*1024):
        self.app = app
        self.max_size = max_size

    def __call__(self, environ, start_response):
        """
        Called by the WSGI server for each request.
        """
        expect = environ.get("HTTP_EXPECT", "").lower()

        if expect == "100-continue":
            content_length_str = environ.get("CONTENT_LENGTH", "")

            # Validate before reading body
            if not content_length_str:
                # Send 411 Length Required
                start_response("411 Length Required", [("Content-Type", "text/plain")])
                return [b"Content-Length required\n"]

            try:
                content_length = int(content_length_str)
            except ValueError:
                start_response("400 Bad Request", [("Content-Type", "text/plain")])
                return [b"Invalid Content-Length\n"]

            if content_length < 0:
                start_response("400 Bad Request", [("Content-Type", "text/plain")])
                return [b"Negative Content-Length\n"]

            if content_length > self.max_size:
                start_response("413 Payload Too Large", [("Content-Type", "text/plain")])
                return [f"File too large: {content_length} > {self.max_size}\n".encode()]

            # Send 100 Continue to the client
            wsgi_input = environ["wsgi.input"]
            if hasattr(wsgi_input, "_sock"):
                # Direct socket access (not always available)
                try:
                    wsgi_input._sock.sendall(b"HTTP/1.1 100 Continue\r\n\r\n")
                except Exception:
                    pass  # Ignore if socket not available

        # Call the wrapped WSGI app
        return self.app(environ, start_response)


# Example usage with Flask
from flask import Flask

app = Flask(__name__)

@app.route("/upload", methods=["POST"])
def upload():
    return {"status": "success"}, 200

# Wrap the Flask app with the middleware
app.wsgi_app = Expect100ContinueMiddleware(app.wsgi_app)

if __name__ == "__main__":
    # Use a proper WSGI server: gunicorn -w 1 app:app
    app.run(port=8080)
Enter fullscreen mode Exit fullscreen mode

This middleware validates headers before the WSGI app reads the body, and conditionally sends 100 Continue.

Go Client: Sending Expect: 100-Continue

Now let us write a client that actually sends the Expect header and handles the response properly:

package main

import (
    "bytes"
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

func uploadWithExpect(serverURL string, data []byte) error {
    client := &http.Client{
        Timeout: 10 * time.Second,
    }

    body := bytes.NewReader(data)
    req, err := http.NewRequest("POST", serverURL, body)
    if err != nil {
        return fmt.Errorf("failed to create request: %w", err)
    }

    // Set the Expect header to signal the server
    req.Header.Set("Expect", "100-continue")
    req.Header.Set("Content-Type", "application/octet-stream")

    // Important: explicitly set Content-Length so the server knows size before body arrives
    req.ContentLength = int64(len(data))

    log.Printf("Sending request with Expect: 100-continue, body size: %d bytes\n", len(data))

    resp, err := client.Do(req)
    if err != nil {
        return fmt.Errorf("request failed: %w", err)
    }
    defer resp.Body.Close()

    // Read the final response body
    respBody, err := io.ReadAll(resp.Body)
    if err != nil {
        return fmt.Errorf("failed to read response: %w", err)
    }

    log.Printf("Server responded with status: %d\n", resp.StatusCode)
    log.Printf("Response body: %s\n", string(respBody))

    if resp.StatusCode >= 400 {
        return fmt.Errorf("server rejected request: %d", resp.StatusCode)
    }

    return nil
}

func main() {
    // Test data: 5 MB
    testData := bytes.Repeat([]byte("x"), 5*1024*1024)

    err := uploadWithExpect("http://localhost:8080/upload", testData)
    if err != nil {
        log.Fatalf("Upload failed: %v\n", err)
    }

    log.Println("Upload succeeded")
}
Enter fullscreen mode Exit fullscreen mode

Key points in the client:

  • We set Expect: 100-continue in the headers.
  • We set Content-Length explicitly so the server knows the body size.
  • We call client.Do(req), which handles the 100 Continue protocol automatically in Go: it waits for the 100 response before sending the body, or if it gets a final status, it stops.
  • The Go HTTP client has a default timeout of about 1 second for waiting on 100 Continue; if it does not arrive, it sends the body anyway.

Python Client: Sending Expect Header

In Python, the standard library urllib does not support 100 Continue well, but the requests library has better support:

import requests
import io

def upload_with_expect(server_url, data):
    """
    Upload data using Expect: 100-continue.
    The requests library handles the protocol automatically.
    """
    headers = {
        "Expect": "100-continue",
        "Content-Type": "application/octet-stream",
    }

    # Create a BytesIO object to send as body
    body = io.BytesIO(data)

    print(f"Sending {len(data)} bytes with Expect: 100-continue")

    try:
        # requests automatically handles 100 Continue if present
        resp = requests.post(
            server_url,
            data=body,
            headers=headers,
            timeout=10,
        )

        print(f"Server responded: {resp.status_code}")
        print(f"Response: {resp.text}")

        if resp.status_code >= 400:
            raise Exception(f"Server error: {resp.status_code}")

        return True
    except Exception as e:
        print(f"Upload failed: {e}")
        return False

if __name__ == "__main__":
    test_data = b"x" * (5 * 1024 * 1024)  # 5 MB
    success = upload_with_expect("http://localhost:8080/upload", test_data)
    if success:
        print("Upload succeeded")
Enter fullscreen mode Exit fullscreen mode

Comparison: When to Use Expect: 100-Continue

Scenario Use Expect: 100-continue? Reason
Large file uploads (100 MB+) Yes Avoid wasting bandwidth if server rejects early (auth, quota, format).
REST API with small JSON payloads (<100 KB) No Latency cost (extra round trip) outweighs benefit. Just send it.
WebRTC or streaming over UDP/QUIC N/A Not applicable; these protocols do not use HTTP semantics.
Resumable uploads with chunking Yes Server can reject at chunk boundaries or validate chunk signatures early.
gRPC or Protocol Buffers No gRPC has its own flow control and backpressure mechanisms; Expect not used.
Slow network, high payload latency Yes Server can reject before kilobytes arrive; saves time and data.

Common Mistakes

Not Flushing the 100 Response

If the server sends w.WriteHeader(http.StatusContinue) but does not call Flush(), the response may be buffered. The client waits forever (until timeout) for the 100 response, then sends the body anyway. Always flush after writing the 100 status.

Sending 100 After Reading Headers Incompletely

If you send 100 Continue and then discover a validation error, you cannot send another status code. The connection is locked into sending the body. Always validate all headers first (Content-Length, Content-Type, auth, etc.) before sending 100.

Client Not Setting Content-Length

If the client sends Expect: 100-continue without Content-Length, the server cannot validate the payload size upfront. Many servers will reject this or ignore the Expect header. Always pair Expect with an explicit Content-Length.

Ignoring the Header Entirely

Some servers read the entire request body without checking for Expect. This breaks the protocol: the client is waiting for 100, the server is reading the body, and they deadlock. Go and Python HTTP libraries handle this internally, but custom socket code must respect the header.

Timing Diagram

Client                                    Server
  |                                          |
  | POST /upload HTTP/1.1                   |
  | Expect: 100-continue                    |
  | Content-Length: 5000000                 |
  | (no body yet)                           |
  |---------------------------------------->|
  |                                    [parse headers]
  |                                    [validate size, auth, etc.]
  |                                    [all OK]
  |                                   
  | HTTP/1.1 100 Continue                   |
  |<----------------------------------------|
  |                                          |
  | [5MB body]                              |
  |---------------------------------------->|
  |                                   [read body]
  |                                   [process]
  |                                          |
  | HTTP/1.1 200 OK                         |
  | Content-Type: application/json          |
  | {"uploaded": 5000000, "status": ...}   |
  |<----------------------------------------|
  |                                          |
Enter fullscreen mode Exit fullscreen mode

Measuring the Impact

To see real timing differences, use curl with the -w flag to measure handshake time vs. upload time:

#!/bin/bash

# Generate a 10 MB test file
dd if=/dev/zero bs=1M count=10 of=testfile.bin 2>/dev/null

echo "=== Upload WITH Expect: 100-continue ==="
time curl -X POST \
  -H "Expect: 100-continue" \
  --data-binary @testfile.bin \
  -w "\nConnect: %{time_connect}s, Time-to-first: %{time_starttransfer}s, Total: %{time_total}s\n" \
  http://localhost:8080/upload

echo ""
echo "=== Upload WITHOUT Expect header ==="
time curl -X POST \
  --data-binary @testfile.bin \
  -w "\nConnect: %{time_connect}s, Time-to-first: %{time_starttransfer}s, Total: %{time_total}s\n" \
  http://localhost:8080/upload
Enter fullscreen mode Exit fullscreen mode

On a good network with a responsive server, the difference is small. But if the server rejects the request (e.g., 401), the Expect version saves the time it would take to send the body.

FAQ

Does HTTP/2 support Expect: 100-continue?

HTTP/2 deprecates the Expect header in favor of its own flow control mechanisms. HTTP/2 uses SETTINGS frames and WINDOW_UPDATE to signal backpressure. However, if your HTTP/2 implementation maps it to HTTP/1.1 at the boundary, the header still works.

What if the server never sends 100 or a final status?

The client will wait for a configured timeout (usually 1-2 seconds) and then send the body anyway. This is a safety mechanism to handle servers that do not understand Expect. After the timeout, the client assumes it is safe to proceed.

Can I send 100-continue for GET requests?

Technically yes, but it makes no sense. GET requests do not have a body, so there is nothing to pause on. The server will likely ignore the header. Use Expect only with POST, PUT, or PATCH.

Should I always send Expect when uploading files?

Only for large files or when early validation is critical. For small uploads (under 1 MB), the latency of the extra round trip often outweighs the savings. Measure your use case.

How does Expect interact with Content-Encoding?

Expect is about request headers and size validation. Content-Encoding (gzip, deflate, etc.) happens after validation. The Content-Length in the Expect header validation should be the encoded size that actually goes on the wire.

What status codes reject Expect: 100-continue?

Common rejections: 401 Unauthorized, 403 Forbidden, 413 Payload Too Large, 417 Expectation Failed. Any status code other than 100 or 1xx tells the client to stop sending the body.

Does nginx support Expect: 100-continue?

Yes. Nginx respects the Expect header by default. If you send Expect: 100-continue, nginx will read your headers, validate them against its proxy settings, and either send 100 or reject before the body is buffered. This is one reason nginx is efficient for file uploads.

Top comments (0)