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
- Transport Layers (
cpp-tcpnetandcpp-quic) - Event Loop and Background Pump
- Session-Affinity Worker Pool
- Server Request Lifecycle
- Client Internals
- Examples Walkthrough
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:
- Inbound (
HandleQuicStreamData): Inspects the first byte of stream data (data[0] < 0x20indicates 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 clientHEADERSframes (0x01) viacpphttp::qpack::Decode, buffersDATAframes (0x00) up tomax_body_size_, and callshttp3::ReconstructHttp11Requeston streamFIN. - Outbound (
Send/ProcessResponseBytes): Incrementally parses the HTTP/1.1 response generated byHttpServerImpl(includingContent-Length,Transfer-Encoding: chunked, and file stream chunks), strips connection-specific headers (Connection,Keep-Alive,Proxy-Connection,Transfer-Encoding,Upgrade), encodes aHEADERSframe (0x01) withqpack::Encode, wraps body pieces inDATAframes (0x00), and sends streamFINonce the full body is written.
Note:
QuicServerTransportenforceskMaxH3FrameSize(64 KB) for control and header frames andmax_body_size_(default10 MB) for requestDATAframes. 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:
- Transport I/O & Worker Threads (
cpptcpnet/cppquic):TcpListenerruns an OS poller thread (pollon Linux/macOS,WSAPollon Windows) that accepts sockets, performs non-blocking reads/writes and TLS handshakes, and publishesConnectionEventandTransferEventmessages viacpppubsub::PubSub(reached viaGetEventBroker()).QuicServerruns its UDP packet loop, encryption, and stream state machine overcppudpnetandcppquic’s worker pool.
- Server Event Pump (
HttpServerImpl::background_thread_): Started byserver.Start()and joined cleanly byserver.Stop(),background_thread_drainstransport_->TryReceiveTransferEvent()andtransport_->TryReceiveConnectionEvent()in a loop, waiting onshutdown_cv_foridle_timeout_(default10ms) whenever both queues are empty:- Send completion & graceful close: When
event->is_sendarrives for a session insessions_to_close_, it decrementspending_send_bytes_[session_id]and callstransport_->Disconnect(session_id)only after every response byte has been handed off to the socket. - Chunked file streaming (
PumpFileTransfer): Decrementssession->file_bytes_in_flightand pumps the next disk chunk (compressing on the fly viaStreamCompressorwhenis_compressed_streamis active) while keeping in-flight bytes undermax_outbound_buffer_size / 2(minimum64 KB). - Disconnect cleanup: On
ConnectionState::Disconnected, removes theSessionStatefromsessions_, invokesws_behavior.on_closefor upgraded WebSockets, and clears pending close tracking.
- Send completion & graceful close: When
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:
- Byte chunks for a single TCP connection arrive at
HandleIncomingDatastrictly in order, preventing race conditions in header reassembly, HTTP pipelining, and WebSocket frame decoding. - Different connections execute in parallel across all CPU cores without a global parser lock.
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::mutexorstd::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/PutStreamroutes are matched immediately afterParseHeaderso upload chunks stream without buffering the body, which means they bypassmiddlewares_.
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:
- Thread safety & shutdown:
request_mutex_serializes concurrent requests on one client instance.*Asynccalls share a globalcppasyncworker::WorkerPool(default isstd::thread::hardware_concurrency(), falling back to 4 when that is ≤ 1; must be set viaSetClientWorkerPoolSizebefore constructing the first client using the default pool, because the pool is a function-local static) or an injected pool, and~HttpClientImpl()setsalive_ = falseand waits for allpending_tasks_before tearing down the transport. - Keep-alive & error recovery: Connections stay open across requests unless the server sends
Connection: close, an error/timeout occurs, or the client redirects to a different origin.
WebSocketClient
WebSocketClient wraps cpptcpnet::TcpClient and a cpppubsub::Worker for connection-state events:
- On
Connect(url, timeout), parsesws://orwss://, configures OpenSSL viaClientTlsConfig(peer verification enabled by default), generates a random 16-byteSec-WebSocket-Key, and verifies the server’s101 Switching Protocols+Sec-WebSocket-Acceptresponse. - All outbound frames sent by
Send,SendBinary,Ping, andCloseare masked with a per-frame random 4-byte key as required by RFC 6455. - Inbound frames are assembled in
ProcessFrames()(supporting continuation frames up tomax_body_size_=10 MB, auto-replyingPongtoPing, and dispatchingOnMessage/OnBinary/OnClose). - Uses
internal::CallbackScopeandStopClientAndWorkerso callingDisconnect()orClose()from inside anOnMessage/OnClosecallback defers thread joining and avoids self-deadlock.
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:
- Generates a temporary
./demo_spa_dist/directory withindex.htmlandstatic/css/style.css, then mounts it at/appviaserver.StaticDir("/app", spa_dir, true)(SPA fallback enabled). - Registers scoped middleware
server.Use("/api/", ...)that checksCookie: session_token=...against a mutex-guardedactive_sessionsset (allowing/api/loginand/api/methrough, returning401JSON otherwise). - Implements
/api/login,/api/logout,/api/me, and/api/dashboard-data, settingHttpOnly; SameSite=Strictcookies viaSet-Cookie.
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:
- Generates
index.htmlplussmall_file.txt(10 KB),medium_file.txt(5 MB), andlarge_file.txt(25 MB) inside./demo_download_dist/and serves them viaserver.StaticDir("/", demo_dir, false). - Registers a global middleware (
server.Use(...)) that copies a customX-Accept-Encodingheader intoreq.headers["Accept-Encoding"], allowing the browser UI’sfetch()speed tests to compare compressed (gzip, br, zstd) vs uncompressed (identity) transfers side-by-side.
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:
- Loads
certs/server.crtandcerts/server.key(usingCPPHTTP_CERTS_DIRinjected by CMake) and enables TLS viaserver.GetListener().EnableSSL(ssl_config). - Serves an interactive chat UI on
GET /and registers a WebSocket echo handler onserver.WebSocket("/ws", std::move(ws_behavior))implementingon_open,on_message, andon_close.
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:
- Attaches
cppquic::SetLoggerfor QUIC diagnostics. - Configures
certs/server.crtandcerts/server.keyon bothserver.GetTransport()->GetTcpTransport().GetListener().EnableSSL(ssl_config)andserver.GetTransport()->GetQuicTransport().GetServer().SetCertificate(cert_file, key_file). - Serves
/,/about, and/api/stats(reading live counters fromserver.GetTransport()->GetServer().GetStats(), includingactive_connections,packets_sent,streams_opened, andretransmissions).
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>:
- Accepts optional CLI arguments:
host(127.0.0.1),port(4433),path(/), andsave_filename(index.html). - Sets a 5-second timeout (
SetTimeout), attachescppquic::SetLogger, sendsclient.Get(path, headers), prints response headers, and either prints JSON bodies or saves HTML tosave_filename.
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/statsdirectly againstquic_http_serverfails TLS verification.quic_http_serverserves a self-signed certificate (server.crt), andquic_http_client.cppdoes not relax verification (ClientTlsConfig::verify_peerdefaults totrue). To connect withquic_http_client, updateexamples/quic_http_client.cppto specify the CA file (ca_file) or allow self-signed certificates viaclient.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:
- Configures
SetMaxBodySize(40 MB),SetMaxOutboundBufferSize(40 MB),SetSendChunkSize(128 KB),cppquic::QuicProfile::HighThroughput(), and TLS certificates for both TCP and QUIC. - Measures and prints throughput (
MB/s) for:- HTTP/1.1 over TLS (
HttpClient):GET /downloadwithClientTlsConfig::ca_file. - HTTP/3 over QUIC (
HttpClientImpl<QuicClientTransport>): Initial handshake pass + warm-connection reuse pass onGET /download. - Secure WebSocket (
WebSocketClient): Echoes 256 KB chunks overwss://until 20 MB is echoed back, reporting combined send+receive throughput.
- HTTP/1.1 over TLS (
Run it:
./build/protocol_throughput_benchmark 8080