Architecture and execution contract¶
PACE separates its coroutine runtime, sockets, base protocol extensions and application protocols into four layers of independently linkable modules. This page explains how the modules fit together, how a reactor runs work, and which ownership and threading rules follow from that design. The execution model and ownership pages go deeper into the last two.
Four independently linkable layers¶
flowchart BT
R["Layer 0 · PACE Runtime<br/>Event loop · I/O backend · execution · timers · threading"]
N["Layer 1 · PACE Networking<br/>TCP socket · UDP socket · socket API"]
E["Layer 2 · Optional extensions<br/>TLS / SSL · DNS resolver · QUIC"]
A["Layer 3 · Optional application protocols<br/>HTTP/1.1 · HTTP/2 · HTTP/3 · WebSocket"]
R --> N
N --> E
N --> A
E --> A
| Layer | Module | Umbrella header | xmake target | Package config |
|---|---|---|---|---|
| 0, core | runtime | <pace/runtime.hpp> |
pace_runtime |
always included |
| 1, core | net | <pace/net.hpp> |
pace_net |
always included |
| 2, optional | tls, dns, quic | <pace/tls.hpp>, <pace/dns.hpp>, <pace/quic.hpp> |
pace_tls, pace_dns, pace_quic |
tls = true, dns = true, quic = true |
| 3 | http | <pace/http.hpp> |
pace_http (header-only) |
always included |
| 3, default on | http1, gateway | <pace/http1.hpp>, <pace/gateway.hpp> |
pace_http1 |
http1 (on by default) |
| 3, optional | http2, http3 | <pace/http2.hpp>, <pace/http3.hpp> |
pace_http2, pace_http3 |
http2 = true, http3 = true |
| 3, default on | websocket | <pace/websocket.hpp> |
pace_websocket |
websocket (on by default) |
Every module follows the same layout. Its public headers are under include/pace/<module>/, with one
umbrella header <pace/<module>.hpp> that includes them all; its implementation is compiled only from
src/<module>/; its xmake target installs only its own headers and links only the modules it depends on, so
xmake build pace_tls builds the runtime, networking and TLS and nothing else. Headers used only by the
implementation live next to it in src/<module>/; they are not installed and not part of the API, and there is
no detail namespace or directory in the public headers. <pace/pace.hpp> includes every module enabled in the
build, and the header-only target pace links all of them and installs <pace/pace.hpp>. It does not produce one monolithic libpace.a:
the pace package installs one static library per enabled module, and add_packages("pace") links them in
dependency order. Applications choose modules with the package configs and never name these targets; a narrow
consumer turns the default modules off, for example {http1 = false, websocket = false} for the runtime and
networking alone, and includes <pace/net.hpp>.
pace_http holds what HTTP/1, HTTP/2 and HTTP/3 share: the messages in <pace/http/types.hpp> and the router
and handler adapters in <pace/http/router.hpp>. HTTP/2 and HTTP/3 therefore do not depend on the HTTP/1
parser. The HTTP/1 module (<pace/http1/protocol.hpp>) holds the HTTP/1 clients and servers, the URL client
calls fetch/get/post and their async_* forms, and the small http::app. The gateway services
(<pace/gateway.hpp>: static files, reverse proxy, response cache) are compiled into pace_http1 for now,
because http::app's mount() and proxy() call them and the proxy uses the HTTP/1 client.
HTTP/1 and WebSocket are on by default and can be disabled; all modules that need third-party libraries are
off by default. TLS uses OpenSSL, HTTP/2 uses nghttp2, and HTTP/3 uses nghttp3 over the QUIC
module. QUIC uses ngtcp2 with OpenSSL by default; quic_backend = "openssl" selects OpenSSL's native QUIC
instead. Both QUIC backends are independent of the TCP TLS module, and HTTP/3 depends on neither HTTP/1 nor
HTTP/2. QUIC and HTTP/3 require POSIX; Windows builds reject these options. See the
platform matrix and the build options.
Core networking has no upward protocol dependencies. Buffer ownership stays explicit through spans, views and
owning message bodies; there is no separate buffer allocator module.
With modules = true, every module is also a C++20 named module (import pace.runtime;, import pace.net;,
import pace.http;, import pace.http1;, import pace.gateway;, import pace.tls;, and so on), built into the
pace_module target. Each named module exports only its own names, so code that imports pace.net also imports
pace.runtime; import pace; imports everything. The module interfaces are generated from
modules/exports.json and re-export the same declarations the headers make, so header and module consumers
share one ABI and can be mixed in one program. A module whose library is disabled still exists and exports
nothing.
One reactor per worker¶
pace::io_context owns a readiness poller, a ready queue, a timer heap, active coroutine roots, and socket wait registrations. Only one thread may execute a context's run() method. Coroutines submitted to that context resume on its running thread and do not migrate between contexts.
pace::runtime owns a fixed vector of contexts. run() creates one worker thread per context and joins all workers before returning. run_on_current_thread() instead runs context zero on the calling thread and creates N−1 workers; with one context it creates no worker. Both modes block, drain and join before returning, and share a single-use guard. The default count is the reported hardware concurrency, with a minimum of one; an explicit positive count overrides it. Access runtime.context(index) to choose where work is submitted. The runtime does not provide work stealing, automatic task balancing, or CPU affinity.
For applications with their own threading model, create independent contexts and run them on application-owned threads. A runtime is optional.
flowchart LR
A[Application] -->|spawn / post| Q0[Worker 0 inbox]
A -->|spawn / post| Q1[Worker 1 inbox]
Q0 --> R0[io_context 0]
Q1 --> R1[io_context 1]
R0 <--> P0[Native poller 0]
R1 <--> P1[Native poller 1]
R0 --> C0[Local coroutine continuations]
R1 --> C1[Local coroutine continuations]
Cross-thread submissions enter a mutex-protected inbox. The first submission after a drain wakes the poller; further submissions share that notification. An atomic pending flag lets the reactor skip inbox allocation and locking when nothing arrived. Enqueue and the empty transition both occur under the inbox mutex, so the first producer after a drain cannot lose its wakeup. Work submitted from the same running context enters its local queues directly.
Ready coroutine and posted-function batches are bounded at 256 items so continuously ready application work still gives the loop opportunities to inspect timers, I/O, and shutdown. A task-only loop skips a zero-timeout native poll when it has no registered descriptors. It still checks inbox submissions and timers on every turn. Once a socket has a registration, normal readiness polling continues.
Optional stage profiling (profiling = true) and component microbenchmarks separate operation cost from kernel waiting. Profiling is disabled by default and must remain disabled for comparative performance measurements.
Readiness backends¶
| Target | I/O notification | Cross-thread wakeup |
|---|---|---|
| Linux | epoll, persistent level-triggered interests |
Nonblocking eventfd |
| macOS / FreeBSD, 64-bit | kqueue, EV_ONESHOT read/write filters |
EVFILT_USER |
| Windows 64-bit, build 20348+ | IOCP socket state notifications | PostQueuedCompletionStatus |
| Windows compatibility / x86 | WSAPoll readiness array |
Nonblocking UDP loopback sockets |
Linux optional uring = true |
io_uring one-shot polls | Nonblocking eventfd |
The internal poller emits a token with readable, writable, and error flags. On
Linux the reactor retains matching interests across successive coroutine waits,
then reconciles dirty subscriptions before its next poll. A resumed reader can
rearm without an epoll_ctl call; an actually idle direction is removed before
polling to avoid spinning on stale readiness. Standalone poller users retain the
one-shot default. On kqueue and Windows event delivery disarms the descriptor
and the reactor rearms remaining waiters. For kqueue, separate read/write events
are merged and any undelivered counterpart is disarmed. Wakeups are internal.
Socket registrations have tokens independent of the native socket handle, allowing the reactor to discard stale deliveries after cancellation and handle reuse. UINT64_MAX is reserved for the internal wakeup token. Windows handles retain their native pointer width.
Selectable backends (pace::io_backend, chosen per context or per runtime) include IOCP socket notifications and optional io_uring polling. Reads and writes still use nonblocking socket calls; these paths do not submit overlapped or direct io_uring data transfers. WSAPoll remains the Windows compatibility path. Performance remains workload-dependent.
Tasks and object ownership¶
pace::task<T> is a lazy, move-only, single-consumer coroutine. Creating a task constructs its coroutine state but does not execute the function body. io_context::spawn(task<void>) transfers a root task to the context. Awaiting a child task transfers ownership into its awaiter; final suspension resumes its parent through coroutine transfer.
// Both forms consume one task exactly once.
co_await stream.write_all(pace::as_bytes(message));
auto pending = stream.read_some(pace::as_writable_bytes(buffer));
const auto count = co_await std::move(pending);
An lvalue task is intentionally not awaitable. A task object that still owns its state destroys that state when destroyed. Root-task ownership belongs to the context until completion. Task exceptions propagate through co_await; an unhandled root task or posted-function exception initiates context shutdown, and run() rethrows the recorded exception after draining. A runtime propagates worker failure after requesting all other contexts to stop and joining its workers.
The coroutine frame does not automatically own every object referenced by the coroutine:
- Keep a socket or listener alive until every operation using it has finished. Moving a socket while an operation on that object is suspended is not supported.
- Keep memory referenced by
std::spanandstd::string_view(including the viewspace::as_bytesandpace::as_writable_bytesreturn) valid throughout the awaited operation. A string literal is safe; a temporary owning string whose lifetime ends before the lazy task runs is not. - Keep the context alive until all sockets and listeners using it have been destroyed.
- A coroutine lambda accesses captures through its closure object. That closure must outlive the coroutine; immediately invoking a temporary capturing coroutine lambda is unsafe. Prefer named coroutine functions with owned values passed as parameters, or explicitly maintain the callable's lifetime.
pace::run(factory)owns the factory it is given until shutdown, which makes a capturing coroutine lambda safe there.
HTTP handler functions are stored by value in the serving tasks. Shared state reachable from handlers still belongs to the application and requires synchronization if used from different worker contexts.
Thread affinity and concurrency¶
spawn(), post(), and stop() are thread-safe entry points. Socket operations, explicit cancellation, socket closure, and timer/yield awaiting belong to the owning context. Creation and setup may be performed before that context starts; object cleanup may also occur after its run thread has joined.
One read waiter and one write waiter can be outstanding per socket simultaneously. A second waiter in the same direction is rejected. Accepting a connection is a read-side operation on its listener. Use post() to request socket manipulation from a different thread; do not close a live socket concurrently with its reactor.
Cooperative scheduling means a coroutine runs until it suspends or finishes. co_await io.yield() schedules another turn, and co_await io.sleep_for(duration) uses a steady-clock timer. An expired or zero-duration sleep still yields. Blocking calls and long CPU computations delay every coroutine assigned to that worker. There is no built-in executor for blocking work; run it on threads the application owns.
Stopping a context¶
Contexts keep running when idle. Call stop() explicitly; it is safe from another thread and wakes a blocked poller. The reactor cancels registered socket waits and timers with std::errc::operation_canceled, then resumes queued work so coroutine frames and resources can unwind. Awaiting I/O or yielding after shutdown also observes cancellation. New submissions after stop are rejected.
A context is single-use: run() cannot be called concurrently, nested inside another running PACE context on the same thread, or restarted after it returns. Destruction does not join an externally owned run thread. Stop the context, join that thread, then destroy sockets/listeners and finally the context. runtime.run() and runtime.run_on_current_thread() perform worker joins before returning. Caller mode cannot be nested inside another running PACE context.
tcp::stream::close() cancels its registered read/write operations before releasing the native socket. Destroying the socket object itself while a suspended member operation still refers to it is invalid: close it on its loop, allow the operation to resume and complete, then destroy the object. A listener passed to http::serve() must outlive that serving task and its accepted connections. Stopping the owning context cancels both accept and accepted-connection waits.
Stop is cooperative, not a forced thread interruption. An application coroutine that never suspends or returns, or application code blocked in a synchronous call, can prevent shutdown from completing. Local cancellation tokens propagate through awaited tasks and structured children; operation boundaries compose the earliest deadline without stopping unrelated work. Scoped callback timers support cancellation on completion; HTTP/1 servers can set receive and write deadlines.
TCP and HTTP¶
The TCP header is <pace/net/tcp.hpp>, included by <pace/net.hpp>. It declares pace::tcp::listener, pace::tcp::stream, pace::tcp::endpoint, and pace::tcp::listen_options; endpoint represents a numeric IPv4/IPv6 address, port, address family and optional numeric IPv6 scope.
TCP uses nonblocking numeric IPv4/IPv6 sockets. IPv6 listeners default to IPv6-only; applications explicitly opt into dual-stack binding. Operations first attempt the native call; when it would block, they await the relevant readiness event and retry. write_all() borrows its input bytes until the complete buffer has been sent. Socket errors use std::system_error. Linux sends suppress SIGPIPE per operation; platforms with SO_NOSIGPIPE configure it on the socket.
After a short TCP read, the next nonempty read waits for level readiness before
retrying recv, avoiding the common redundant EAGAIN call. This is a hint,
not an EOF decision: queued data, new arrivals and peer shutdown are still
reported by the poller and verified with recv. Full-buffer reads keep the
immediate-read path; the hint follows move operations.
TCP, TLS and QUIC streams share one interface, in bytes, named by the
pace::byte_stream concept: read_some(std::span<std::byte>),
write_all(std::span<const std::byte>), shutdown_write(), close() and context(). A transport carries bytes, not
text, so the stream boundary says so, and there is a single overload per operation instead of parallel char and
std::byte forms. Text crosses the boundary through zero-copy views (pace::as_bytes, pace::as_writable_bytes,
pace::as_text), which compile to a pointer cast; the protocol parsers (HTTP/1, WebSocket) keep working on characters
internally. Paired runs against the earlier interface kept TCP echo, WebSocket frames, HTTP/1
and HTTP/1 over TLS within 1%. Because tls::stream takes any byte stream as its transport and is one itself, the
same TLS code runs over TCP, over a QUIC stream or over another TLS stream, and an application adapter that models
the concept works with pace::write, pace::read_exact and TLS without further glue.
co_await stream.close_gracefully() half-closes the send side, then drains peer input until EOF, a 100 ms deadline, or 64 KiB of discarded data. Both bounds are configurable. A cancellable timer avoids blocking the reactor while waiting for the peer. The operation always releases the socket, including on cancellation or error, and requires that no other socket operation is outstanding. HTTP uses this bounded close after its final response so unread rejected-request bytes do not immediately reset the connection. Reaching either bound can still terminate a noncooperating peer before an orderly close; this is a shutdown bound, not a request timeout.
The multithreaded echo and HTTP examples create one listener per worker on the same port using SO_REUSEPORT where available. This lets the operating system distribute incoming connections. The Windows implementation does not provide this listener-sharing strategy; those examples require one worker on Windows. Separate ports and outbound connections can still use multiple Windows contexts.
The HTTP/1 module supports clients and servers, Content-Length and chunked framing, trailers, and sequential persistent connections. Default limits are 16 KiB of request headers, 1 MiB of request body, and 1,000 requests per connection; field counts, trailers and chunk metadata have separate bounds. Framing headers are generated by the library. The basic API buffers bodies; opt-in request-head admission chooses per-request body limits before upload, and owned response sources stream through bounded buffers with backpressure. See the HTTP/1 reference for validation and response semantics.
UDP preserves datagram boundaries and reports source addresses and truncation. TLS uses optional OpenSSL with certificate-chain and hostname verification, SNI and ALPN. A TLS stream permits one outstanding asynchronous operation in total, including read versus write. OpenSSL reads and writes through a custom BIO over PACE's own transport, so it never touches the socket directly; this keeps Windows handle width intact and suppresses SIGPIPE on supported platforms.
HTTP/2 uses optional nghttp2 for framing, HPACK and flow control. The client owns one connection for a batch of multiplexed requests. The server buffers bounded stream bodies; one driver owns the session and transport, and completed requests are dispatched to handlers that run concurrently up to max_concurrent_handlers. WebSocket handles HTTP upgrades on its own owned transport, then validates masking, fragmentation, UTF-8 and control frames. The HTTP/1 parser does not transfer its buffered transport into another protocol.
DNS uses reactor sockets and timers. It resolves A/AAAA and CNAME records without a blocking network lookup thread. QUIC exposes bidirectional and unidirectional streams over UDP. Its default transport is ngtcp2 with OpenSSL for TLS 1.3. Native OpenSSL QUIC is also available. HTTP/3 uses nghttp3 for HTTP framing and QPACK over those streams, with the same handler concurrency model as HTTP/2. These protocols are optional and are tested against local peers.
CONNECT tunneling, streaming incoming HTTP bodies and asynchronous file operations are not exposed. HTTP/2 and HTTP/3 retain buffered bodies; HTTP/1 offers known-length streaming responses through application-owned sources. Header/body limits bound individual message parsing; they do not generally bound connection lifetimes. Each protocol reference states its deadlines, ownership and concurrency limits.
Measurement and validation¶
The first benchmark measures one server reactor under a closed-loop localhost TCP echo workload. PACE and Asio use coroutines; libuv uses callbacks. Payloads and completed-request counts are validated, runs are repeated in rotating backend order, and every raw result is preserved. See the benchmark methodology for timing boundaries, limitations, and reproducible commands.
This workload does not establish HTTP performance, multiworker scalability, open-loop tail latency, or general superiority over another library. CI runs functional builds on Linux, macOS, and Windows, plus a FreeBSD VM, emulated architectures and mobile SDK compilation, and preserves correctness-check artifacts; see CI coverage. Published performance measurements come from local Linux. Current workflow results, tests, and evidence files determine what has actually been validated.
The separate worker/execution scaling study keeps total clients fixed, balances them across one listening port per context, and compares runtime-managed threads, caller participation and application-owned threads. Startup, warmup, steady state and shutdown have separate timing windows. Complete performance results include the README chart's unselected comparisons and negative findings.
Embedded HTTP gateway¶
Layer 3 includes directory mounts and reverse proxies. Connection pools and load-balancing counters are owned by each reactor, while bounded response caches use sharded CLOCK slots and immutable snapshots. Runtime descriptors also use generation-checked contiguous slots for event dispatch. These structures require no machine-specific cache tuning.