← Back to Pull requests

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

Closed
unknown closed this pull request without merging on Nov 21, 2026 10:39 UTC
View on GitHub
unknown unknown commented on Nov 21, 2026 07:38 UTC
Author

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.

    <details><summary>Script</summary>

    '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()
    

    </details>

    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.
    <!--
    Thank you for your pull request. Please provide a description above and review
    the requirements below.

    Bug fixes and new features should include tests and possibly benchmarks.

    Contributors guide: https://github.com/fastify/fastify/blob/main/CONTRIBUTING.md

    By making a contribution to this project, I certify that:

    (a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

    (b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

    (c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

  • (d) I understand and agree that this project and the contribution

  • are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
    -->

    Checklist

  • run npm run test && npm run benchmark --if-present

  • tests and/or benchmarks are included

  • documentation is changed or added

  • commit message and code follows the Developer's Certification of Origin

  • and the Code of conduct

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: mcollina Review duration: 180m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #934"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%