Skip to content

perf: use performance.now() for query execution timing - #12750

Merged
alumni merged 4 commits into
typeorm:masterfrom
pri12ya871:perf-now-query-timing
Oct 21, 2026
Merged

alumni merged 4 commits into
typeorm:masterfrom
pri12ya871:perf-now-query-timing

Conversation

@pri12ya871

@pri12ya871 pri12ya871 commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Description of change

QueryRunner.query() measured elapsed execution time with Date.now(). That is a wall-clock source, so an NTP correction or a manual clock change mid-query can make the measurement jump backwards, producing a negative or inflated duration. performance.now() is monotonic and higher resolution, which is what an elapsed-time measurement wants.

Current behavior: queryExecutionTime is derived from two Date.now() readings, at whole-millisecond resolution, and is not monotonic.

New behavior: the same measurement uses performance.now(). The value feeding the maxQueryExecutionTime comparison and logQuerySlow is now monotonic and sub-millisecond.

This replaces the 30 timing call sites across the 13 driver query runners.

Date.now() is deliberately left in place wherever the value is a real timestamp rather than an elapsed measurement — swapping those would be a bug, since performance.now() is relative to process start rather than the epoch:

  • src/cache/DbQueryResultCache.ts
  • src/cache/RedisQueryResultCache.ts
  • src/commands/CommandUtils.ts
  • src/query-builder/SelectQueryBuilder.ts

How I verified it: pnpm run compile passes, eslint reports no new errors on the changed files, and prettier --check is clean. No import is needed — performance has been a Node global since v16 and this package requires ^20.19.0 || ^22.13.0 || >=24.11.0.

One decision worth your call

Date.now() returns an integer; performance.now() returns a float. That value is interpolated straight into the slow-query log in FileLogger:

`[SLOW QUERY: ${message.additionalInfo?.time} ms]: ${message.message}`

so slow-query lines change from [SLOW QUERY: 1234 ms] to e.g. [SLOW QUERY: 1234.5678901 ms]. The maxQueryExecutionTime comparison stays correct; only the rendered text changes.

I left it unrounded because the issue asks for a higher-resolution timer and rounding to whole milliseconds would discard exactly that. Rounding at the log boundary instead would touch AbstractLogger and affect every logger implementation, which felt broader than this issue's scope. Happy to add rounding at either the measurement or the log boundary if you would prefer to keep the existing log format — just say which.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword: Closes Replace Date.now() with performance.now() in query() method #12731
  • There are new or updated tests validating the change (tests/**.test.ts) — N/A, see below
  • Documentation has been updated to reflect this change (docs/docs/**.md) — N/A, no user-facing API change

On tests: this is a like-for-like swap of the timing source with no behavioral branch to assert, and the driver query paths need live database connections, so test:fast does not reach them. If you would like coverage, the meaningful place is a logger-level assertion on the slow-query path — glad to add one if you want it in this PR.

@github-actions github-actions Bot added the linked-issue PR references an issue label Aug 2, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. logQuerySlow rounding undocumented ⊘ Outdated
Description
AbstractLogger.logQuerySlow now rounds every supplied duration, changing the observable output for
custom loggers that pass fractional values, but the PR does not update the logging documentation.
This user-facing behavior change violates the requirement to document public usage changes.
Code

src/logger/AbstractLogger.ts[112]

+        const roundedTime = Math.round(time)
Evidence
PR Compliance ID 2 requires documentation for user-facing changes. The added Math.round(time) is
fed into both logger message fields, while docs/docs/logging.md publicly recommends extending
AbstractLogger without documenting this rounding behavior.

Rule 2: Docs updated for user-facing changes
src/logger/AbstractLogger.ts[109-130]
docs/docs/logging.md[99-116]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`AbstractLogger.logQuerySlow` now rounds fractional execution times before passing messages to logger implementations, but this observable behavior is not documented.
## Issue Context
`AbstractLogger` is a documented extension point for custom loggers, so subclasses can observe the changed `message` and `additionalInfo.time` values.
## Fix Focus Areas
- docs/docs/logging.md[99-116]
- src/logger/AbstractLogger.ts[109-130]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Slow log contradicts threshold ⊘ Outdated
Description
Math.round(time) can round a duration just above maxQueryExecutionTime back down to the
threshold, so a 1000.1 ms query classified as slow is emitted as [SLOW QUERY: 1000 ms]. This makes
the warning contradict its configured condition and can mislead users or log-based monitoring that
consumes the reported duration.
Code

src/logger/AbstractLogger.ts[112]

+        const roundedTime = Math.round(time)
Evidence
Query runners compare the unrounded high-resolution value using a strict greater-than check before
calling logQuerySlow, while AbstractLogger rounds that value and FileLogger renders the
rounded field verbatim. The option is documented as the maximum execution time, so reporting the
threshold itself on a warning that only fires above it is inconsistent.

src/driver/postgres/PostgresQueryRunner.ts[279-300]
src/logger/AbstractLogger.ts[109-130]
src/logger/FileLogger.ts[79-86]
src/data-source/BaseDataSourceOptions.ts[87-90]
test/unit/logger/abstract-logger.test.ts[28-51]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Slow-query classification uses the high-resolution duration, but nearest-integer rounding can emit a duration equal to or below the threshold that triggered the warning.
## Issue Context
For example, with `maxQueryExecutionTime: 1000`, an elapsed time of `1000.1` passes the strict `>` check but is logged as `1000 ms`. Keep integer-formatted logs while ensuring the rendered value remains consistent with slow-query classification, and update the logger unit tests with a threshold-boundary case.
## Fix Focus Areas
- src/logger/AbstractLogger.ts[109-130]
- test/unit/logger/abstract-logger.test.ts[28-51]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Clock source may mismatch ⊘ Outdated
Description
PlatformTools.performanceNow() re-checks global.performance.now on every invocation, so if
application/runtime code adds/removes/replaces performance.now between the start and end reads,
queryExecutionTime can subtract values from different time origins and become negative or
extremely large. This can lead to incorrect slow-query logging and incorrect
afterQuery.executionTime values in affected query runners.
Code

src/platform/PlatformTools.ts[R42-45]

+        const globalVariable = PlatformTools.getGlobalVariable()
+        if (typeof globalVariable?.performance?.now === "function") {
+            return globalVariable.performance.now()
+        }
Evidence
The new helper chooses between performance.now() and Date.now() each time it’s called, and query
runners compute elapsed time by subtracting two independent calls; if the chosen source changes
between those calls, the subtraction mixes different time origins and yields a nonsensical duration.

src/platform/PlatformTools.ts[24-47]
src/driver/mysql/MysqlQueryRunner.ts[199-247]
src/platform/BrowserPlatformTools.template[16-45]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`PlatformTools.performanceNow()` dynamically selects between `performance.now()` and `Date.now()` on each call. If `globalThis.performance.now` is polyfilled/monkey-patched (added/removed/replaced) during an in-flight query, the start and end reads can come from different clocks (different origins), producing an invalid duration.
### Issue Context
Query runners call `PlatformTools.performanceNow()` at the start and again at the end, then subtract the two values to compute `queryExecutionTime`.
### Fix
Stabilize the clock source by selecting it once and reusing it (cache a bound `now()` function), so both start/end reads always use the same origin for the lifetime of the process/module.
Implementation sketch:
- Add a private static cached function (e.g. `_nowFn?: () => number`).
- On first call, detect `globalVariable?.performance?.now`, and set `_nowFn` to either `globalVariable.performance.now.bind(globalVariable.performance)` or `Date.now`.
- Return `_nowFn()`.
- Mirror the same change in the browser template so the browser build has identical behavior.
### Fix Focus Areas
- src/platform/PlatformTools.ts[41-47]
- src/platform/BrowserPlatformTools.template[39-45]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Missing performance.now fallback ✓ Resolved
Description
Several query runners now call performance.now() directly; if the global performance object (or
performance.now) is missing in a target runtime, QueryRunner.query() will throw before executing
the query. This is a behavior change from Date.now() (which is always present) and can break
database access for those environments.
Code

src/driver/cordova/CordovaQueryRunner.ts[R66-68]

const broadcasterResult = new BroadcasterResult()
-        const queryStartTime = Date.now()
+        const queryStartTime = performance.now()
Evidence
The changed query runners now reference performance.now() unconditionally, and the codebase does
not provide a cross-runtime timing abstraction (only a global accessor via
PlatformTools.getGlobalVariable()). Since TypeORM explicitly supports multiple platform-oriented
drivers (Expo/React Native/etc.), directly accessing a potentially-missing global can hard-fail
query execution in those environments.

src/driver/cordova/CordovaQueryRunner.ts[61-84]
src/driver/react-native/ReactNativeQueryRunner.ts[62-81]
src/driver/expo/ExpoQueryRunner.ts[38-54]
src/driver/nativescript/NativescriptQueryRunner.ts[66-76]
src/driver/sqljs/SqljsQueryRunner.ts[97-119]
src/platform/PlatformTools.ts[17-31]
src/platform/PlatformTools.ts[40-70]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Query runners now assume a global `performance.now()` exists. In any runtime where `performance` (or `performance.now`) is undefined, evaluating `performance.now()` throws and prevents the query from running.
## Issue Context
TypeORM includes drivers intended for non-Node targets (e.g., React Native / Expo / Cordova / sql.js). These environments do not share a single guaranteed global API surface unless we guard access.
## Fix
1. Add a shared helper (e.g., `PlatformTools.performanceNow()` or `PlatformTools.elapsedMillis()`) that returns a monotonic timestamp when available:
- Prefer `globalThis.performance?.now?.()` when present.
- Fallback to `Date.now()` otherwise.
2. Replace direct `performance.now()` calls in query runners with the helper.
## Fix Focus Areas
- src/platform/PlatformTools.ts[17-31]
- src/platform/PlatformTools.ts[40-70]
- src/driver/cordova/CordovaQueryRunner.ts[63-84]
- src/driver/react-native/ReactNativeQueryRunner.ts[64-82]
- src/driver/expo/ExpoQueryRunner.ts[41-54]
- src/driver/nativescript/NativescriptQueryRunner.ts[66-76]
- src/driver/sqljs/SqljsQueryRunner.ts[97-119]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

5. Falsy start-time check ✓ Resolved
Description
SqlServerQueryRunner computes error-path timing with queryStartTime ? ... : undefined; with
performance.now() it is possible for queryStartTime to be 0, causing timing to be treated as
unset. This can suppress queryExecutionTime for after-query broadcasting and slow-query logging on
the error path.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R315-317]

const queryExecutionTime = queryStartTime
-                ? Date.now() - queryStartTime
+                ? performance.now() - queryStartTime
: undefined
Evidence
The code declares queryStartTime as number | undefined, assigns it from performance.now(), and
later uses queryStartTime ? ... : undefined in the catch path; this condition treats 0 as
"unset" because it is falsy in JavaScript.

src/driver/sqlserver/SqlServerQueryRunner.ts[231-317]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
In `SqlServerQueryRunner`, the catch-path uses a truthiness check to decide whether to compute `queryExecutionTime`. After switching to `performance.now()`, a start time of `0` is possible and is falsy, so the code can incorrectly skip timing.
## Issue Context
`queryStartTime` is typed as `number | undefined` and is assigned from `performance.now()`.
## Fix
Change the condition to an explicit undefined check:
- `queryStartTime !== undefined ? (now - queryStartTime) : undefined`
Optionally, use the same shared timing helper as other query runners.
## Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[231-318]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Tip of the day
💡 Did you know, you can start a comment with 'qodo' or '@qodo' to chat about any finding

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@gioboa
gioboa requested a review from Cprakhar August 2, 2026 19:35
@pri12ya871

Copy link
Copy Markdown
Contributor Author

Both findings were correct — fixed in a74a442.

1. Missing performance.now fallback. This was the more serious of the two and I had reasoned about it wrongly: I checked engines.node and concluded performance was safe as a global, but that field describes the build environment, not the runtimes the Cordova / React Native / Expo / NativeScript / sql.js drivers actually execute in. Unguarded, this would have thrown before the query ran — turning a timing improvement into broken database access.

Added PlatformTools.performanceNow(), which prefers performance.now() where the runtime exposes it and falls back to Date.now() otherwise, and routed all 30 call sites through it. It goes via the existing getGlobalVariable() accessor to stay consistent with how this codebase already handles platform globals.

Two details worth flagging, since they were not in the review and would each have been silent failures:

  • BrowserPlatformTools.template replaces PlatformTools in browser builds (per the browser mapping in package.json), so the helper is added there too. Adding it only to PlatformTools.ts would have left the browser bundle without it — precisely the targets this finding is about.
  • 7 of the 13 query runners referenced PlatformTools only through import type { ReadStream }, which erases at runtime. Those now carry an explicit value import; reusing the type-only import would have compiled cleanly and failed in production.

2. Falsy start-time check. Correct, and I introduced it. SqlServerQueryRunner declares queryStartTime: number | undefined and guarded the error path with a truthiness check. Date.now() could never return 0, so the guard was previously safe by accident; performance.now() can, which would have silently suppressed queryExecutionTime for after-query broadcasting and slow-query logging. Now an explicit !== undefined check.

pnpm run compile passes, eslint reports no errors on the changed files, and prettier is clean.

The open question from the original description still stands for a maintainer: performance.now() returns a float, and FileLogger interpolates it straight into [SLOW QUERY: ${time} ms], so slow-query lines gain decimals. I left it unrounded because the issue asks for higher resolution, but happy to round at the measurement or the log boundary if you would rather preserve the existing output.

Comment thread src/platform/PlatformTools.ts Outdated
* Only ever use the returned value to compute a duration: its time origin
* is not the Unix epoch.
*/
static performanceNow(): number {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

PlatformTools (and BrowserPlatformTools) are for those utility functions that are different across platforms. Since the implementation is the same for both NodeJS and browsers, this functions could be moved maybe to DateUtils.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved — thanks, that's the right call. performanceNow() is gone from both PlatformTools.ts and BrowserPlatformTools.template (both files are byte-identical to master again) and now lives in DateUtils, which the 13 query runners import instead. DateUtils already has unit coverage in test/unit/util/date-utils.test.ts, so it seems a natural home for it.

Done in a511c24.

Comment thread src/platform/PlatformTools.ts Outdated
* is not the Unix epoch.
*/
static performanceNow(): number {
const globalVariable = PlatformTools.getGlobalVariable()

@alumni alumni Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think globalThis can safely be used everywhere. PlatformTools.getGlobalVariable() is probably not necessary anymore.

globalThis.performance?.now() ?? Date.now()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and applied — the helper is now just:

static performanceNow(): number {
    return globalThis.performance?.now() ?? Date.now()
}

PlatformTools.getGlobalVariable() is no longer involved. As a side effect this also settles the bot's "clock source may mismatch" note above: with no per-call resolution left, there is nothing that can change between the start and end readings.

@alumni

alumni commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator

Hi @pri12ya871, thanks for the PR, only wrote a small comment.

Heads up for reviewers: there might be other PRs changing lines with Date.now(), check before merge.

@github-actions github-actions Bot added the possible-duplicate PR may duplicate an existing open PR label Aug 26, 2026
@Cprakhar

Copy link
Copy Markdown
Collaborator

@pri12ya871 You can round-off the time at logger level - only few changes.

@pri12ya871

Copy link
Copy Markdown
Contributor Author

Thanks both — pushed an update addressing all of this.

@Cprakhar rounding is now done at the logger level as you suggested (c3cdafa). A single Math.round() in AbstractLogger.logQuerySlow covers both additionalInfo.time and the execution-time message, so every logger implementation keeps its existing output and [SLOW QUERY: 1234 ms] renders exactly as it did before. The maxQueryExecutionTime comparison and the afterQuery event keep the unrounded value, so no resolution is lost where it actually matters. If you would rather keep some sub-millisecond detail in the log, Number(time.toFixed(2)) is a one-word change — just say so.

@alumni both of your comments are addressed in a511c24: the helper is out of PlatformTools/BrowserPlatformTools.template (both are byte-identical to master again) and into DateUtils as globalThis.performance?.now() ?? Date.now(). I have left the threads open for you to resolve.

I also added test/unit/logger/abstract-logger.test.ts, which asserts the rounding without needing a database connection, so it runs under test:fast. Locally: pnpm run compile is clean, eslint reports no new errors on the changed files, and the fast suite passes.

On the possible-duplicate label: #12756 covers the same driver call sites. This one predates it and additionally handles the integer-to-float change in the slow-query log format, plus test coverage. No strong feelings about which lands — happy to close mine or rebase on top of it, whichever the maintainers prefer.

@pkg-pr-new

pkg-pr-new Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12750
    

commit: eb640a2

@pri12ya871

Copy link
Copy Markdown
Contributor Author

Rebased onto current master (b495ed4). It replayed cleanly with no conflicts and the diff is unchanged — still 16 files, +123/-34.

@alumni that should also tie off your heads-up about other PRs touching these lines: on top of current master there are no Date.now() calls left in any queryStartTime/queryEndTime assignment, and the four remaining Date.now() uses in src/ are the epoch timestamps listed in the description, which are intentionally left alone.

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @pri12ya871 👏

@pri12ya871

Copy link
Copy Markdown
Contributor Author

Thanks for approving! Just checking if anything else is needed. If it's all good, could you please merge it when you get a chance?

@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

QueryRunner.query() measured elapsed time with Date.now(), which is
wall-clock and can jump backwards when the system clock is adjusted,
producing negative or inflated durations. performance.now() is monotonic
and higher resolution, which is what an elapsed-time measurement wants.

Replaces the 30 timing call sites across the 13 driver query runners.
Date.now() is deliberately left where the value is a real timestamp
rather than an elapsed measurement: query result cache expiry in
DbQueryResultCache and RedisQueryResultCache, CommandUtils, and
SelectQueryBuilder.

Closes typeorm#12731
…-time check

Two follow-ups on the Date.now() to performance.now() change.

1. performance is not guaranteed on every runtime TypeORM targets. The
   Cordova, React Native, Expo, NativeScript and sql.js drivers run outside
   Node, and calling performance.now() unconditionally would throw before the
   query executed, turning a timing improvement into broken database access.
   Adds PlatformTools.performanceNow(), which prefers the monotonic
   performance.now() when the runtime exposes it and falls back to Date.now()
   otherwise, and routes every query runner through it. The helper is added to
   BrowserPlatformTools.template as well, since that replaces PlatformTools in
   browser builds.

2. SqlServerQueryRunner guarded its error-path timing with a truthiness check
   on queryStartTime. Date.now() could never return 0, but performance.now()
   can, which would silently suppress queryExecutionTime for after-query
   broadcasting and slow-query logging. Uses an explicit undefined check.
The implementation was identical in PlatformTools and
BrowserPlatformTools.template, so it was not platform-specific code and
did not belong in that pair. Moved to DateUtils and reduced to
`globalThis.performance?.now() ?? Date.now()`, which drops the
getGlobalVariable() indirection.
performance.now() is sub-millisecond, so the interpolated slow-query
line changed from `[SLOW QUERY: 1234 ms]` to `[SLOW QUERY: 1234.5678 ms]`.
Rounding once in AbstractLogger.logQuerySlow keeps the existing output
format for every logger implementation, while maxQueryExecutionTime and
the afterQuery event keep the unrounded value.
@pri12ya871
pri12ya871 force-pushed the perf-now-query-timing branch from 1c652b5 to eb640a2 Compare October 21, 2026 06:03
@alumni
alumni enabled auto-merge (squash) October 21, 2026 14:19
@alumni
alumni merged commit dca49fd into typeorm:master Oct 21, 2026
46 checks passed
@github-actions github-actions Bot added this to the 2.0.next milestone Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR

Development

Successfully merging this pull request may close these issues.

Replace Date.now() with performance.now() in query() method

5 participants