Skip to content

Build the TLS context once for an ssl object instead of for every connection - #1280

Merged
porsager merged 2 commits into
porsager:masterfrom
GrahamCampbell:tls-context
Nov 1, 2026
Merged

porsager merged 2 commits into
porsager:masterfrom
GrahamCampbell:tls-context

Conversation

@GrahamCampbell

@GrahamCampbell GrahamCampbell commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

When ssl is an object, every connection passes it to tls.connect, which builds a new TLS context from it each time. Building one parses every certificate in ca, so with a CA bundle, which managed databases ask clients to pass, each new connection spends milliseconds of CPU on the same work, and a burst of new connections, as when a pool fills up, blocks the event loop while it builds one for each. 3.4.9 does the same.

This builds the context once, with tls.createSecureContext, from an ssl object that has a ca, and gives it to every connection as secureContext together with the object's other options, so those that belong to a connection, such as servername, checkServerIdentity and rejectUnauthorized, still reach tls.connect. The context is kept for each ssl object and built again when one of the object's values is replaced, so a renewed cert on sql.options.ssl is picked up by the next connection as before; a change made inside a value, such as a push onto the same ca array, is not. An object without a ca is passed on as before, so each connection still builds its own context from Node's default certificate authorities as they are then, and follows tls.setDefaultCACertificates(). A secureContext given in the object is used as it is. It applies on Node.js only, so Bun, Deno and Cloudflare Workers connect as before. The README says so in its SSL section, and a test counts the contexts built for an object without a ca, with one, and after a value in it is replaced.

Reproduction

Against PostgreSQL 17 with TLS, on Node.js 22, with Node's 116 root certificates and the server's own CA as ca. On 4.0.0:

one at a time: TLS contexts built 20, per connection 10.6 ms, 7.8 ms of CPU
all at once:   TLS contexts built 20, event loop blocked up to 78 ms

With this change:

one at a time: TLS contexts built 1, per connection 5.0 ms, 2.6 ms of CPU
all at once:   TLS contexts built 1, event loop blocked up to 7 ms
import fs from 'node:fs'
import tls from 'node:tls'
import { monitorEventLoopDelay } from 'node:perf_hooks'
import postgres from 'postgres'

// Server and credentials from PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE, the server's CA from PGSSLROOTCERT.
// The CA list is Node's root certificates and that one, the shape of a provider's bundle. 20 connections each way.
let built = 0
const create = tls.createSecureContext
tls.createSecureContext = (...xs) => (built++, create(...xs))
const ca = [...tls.rootCertificates, fs.readFileSync(process.env.PGSSLROOTCERT, 'utf8')]

const one = postgres({ ssl: { ca }, max: 20 })
    , cpu = process.cpuUsage()
    , start = performance.now()
    , held = []
for (let i = 0; i < 20; i++)
  held.push(await one.reserve())
const used = process.cpuUsage(cpu)
console.log(`one at a time: TLS contexts built ${ built }, per connection ${ ((performance.now() - start) / 20).toFixed(1) } ms,`,
  `${ ((used.user + used.system) / 20000).toFixed(1) } ms of CPU`)
held.forEach(x => x.release())
await one.end()

built = 0
const burst = postgres({ ssl: { ca }, max: 20 })
    , loop = monitorEventLoopDelay({ resolution: 1 })
loop.enable()
const all = await Promise.all(Array.from({ length: 20 }, () => burst.reserve()))
loop.disable()
console.log(`all at once:   TLS contexts built ${ built }, event loop blocked up to ${ Math.round(loop.max / 1e6) } ms`)
all.forEach(x => x.release())
await burst.end()

@porsager

porsager commented Nov 1, 2026

Copy link
Copy Markdown
Owner

Ah - that's a nice optimization! Thank you

@porsager
porsager merged commit a990040 into porsager:master Nov 1, 2026
71 of 72 checks passed
@GrahamCampbell
GrahamCampbell deleted the tls-context branch November 1, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants