Architecting High-Throughput REST APIs in 2026: Zero-Copy Serialization, Connection Pooling, and N+1 Query Elimination

Building a REST API that serves a few hundred requests per second is straightforward with almost any modern web framework. Scaling that same service to handle tens of thousands of concurrent requests per node—while keeping tail latency predictable and memory consumption flat—requires stripping away the hidden inefficiencies of default application stacks. When backend engineers profile a saturated production API server, CPU flame graphs rarely show business logic at the top. Instead, processor cycles are overwhelmingly consumed by three systemic bottlenecks: redundant memory allocations during user-space serialization, database connection thrashing across unpooled or over-allocated backend processes, and chatty N+1 or high-offset SQL query patterns.

High-Throughput Backend Server Infrastructure

High-Throughput Backend Server Infrastructure

This engineering guide examines the full data path of a high-throughput REST API from the Linux kernel socket buffer up to the relational query planner. Every architectural pattern, kernel flag, bit-level wire layout, and pool configuration parameter discussed below is grounded in primary technical specifications—including the IETF HTTP standards (RFC 9110, RFC 9113, and RFC 9114), the Linux kernel networking and system call documentation (MSG_ZEROCOPY, sendfile(2), and splice(2)), the Cap'n Proto binary encoding specification, the simdjson vector parsing architecture, and the official PostgreSQL 19 and PgBouncer documentation.


1. The Anatomy of REST API Latency and Memory Bloat

In a naive web service lifecycle, fulfilling a single GET request triggers a cascade of data copies across privilege boundaries and heap allocations:

  1. Database Socket Read: The relational database sends row tuples over a TCP or Unix-domain socket into the kernel's socket receive buffer (sk_buff).
  2. User-Space Driver Copy: The application's database driver reads those bytes across the kernel-to-user-space boundary into a runtime buffer and parses the wire protocol into boxed language objects (structs, dictionaries, or ORM model instances).
  3. Intermediate DTO Allocation: Business logic maps the ORM instances into Data Transfer Objects (DTOs), allocating fresh heap memory and duplicating strings and arrays.
  4. JSON Serialization Buffer: A traditional text serializer walks the object tree through reflection, escaping UTF-8 strings, formatting floating-point numbers into ASCII decimal representations, and appending bytes to a dynamically resizing contiguous byte array.
  5. Socket Write Copy: The HTTP server passes the serialized byte array to write(2) or send(2), copying the payload from user space back into a kernel socket send buffer before the Network Interface Card (NIC) transfers the frames via Direct Memory Access (DMA).

When multiplied across thousands of concurrent requests, this five-stage copy pipeline saturates memory bandwidth, triggers frequent garbage collection (GC) or allocator lock contention, and pollutes CPU L1/L2/L3 caches.

Core Systems Principle: Bandwidth vs. Cache Locality

Every unnecessary byte copy between user space and kernel space—or between an ORM entity and an intermediate JSON DOM tree—consumes twice its payload size in memory bus traffic (one read and one write) while evicting active working-set instructions and data from processor caches.

Eliminating these bottlenecks requires attacking each layer systematically: upgrading the HTTP transport layer to eliminate connection-level stalls, bypassing kernel-to-user copies with zero-copy socket primitives, replacing reflection-driven text parsing with SIMD vector instructions or zero-copy binary layouts, bounding database concurrency with transaction-mode connection pooling, and rewriting iterative data access into single-roundtrip batched and keyset-indexed queries.


2. Transport-Layer Multiplexing: HTTP Semantics Across RFC 9110, HTTP/2 (RFC 9113), and HTTP/3 (RFC 9114)

Before optimizing payload serialization, an API architect must ensure the underlying transport protocol does not serialize concurrent requests behind network stalls. In June 2022, the Internet Engineering Task Force (IETF) completed a foundational restructuring of the HTTP specification suite, separating core protocol semantics from wire-level framing:

  • RFC 9110 (STD 97: HTTP Semantics): Defines version-independent HTTP architecture, uniform resource interfaces, methods, status codes, content negotiation, and conditional validators. RFC 9110 updates RFC 3864 and obsoletes RFCs 2818, 7231, 7232, 7233, 7235, 7538, 7615, 7694, and portions of RFC 7230.
  • RFC 9113 (HTTP/2): Obsoletes RFC 7540 and RFC 8740, defining binary message framing and stream multiplexing over TCP.
  • RFC 9114 (HTTP/3): Maps RFC 9110 HTTP semantics directly onto the QUIC transport protocol (RFC 9000) running over UDP with integrated TLS 1.3.
Network Fiber and High-Density Switching Hardware

Network Fiber and High-Density Switching Hardware

Application vs. Transport Head-of-Line (HOL) Blocking

As documented in Section 1 of RFC 9113, HTTP/1.0 permitted only a single outstanding request per TCP connection at any instant. While HTTP/1.1 introduced request pipelining, it remained vulnerable to application-layer head-of-line blocking: if the first request in a pipeline required a slow database query, all subsequent responses queued behind it on that connection were delayed. Consequently, HTTP/1.1 clients were forced to open multiple parallel TCP connections to the same origin, which prevented shared congestion control and rapidly filled the initial TCP congestion window with repetitive, uncompressed text headers.

HTTP/2 (RFC 9113) solves application-layer head-of-line blocking by decomposing HTTP messages into binary frames (HEADERS, DATA, SETTINGS, WINDOW_UPDATE, and PUSH_PROMISE) assigned to independent bidirectional streams (Section 5). Multiple streams are interleaved over a single TCP connection, and redundant HTTP header fields are compressed (Section 4.3), allowing dozens of concurrent API calls to fit inside a single TCP segment. Notably, RFC 9113 Section 5.3 explicitly deprecates the complex stream priority signaling tree introduced in RFC 7540 because it proved difficult to implement interoperably and frequently degraded performance when misconfigured.

However, as both RFC 9113 Section 1 and RFC 9114 Section 1.1 emphasize, HTTP/2 cannot eliminate TCP transport-layer head-of-line blocking. Because the TCP kernel stack views an HTTP/2 connection as a single ordered byte stream and has no visibility into HTTP/2 stream boundaries, a single lost or reordered TCP packet forces the operating system to hold back delivery of all subsequent packets across every active HTTP/2 stream until the missing segment is retransmitted.

How HTTP/3 and QUIC Isolate Stream Loss

RFC 9114 (HTTP/3) eliminates transport-layer head-of-line blocking by delegating stream multiplexing, per-stream flow control, and reliable in-order delivery to the QUIC transport layer (Section 1.2). Because QUIC understands stream identifiers natively at the transport layer, a lost UDP datagram carrying data for Stream 4 blocks only Stream 4; frames arriving on Streams 8, 12, and 16 are immediately decrypted and delivered to the application handler. Furthermore, by integrating TLS 1.3 directly into the QUIC handshake, HTTP/3 achieves connection establishment latency comparable to TCP Fast Open (TFO) without separate TCP and TLS round trips.

Architectural Dimension HTTP/1.1 (RFC 9110 / RFC 9112) HTTP/2 (RFC 9113) HTTP/3 (RFC 9114)
Underlying Transport TCP (typically with separate TLS handshake) Single multiplexed TCP connection with TLS QUIC (RFC 9000) over UDP with integrated TLS 1.3
Message Framing Syntax Whitespace-delimited ASCII text lines & chunked delimiters Binary framing (`HEADERS`, `DATA`, `SETTINGS`, `WINDOW_UPDATE`) Binary HTTP/3 frames inside independent QUIC streams
Application HOL Blocking Present on single connection; mitigated via multiple TCP sockets Eliminated via concurrent bidirectional streams Eliminated via native QUIC stream multiplexing
Transport HOL Blocking Per-TCP connection stall on packet loss Present: single lost TCP packet stalls all multiplexed streams Eliminated: lost UDP packet stalls only affected QUIC stream
Priority Signaling Scheme None (ordered by connection or FIFO queue) RFC 7540 priority tree deprecated in RFC 9113 Section 5.3 Extensible HTTP priorities decoupled from legacy tree

3. Linux Kernel Zero-Copy I/O Primitives: sendfile(2), splice(2), and MSG_ZEROCOPY

When an API gateway or storage microservice transmits large payloads—such as analytical exports, media blobs, cached JSON snapshots, or pre-serialized binary buffers—using standard read(2) and write(2) system calls forces the CPU to copy every byte twice across the user/kernel privilege boundary and triggers four context switches per cycle. The Linux kernel provides three distinct copy-avoidance mechanisms, each governed by strict operational constraints documented in the Linux kernel manuals.

1. In-Kernel Descriptor Transfer with sendfile(2)

Introduced in Linux 2.2 (with glibc 2.1 wrapper support and 64-bit offset support added via sendfile64() in Linux 2.4), sendfile(2) transfers data directly between two file descriptors entirely inside kernel space:

#include <sys/sendfile.h>

ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);

According to the Linux sendfile(2) manual page (man-pages 6.19):

  • Input Descriptor Requirement: The in_fd argument must correspond to a file descriptor that supports mmap(2)-like operations (meaning in_fd cannot be a socket).
  • Output Descriptor Evolution: Prior to Linux 2.6.33, out_fd had to refer to a socket. Since Linux 2.6.33, out_fd can refer to any file, and since Linux 5.12, if out_fd is a pipe, sendfile(2) automatically desugars into a splice(2) operation.
  • Maximum Single-Call Transfer Limit: On both 32-bit and 64-bit Linux architectures, a single invocation of sendfile() transfers at most 0x7ffff000 (2,147,479,552) bytes, returning the exact byte count transferred. API servers streaming payloads larger than ~2.14 GB must loop and advance the offset until all bytes are drained.
  • Header Coalescing with TCP_CORK: When an HTTP server must prepend HTTP response headers before streaming a file payload via sendfile(), setting the TCP_CORK socket option (described in tcp(7)) prevents the kernel from transmitting a partially filled TCP segment containing only the headers, coalescing headers and initial file data into full Maximum Segment Size (MSS) packets.

2. Reference-Counted Pipe Buffers with splice(2)

Introduced in Linux 2.6.17 (glibc 2.5), splice(2) generalizes zero-copy data movement between arbitrary file descriptors—such as proxying an upstream microservice socket directly to a downstream client socket—provided at least one descriptor is a kernel pipe (and since Linux 2.6.31, both descriptors may refer to pipes):

#define _GNU_SOURCE
#include <fcntl.h>

ssize_t splice(int fd_in, off_t *off_in, int fd_out, off_t *off_out,
               size_t size, unsigned int flags);

As explained in the splice(2) NOTES section, the Linux kernel implements a pipe buffer as a set of reference-counted pointers to pages of kernel memory. When splice() moves data from an input descriptor through a pipe to an output socket, the kernel avoids copying page bytes by creating new pointers referencing the existing kernel memory pages and incrementing their reference counts. Engineers should note a critical historical detail documented in splice(2): the SPLICE_F_MOVE flag was buggy in early kernels and has been a no-op since Linux 2.6.21, whereas SPLICE_F_NONBLOCK and SPLICE_F_MORE remain active flags for non-blocking pipe operations and socket packet coalescing.

3. User-Space Buffer Pinning with MSG_ZEROCOPY

While sendfile(2) and splice(2) excel when data already resides in a kernel page cache or pipe, dynamic REST APIs frequently construct response payloads in user-space memory. The Linux kernel's MSG_ZEROCOPY flag (documented in the Linux Kernel 7.4 documentation under networking/msg_zerocopy.html) extends copy avoidance to standard socket send(2), sendto(2), sendmsg(2), and sendmmsg(2) calls for TCP, UDP, and VSOCK (with virtio transport) sockets.

The 10 KB Threshold and Page-Pinning Economics

As the Linux kernel documentation explicitly warns, copy avoidance via MSG_ZEROCOPY is not a free lunch. Because the kernel pins the user-space memory pages in physical RAM so the NIC can read them directly via scatter-gather DMA, it replaces per-byte CPU copy cost with page accounting and asynchronous completion notification overhead. Consequently, the kernel documentation states that MSG_ZEROCOPY is generally only effective at writes over around 10 KB. For small REST API JSON responses (such as a 500-byte status payload), a conventional copying send() is faster than pinning pages and polling the socket error queue; fortunately, the kernel permits safely mixing calls with and without MSG_ZEROCOPY on the same socket.

/* Step 1: Signal intent by enabling SO_ZEROCOPY on the socket */
int one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, &one, sizeof(one))) {
    perror("setsockopt SO_ZEROCOPY");
}

/* Step 2: Transmit buffers > 10 KB with MSG_ZEROCOPY */
ssize_t ret = send(fd, payload_buf, payload_len, MSG_ZEROCOPY);
if (ret == -1 && errno == ENOBUFS) {
    /* Socket exceeded optmem limit or user exceeded ulimit on locked pages */
}

Asynchronous Completion Notifications and SO_EE_CODE_ZEROCOPY_COPIED

Because MSG_ZEROCOPY shares the user-space buffer directly with the network stack, the application must not overwrite or free the buffer immediately after send() returns. Modifying the buffer while packets are in flight will corrupt the outbound data stream. Instead, the application must wait for the kernel to queue a completion notification on the socket error queue (MSG_ERRQUEUE):

  • 32-Bit Invocation Counter: Each socket maintains an internal unsigned 32-bit counter that increments once per successful MSG_ZEROCOPY system call (counting syscalls, not bytes, and wrapping after UINT_MAX).
  • Notification Range [ee_info, ee_data]: When reading struct sock_extended_err from the error queue where ee_origin == SO_EE_ORIGIN_ZEROCOPY and ee_errno == 0, the kernel reports the inclusive range [ee_info, ee_data] of completed send call IDs whose buffers are now safe to reuse.
  • Deferred Copies and Loopback Caveat: Passing MSG_ZEROCOPY is a contract for completion notifications, not an unconditional guarantee that a copy is elided. If the target NIC lacks scatter-gather I/O, if the stack must compute a software checksum, or if traffic is routed over a local loopback socket, a packet socket (such as tcpdump), or a tun device, the kernel performs a deferred copy and sets the SO_EE_CODE_ZEROCOPY_COPIED flag in serr->ee_code. Applications inspecting ee_code can dynamically disable MSG_ZEROCOPY on sockets that consistently report SO_EE_CODE_ZEROCOPY_COPIED.
Linux Primitive Kernel / glibc Version Descriptor / Payload Constraints Buffer Reuse & Limit Semantics
sendfile(2) Linux 2.2 / glibc 2.1 (sendfile64 in 2.4; pipe desugar in 5.12) in_fd must support mmap(2) (cannot be a socket) Max 0x7ffff000 (2,147,479,552) bytes per call on 32/64-bit
splice(2) Linux 2.6.17 / glibc 2.5 (dual-pipe support since 2.6.31) At least one FD must be a pipe; manipulates ref-counted kernel page pointers SPLICE_F_MOVE is a no-op since Linux 2.6.21; supports SPLICE_F_MORE
MSG_ZEROCOPY TCP, UDP, and VSOCK (virtio) with SO_ZEROCOPY Effective only for writes over ~10 KB due to page-pinning overhead Must poll error queue for SO_EE_ORIGIN_ZEROCOPY range [ee_info, ee_data]

4. Zero-Copy Binary Serialization vs. SIMD-Accelerated JSON Parsing

Once network I/O copies are minimized, payload serialization and deserialization become the dominant CPU consumers in high-throughput APIs. Backend architectures generally fall into two operational camps: public REST APIs that must accept and emit standard UTF-8 JSON for browser and third-party interoperability, and internal microservice or high-frequency telemetry endpoints that can negotiate binary representations via HTTP Accept and Content-Type headers (as standardized in RFC 9110).

Processor Architecture and SIMD Data Paths

Processor Architecture and SIMD Data Paths

1. SIMD-Accelerated JSON Parsing (simdjson)

When JSON is mandatory, standard recursive-descent character-by-character parsers spend excessive CPU cycles branching on quotes, backslashes, whitespace, and UTF-8 multi-byte sequences. In their landmark VLDB Journal paper ("Parsing Gigabytes of JSON per Second", arXiv:1902.08318, v7 revised July 2024), Geoff Langdale and Daniel Lemire introduced simdjson, the first standard-compliant validating JSON parser capable of processing gigabytes of JSON per second on a single processor core.

As documented in the arXiv:1902.08318 abstract and the official simdjson.org specification:

  • 75%+ Instruction Reduction: By replacing byte-by-byte branch loops with wide Single Instruction, Multiple Data (SIMD) vector instructions (automatically dispatching at runtime across AVX-512, AVX2, ARM NEON, RISC-V, LoongArch, and POWER), simdjson executes a quarter (25%) or fewer CPU instructions than a state-of-the-art reference C++ parser like RapidJSON.
  • Verified Throughput Benchmarks: The simdjson On-Demand API achieves up to 25 GB/s parsing throughput—over 4Ă— faster than RapidJSON and 25Ă— faster than JSON for Modern C++ (nlohmann::json). Its standalone vector routines achieve 30 GB/s for full UTF-8 validation, 12 GB/s for JSON minification (stripping whitespace without building a DOM), and 3.5 GB/s for multithreaded newline-delimited JSON (NDJSON) streaming.
  • On-Demand Zero-DOM Iteration: Instead of materializing an entire tree of heap-allocated objects before reading a single field, the ondemand::parser iterates directly over the padded input buffer (padded_string), allowing an API handler to extract specific fields via JSON Pointer (/statuses/0/user/name) while skipping unused subtrees entirely.
  • Language Bindings (fastsimdjson): For Python REST services (such as FastAPI or ASGI microservices), the official fastsimdjson binding provides prebuilt wheels for Python 3.10 to 3.15 (including free-threaded Python), running over 3Ă— faster than the Python standard library json module and converting JSON to MessagePack 3 to 4Ă— faster than orjson paired with ormsgpack.

2. True Zero-Copy Memory-Mapped Serialization: Cap'n Proto and FlatBuffers

Even with SIMD acceleration, JSON remains a text format: numbers must be converted between ASCII base-10 digits and IEEE-754 or two's-complement hardware registers, and keys are repeated across every object in an array. True zero-copy binary formats—specifically Cap'n Proto and FlatBuffers—eliminate the parsing and serialization step altogether by structuring their wire format identically to an in-memory C/Rust struct hierarchy aligned to CPU word boundaries.

According to the official Cap'n Proto Encoding Specification (capnproto.org/encoding.html):

  • 64-Bit Word Alignment: A Cap'n Proto word is strictly 64 bits (8 bytes). All objects (structs, lists, and blobs) are aligned to 64-bit word boundaries. Primitive fields are aligned to multiples of their native size in little-endian byte order: integers use two's complement, floating-point values use little-endian IEEE-754, Enum values occupy 16 bits (UInt16), and Bool values occupy exactly 1 bit (packing 8 booleans into a single byte).
  • Message Segments and Root Pointer: A message consists of one or more contiguous memory segments. The first 64-bit word of the first segment is always a pointer to the root struct. Because every pointer inside a segment uses relative word offsets rather than absolute virtual memory addresses, a buffer received from a socket or mapped via mmap(2) can be dereferenced immediately without parsing a single field.
  • 64-Bit Struct Pointer Layout: Every struct is divided into a fixed-width data section followed immediately by a pointer section, referenced by a 64-bit pointer divided into four bitfields:
  • A (2 bits = 0): Identifies the word as a struct pointer.
  • B (30 bits): Signed offset, in 64-bit words, from the end of the pointer to the start of the struct's data section.
  • C (16 bits): Size of the struct's data section, in 64-bit words.
  • D (16 bits): Size of the struct's pointer section, in 64-bit words.
  • Padding Invariant and XOR Default Values: The schema compiler places later-numbered fields into alignment holes left by earlier fields, guaranteeing that a struct never contains more than 63 bits of padding. Furthermore, primitive fields in the data section are stored XOR'd with their schema-defined default values so that a default-valued struct is always all-zeros in memory (0x00), enabling instant zero-initialization and high compression ratios. To distinguish a zero-sized struct from an all-zero null pointer, a zero-sized struct encodes A = 0, C = 0, D = 0, and signed offset B = -1.
  • 64-Bit List and Inter-Segment Far Pointers: Lists use A = 1 (2 bits), signed word offset B (30 bits), element size tag C (3 bits, encoding values 0 through 7, where 7 denotes fixed-width composite structs prefixed by a tag word), and size field D (29 bits). When a message spans multiple memory segments, an inter-segment far pointer uses A = 2 (2 bits), landing-pad size flag B (1 bit: 0 for one word, 1 for two words), unsigned target word offset C (29 bits), and target segment ID D (32 bits).

Architectural deep dive: Comparing wire encoding layouts and zero-copy deserialization mechanics across Protocol Buffers, FlatBuffers, and Cap'n Proto.


5. The Mathematics of Database Connection Pooling: Why More Connections Degrade Throughput

Even if an API server parses requests at 25 GB/s and writes responses with zero-copy sockets, throughput will collapse if every concurrent HTTP worker opens a dedicated connection to the relational database. In PostgreSQL, each client connection spawns a dedicated operating system backend process (postgres), allocating per-backend memory structures and competing for shared memory locks.

Why Throughput Collapses Past the Saturation "Knee"

As documented in the official PostgreSQL Wiki ("Number Of Database Connections", wiki.postgresql.org/wiki/Number_Of_Database_Connections) and Chapter 19 of the PostgreSQL 19 Server Configuration documentation (runtime-config-connection.html and runtime-config-resource.html), plotting transaction throughput (TPS) on the vertical axis against active database connections on the horizontal axis always exhibits a sharp saturation "knee". Once active transactions saturate available CPU cores and I/O channels, adding more connections actively reduces total throughput due to five compounding hardware and kernel penalties:

  1. CPU Cache Line Contention: When dozens of PostgreSQL backend processes are scheduled across the same physical CPU cores, each context switch evicts L1/L2/L3 processor cache lines populated by the previous query. The PostgreSQL Wiki highlights a stark empirical finding from an oprofile profiling run on a heavily contended database server: 10% of total CPU time was attributed to a single 1-byte noop instruction purely because the processor core had to stall waiting on a contended CPU cache line for the following machine instruction.
  2. Spinlock and LWLock Contention: PostgreSQL coordinates access to shared buffer headers and lock tables using multi-tiered locks: hardware atomic spinlocks protect Lightweight Locks (LWLocks), which in turn guard heavyweight and predicate lock tables (pg_locks). As concurrent active connections exceed physical core counts, backend processes burn a high percentage of CPU time spinning on atomic compare-and-swap loops rather than executing SQL plan nodes.
  3. Per-Node work_mem Multiplication and OS Page Cache Eviction: Under PostgreSQL 19 defaults (runtime-config-resource.html), shared_buffers defaults to 128 MB (with 25% to 40% of system RAM recommended on dedicated servers with 1 GB or more of RAM), temp_buffers defaults to 8 MB per session (~64 bytes descriptor overhead per unused increment, 8,192 bytes when allocated for BLCKSZ = 8kB), and work_mem defaults to 4 MB. Crucially, work_mem is allocated per sort or hash plan node, not per connection—and hash-based operations multiply work_mem by hash_mem_multiplier (which defaults to 2.0, allowing 8 MB per hash node by default, or 2.0 to 8.0 in tuned environments where work_mem is 40 MB or higher). If 500 concurrent connections each run a query containing three hash joins at a tuned 32 MB work_mem (32 MB × 2.0 × 3 = 192 MB per query), peak transient memory allocation can spike to 96 GB, trashing the OS page cache or triggering the Linux Out-Of-Memory (OOM) killer.
  4. OS Scheduler Context Switching: Every time the kernel preempts one backend process to schedule another on the same core, it must flush registers, save execution state, and switch virtual memory page tables (which is why PostgreSQL 19 enables huge_pages = try by default for 2 MB and 1 GB hardware pages while explicitly discouraging Linux Transparent Huge Pages / THP).
  5. Super-Linear Internal Scaling: Certain internal PostgreSQL data structures sized proportionally to max_connections (which defaults to 100 connections, alongside 3 superuser_reserved_connections and 0 reserved_connections on default port 5432) scale at $O(N \log N)$ or $O(N^2)$ during snapshot acquisition.

The Core-Bound Pool Sizing Formula

To keep the database operating right at peak throughput before the saturation knee, the PostgreSQL Wiki establishes the canonical empirical sizing formula for active connections:

$$\text{Optimal Active Connections} = (\text{Core Count} \times 2) + \text{Effective Spindle Count}$$

  • Core Count represents physical processor cores only and must not include Hyper-Threading (SMT) logical threads, even when hyperthreading is enabled.
  • Effective Spindle Count is 0 when the active working dataset is fully cached in RAM, and approaches the number of physical storage spindles only as the cache hit rate drops.

As the PostgreSQL Wiki notes, a database server will routinely complete 10,000 transactions faster by executing them 5, 10, or 20 at a time than by executing 500 simultaneously—queuing excess incoming requests in a lightweight connection pooler until an active slot frees up.


6. Production Connection Pool Architecture: PgBouncer Pooling Modes and Protocol Multiplexing

As explained in the PostgreSQL Wiki, PostgreSQL deliberately omits an internal connection pooler because running an event-driven pooler as a separate process (or on a dedicated proxy host) isolates connection state overhead and prevents TLS termination and idle client sockets from consuming database backend processes. PgBouncer is the industry-standard lightweight connection pooler for PostgreSQL, listening by default on TCP/Unix port 6432 (pgbouncer.org/config.html).

Technical walkthrough: Configuring PgBouncer pooling modes and multiplexing thousands of client sockets onto a bounded PostgreSQL backend pool.

Comparing the Three PgBouncer Pooling Modes

According to the official PgBouncer configuration specification (pgbouncer.ini), the pool_mode parameter dictates when a PostgreSQL server connection is released back into the shared pool for other clients:

  1. session Mode (Default): A server connection is assigned to a client when it connects and remains pinned to that client until the client disconnects. While this preserves 100% of session-level PostgreSQL features (advisory locks, LISTEN/NOTIFY, temporary tables, and session SET variables), it does not multiplex active horizontal API workers that hold persistent connections open.
  2. transaction Mode (Recommended for High-Throughput REST APIs): A server connection is assigned to a client only for the duration of a single SQL transaction (BEGIN ... COMMIT/ROLLBACK) and is immediately returned to the pool the millisecond the transaction finishes. This allows 2,000 concurrent REST API worker threads or event-loop coroutines to share a pool of just 20 active PostgreSQL server connections (default_pool_size = 20).
  3. statement Mode: The server connection is released immediately after every individual query completes. Multi-statement transactions are strictly disallowed and raise an error, restricting this mode to simple autocommit read/write workloads.

Protocol-Level Prepared Statement Multiplexing (max_prepared_statements)

Historically, backend engineers avoided transaction pooling mode when using ORMs or drivers that rely on PostgreSQL protocol-level named prepared statements, because a statement prepared on Server Connection A would be missing when the client's next transaction was routed to Server Connection B—or would collide with another client's prepared statement name.

Modern PgBouncer resolves this completely via the max_prepared_statements setting (pgbouncer.org/config.html):

  • When max_prepared_statements is set to a non-zero integer (defining the size of the per-server-connection LRU prepared statement cache; default is 0 / disabled), PgBouncer intercepts all Extended Query protocol prepared statement commands.
  • PgBouncer hashes each unique SQL query string and assigns it a deduplicated internal identifier formatted as PGBOUNCER_{unique_id} (for example, rewriting a client's my_prepared_statement into PGBOUNCER_123).
  • If 500 API workers prepare the exact same parameterized query, PgBouncer prepares it only once on each backing PostgreSQL server connection under the shared PGBOUNCER_{unique_id} name. If a client executes a statement on a newly assigned server connection where that query is not yet prepared, PgBouncer transparently prepares it on the fly before forwarding the execution packet.
  • Important Protocol Distinction: As the PgBouncer manual notes, this transparent rewriting applies strictly to protocol-level Extended Query prepared statements; SQL-level PREPARE, EXECUTE, and DEALLOCATE statements are forwarded directly to PostgreSQL (with the exception of DEALLOCATE ALL and DISCARD ALL, which properly clear PgBouncer's tracked client statement table).

File Descriptor Math, LIFO Reuse, and Tracked Parameters

When sizing a production pgbouncer.ini for a high-throughput API cluster, engineers must account for four documented operational mechanics:

  • File Descriptor Limit Calculation: PgBouncer's default max_client_conn is 100 and default_pool_size is 20 per user/database pair (with reserve_pool_size = 0 and reserve_pool_timeout = 5.0 seconds). When scaling max_client_conn to thousands of connections, the OS ulimit -n file descriptor ceiling must exceed the theoretical maximum formula given in the PgBouncer documentation: $$\text{Max File Descriptors} = \text{max\_client\_conn} + (\text{max pool\_size} \times \text{total databases} \times \text{total users})$$ (Or $\text{max\_client\_conn} + (\text{max pool\_size} \times \text{total databases})$ when a single forced database user is configured in the [databases] section.)
  • LIFO vs. Round-Robin Connection Reuse (server_round_robin): By default (server_round_robin = 0), PgBouncer reuses server connections in LIFO (Last-In, First-Out) order so that a small subset of backend connections handles the majority of traffic while idle connections can time out cleanly—maximizing CPU cache warmth on a single PostgreSQL primary. When load-balancing across multiple read replicas behind a DNS or TCP VIP, setting server_round_robin = 1 switches to uniform round-robin distribution.
  • Tracked Session Parameters: By default, PgBouncer caches and restores ten startup/client-reported parameters across transaction handoffs: application_name, client_encoding, DateStyle, default_transaction_read_only (tracked since PostgreSQL 14), IntervalStyle, scram_iterations (since PostgreSQL 16), search_path (reported natively since PostgreSQL 18 and Citus 12.0+), session_authorization, standard_conforming_strings, and TimeZone.
  • Security Hardening with disable_pqexec: Setting disable_pqexec = 1 (default 0) disables the legacy Simple Query protocol (PQexec), which permits concatenating multiple semicolon-separated SQL statements in a single network packet, enforcing exclusive use of the Extended Query protocol and blocking multi-statement SQL injection payloads at the pooler layer.
[databases]
api_prod = host=10.0.1.50 port=5432 dbname=api_prod user=app_svc pool_size=24

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
pool_mode = transaction
max_client_conn = 4000
default_pool_size = 24
min_pool_size = 8
reserve_pool_size = 4
reserve_pool_timeout = 5.0
max_db_connections = 28
max_prepared_statements = 256
server_round_robin = 0
disable_pqexec = 1
stats_period = 60

7. Eliminating N+1 Query Storms and High-Offset Pagination Bottlenecks

Even with a properly sized transaction pool (pool_size = 24 on a 12-core database host), a single poorly structured REST endpoint can monopolize a pooled connection for hundreds of milliseconds—starving thousands of queued requests. The two most destructive SQL anti-patterns in REST APIs are iterative N+1 lazy-loading loops and high-offset (LIMIT / OFFSET) pagination.

Clean Code and Database Query Optimization

Clean Code and Database Query Optimization

1. Coalescing N+1 Queries with Parameterized Array Batching (ANY($1))

An N+1 query storm occurs when an endpoint fetches a parent collection of $N$ records (1 query) and then executes $N$ individual lookup queries inside a serialization loop to fetch an associated child relation (such as fetching the recent orders or permissions for 100 returned users = 101 sequential database round trips). Even if each query takes only 0.4 ms over a local network, 101 sequential round trips add 40.4 ms of pure network and pool-checkout latency to a single HTTP request while acquiring and releasing a PgBouncer transaction slot 101 times.

In high-throughput REST services, engineers eliminate N+1 queries using two deterministic patterns:

  • Single-Tick Request Batching (DataLoader Pattern): When multiple resolver functions or nested serializer components request child entities by ID within the same event-loop tick, a batch loader coalesces all requested keys into a deduplicated set and dispatches a single parameterized WHERE parent_id = ANY($1::bigint[]) query.
  • In-Database JSON or Array Aggregation: When building read-heavy REST endpoints, pushing child aggregation into a single indexed join or lateral subquery (COALESCE(jsonb_agg(...), '[]'::jsonb)) allows PostgreSQL to stream a complete, pre-structured document in one round trip.
from collections.abc import Sequence
from dataclasses import dataclass
import asyncpg

@dataclass(frozen=True)
class OrderSummary:
    order_id: int
    customer_id: int
    total_cents: int
    status: str

async def fetch_orders_for_customers_batched(
    pool: asyncpg.Pool,
    customer_ids: Sequence[int],
) -> dict[int, tuple[OrderSummary, ...]]:
    """Eliminates N+1 round trips by fetching all child orders in one parameterized ANY($1) query."""
    if not customer_ids:
        return {}

    unique_ids = list(dict.fromkeys(customer_ids))
    query = """
        SELECT id, customer_id, total_cents, status
        FROM orders
        WHERE customer_id = ANY($1::bigint[])
        ORDER BY customer_id ASC, created_at DESC, id DESC
    """
    async with pool.acquire() as conn:
        rows = await conn.fetch(query, unique_ids)

    grouped: dict[int, list[OrderSummary]] = {cid: [] for cid in unique_ids}
    for row in rows:
        grouped[row["customer_id"]].append(
            OrderSummary(
                order_id=row["id"],
                customer_id=row["customer_id"],
                total_cents=row["total_cents"],
                status=row["status"],
            )
        )
    return {cid: tuple(items) for cid, items in grouped.items()}

2. Why OFFSET Pagination Degrades Linearly—and How Keyset Pagination Restores $O(\log N)$

Many REST APIs expose collection pagination via ?page=5000&limit=20, which translates into SQL LIMIT 20 OFFSET 100000. As explicitly documented in Section 7.6 ("LIMIT and OFFSET") of the official PostgreSQL 19 documentation (postgresql.org/docs/current/queries-limit.html):

  1. Server-Side Row Computation Penalty: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." To return rows 100,001 through 100,020, PostgreSQL must scan, filter, visibility-check, and discard the first 100,000 rows on every request. As a client paginates deeper, query latency scales linearly ($O(\text{OFFSET} + \text{LIMIT})$) until deep page requests exhaust CPU and I/O budgets.
  2. Unpredictable Query Plans Without Unique ORDER BY: Section 7.6 warns that the PostgreSQL query optimizer takes LIMIT and OFFSET directly into account when costing query plans. Consequently, changing LIMIT and OFFSET values across consecutive API calls frequently causes the planner to switch between an Index Scan, a Bitmap Heap Scan, and a Sequential Scan—yielding inconsistent or duplicate rows unless the query enforces a deterministic, unique ordering via ORDER BY.

Keyset (Cursor / Seek) Pagination replaces OFFSET with a tuple comparison against a composite B-tree index on (created_at DESC, id DESC):

-- Composite B-tree index supporting deterministic O(log N) keyset seeks
CREATE INDEX CONCURRENTLY idx_events_created_id_desc
    ON api_events (created_at DESC, id DESC);

-- Keyset pagination query: zero discarded OFFSET rows regardless of depth
SELECT id, tenant_id, event_type, payload, created_at
FROM api_events
WHERE (created_at, id) < ($1::timestamptz, $2::bigint)
ORDER BY created_at DESC, id DESC
LIMIT 50;

Because (created_at, id) forms a strictly unique total ordering, PostgreSQL seeks directly to the cursor entry in the B-tree index in $O(\log N)$ time and reads only the 50 requested leaf entries—delivering identical sub-millisecond query execution whether the client is fetching page 1 or page 500,000.

Pagination Strategy SQL Predicate Structure Rows Scanned at Page 5,000 (Limit 20) Consistency Under Concurrent Inserts
Offset Pagination ORDER BY created_at DESC LIMIT 20 OFFSET 100000 100,020 rows computed inside server (100,000 discarded) Vulnerable to row drift (skipped or duplicate items when new rows insert)
Keyset (Cursor) Pagination WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20 20 rows via direct B-tree index seek (0 rows discarded) Deterministic and drift-free across concurrent writes

8. End-to-End High-Throughput REST API Architecture Checklist

To synthesize these kernel, serialization, transport, and database techniques into a cohesive deployment standard, backend engineering teams should verify their production REST API stack against the following architectural checklist:

  1. Transport & Edge Framing: Expose HTTP/2 (RFC 9113) and HTTP/3 over QUIC (RFC 9114) at the ingress load balancer or API gateway to eliminate application-layer and TCP transport-layer head-of-line blocking for multiplexed clients.
  2. Kernel Zero-Copy I/O: Use sendfile(2) (observing the 0x7ffff000 / 2,147,479,552-byte per-call cap and TCP_CORK header coalescing) or splice(2) for static/cached file and pipe transfers, and enable SO_ZEROCOPY + MSG_ZEROCOPY only for dynamic socket payloads exceeding the 10 KB page-pinning break-even threshold with proper MSG_ERRQUEUE completion polling.
  3. Vectorized & Zero-Copy Serialization: Replace standard reflection-based JSON parsers with SIMD-accelerated parsers (simdjson / fastsimdjson, executing $\le 25\%$ of RapidJSON's instruction count at up to 25 GB/s), and adopt 64-bit word-aligned zero-copy binary schemas (Cap'n Proto or FlatBuffers) for high-frequency internal service-to-service endpoints.
  4. Bounded Transaction Pooling: Deploy PgBouncer on port 6432 in pool_mode = transaction with max_prepared_statements enabled (e.g., 256 per server connection for PGBOUNCER_{unique_id} protocol-level prepared statement multiplexing) and size the active server pool near $(\text{Physical Cores} \times 2) + \text{Effective Spindle Count}$.
  5. PostgreSQL Memory Discipline: Bound per-node work_mem (default 4 MB) and hash_mem_multiplier (default 2.0) relative to the pooled active connection ceiling so concurrent multi-hash queries never evict shared_buffers (25%–40% of system RAM) or trigger OS swap thrashing.
  6. Single-Roundtrip Batched & Keyset Queries: Enforce parameterized ANY($1) array batching to prevent N+1 query loops and mandate composite-index keyset pagination (sort_col, tiebreaker_id) < ($1, $2) on all collection endpoints.

9. Frequently Asked Questions (FAQ)

Why does Linux MSG_ZEROCOPY reduce performance on small REST API JSON responses under 10 KB? Because MSG_ZEROCOPY avoids copying bytes by pinning the user-space virtual memory pages in physical RAM until the network card finishes transmitting the packet and then queuing an asynchronous completion notification (SO_EE_ORIGIN_ZEROCOPY) on the socket error queue. As documented in the Linux kernel MSG_ZEROCOPY specification, page accounting and error-queue notification processing cost more CPU cycles than a fast L1/L2-cached memcpy for payloads smaller than approximately 10 KB.

How can an application safely use prepared statements with PgBouncer in transaction pooling mode? By setting max_prepared_statements to a positive integer (such as 128 or 256) in pgbouncer.ini and using a database driver that utilizes PostgreSQL's Extended Query protocol rather than SQL-level PREPARE strings. PgBouncer intercepts protocol-level prepared statements, assigns each unique query string a shared internal identifier (PGBOUNCER_{unique_id}), and automatically prepares missing statements on whichever backing PostgreSQL server connection is assigned to the transaction.

Why should Hyper-Threading logical threads be excluded from the ((core_count * 2) + effective_spindle_count) database pool sizing formula? Hyper-Threading (Simultaneous Multithreading) allows two logical threads to share the execution units and L1/L2 caches of a single physical processor core. As the PostgreSQL Wiki explains, counting logical threads doubles the active connection target, causing backend processes on the same physical core to evict each other's CPU cache lines and contend for spinlocks and LWLocks, pushing the database past the throughput saturation knee.

How does Cap'n Proto achieve zero-copy deserialization without an explicit parsing step? Cap'n Proto structures its wire format as contiguous segments of 64-bit (8-byte) aligned words where structs have fixed-size data and pointer sections, pointers use signed 30-bit relative word offsets rather than virtual memory addresses, and default values are stored XOR'd so default fields are all-zeros (0x00). Because the wire bytes are already laid out in little-endian CPU-native form, an application can read fields directly from the received memory buffer or mmap(2) region via pointer offset arithmetic with zero heap allocations.

What happens when MSG_ZEROCOPY is used over a local loopback interface (127.0.0.1) or while tcpdump is active? To prevent a slow local receiver from pinning sender pages indefinitely, the Linux kernel forces a deferred copy whenever a MSG_ZEROCOPY packet is looped to a local TCP/UDP socket, a packet socket (such as tcpdump), or a tun device. When this happens, the kernel sets the SO_EE_CODE_ZEROCOPY_COPIED flag in the ee_code field of the completion notification so the sender knows copy avoidance did not occur.

Why can changing LIMIT and OFFSET values return duplicate or missing rows in PostgreSQL even when no writes occur? As documented in PostgreSQL 19 Section 7.6 ("LIMIT and OFFSET"), SQL does not guarantee row ordering unless constrained by an ORDER BY clause, and the PostgreSQL query optimizer explicitly factors the LIMIT and OFFSET numbers into its plan cost estimates. Different OFFSET values frequently cause the planner to switch execution strategies (for example, from an index scan to a parallel sequential scan), changing the physical traversal order unless the ORDER BY clause specifies a strictly unique column combination such as (created_at DESC, id DESC).


10. Sources

  1. Linux Kernel Documentation — MSG_ZEROCOPY Socket Copy Avoidance Specification: https://docs.kernel.org/networking/msg_zerocopy.html
  2. Linux Programmer's Manual (man-pages 6.19) — sendfile(2) System Call Manual: https://man7.org/linux/man-pages/man2/sendfile.2.html
  3. Linux Programmer's Manual (man-pages 6.19) — splice(2) System Call Manual: https://man7.org/linux/man-pages/man2/splice.2.html
  4. Cap'n Proto Official Documentation — Binary Encoding Specification (64-bit Words, Structs, Lists, and Far Pointers): https://capnproto.org/encoding.html
  5. Geoff Langdale & Daniel Lemire — "Parsing Gigabytes of JSON per Second" (The VLDB Journal, 28(6), arXiv:1902.08318v7): https://arxiv.org/abs/1902.08318
  6. PostgreSQL Wiki — Number Of Database Connections (Saturation Knee and Pool Sizing Formula): https://wiki.postgresql.org/wiki/Number_Of_Database_Connections
  7. PgBouncer Official Documentation — pgbouncer.ini Configuration Reference (Pooling Modes, File Descriptor Formula, and max_prepared_statements): https://www.pgbouncer.org/config.html
  8. PostgreSQL 19 Official Documentation — Section 19.3: Connections and Authentication (max_connections, reserved_connections): https://www.postgresql.org/docs/current/runtime-config-connection.html
  9. PostgreSQL 19 Official Documentation — Section 19.4: Resource Consumption (shared_buffers, work_mem, hash_mem_multiplier, huge_pages): https://www.postgresql.org/docs/current/runtime-config-resource.html
  10. PostgreSQL 19 Official Documentation — Section 7.6: LIMIT and OFFSET Query Planning and Execution: https://www.postgresql.org/docs/current/queries-limit.html
  11. IETF RFC 9110 (STD 97) — HTTP Semantics (June 2022): https://www.rfc-editor.org/rfc/rfc9110
  12. IETF RFC 9113 — HTTP/2 Binary Framing and Stream Multiplexing (June 2022): https://www.rfc-editor.org/rfc/rfc9113
  13. IETF RFC 9114 — HTTP/3 Mapping over QUIC (June 2022): https://www.rfc-editor.org/rfc/rfc9114
đź”— Share Post

Reading next story...

Back to Feed