Skip to content

perf: walk schema objects without a WeakSet in assertObjectDepth - #934

Merged
Tony133 merged 2 commits into
fastify:mainfrom
iammerlijn:perf/object-depth
Nov 21, 2026
Merged

Tony133 merged 2 commits into
fastify:mainfrom
iammerlijn:perf/object-depth

Conversation

@iammerlijn

@iammerlijn iammerlijn commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

This makes Fastify startup 8-9% faster for an app with 200 routes and 40 shared schemas. The checks and the errors do not change.

Why

Fastify compiles one serializer for each response schema. Each time, it passes all shared schemas (app.addSchema) in options.schema. build() makes a new RefResolver for each call, so it walks every shared schema again with assertObjectDepth (index.js:487). For 200 routes with 2 status codes and 40 shared schemas, that is 16,000 walks at startup. In a CPU profile of that app (Node 24, median of 7 runs), assertObjectDepth took 138 ms of the 789 ms in build(), about 17%. With this change it takes 91 ms.

For each node, the walk allocated 2 { value, depth, exit } entries, and it did a WeakSet add, has and delete.

What changed

  • assertObjectDepth keeps the same iterative depth-first walk, in the same order. Two arrays (values, depths) hold the pending nodes. An array path holds the ancestors of the current node, cut to the current depth. A node that is already in path is a cycle. The depth limit (maxDepth * 2) keeps path at 201 entries or fewer, so the scan stays cheap.
  • A root that is not an object returns at once, the same as before.

The walk stays iterative, so the stack-safety fix from #874 is kept. A shared sub-object that is not a cycle is still accepted. The two error messages, and the node where each one is thrown, are the same.

Numbers

Apple M3 Pro, Fastify() to ready(), fastify 5.12.8 with @fastify/fast-json-stringify-compiler, separate processes, old and new in alternating order, median of 21 runs (11 runs for the 10-route app on Node 26 and the app without shared schemas):

app Node 24.22 main → PR Node 26.13 main → PR
200 routes, 40 shared schemas 781.6 → 717.1 ms (-8.3%) 726.6 → 660.0 ms (-9.2%)
10 routes, 40 shared schemas 71.7 → 67.3 ms (-6.1%) 62.4 → 58.8 ms (-5.8%)
10 routes, no shared schemas 28.4 → 27.9 ms (-1.7%, noise)

On Node 26, every new run was faster than every old run. The worst cases are not slower: a chain of depth 199 with 200k leaves takes 51-54 ms on main and 37-40 ms with this change.

The repo bench measures only serialization, so I used a small script. Each shared schema has about 12 properties, a nested object and a $ref to the one before it. Each route has a 200 response with 2 $refs and a 404 response.

Script
'use strict'
// usage: node startup.js <fast-json-stringify dir> <routes> <shared schemas>
const Module = require('module')
const path = require('path')
const target = path.resolve(process.argv[2], 'index.js')
const orig = Module._resolveFilename
Module._resolveFilename = function (req, ...rest) {
  if (req === 'fast-json-stringify') return target
  return orig.call(this, req, ...rest)
}
const ROUTES = Number(process.argv[3])
const SHARED = Number(process.argv[4])
const Fastify = require('fastify')

function shared (i) {
  const props = { id: { type: 'string' }, createdAt: { type: 'string', format: 'date-time' }, count: { type: 'integer' }, tags: { type: 'array', items: { type: 'string' } } }
  for (let j = 0; j < 8; j++) props['f' + j] = { type: ['string', 'number', 'boolean'][j % 3] }
  if (i > 0) props.parent = { $ref: 's' + (i - 1) + '#' }
  props.meta = { type: 'object', properties: { a: { type: 'string' }, b: { type: 'object', properties: { c: { type: 'number' } } } } }
  return { $id: 's' + i, type: 'object', properties: props, required: ['id'] }
}

async function main () {
  const t0 = process.hrtime.bigint()
  const app = Fastify()
  for (let i = 0; i < SHARED; i++) app.addSchema(shared(i))
  for (let r = 0; r < ROUTES; r++) {
    const s = r % Math.max(SHARED, 1)
    app.get('/r' + r, {
      schema: {
        response: {
          200: SHARED
            ? { type: 'object', properties: { data: { $ref: 's' + s + '#' }, list: { type: 'array', items: { $ref: 's' + ((s + 1) % SHARED) + '#' } } } }
            : { type: 'object', properties: { a: { type: 'string' } } },
          404: { type: 'object', properties: { message: { type: 'string' } } }
        }
      }
    }, async () => ({}))
  }
  await app.ready()
  console.log((Number(process.hrtime.bigint() - t0) / 1e6).toFixed(2))
}
main()

Tests

  • New test in test/schema-depth.test.js: shared sub-objects are accepted, a cycle through an array is rejected, the depth error for an external schema has its name, and a function as the schema still gives schema is invalid. The test also passes on main.
  • I compared the old and new function on about 1.2 million random object graphs (trees, shared children, cycles, self-loops, arrays, $ref keys, roots that are not objects, maxDepth 0 to 5). The result, the error and the error order were the same every time.
  • npm test passes with 100% coverage, and lint is clean.

Related: #874 (added assertObjectDepth), #900 (added hasRef), #506 (slow cold start with many shared schemas).

I used Claude (Opus 5.5) to write and benchmark this change. I checked the results and the reasoning before opening it.

Checklist

build() walks every external schema with assertObjectDepth, and Fastify
passes all shared schemas to every route build. The walk allocated two
{ value, depth, exit } entries and did WeakSet add/has/delete for each
node.

Keep the same iterative depth-first walk and the same errors, but hold
the pending nodes in two arrays and the ancestors in a path array that
is cut to the current depth. The depth limit keeps the path short.

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm

@Tony133 Tony133 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@Tony133
Tony133 merged commit 7fbddd4 into fastify:main Nov 21, 2026
19 checks passed
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.

3 participants