Skip to content

Memory Leak: fastify instance kept in memory after calling .close() #4843

@johannes-wtfoxtrot

Description

@johannes-wtfoxtrot

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.13.0

Plugin version

No response

Node.js version

v18.16.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.0.1

Description

We are experiencing OOM errors in our tests, both locally (macOS) and in CI (linux).

After some analysis we found that the fastify instances are kept in memory even after .close() was called.

We were able to reproduce this in a minimal reproduction, where only the repeated invocation of Fastify().close() leads to the allocation of more and more memory.

Screenshot 2023-06-22 at 09 33 19

What looks interesting is the connectionsCheckingInterval. This is new in Node.js v18.0.0: https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener. When running the script with Node.js v16.13.0, memory still increases, but not as much and there are no Router/Server instances in memory after the script has finished.

Steps to Reproduce

// memory-test.js
const Fastify = require('fastify')

const initialRss = process.memoryUsage().rss

async function main() {
  for (let i = 0; i < 2000; i += 1) {
    if (i % 100 === 0) {
      global.gc()
      console.log('server', i, process.memoryUsage().rss - initialRss)
    }
    const server = Fastify()
    // eslint-disable-next-line no-await-in-loop
    await server.close()
  }
  await new Promise(resolve => setTimeout(resolve, 1000))
  global.gc()
  debugger
}

main()

Run with node --expose-gc ./memory-test.js to see logs or node --inspect-brk --expose-gc ./memory-test.js to analyse memory allocation.

Expected Behavior

Fastify instances being freed after calling .close().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions