Architecture & Examples

cpp-http is a protocol layer built over a modular, asynchronous C++17 networking stack. It separates socket/QUIC I/O, thread scheduling, event publication, and HTTP/1.1, HTTP/3, and WebSocket protocol handling into cleanly layered components.

Table of Contents


Layered Stack Overview

At compile time, HttpServerImpl<Transport> and HttpClientImpl<Transport> bind to either TCP (cpp-tcpnet) or QUIC/UDP (cpp-quic), or to HybridServerTransport to serve both simultaneously.

flowchart TB
    App["Application Layer<br/>Routes, Middleware, StaticDir"]
    Core["cpphttp Core<br/>Server, Client, WSS<br/>HTTP/1.1, HTTP/3"]
    Trans["Transport Wrappers<br/>TCP, QUIC, and Hybrid Transports"]
    TcpNet["cpp-tcpnet<br/>TcpListener / TcpClient<br/>poll/WSAPoll + OpenSSL"]
    Quic["cpp-quic<br/>QuicServer, QuicClient<br/>TLS 1.3 Transport"]
    Infra["Runtime Primitives<br/>WorkerPool & PubSub"]

    App --> Core
    Core --> Trans
    Trans --> TcpNet
    Trans --> Quic
    TcpNet --> Infra
    Quic --> Infra

Transport Layers (cpp-tcpnet and cpp-quic)

All protocol classes delegate socket and datagram I/O to thin transport adapters in cpphttp.hpp:

Adapter Underlying Engine Responsibilities
TcpServerTransport cpptcpnet::TcpListener Non-blocking TCP accept/read/write, optional OpenSSL/LibreSSL TLS, ConnectionProfile tuning, state_events & transfer_events subscriptions
TcpClientTransport cpptcpnet::TcpClient + cpppubsub::Worker Outbound TCP/TLS connect with ClientTlsConfig, asynchronous read callbacks, disconnect signaling, transfer_events subscriber
QuicServerTransport cppquic::QuicServer UDP/QUIC stream handling, auto-detection of HTTP/3 (HEADERS/DATA/SETTINGS + QPACK) vs raw HTTP/1.1-over-QUIC, maps (conn_id, stream_id) to session_id
QuicClientTransport cppquic::QuicClient Opens bidirectional QUIC streams per request (OpenStream(true)), decodes HTTP/3 HEADERS/DATA frames back into HTTP/1.1 responses for HttpClientImpl
HybridServerTransport TcpServerTransport + QuicServerTransport Binds TCP and UDP to the same port, maps (is_quic, transport_session_id) to unified uint64_t session IDs so one HttpServerImpl serves both protocols

How HTTP/3 Translation Works

HttpServerImpl speaks HTTP/1.1 internally, while QuicServerTransport acts as a bidirectional protocol bridge:

  1. Inbound (HandleQuicStreamData): Inspects the first byte of stream data (data[0] < 0x20 indicates HTTP/3 unidirectional/framed streams). For HTTP/3 connections, it opens the server’s control (0x00 + SETTINGS) and QPACK encoder/decoder (0x02, 0x03) unidirectional streams, decodes client HEADERS frames (0x01) via cpphttp::qpack::Decode, buffers DATA frames (0x00) up to max_body_size_, and calls http3::ReconstructHttp11Request on stream FIN.
  2. Outbound (Send / ProcessResponseBytes): Incrementally parses the HTTP/1.1 response generated by HttpServerImpl (including Content-Length, Transfer-Encoding: chunked, and file stream chunks), strips connection-specific headers (Connection, Keep-Alive, Proxy-Connection, Transfer-Encoding, Upgrade), encodes a HEADERS frame (0x01) with qpack::Encode, wraps body pieces in DATA frames (0x00), and sends stream FIN once the full body is written.

Note: QuicServerTransport enforces kMaxH3FrameSize (64 KB) for control and header frames and max_body_size_ (default 10 MB) for request DATA frames. Protocol violations or malformed pseudo-headers close the QUIC connection immediately.


Event Loop and Background Pump

HttpServerImpl coordinates network I/O and asynchronous transfers using two complementary execution contexts:

  1. Transport I/O & Worker Threads (cpptcpnet / cppquic):
    • TcpListener runs an OS poller thread (poll on Linux/macOS, WSAPoll on Windows) that accepts sockets, performs non-blocking reads/writes and TLS handshakes, and publishes ConnectionEvent and TransferEvent messages via cpppubsub::PubSub (reached via GetEventBroker()).
    • QuicServer runs its UDP packet loop, encryption, and stream state machine over cppudpnet and cppquic’s worker pool.
  2. Server Event Pump (HttpServerImpl::background_thread_): Started by server.Start() and joined cleanly by server.Stop(), background_thread_ drains transport_->TryReceiveTransferEvent() and transport_->TryReceiveConnectionEvent() in a loop, waiting on shutdown_cv_ for idle_timeout_ (default 10ms) whenever both queues are empty:
    • Send completion & graceful close: When event->is_send arrives for a session in sessions_to_close_, it decrements pending_send_bytes_[session_id] and calls transport_->Disconnect(session_id) only after every response byte has been handed off to the socket.
    • Chunked file streaming (PumpFileTransfer): Decrements session->file_bytes_in_flight and pumps the next disk chunk (compressing on the fly via StreamCompressor when is_compressed_stream is active) while keeping in-flight bytes under max_outbound_buffer_size / 2 (minimum 64 KB).
    • Disconnect cleanup: On ConnectionState::Disconnected, removes the SessionState from sessions_, invokes ws_behavior.on_close for upgraded WebSockets, and clears pending close tracking.

Session-Affinity Worker Pool

In TcpListener, incoming socket bytes are not processed on the OS poll thread. Instead, TcpListener creates N independent single-threaded cppasyncworker::WorkerPool(1) workers (defaulting to std::thread::hardware_concurrency(), configurable via server.GetListener().SetWorkerThreadCount(N)).

flowchart LR
    Poll["TcpListener Poll Thread<br/>(poll / WSAPoll)"]
    Hash["Session-Affinity Hash<br/>worker_idx = session_id % N"]
    W0["WorkerPool #0 (1 thread)<br/>Sessions 0, N, 2N..."]
    W1["WorkerPool #1 (1 thread)<br/>Sessions 1, N+1, 2N+1..."]
    WN["WorkerPool #N-1 (1 thread)<br/>Sessions N-1, 2N-1..."]

    Poll -->|"session_id, bytes"| Hash
    Hash --> W0
    Hash --> W1
    Hash --> WN

Because each session_id always maps to the same single-threaded worker:

Tip: Route callbacks run directly on these worker threads. Per-connection parsing is serialized automatically, but any shared application state (maps, counters, databases) accessed across routes must still be protected with std::mutex or std::atomic.


Server Request Lifecycle

Every packet delivered to HttpServerImpl::HandleIncomingData moves through the pipeline below:

flowchart TD
    In["Incoming Bytes"] --> Append["Append to session buffer"]
    Append --> WsCheck{"session is websocket?"}
    WsCheck -- Yes --> WsParse["Parse WebSocket frame<br/>Dispatch event"]
    WsCheck -- No --> StreamActive{"Stream route active?"}
    StreamActive -- Yes --> StreamBody["HandleStreamRoute<br/>Feed body slices"]
    StreamActive -- No --> Term{"Found CRLF CRLF?"}
    Term -- No --> HdrLimit{"buffer > max_header?"}
    HdrLimit -- Yes --> E431["Send 431 + Close"]
    HdrLimit -- No --> Wait["Wait for packets"]
    Term -- Yes --> ParseHdr["ParseHeader & decode"]
    ParseHdr --> StreamMatch{"Matches stream route?"}
    StreamMatch -- Yes --> StreamBody
    StreamMatch -- No --> BodyCheck["Read body<br/>Enforce max_body_size"]
    BodyCheck --> MW

    subgraph Dispatch ["DispatchRequest"]
        direction TB
        MW["1. Run middleware pipeline"]
        WS["2. Match WebSocket upgrade"]
        RT["3. Exact routes -> Pattern -> HEAD/404"]
        Merge["4. Merge middleware headers"]
        MW --> WS --> RT --> Merge
    end

    Merge --> Post["Post-Process: Alt-Svc, Vary, Compress"]
    Post --> Send{"is_file?"}
    Send -- Yes --> Pump["Send headers + PumpFileTransfer"]
    Send -- No --> SendAll["Serialize & transport Send"]
    Pump --> Erase["Erase consumed bytes"]
    SendAll --> Erase

Note: Notice in the lifecycle above that PostStream / PutStream routes are matched immediately after ParseHeader so upload chunks stream without buffering the body, which means they bypass middlewares_.


Client Internals

HttpClientImpl<Transport>

HttpClientImpl provides synchronous, asynchronous (*Async), streaming download (GetStream / PostStream), and streaming upload (PostStreamAsync / PutStreamAsync) APIs over a persistent keep-alive connection:

sequenceDiagram
    participant Caller
    participant Pool as WorkerPool
    participant Client as HttpClientImpl
    participant Trans as ClientTransport

    opt Async API (*Async)
        Caller->>Pool: Enqueue request task
        Pool->>Client: Execute under request_mutex
    end
    Caller->>Client: Synchronous Get / Post
    Client->>Trans: EnsureConnected()
    Client->>Trans: Send headers & body
    Trans-->>Client: OnData -> append buffer
    Client->>Client: ReadResponse() framing check
    alt 3xx Redirect
        Client->>Client: Follow safe redirect
    else Final Response
        Client->>Client: Decompress (zstd/br/gzip)
        Client-->>Caller: Return HttpResponse
    end

Key internal behaviors:

WebSocketClient

WebSocketClient wraps cpptcpnet::TcpClient and a cpppubsub::Worker for connection-state events:


Examples Walkthrough

All example programs live in examples/ and are configured in CMakeLists.txt under CPPHTTP_BUILD_EXAMPLES (enabled by default when cpp-http is the top-level CMake project).

Building All Examples

cmake -B build
cmake --build build -j

To build without QUIC/HTTP3 targets:

cmake -B build -DCPPHTTP_ENABLE_QUIC=OFF
cmake --build build -j

Summary of Example Targets

Target Name Requirements & Port Primary Features Shown
spa_example Port 8085 (TCP) StaticDir SPA mode, scoped auth, cookie sessions, JSON API
download_example Port 8086 (TCP) Async file streaming, compression benchmarks, header rewrites
websocket_example Port 8087 (TLS) HTTPS (EnableSSL), WebSocket (wss://) echo, Web UI
quic_http_server Port 4433 (QUIC) HybridHttpServer (HTTPS + HTTP/3), server statistics
quic_http_client QUIC CLI HttpClientImpl<QuicClientTransport>, logging, file output
protocol_throughput_benchmark Port 8080 (QUIC) 20 MB throughput comparison: HTTPS vs HTTP/3 vs WSS

1. examples/spa_example.cpp (spa_example)

Demonstrates a full Single Page Application backend with cookie-based authentication:

Run it:

./build/spa_example
# Open http://localhost:8085/app/ in browser (admin / password123)

2. examples/download_example.cpp (download_example)

Demonstrates memory-efficient static file streaming and live compression benchmarking:

Run it:

./build/download_example
# Open http://localhost:8086/ in your browser

3. examples/websocket_example.cpp (websocket_example)

Demonstrates HTTPS and secure WebSocket (wss://) communication:

Run it:

./build/websocket_example
# Open https://localhost:8087/ in browser (accept self-signed cert)

4. examples/quic_http_server.cpp (quic_http_server)

Demonstrates cpphttp::HybridHttpServer serving both HTTPS (TCP) and HTTP/3 (UDP/QUIC) on the same port:

Run it:

./build/quic_http_server 4433 0.0.0.0
# Open https://localhost:4433/ in Chrome/Edge or test with curl --http3

5. examples/quic_http_client.cpp (quic_http_client)

Demonstrates querying a QUIC/HTTP/3 server from C++ with HttpClientImpl<QuicClientTransport>:

Verify the server with curl (main check with HTTP/3 support):

curl --http3-only -k https://127.0.0.1:4433/api/stats

Warning: Running ./build/quic_http_client 127.0.0.1 4433 /api/stats directly against quic_http_server fails TLS verification. quic_http_server serves a self-signed certificate (server.crt), and quic_http_client.cpp does not relax verification (ClientTlsConfig::verify_peer defaults to true). To connect with quic_http_client, update examples/quic_http_client.cpp to specify the CA file (ca_file) or allow self-signed certificates via client.SetAllowSelfSigned(true);.


6. examples/protocol_throughput_benchmark.cpp (protocol_throughput_benchmark)

Benchmarks a 20 MB transfer across all three protocols against an in-process HybridHttpServer:

Run it:

./build/protocol_throughput_benchmark 8080