GeezerVison is showing github.com — Performance & diagnostics best practices - call for ideas · Issue #256 · goldbergyoni/nodebestpractices
Performance & diagnostics best practices - call for ideas #256DescriptionWe're kicking off the performance best practices section. Any idea regarding performance best practices or great bibliography to extract ideas from (youtube, blog post, etc)?
This issue will summarize all the ideas and bibliography and serve as a TOC for the writers. This is also a call for write or would like to learn by practicing, discussing and writing.
@sagirk @BrunoScheufler @js-kyle
Reacted by Sagir Khan, Bruno Scheufler, Maximilian Berkmann, Serhii Stotskyi and Alex Ivanov Reacted by Sagir Khan, Bruno Scheufler, nghiadd90, berpj, Wasuwat Limsuparhat and Alex Ivanov Reacted by Sagir Khan, Nguyen Van Vy and mola Activitygoldbergyoni commented on Sep 26, 2018 Title: Monitor first customer-facing metrics
Gist: Going by Google's SRE book, monitoring should focus on metrics that immediately impact the customer, practically the golden signals: API Latency, Traffic, Errors, and Saturation. Also relevant are the RED framework and the USE method
Anything else you monitor (e.g. event loop) is a cause and not a symptom. Quote from My Philosophy on Alerting:
"But," you might say, "I know database servers that are unreachable results in user data unavailability." That's fine. Alert on the data unavailability. Alert on the symptom: the 500, the Oops!, the whitebox metric that indicates that not all servers were reached from the database's client. Why?
Examples: we will show how to acheive this in Node.js Reacted by Bruno Scheufler and Sagir Khan profnandaa commented on Sep 26, 2018 Reacted by Yoni Goldberg and Sagir Khan js-kyle commented on Sep 27, 2018 Reacted by Sagir Khan, Bruno Scheufler, Yoni Goldberg and Tommy Byrd sagirk commented on Sep 27, 2018 Reacted by Yoni Goldberg and Bruno Scheufler sagirk commented on Sep 27, 2018 Reacted by Kyle Martin, Yoni Goldberg, Bruno Scheufler and Poorshad Shaddel AbdelrahmanHafez commented on Sep 27, 2018 Deal with database and external APIs in batches, meaning that a developer should favor, and try to fetch a 100 entities using a single HTTP request, instead of a 100 HTTP requests with a single document each.
Same goes for database operations, writing and fetching data are faster when done in batch rather than multiple operations. Reacted by Yoni Goldberg and Sagir Khan goldbergyoni commented on Sep 27, 2018 Copy pasting from the reddit discussion:
"I usually write to log/monitor on DB query start and query end so I can later identify avg query time and identify the slowest queries. Using Sequelize you can pass the flag {benchmark:true} and get the query times logged. Later you can bake/export to your monitoring system and create metrics based on it"
goldbergyoni commented on Sep 27, 2018 Reacted by Sagir Khan and Ahmad Alkhous VinayaSathyanarayana commented on Oct 1, 2018 Reacted by Yoni Goldberg, Sagir Khan and lsmialowskiPGS goldbergyoni commented on Oct 2, 2018 When evaluating alternatives and need to measure performance, use benchmark tooling like auto-canon and benchmark js which can provide more precise results (microtime, run many iterations) and better benchmarking performance (e.g. issue more call per second) Reacted by Sagir Khan and lsmialowskiPGS TheHollidayInn commented on Oct 5, 2018 Analyzing and monitoring cpu bottlenecks or memory leaks with Node Clinic/Prometheus
Reacted by Yoni Goldberg and Sagir Khan TheHollidayInn commented on Oct 7, 2018 A few others:
- Use gzip compression
- Serve from a CDN
- use a priority queue for high db usage/long running cpu processes
- optimize queries (such as indexing)
- parallelize operation where possible
- use http2
- use the cluster module
References:
Reacted by Bruno Barreto Carvalho, Kyle Martin and Sagir Khan migramcastillo commented on Mar 19, 2019
@migramcastillo Makes a lot of sense. Do you want to write that bullet?
I'd be glad to, in which branch should I make the PR? sagirk commented on Mar 21, 2019
I'd be glad to, in which branch should I make the PR?
@migramcastillo If you meant to ask what branch to raise your PR against, that would be master. If you meant to ask what branch to make your changes in, feel free to create a new branch in your fork. stale commented on Jun 19, 2019 Hello there! 👋
This issue has gone silent. Eerily silent. ⏳
We currently close issues after 100 days of inactivity. It has been 90 days since the last update here.
If needed, you can keep it open by replying here.
Thanks for being a part of the Node.js Best Practices community! 💚 abhishekshetty commented on Apr 10, 2020
* Promisify your DB Connections and run queries in paralllel via async/await and Promise.all()
Not only for DB purpose, using Promise.all instead of lot of async/await should be a performance best practice, i.e. we need to call 4 API calls correctly with Axios to build our complete response, instead of using await for each one is better to use a single await with Promise.all().
Although Promise.all is better than sequential non-dependent promises in most of the cases, It works best only when the number of calls/promises are known before hand or atleast few. In case of dynamic number of promises, e.g. batching in runtime and if the number of calls increases significantly it might endup exhausting all the connection pool or create deadlocks or if it http calls then spam the service. sample stackoverflow link https://stackoverflow.com/questions/53964228/how-do-i-perform-a-large-batch-of-promises abhishekshetty commented on Apr 10, 2020
-
Maybe have a section for in-memory cache and best practices around implementing and maintaining cache. There are few packages that supports this functionality. Also it seems there is no shared in-memory cache implementation possible in cluster mode.
-
Would like to highlight a recent video released by chrome team https://www.youtube.com/watch?v=ff4fgQxPaO0, that talks about how to have faster apps when dealing with large object literals.
Reacted by Yoni Goldberg Reacted by Yoni Goldberg victor-homyakov commented on Oct 12, 2020 When writing NPM module, it's a good idea to measure the time needed to require() the module you are developing, e.g.
console.time('require');
const myModule = require('my-module');
console.timeEnd('require');
Reason: this time is added to the overall startup time of every code that uses your module. It doesn't play a big role for long-running servers, but is very important for CLI utilities (pre-commit hooks, linters etc.).
Few examples:
How to fix/mitigate:
- provide granular exports in your module, like ramda and lodash do - consumers may
require() only what they need
- use exact imports, e.g.
const complement = require('ramda/src/complement'); instead of const R = require('ramda');
- use https://www.npmjs.com/package/import-lazy or something similar, require modules only when you are 100% sure you need them, e.g. ESLint should not load every plugin listed in config, but only those needed to lint specified files (don't load TSX rules if you are checking just plain JS file, don't load mocha-specific rules if there is no mocha test file to lint)
Aschen commented on Jan 6, 2021 Aschen commented on Jan 6, 2021 Prefer monomorphic function
Prefer the usage of monomorphic function instead of polymorphic functions.
This will allows:
- Turbofan to compile them into optimized assembly
- better inline caching for fast property access
example
// don't
function add (a, b) {
return a + b
}
add(21, 42);
add(21.2, 42.3);
// do
function addInt(a, b) {
return a + b;
}
function addFloat(a, b) {
return a+ b;
}
addInt(21, 42);
addFloat(21.2, 42.3);
If you are interested I can write a section on this topic, providing code example, performance diff, etc
Inline Caches with Monomorphism, Polymorphism and Megamorphism
Interpreter and Compiler: hidden classes, inline caching, polymorphism and megamorphism Aschen commented on Jan 6, 2021 Avoid dynamic allocation of function
Avoid to declare function inside function.
Function are object and object allocation is costly as well as the garbage collection.
Also, since the function is re-declared at each call, v8 will not be able to optimize it (compilation into optimized assembly, inline caching for fast property access)
example
// don't
function add(a, b) {
const addInt = (a, b) => {
return a + b;
}
if (typeof a === 'number') {
return addInt(a, b);
}
if (typeof a.x === 'number') {
return addInt(a.x, b.x);
}
}
// do
function addInt(a, b) {
return a + b;
}
function add(a, b) {
if (typeof a === 'number') {
return addInt(a, b);
}
if (typeof a.x === 'number') {
return addInt(a.x, b.x);
}
}
If you are interested I can write a section on this topic, providing code example, performance diff, etc
Closures Compilation and Allocation
How Closures Works kibertoad commented on Jan 6, 2021 Reacted by Manuel Spigolon and Maksym Shenderuk Aschen commented on Jan 10, 2021 @goldbergyoni Are you still looking for contributor on this topic? rluvaton commented on Mar 24, 2022 There are really good ideas here! We should add it
I also have some:
- Prefer branchless programming (but make sure it's not effecting readability and always measure before to check if it worth it - as all performance tips)
- Wrap large data with closure so it can get garbage collected
// Bad - really large file not getting garbage collected
function run() {
const reallyLargeFile = readFile()
const transformed = transformData(reallyLargeFile)
// do some extra work
}
// Good - really large file getting garbage collected
function run() {
let transformed;
// prefer extract to function instead of empty closure
{
const reallyLargeFile = readFile()
transformed = transformData(reallyLargeFile)
}
// do some extra work
}
- Read large files in streams instead all at once
victor-homyakov commented on Mar 31, 2022
- Wrap large data with closure so it can get garbage collected
// prefer extract to function instead of empty closure
{
const reallyLargeFile = readFile()
transformed = transformData(reallyLargeFile)
}
// do some extra work
Looks like in order to benefit from this change, the "extra work" part
- either should have a significant execution time, e.g. 5 seconds - then in original code
reallyLargeFile will be unavailable for GC during these 5 seconds, and in modified code, it could be GCed if the engine decides to start GC during that time
- or should have high memory consumption, to trigger Full GC (usually the engine gives it a last try and tries to free all possible memory before throwing the "out of memory" error)
I think these details should be noted - the readers should not follow the advice blindly but should have some understanding of why and when it helps.
Also, it would be great to have some proofs or benchmarks to illustrate this idea.
- Read large files in streams instead all at once
But we've already seen const reallyLargeFile = readFile() in advice number 2. Could you please make the code example from advice 2 consistent with advice 3 (i.e. use something else instead of reading a large file at once)?
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|