Title: expressIntegration: layer spans end when `next()` returns instead of when it is called, piling up `finish` listeners (MaxListenersExceededWarning) and inflating middleware span durations · Issue #24853 · getsentry/sentry-javascript · GitHub
Open Graph Title: expressIntegration: layer spans end when `next()` returns instead of when it is called, piling up `finish` listeners (MaxListenersExceededWarning) and inflating middleware span durations · Issue #24853 · getsentry/sentry-javascript
X Title: expressIntegration: layer spans end when `next()` returns instead of when it is called, piling up `finish` listeners (MaxListenersExceededWarning) and inflating middleware span durations · Issue #24853 · getsentry/sentry-javascript
Description: Is there an existing issue for this? I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues I have reviewed the documentation https://docs.sentry.io/ I am using the latest SDK release https://github.com/...
Open Graph Description: Is there an existing issue for this? I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues I have reviewed the documentation https://docs.sentry.io/ I am using th...
X Description: Is there an existing issue for this? I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues I have reviewed the documentation https://docs.sentry.io/ I am using th...
Opengraph URL: https://github.com/getsentry/sentry-javascript/issues/24853
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"expressIntegration: layer spans end when `next()` returns instead of when it is called, piling up `finish` listeners (MaxListenersExceededWarning) and inflating middleware span durations","articleBody":"\n### Is there an existing issue for this?\n\n- [x] I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues\n- [x] I have reviewed the documentation https://docs.sentry.io/\n- [x] I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases\n\n### How do you use Sentry?\n\nSentry Saas (sentry.io)\n\n### Which SDK are you using?\n\n@sentry/node\n\n### SDK Version\n\n11.1.0 (also 11.0.0; not present on 10.75.0)\n\n### Framework Version\n\nExpress 5.2.1 (`router` 2.x) and Express 4.22.3, Node 24.18.1\n\n### Link to Sentry event\n\nN/A. The symptom is a Node process warning plus span timings, not a captured event.\n\n### Reproduction Example/SDK Setup\n\n`instrument.mjs`\n\n```js\nimport * as Sentry from '@sentry/node';\n\nexport const spans = [];\n\nSentry.init({\n dsn: 'https://public@o0.ingest.sentry.io/0',\n tracesSampleRate: 1.0,\n transport: () => ({ send: async () => ({}), flush: async () => true }),\n beforeSendSpan(span) {\n spans.push(span);\n return span;\n },\n});\n```\n\n`app.mjs`\n\n```js\nimport http from 'node:http';\nimport express from 'express';\nimport { spans } from './instrument.mjs';\n\nprocess.on('warning', warning => console.log(`${warning.name}: ${warning.message}`));\n\nconst app = express();\n\n// Ten ordinary synchronous middleware (request id, helmet, cors, body parsers, loggers, ...)\nfor (let i = 0; i \u003c 10; i++) {\n app.use(function syncMiddleware(_req, _res, next) {\n next();\n });\n}\n\napp.get('/test', (_req, res) => {\n console.log(`'finish' listeners on the response inside the handler: ${res.listenerCount('finish')}`);\n const until = Date.now() + 50; // 50ms of synchronous work in the handler\n while (Date.now() \u003c until);\n res.json({ ok: true });\n});\n\nconst server = app.listen(0, () => {\n http.get(`http://127.0.0.1:${server.address().port}/test`, res => {\n res.resume().on('end', () => {\n setTimeout(() => {\n const first = spans.find(span => span.attributes?.['express.type'] === 'middleware');\n const ms = (first.end_timestamp - first.start_timestamp) * 1000;\n console.log(`duration of the first (no-op) middleware span: ${ms.toFixed(1)}ms`);\n server.close();\n }, 100);\n });\n });\n});\n```\n\n### Steps to Reproduce\n\n1. `npm i @sentry/node@11.1.0 express@5.2.1`\n2. `node --import ./instrument.mjs app.mjs`\n\n### Expected Result\n\nEach layer's span ends, and its `finish` listener is removed, when the layer calls `next()`. That is how v10's OpenTelemetry-based Express instrumentation behaved. The number of `finish` listeners stays constant no matter how many layers a request passes through, and a middleware span measures only that middleware.\n\n### Actual Result\n\n```\n'finish' listeners on the response inside the handler: 12\nMaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit\nduration of the first (no-op) middleware span: 50.7ms\n```\n\n- Every request whose synchronous middleware/router chain is about 9 or more layers deep logs one `MaxListenersExceededWarning`. In our production Express 5 API that is one warning every few seconds, which our platform surfaces as error-level logs.\n- It also happens for unsampled requests: `tracesSampleRate: 0` produces the same warning.\n- Express 4.22.3 is affected the same way (14 listeners in the same repro).\n- The listeners are released when the response finishes, so this is not a real memory leak. The problems are the warning noise and inflated span durations.\n\n### Additional Context\n\n**Root cause**\n\n- `getSpanForLayer` adds `res.once('finish', onFinish)` for every traced layer ([instrumentation.ts L332-L338](https://github.com/getsentry/sentry-javascript/blob/6baedf11cfbbe465867d4f93628e7100056b425c/packages/server-utils/src/integrations/express/instrumentation.ts#L332-L338)). The comment there expects the helper to end the span, and drop the listener, \"when `next` *is* called\".\n- `bindTracingChannelToSpan` actually ends the span on `asyncEnd` ([tracing-channel.ts L197-L203](https://github.com/getsentry/sentry-javascript/blob/6baedf11cfbbe465867d4f93628e7100056b425c/packages/server-utils/src/tracing-channel.ts#L197-L203)). For the `Callback` kind, `asyncEnd` is published only after the callback **returns**.\n- In Express, `next()` runs the rest of the chain synchronously. It only returns after every downstream layer has run up to its first async hop. So every layer on that synchronous chain holds a live span and a `finish` listener at the same time: one per middleware and router, plus the route handler. That passes Node's default limit of 10.\n- The same cause makes each middleware span include the synchronous work of every layer after it. In the repro, a no-op middleware reports 50.7ms because the handler does 50ms of synchronous work.\n- The rest of the integration already treats `asyncStart` as the moment `next` is called, before the downstream layer runs ([instrumentation.ts L97-L108](https://github.com/getsentry/sentry-javascript/blob/6baedf11cfbbe465867d4f93628e7100056b425c/packages/server-utils/src/integrations/express/instrumentation.ts#L97-L108)). The orchestrion config also says the transform \"ends the traced operation when `next` is invoked\" ([config/express.ts L11-L13](https://github.com/getsentry/sentry-javascript/blob/6baedf11cfbbe465867d4f93628e7100056b425c/packages/server-utils/src/orchestrion/config/express.ts#L11-L13)). Ending on `asyncEnd` therefore looks unintended.\n\n**Suggested fix**\n\nEnd the layer span in the existing `asyncStart` subscriber:\n\n```diff\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n- asyncStart: popLayerPathForLayer,\n+ asyncStart: data => {\n+ popLayerPathForLayer(data);\n+ endLayerSpan(data);\n+ },\n });\n```\n\n```ts\n/** End a layer's span when it hands off via `next`, before the downstream layer runs. */\nfunction endLayerSpan(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n```\n\nThe helper's later `asyncEnd` then does nothing: `removeListener` on an already-removed listener is a no-op, and `span.end()` is idempotent. `next(err)` still marks the span as errored, because the channel publishes `error` before `asyncStart`.\n\nI applied this change to the published 11.1.0 build and re-ran the repro:\n\n```\n'finish' listeners on the response inside the handler: 2\nduration of the first (no-op) middleware span: 0.1ms\n```\n\nOther behaviour I checked with the patch, compared against the unpatched build:\n\n- async middleware (`setTimeout(next, 20)`)\n- fall-through routers mounted on the same prefix\n- `next(err)`: the span status stays `error`\n- transaction and route names (`GET /api/items/:id`)\n\nAll are unchanged, apart from span durations and end order now being correct.\n\n**Workarounds** until a fix ships:\n\n- `expressIntegration({ ignoreLayersType: ['middleware', 'router'] })`\n- leaving `tracesSampleRate` unset\n\n**PR**\n\nI'm happy to open a PR with this change and a node-integration-test.\n","author":{"url":"https://github.com/diobriggs","@type":"Person","name":"diobriggs"},"datePublished":"2026-09-29T19:30:23Z","url":"https://github.com/getsentry/sentry-javascript/issues/24853"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:ead708c2-7a1c-996e-1c4b-0f3686d2adba |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D07A:1F60EA:477DA8:641A93:6B044201 |
| html-safe-nonce | 65459c8d295fa0dff1755b29e78092fb9d1ce49103a551c8e9a64aaafe5c7107 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMDdBOjFGNjBFQTo0NzdEQTg6NjQxQTkzOjZCMDQ0MjAxIiwidmlzaXRvcl9pZCI6IjI3ODkyODUyOTAwNTYxMDY0OTciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 362885aceceb959803a045e5edc1158504a04213a1ad26aa688fe95bd96fb6d6 |
| hovercard-subject-tag | issue:5635890398 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/getsentry/sentry-javascript/24853/issue_layout |
| twitter:image | https://opengraph.githubassets.com/7f60cb823f204a7c1737d2c3b7891b87ed23172a0ad42bacaa0a7d7ee401acc3/getsentry/sentry-javascript/issues/24853 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/7f60cb823f204a7c1737d2c3b7891b87ed23172a0ad42bacaa0a7d7ee401acc3/getsentry/sentry-javascript/issues/24853 |
| og:image:alt | Is there an existing issue for this? I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues I have reviewed the documentation https://docs.sentry.io/ I am using th... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | diobriggs |
| hostname | github.com |
| expected-hostname | github.com |
| None | 9185ccfefd80c1ff2d9ddcdb0cd2becf46b5a1efbbf30741a895e4bb8de25e64 |
| turbo-cache-control | no-preview |
| go-import | github.com/getsentry/sentry-javascript git https://github.com/getsentry/sentry-javascript.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 3328572 |
| octolytics-dimension-repository_nwo | getsentry/sentry-javascript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 3328572 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-javascript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 06dc448a76fe4751ac1db26524aefa3aa3e889a8 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width