Leanpub Header

Skip to main content

The Production C++ Systems Library

Nine books. One discipline. From the build system to the GPU, from the memory model to the async runtime, every layer of production C++ built, measured, and proven. Nothing is true until it has been profiled, fuzzed, and replayed.

Bought separately

$354.97

Minimum price

$149

$199

You pay

Author earns

$

Also available for 5 book credits with a Reader Membership

These books have a total suggested price of $354.97. Get them now for only $149!
About

About

About the Bundle

Nine books. One complete systems stack in modern C++. All finished.

Most C++ books stop where production starts. They show a build that works on one laptop, a benchmark that measures an empty loop, a queue that passes its tests on x86, and a server that handles ten connections. Then the code meets a real codebase, real load, and a second architecture.

This library starts where those books stop.

Nine complete books follow a production C++ system from the first build to the last token, in the order you would actually need them. Every technique comes with the measurement that proves it, the trade-off it costs, and the failure it prevents.

What's inside

Build it and measure it

  1. Production CMake for C++ Engineers: Fix dependency hell and slow builds with modern targets, presets, and modules.
  2. Bare-Metal Performance Engineering in C++: Profile with perf and Top-Down Microarchitecture Analysis, read assembly, and build benchmarks that don't lie.

Make it correct and concurrent

3. Memory-Safe C++ in Production: Enforce bounds and lifetime safety with hardened libraries, sanitizers, static analysis, and fuzzing.

4. Lock-Free C++ in Production: Master the memory model, hazard pointers, and epoch-based reclamation, and prove concurrent code correct on x86 and ARM.

5. Production C++23/26 Coroutines: Engineer zero-allocation async runtimes with std::generator, std::execution, and structured concurrency.

Make it serve and persist

6. Bare-Metal Network Programming in C++: Build zero-copy io_uring servers with coroutine scheduling and registered buffer pools that hold tail latency under load.

7. Deterministic Storage Engines in C++: Build crash-consistent LSM trees with write-ahead logging and io_uring, and test recovery under simulated power loss.

Make it parallel

8. Production CUDA for C++ Engineers: Optimize warp-level primitives and shared-memory tiling, guided by Nsight.

9. Bare-Metal LLM Inference in C++: Build quantized GEMM kernels and paged KV-cache systems for continuous batching.

How the series works

Every chapter closes with a running ledger that records what changed at that stage, so you can see exactly what each technique bought you. Code is modern C++20/23, with C++26 features marked where they apply, and written to compile. Compiler and library support is stated for every feature that needs it.

Who it's for

  • Senior and mid-level C++ engineers who ship and debug production systems
  • Engineers moving into infrastructure, databases, networking, or AI systems
  • Teams inheriting slow builds, flaky concurrency, or memory-unsafe code

You should be comfortable with modern C++ and Linux. These books do not teach syntax.

What you get

  • All nine complete books as DRM-free PDFs
  • Every future update to every book, at no extra cost
  • A reading path from toolchain to AI inference

Suggested reading order Build it right, measure it right, make it correct, make it concurrent, make it asynchronous, make it serve, make it durable, make it parallel, and put it all together.

Nothing is true until it has been profiled, fuzzed, and replayed.

Books

About the Books

Bare-Metal Performance Engineering in C++

Bare-Metal Performance Engineering in C++

Profiling with perf and Top-Down Microarchitecture Analysis to Build Benchmarks That Don’t Lie

Your benchmark says 4x faster and production doesn’t move. This book is about why, and how to make your numbers tell the truth.

Most C++ performance advice is folklore: virtual calls are slow, exceptions are free, -O3 beats -O2, more threads means more throughput. Each of these is true on some hardware, for some workloads, some of the time, and teams lose weeks acting on them without measuring. Meanwhile the real costs go unseen: a compiler that quietly deleted the code being benchmarked, a profiler that blamed the instruction after the one that missed cache, a hash table that waits on DRAM twice per lookup, a load test that misses the stalls production clients hit.

Bare-Metal Performance Engineering in C++ teaches the discipline that replaces guesswork with evidence. You’ll learn to write benchmarks the compiler can’t fool, to read hardware counters without being misled by multiplexing or skid, and to use Top-Down Microarchitecture Analysis to find in one run whether code is starved in the front end, losing work to mispredictions, or stalled on memory. Then you’ll apply that method from the compiler out to the kernel, and keep the results in place in production.

The book follows a single realistic workload from start to finish: a request-handling service that parses JSON, looks keys up in a multi-million-entry hash table, and serializes responses. Every chapter ends with a Bottleneck Ledger entry recording the service’s cycles per request, IPC, cache misses, and latency percentiles, the dominant bottleneck at that stage, what changed, and how the change was verified. By the end, the service uses about a third to a quarter of the CPU per request it started with, with a fraction of its original tail latency, and every step of that improvement is shown and justified.

What you’ll learn
  • How microbenchmarks lie through dead code elimination, constant folding, and hoisting, and how to prove they don’t with assembly and statistics
  • How to control frequency scaling, turbo, SMT, and core isolation so that a 2 percent difference means something
  • How the front end, out-of-order back end, branch predictor, SIMD units, caches, TLBs, and NUMA actually determine your code’s speed, with differences across Intel, AMD, and Arm called out
  • How to use perf stat, perf record, precise events, call graphs, flame graphs, and differential profiles correctly
  • How to diagnose bottlenecks with Top-Down analysis using perf, toplev, and VTune
  • How to read x86-64 and ARM64 compiler output well enough to spot missed vectorization, spills, bounds checks, and hidden calls
  • How to find time spent waiting rather than computing, using off-CPU profiling, eBPF, Perfetto, LTTng, and Intel Processor Trace
  • How to get the most from the compiler with LTO, PGO, AutoFDO, BOLT, and optimization remarks
  • What C++ abstractions really cost under measurement: virtual dispatch, exceptions, std::function, and template bloat
  • How to apply data layout, allocation, container, branchless, SIMD, and loop-transformation techniques, each shown as a measured before-and-after pair
  • How to scale concurrency: diagnose false sharing, coherence traffic, and lock contention, and choose between locks, sharding, and lock-free snapshots
  • How to tune at the system level: system call costs, page faults, io_uring, interrupt affinity, and transparent huge pages
  • How to keep it fast with HDR histograms, open-loop load testing, continuous profiling, and regression gates in CI
Who this book is for

This book is for C++ engineers who own the performance of code that runs in production: backend and infrastructure engineers with latency objectives, library maintainers, low-latency and trading developers, and anyone who reviews pull requests that claim speedups. It assumes you’re comfortable with modern C++ and basic computer architecture terms like caches and pipelines. It doesn’t assume prior experience with perf, assembly, or Top-Down analysis, because each tool is introduced from first principles where it’s needed.

It isn’t an algorithms book. It covers what happens after you’ve chosen the right algorithm, when two implementations of it differ by a factor of five because of how they use the machine.

What makes it different
  • Measurement first. Every performance claim is either measured with the method shown or framed as something you must measure. Figures are given as realistic ranges, not invented benchmark results.
  • Real code. The listings are complete, modern C++20/23 and are meant to compile, with the error handling real benchmarks and profiling harnesses need. Assembly listings state the compiler, version, and flags.
  • Hardware-aware. Claims name the microarchitecture they apply to, and the book points out where Intel, AMD, and Arm cores behave differently.
  • Trade-offs stated up front. Every technique comes with its costs: code size, memory, semantics, portability.
  • Production-ready. The final part covers tail-latency measurement, continuous profiling, CI regression detection, and a step-by-step investigation runbook.
What you need
  • A Linux machine, either x86-64 or AArch64, ideally bare metal, since many cloud VMs expose few or no hardware counters
  • GCC 13 or newer, or Clang 17 or newer
  • CMake and Google Benchmark
  • perf

VTune, AMD uProf, bpftrace, and Perfetto are used in later chapters. Four appendices give quick references for perf, hardware events and Top-Down metrics, compiler flags, and a full benchmarking and profiling checklist.

Production CMake for C++ Engineers

Production CMake for C++ Engineers

Fixing Dependency Hell and Slow Builds with Modern Targets, Presets and Modules

Your build shouldn’t be the slowest, least understood part of your system.

Most C++ engineers never chose to learn CMake. They inherited a CMakeLists.txt, copied a block to add a dependency, and moved on. Then the clean build hits half an hour, a dependency upgrade breaks three teams, and the release binary behaves differently from the one that passed CI.

This book is for that moment. It isn’t a beginner’s tour of CMake commands. It’s a field manual for fixing real production builds. Every chapter opens with a real-world failure: a version endpoint reporting the wrong commit, two copies of a library in one binary, a CI pipeline that broke without a single commit. Each one is traced back to its cause, and the fix is one you can apply, verify, and keep.

What you’ll learn:

  • How CMake actually works: configure, generate, and build phases, the cache, scope rules, and the policy system
  • Target-based CMake done properly, with PUBLIC, PRIVATE, and INTERFACE usage requirements and no leaked flags
  • Presets and toolchain files that make a build depend on the repository, not on the machine running it
  • Consuming dependencies with find_package, FetchContent, vcpkg, and Conan, and using dependency providers to control all of them from one place
  • Fixing dependency hell: diamond dependencies, ODR violations, version conflicts, and old dependencies that stop configuring on CMake 4
  • Producing relocatable packages others can consume, plus Python wheels built from the same project with nanobind and scikit-build-core
  • Faster builds with Ninja, ccache, precompiled headers, and unity builds, and diagnosing slow builds with -ftime-trace, build timelines, and faster linkers
  • C++20 modules and import std in CMake, including a migration path for existing codebases
  • Cross-compiling for ARM, embedded, Android, iOS, WebAssembly, and Apple universal binaries, plus CUDA as a first-class language
  • Testing and code quality: CTest, sanitizers, coverage, clang-tidy, libFuzzer targets, and SARIF annotations on pull requests
  • Production concerns: CI caching, reproducible builds, CPack, SBOMs, license tracking, and code signing
  • CMake at scale: monorepos, superbuilds, debugging CMake itself, and migrating from legacy builds

Every chapter ends with a Build Health Ledger, a measured record of what changed in configure time, clean build time, incremental rebuild time, and which problems were removed, along with how each fix was verified. Appendix D gathers every check into one build health checklist you can run against any codebase.

Who it’s for: C++ engineers who already use CMake and want to use it well, and anyone who has just been handed a team’s build and told to make it faster and stop it breaking.

Requirements: CMake 3.28 or later. Features from newer releases, including CMake 4.x, are marked by version.

Memory-Safe C++ in Production

Memory-Safe C++ in Production

Enforcing Bounds and Lifetime Safety Through Hardened Libraries and Sanitizer-Driven Development

Most of a large C++ codebase's serious security bugs come from a short list of failures: an index one past the end, a reference kept after its object is gone, a cast that trusts the wrong field, a value nobody initialized, a race on a shared string. Large vendors keep reporting that memory-safety issues make up the majority of their high-severity vulnerabilities. The tools that prevent most of them already exist. Most teams just don't use them every day.

Memory-Safe C++ in Production shows you how to use them every day.

You won't get a lecture on best practices. You'll take one realistic service and harden it from start to finish. relay is a network-facing message gateway with an untrusted input boundary, shared state across threads, hot paths where every check has a cost, and third-party code nobody owns. It ships with eight seeded memory bugs, one or more for each bug class, plus two that aren't listed. Over thirteen chapters you'll find them, fix them so their whole class can't come back, and build the tooling that catches the next one before it reaches production.

Every chapter ends with the Safety Ledger, a running record of what relay now enforces, what detects each bug class, which defects are still open, and what each step cost in measured performance. You always know what changed, what it bought and what it cost.

What you'll learn

  • Make spatial errors impossible to write. Use span-based interfaces, hardened libc++ and libstdc++ modes, C++26 contracts, Clang's Safe Buffers and checked parsing at the network boundary. Then measure the real cost of bounds checks, which is usually within noise, and fix the few that aren't.
  • Control lifetimes. Deal with dangling views, iterator invalidation, escaping lambdas, coroutine lifetime traps, shared_ptr cycles and use-after-move. Back up the fixes with explicit ownership, generational handles, arenas and compiler lifetime annotations.
  • Close the quiet bug classes. Cover type confusion, strict aliasing, unions versus std::variant, C++26 erroneous behavior, automatic variable initialization and checked integer arithmetic.
  • Build a sanitizer-first workflow. Run ASan, UBSan, MSan, TSan and HWASan on every build. Put GWP-ASan in production. Add static analysis with custom clang-tidy checks, and coverage-guided, stateful and differential fuzzing that runs continuously.
  • Harden what survives. Add stack protectors, _FORTIFY_SOURCE, control-flow integrity, shadow stacks, hardened allocators and ARM Memory Tagging, and verify all of it on the binary you actually ship.
  • Migrate real codebases. Audit by exposure. Define a safe subset the build enforces. Apply refactoring patterns that remove whole bug classes. Build safe C++/Rust interop with cxx. Decide rewrite versus harden honestly, one component at a time.
  • Run it as a program. Track metrics that can't be gamed, set up CI/CD safety gates and canary comparison, follow an incident runbook for memory corruption, and write a multi-year roadmap for a real organization.

What makes this book different

  • Every claim can be checked. Costs are measured with a stated protocol and reported as ranges, never as one convenient number from one machine.
  • Every technique is applied to real code that builds, runs and is tested under sanitizers. There is no pseudocode.
  • It's honest about limits. Hardened C++ is not memory-safe by construction, and the book says exactly where the remaining risk lives and how to contain it.
  • It covers the whole lifecycle, from the first build flag to production detection, incident response and the decision to rewrite.

Who it's for

The book is for engineers who ship and maintain production C++: application and systems developers, tech leads, security engineers and platform teams. You should know modern C++. You don't need prior experience with sanitizers, fuzzers or the memory model. Each tool is introduced from first principles before you rely on it.

Four reference appendices come with the book: a sanitizer and hardening flag reference, an undefined behavior catalog, a static analysis check reference and a memory safety audit checklist you can run on your own codebase tomorrow.

Lock-Free C++ in Production

Lock-Free C++ in Production

Mastering the Memory Model with Hazard Pointers and Epoch-Based Reclamation

our lock-free queue passed every test. It ran clean under ThreadSanitizer for a year. Then it moved to ARM servers and started returning corrupted data, with no crash and no warning.

This book is about that gap between code that runs and code that is correct.

Most lock-free code works because of hardware it was never written for. x86 quietly adds orderings the code never asked for, and test machines rarely stall a thread at the worst possible instruction. This book shows you how to build lock-free C++ that is correct by proof rather than by luck, and how to verify it on every architecture you ship to.

What you’ll learn:

  • The C++ memory model, precisely. Every ordering is justified by the happens-before edge it creates, not by what one CPU happens to do.
  • Production data structures. SPSC, MPSC and MPMC queues, the Michael-Scott queue, Chase-Lev work-stealing, lock-free hash maps, skip lists, seqlocks, RCU and MCS locks, each with its progress guarantee stated.
  • Memory reclamation, solved. Hazard pointers, epoch-based reclamation, QSBR and interval-based schemes, built from the algorithm up to production domains, including C++26’s std::hazard_pointer and std::rcu.
  • Verification that finds real bugs. ThreadSanitizer’s blind spots, controlled scheduling, model checking with GenMC and Relacy, and linearizability checking.
  • Performance that holds up. False sharing, contention management, scalability measurement and NUMA placement.
  • Running it in production. Misuse-resistant APIs, debugging with core dumps and rr, and porting from x86 to ARM.

Every structure ships with complete, compilable modern C++, its stress test, and the deliberate bugs that prove the tests can catch it.

For C++ engineers who will run lock-free code in production, and who need it to be right.

Production C++23/26 Coroutines

Production C++23/26 Coroutines

Engineering Zero-Allocation Async Runtimes with std::execution and Structured Concurrency

Your coroutines pass every test. Then production load makes the I/O genuinely asynchronous.

A const std::string& parameter dangles. A stack overflows only when the cache is warm. A lost wakeup stalls a pool for fifty milliseconds. A fire-and-forget coroutine crashes the service at shutdown, once every twenty deploys. None of these are compile errors, and none show up in a thread dump, because a suspended coroutine is not on any stack.

This book is about those failures: why they happen, how to reproduce them on demand, and how to build a runtime where they cannot.

What you will build

Over fourteen chapters you build one runtime, piece by piece, and every piece is tested under AddressSanitizer and ThreadSanitizer:

  • A lazy task type with symmetric transfer, and a measured explanation of why chains of synchronous completions overflow the stack
  • sync_wait, a single-threaded run loop, a thread pool, and a work-stealing scheduler, with the sleep protocol that avoids lost wakeups
  • Frame allocators (per-worker pools and request arenas) that bring steady-state heap allocations to a proven zero
  • when_all, when_any, async scopes, and fail-fast error propagation that make fire-and-forget impossible
  • Cooperative cancellation with std::stop_token, deadlines, race-free cancellation, and shielded async cleanup
  • Async mutexes, semaphores, channels, and a timer wheel integrated into the event loop
  • Adapters that connect all of it to C++26 std::execution, with a phased migration plan for an existing runtime

What makes it different

  • Every chapter opens with a production failure and closes with a ledger. The Allocation and Latency Ledger records heap allocations per operation, suspend-and-resume cost, and how correctness was verified. Read in sequence, the ledgers trace the runtime from three heap allocations for three trivial calls to a measured zero.
  • Real sanitizer output, not hand-waving. You see the actual AddressSanitizer and ThreadSanitizer reports for each bug, with the lines that identify it, so you can recognize them in your own logs.
  • Numbers as honest ranges. Costs are given as typical ranges, never as invented benchmark results, and "zero-allocation" is always shown with a counter, never asserted.
  • Opinionated where the field is divided. Lazy over eager tasks. Parameters by value. No detached coroutines. Hop to change the kind of thread, never just the thread. You get a position and the reasoning behind it.
  • Debugging and testing built in. Async stack traces, a live-frame registry, seeded simulation of coroutine interleavings with virtual time, sync-point tests that force a lost wakeup on every run, and tracing that survives thread hops.
  • GCC, Clang, and MSVC, side by side. Elision, tail calls, frame layout, diagnostics, and sanitizer support differ between compilers, and the book says exactly how.

Inside the book

  • Part I, Foundations: frames, promises, awaiters, handles, and the real cost model
  • Part II, Generators: std::generator, ranges composition, elements_of, and where a hand-written iterator still wins
  • Part III, Tasks and Runtimes: task types, symmetric transfer, schedulers, zero-allocation frames
  • Part IV, Structured Concurrency: scopes, when_all, cancellation, timeouts, lifetimes across suspension
  • Part V, std::execution: senders and receivers, custom senders, coroutines and senders in both directions, migration
  • Part VI, Production: wrapping C libraries, timers, async primitives, interop with threads, debugging, profiling, library API design
  • Appendices: customization points, std::execution algorithm reference, compiler and library support matrix, and a coroutine code review checklist
Who this book is for
  • Engineers who will run coroutine code in production: request services, market data and trading infrastructure, storage engines, database clients, game job systems
  • Library authors designing coroutine or sender-based APIs
  • Teams migrating callback or future-based code, or a custom runtime, toward std::execution

You should be comfortable with templates, move semantics, RAII, the memory model, and threads. This is not an introduction to what coroutines are.

What you will be able to do
  • Predict which thread resumes a coroutine, and who owns its frame, from the code alone
  • Find and fix dangling parameters, closure traps, double destroys, lost wakeups, and cancellation races
  • Prove a request path allocates nothing, and keep it that way in CI
  • Choose between your own runtime, stdexec, and the standard task, and migrate between them in safe phases
  • Review coroutine code against a concrete checklist
Requirements

GCC 13+, Clang 17+, or Visual Studio 2022; CMake 3.25+; NVIDIA stdexec for Part V onward. Linux is recommended for ThreadSanitizer and perf.

Bare-Metal Network Programming in C++

Bare-Metal Network Programming in C++

Building Zero-Copy io_uring Servers with Coroutine Scheduling and Registered Buffer Pools

Your server isn't slow. It's paying a tax on every request, and you can't see it.

You profiled the handler, tuned the hash table and rewrote the JSON serializer, and the p99 still jumps the moment real traffic arrives. That's because most of a request's cost was never in your code. It's in the system calls, the copies, the wakeups, the context switches, and the queue nobody is measuring. Swapping epoll for io_uring won't fix it either, because a completion-based ring needs a different server design.

Bare-Metal Network Programming in C++ is about that design. It builds one production-grade server from start to finish: an HTTP/1.1 front end for an in-memory cache, with keep-alive, pipelining, TLS and clients that misbehave. Every chapter changes one layer and ends with a ledger of what changed: throughput, p50/p99/p99.9 latency, connection capacity, CPU per request, and how each result was verified under load.

This book doesn't use echo servers or skip error handling. The code is C++23 and handles the failures a live server actually hits: partial reads and writes, connection resets, exhausted buffer rings, completion queue overflow, cancellation races, slow clients and malformed requests.

What you'll build and learn

  • Why a straight port from epoll to io_uring keeps most of the old costs, and the server shape that removes them
  • Multishot accept and receive, provided buffer rings and registered buffers sized from real equations, not guesswork
  • Zero-copy send done correctly, including the two-completion ownership rule that silently leaks other clients' data when it's done wrong
  • Coroutines as io_uring awaitables, with frames that are never freed while the kernel is still writing into them
  • Thread-per-core executors, cross-core messaging with MSG_RING, cancellation that always waits for the kernel, and structured concurrency for safe teardown
  • A strict, allocation-free HTTP/1.1 parser that rejects request smuggling, plus ordered pipelining and chunked decoding
  • TLS without giving back the I/O model: OpenSSL as a pure state machine, kernel TLS, session tickets, and defenses against Slowloris and slow-read attacks
  • High-throughput UDP with GSO and GRO, multicast feed handling, and QUIC design decisions
  • Backpressure, admission control and load shedding that keep the server serving at 200% offered load instead of falling over
  • NUMA placement, batching trade-offs, honest load testing that corrects for coordinated omission, and when AF_XDP or DPDK is worth it
  • Zero-downtime restarts, observability, fault injection, fuzzing, io_uring restrictions and seccomp hardening

Who this book is for

It's for backend, infrastructure and systems engineers who build or run proxies, gateways, caches, trading infrastructure or high-connection servers, and who need them fast under real load, not just in a benchmark. You should already know modern C++, sockets and TCP, and have written a non-blocking server before. This book starts where the tutorials stop.

What's inside

  • Six parts across 15 chapters, from the cost of a single request to running in production
  • Every io_uring feature named with the kernel version that introduced it and the fallback when it's missing
  • Compilable C++23 code using liburing, OpenSSL 3, eBPF and standard Linux tooling
  • Four reference appendices: io_uring operations and flags, socket options and kernel tuning, coroutine awaitable patterns, and a production readiness checklist

About the author

Weston Ashgrove has spent more than a decade building high-performance network infrastructure in C++: low-latency trading gateways, servers holding hundreds of thousands of connections, and the asynchronous runtimes underneath them. He writes about the failures he has personally debugged.

Stop paying the tax. Build the server the kernel was waiting for.

Deterministic Storage Engines in C++

Deterministic Storage Engines in C++

Building Crash-Consistent LSM Trees with Write-Ahead Logging and io_uring

Your engine passed every kill -9 test. Then the power failed, and acknowledged writes were gone.

Book description

Most storage engines don't lose data because of a recovery bug. They lose it because of a missing barrier. The new manifest was written and synced, then renamed into place, and nobody synced the directory. The contents reached the disk. The record of where to find them never did.

Deterministic Storage Engines in C++ is a build-it-yourself guide to an LSM tree where every durability promise names the barrier that provides it, the failure it survives, and the test that proves it.

You build a complete reference engine in modern C++23 on Linux:

  • A write-ahead log with framing, group commit, segment recycling, and torn-tail recovery
  • io_uring paths that keep durability ordering intact, with the minimum kernel version named for every feature
  • Memtables, SSTables, Bloom and Ribbon filters, compression with dictionaries, and leveled, tiered, and hybrid compaction
  • A B+ tree on the same log and crash harness, so the two designs are compared by measurement and not by opinion
  • MVCC, snapshots, optimistic and pessimistic transactions, and the isolation anomalies each one permits
  • Deterministic simulation, fuzzing, and crash testing from simulated disks up to physical power-cut rigs

This is not a survey of database papers. Each chapter opens with a concrete failure and works through the mechanism that prevents it:

  • Why O_DIRECT is not durability
  • Why a failed fsync can never be retried
  • Why a valid frame after a damaged one can be the correct thing to discard
  • Why leveled compaction quietly consumes a drive's endurance
  • Why a latency spike that matches compaction is a device cache flush

Every chapter closes with a Durability and Throughput Ledger covering throughput and latency ranges, read, write, and space amplification, and exactly how durability was verified.

Who it's for
  • Engineers building or maintaining embedded key-value stores, metadata services, message-queue persistence, time-series ingestion, or order journals
  • Teams that already have an engine and need it to stop losing data
  • Developers who know C++ and Linux systems programming and want the missing layer between fsync and a correct database
What you will be able to do
  • Specify durability per operation: process crash, kernel crash, or power loss
  • Order flush, compaction, and manifest installs so a crash at any point recovers to a valid prefix
  • Choose a compaction strategy from write-amplification and endurance arithmetic
  • Find tail-latency interference with stage timers, not flame graphs
  • Prove your crash tests can fail, using broken builds that must be caught
  • Run, back up, upgrade, and troubleshoot the engine in production
Inside the book
  • 15 chapters in 6 parts, plus 4 reference appendices
  • Complete C++23 listings with real syscalls and liburing, built to compile
  • On-disk format tables with offsets, versions, and checksums
  • A crash-consistency release checklist you can adopt as a gate
Production CUDA for C++ Engineers

Production CUDA for C++ Engineers

Optimizing Warp-Level Primitives and Shared-Memory Tiling with Nsight.

Your kernel runs. Every launch succeeds. The sums are almost right.

That is the worst kind of CUDA bug. It's the warp reduction that relied on lockstep execution the hardware stopped promising. It's the tile size that fit one architecture's shared memory, or the single extra register that dropped a kernel from four blocks per SM to three. Nothing crashes, and you find out weeks later, in a number that is slightly off.

Production CUDA for C++ Engineers is about writing kernels that stay fast and correct across GPU generations, and about the profiling discipline that tells you, with evidence, when they aren't.

It doesn't sell you on GPUs. It assumes you write production C++ already. A GPU is treated as a throughput machine with specific constraints, and every optimization is tied to a profiler metric you can read: sectors per request, wavefronts per shared load, eligible warps per scheduler, the dominant warp stall.

Every chapter opens with a failure you may recognize and ends with a Kernel Ledger: the fraction of peak reached, the occupancy and dominant stall, and how correctness was verified. Every kernel is validated against a CPU reference, with the tolerance stated and derived, not guessed.

You will learn to:

  • Diagnose a slow kernel as memory-bound, compute-bound, or latency-bound from one Nsight Compute profile, using the roofline as the yardstick
  • Fix uncoalesced access, bank conflicts, spills, and occupancy cliffs, with counters before and after
  • Write warp-level code with explicit masks that survives independent thread scheduling
  • Build deterministic reductions and scans, and understand exactly when atomics break reproducibility
  • Pipeline loads with cp.async and TMA, and know why low-occupancy kernels can beat high-occupancy ones
  • Move from wmma to mma.sync to wgmma, use CUTLASS and CuTe, and choose precisions with error bounds you can defend
  • Overlap transfers and compute, capture work in CUDA Graphs, and scale across GPUs with NCCL
  • Use Nsight Systems, compute-sanitizer, and cuda-gdb on kernels that contain real, realistic faults
  • Ship it: fatbins and NVRTC, capture-safe C++ APIs, DCGM monitoring, Xid handling, and performance regression tests that fail the build

What makes it different

  • Measured claims, no hype. Performance is stated as typical ranges anchored to the roofline, never as invented benchmarks, and speedups are never measured against a naive CPU baseline.
  • Architecture-aware. Every hardware claim names the compute capability and notes where behavior changed, from Ampere through Hopper to Blackwell.
  • Production code. Modern C++20, every CUDA call checked through RAII wrappers, every warp primitive given an explicit mask, and the failure modes a live GPU system actually hits.
  • Failures you can reproduce. Labs with known bugs show what the sanitizer, the debugger, and the profiler actually report.
What's inside

Part I: Foundations. The GPU mental model for C++ engineers, SIMT, launch geometry, toolchains and CMake, error handling with RAII, and unified memory.

Part II: The Memory System. Coalescing, vectorized loads, the L1/L2 paths, the bandwidth roofline, bank conflicts and swizzling, tiling, asynchronous copies and TMA, registers, spills, occupancy, and instruction throughput.

Part III: The Execution Model. Warp shuffles, votes, cooperative groups, thread block clusters, divergence, reductions, scans, scoped atomics, histograms, tiled GEMM, tensor cores, CUTLASS and CuTe, and mixed precision.

Part IV: Concurrency and Scale. Streams, overlap, pinned memory, CUDA Graphs, peer-to-peer and NVLink, NCCL, MPS and MIG, and multi-GPU scaling.

Part V: Tools and Correctness. Nsight Systems and Nsight Compute in depth, compute-sanitizer, cuda-gdb, numerical reproducibility, and testing strategies for GPU kernels.

Part VI: Production. Libraries versus custom kernels, API design, fatbins, PTX JIT and NVRTC, stdpar, containers and driver compatibility, DCGM monitoring, Xid handling, and kernel performance regression testing.

Appendices. The CUDA memory and execution model, compute capability reference, an Nsight metrics reference, and a kernel optimization checklist.

Who this book is for
  • C++ engineers moving compute onto GPUs
  • Performance engineers handed a GPU budget
  • Quant, simulation, and inference developers whose CUDA works but needs to be fast and maintainable on more than one architecture
  • Anyone who has stared at an Nsight report and wanted to know which number to believe

Not for you if you need an introduction to C++ or parallel programming. The book assumes both from page one.

Prerequisites

Solid modern C++ (templates, RAII, the memory model). Basic parallel programming. A CUDA-capable GPU (compute capability 8.0 or later is ideal; the book notes where Hopper or Blackwell is needed). CUDA Toolkit 13.x, or 12.8 or later.

Bare-Metal LLM Inference in C++

Bare-Metal LLM Inference in C++

Building Quantized GEMM Kernels and Paged KV-Cache Systems for Continuous Batching

Your quantized model passed perplexity. It’s still failing a few percent of your customers’ JSON, and nothing on your dashboard will tell you that.

Most inference engines are built for benchmarks. They post strong numbers on 128-token prompts with one polite client. In production, three things break them:

  • Bursty traffic. Real load comes in spikes, not one request at a time.
  • Long prompts. A single 12,000-token prefill can freeze every user who is mid-stream.
  • KV-cache waste. Servers run out of KV-cache memory while more than 80% of it holds no tokens at all.

None of these failures crash anything. Health checks stay green while the output quietly goes wrong.

Bare-Metal LLM Inference in C++ is the engineering manual for the layer underneath LLM serving, the part that turns weights and a prompt into tokens. You build a complete production inference engine in modern C++, from a validated model loader to a streaming server with admission control. Each decision is derived from the hardware, measured against a roofline, and checked against a reference implementation before it is allowed to be fast.

What you’ll build
  • A cost model that predicts performance before you write a kernel. It covers bytes per token, arithmetic intensity, and ridge points. You’ll learn why decode at batch size one is waiting on memory bandwidth, and why no amount of FLOPs fixes that.
  • Vectorized and quantized kernels for AVX2, AVX-512, AMX, NEON and SDOT. They include packed GEMM, bandwidth-saturating GEMV, tiled attention, and fused norms and activations. Every SIMD kernel ships with the scalar reference it is tested against.
  • INT8 and 4-bit quantization measured the honest way. That means logit divergence, tail KL on structural tokens, and paired task evaluation, not a single perplexity number. The book handles activation outliers, supports GPTQ and AWQ checkpoints, and imports GGUF formats exactly.
  • A paged, reference-counted KV cache with radix-tree prefix sharing, scan-resistant eviction, INT8 cache quantization, sliding windows, attention sinks, and copy-on-write for beam search.
  • A continuous-batching scheduler with chunked prefill, preemption, fair multi-tenant queueing, and a step-time model the scheduler fits online from its own measurements.
  • Speculative decoding with exact verification. Output matches the target model’s distribution exactly, and an adaptive controller switches speculation off before it costs you throughput.
  • NUMA-aware parallelism on multi-socket CPUs, plus tensor-parallel, pipeline-parallel, and hybrid CPU/GPU execution plans.
  • A production server with lock-free token streaming, cancellation that frees memory within one step, admission control, and an optional deterministic mode that returns bitwise-identical outputs regardless of batch composition.
  • The machinery that keeps it honest: open-loop load testing, a five-rung validation ladder, regression suites, capacity planning, and a release checklist that blocks silent failures.
What makes this book different

Every claim is checkable. Performance figures are given as ranges derived from first principles, never as numbers from benchmarks nobody ran. Every accuracy claim names how it was measured, and every optimization comes with its trade-off stated in the same breath.

The code is real. It is C++20/23 that compiles and handles the failures a live engine actually hits: misaligned buffers, NaNs in activations, integer accumulator overflow, KV-cache exhaustion mid-generation, cancelled requests, and malformed model files. It contains no pseudocode and no “error handling omitted.”

It is written by someone who has debugged these failures. That includes a server that ran out of memory at a fraction of its capacity, a 4-bit model that broke structured output while passing every check, and a dual-socket box that ran slower on twice the threads. Each chapter opens with a failure like these and builds what prevents it. Each chapter closes with the Tokens and Accuracy Ledger, which records what the chapter’s work bought in throughput, latency and memory, and what it cost in accuracy.

Who this book is for

This book is for engineers who will run inference in production:

  • systems and performance engineers,
  • infrastructure and platform teams,
  • anyone responsible for making a model fast, correct and affordable on real hardware.

You should be comfortable with modern C++ and SIMD basics. You don’t need a machine-learning background, because the transformer is introduced only where the engine needs it, and only from the serving side.

If you have ever shipped a speedup and wondered what it broke, this book gives you a way to know.

About the Author

Weston Ashgrove is a systems engineer with more than a decade of experience building high-performance C++ infrastructure. He started in low-latency systems and numerical computing, then moved into performance engineering for compute-heavy workloads. Today he works on the layer underneath large language model serving: inference runtimes, quantized compute kernels, KV-cache memory management, and the schedulers that decide which tokens get computed when. He writes for engineers who have to make systems run correctly in production, not just in a benchmark.

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub