How vapor/postgres-nio works
Project type and purpose
• This is a Swift library (not an end-user application) that provides a non-blocking, event-driven PostgreSQL client built on SwiftNIO.
• It exposes two primary abstraction layers:
• PostgresNIO: the low-level connection, message encoder/decoder, and state machines
• PostgresClient (in PostgresNIO/Pool): a connection-pooling, async/await front end for user code
File structure
• Top-level:
• Sources/ConnectionPoolModule: generic pool state machine, request queuing, connection lifecycle
• Sources/PostgresNIO: the core library split into subfolders (Connection, Data, Message, New, Utilities, Docs)
• Benchmarks, Snippets: example code and performance tests
• Tests: unit/integration suites for both modules
• Config and CI:
• .github/workflows: tests, docs generation
• Package.swift, docker-compose.yml, dev scripts
Key architecture elements (to show
a. External Systems
• PostgreSQL Server (over TCP or Unix Domain Socket)
• Logging (SwiftLog) & ServiceLifecycle hooks (optional)
b. SwiftNIO Layer
• EventLoopGroup
• ChannelPipeline with
– PostgresFrontendMessageEncoder
– PostgresChannelHandler
– PostgresBackendMessageDecoder
c. Connection State Machine (in New/Connection State Machine)
• Manages authentication, query, extended query, row streaming, listen, close
d. Data Model & Wire Format
• PostgresDataConvertible, PostgresData, PostgresRow, PostgresRowSequence
• ExpressibleByStringInterpolation → PostgresQuery → parameter binding
e. PostgresConnection API (in Connection/PostgresConnection.swift)
• (), query(), prepare(), decode(), execute()
f. ConnectionPoolModule
• ConnectionPool: acquires/releases PostgresConnection instances
• ConnectionRequest, PoolStateMachine, ConnectionIDGenerator, observability hooks
g. PostgresClient (in PostgresNIO/Pool)
• user-facing pool wrapper with async/await run() and query(…) methods
Relationships & data flow
1. User code calls PostgresClient.query(…).
2. PostgresClient delegates to ConnectionPool → acquires a PostgresConnection.
3. PostgresConnection builds a PostgresQuery, encodes via the ChannelPipeline.
4. SwiftNIO writes framed bytes to PostgreSQL server.
5. Server responses arrive as bytes → go through BackendMessageDecoder.
6. Messages are fed into the Connection State Machine → assembled into rows.
7. PostgresRowSequence yields decoded Swift types to user code.
8. On completion or error, connection is returned to the pool (or closed).
Architectural patterns & principles
• Non-blocking reactor pattern via SwiftNIO EventLoopGroup
• Finite State Machines for protocol stages
• AsyncSequence for streaming row results with backpressure
• Separation of concerns:
• Wire encoding/decoding
• Protocol state transitions
• Connection pooling
• High-level async API